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
app/src/main/java/com/chenqianhe/lohasfarm/ui/main/nav/Actions.kt
chenqianhe
512,742,106
false
null
package com.chenqianhe.lohasfarm.ui.main.nav import androidx.navigation.NavHostController class Actions(navController: NavHostController) { val toMainPage: () -> Unit = { navController.navigate(Destinations.MAIN_ROUTE) } val toLoginPage: () -> Unit = { navController.navigate(Destinations.LOGIN_ROUTE) } val toWebPage: (url: String, title: String) -> Unit = { url: String, title: String -> navController.navigate("${Destinations.WEB_PAGE_ROUTE}/${url}/${title}") } val toTutorPage: () -> Unit = { navController.navigate(Destinations.TUTOR_ROUTE) } val toCropManagementPage: () -> Unit = { navController.navigate(Destinations.CROP_MANGE_ROUTE) } val upPress: () -> Unit = { navController.navigateUp() } val toDetailMessagePage: (id: String, title: String) -> Unit = { id: String, title: String -> navController.navigate("${Destinations.DETAIL_MESSAGE_ROUTE}/${id}/${title}") } val toPersonalInfo: (uid: String, ugid: String, name: String, profile_photo_url: String) -> Unit = { uid: String, ugid: String, name: String, profile_photo_url: String -> navController .navigate("${Destinations.PERSONAL_INFO_ROUTE}/${uid}/${ugid}/${name}/${profile_photo_url}") } val toOthersLandDetail: (uid: String, name: String, landPlantedArea: Int, landTotalArea: Int, profile_photo_url: String) -> Unit = { uid: String, name: String, landPlantedArea: Int, landTotalArea: Int, profile_photo_url: String -> navController .navigate("${Destinations.OTHERS_LAND_ROUTE}/${uid}/${name}/${landPlantedArea}/${landTotalArea}/${profile_photo_url}") } val toMineLandDetail: (uid: String, name: String, landPlantedArea: Int, landTotalArea: Int, profile_photo_url: String, landLeaseTerm: String) -> Unit = { uid: String, name: String, landPlantedArea: Int, landTotalArea: Int, profile_photo_url: String, landLeaseTerm: String -> navController .navigate("${Destinations.MINE_LAND_ROUTE}/${uid}/${name}/${landPlantedArea}/${landTotalArea}/${profile_photo_url}/${landLeaseTerm}") } val toMineLandInfo: ( name: String, landLeaseTerm: String, area: String) -> Unit = { name: String, landLeaseTerm: String, area: String -> navController .navigate("${Destinations.MINE_LAND_INFO_ROUTE}/${name}/${landLeaseTerm}/${area}") } /** * 清理栈中页面,实现后续页面返回直接到桌面 */ val clearBackStack: () -> Unit = { while (!navController.backQueue.isEmpty()) { navController.popBackStack(navController.currentDestination!!.id, inclusive = true, saveState = false ) } } }
0
Kotlin
0
1
5e15aeab1693a1e242c29901171b08ee165e8eb4
2,784
LOHAS-Farm-Android
MIT License
src/jvmMain/kotlin/acidicoala/koalageddon/core/io/Json.kt
acidicoala
584,899,259
false
null
package acidicoala.koalageddon.core.io import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json @OptIn(ExperimentalSerializationApi::class) val appJson = Json { encodeDefaults = true prettyPrint = true coerceInputValues = true ignoreUnknownKeys = true prettyPrintIndent = " " }
1
Kotlin
4
50
9ec09a7ba5cabc7b1be173a9c8e8794c93984a24
340
Koalageddon2
The Unlicense
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/extensions/RxExtensions.kt
Waboodoo
34,525,124
false
null
package ch.rmy.android.http_shortcuts.extensions import ch.rmy.android.framework.utils.Destroyer import ch.rmy.android.http_shortcuts.exceptions.CanceledByUserException import io.reactivex.CompletableEmitter import io.reactivex.SingleEmitter import io.reactivex.disposables.Disposable fun CompletableEmitter.cancel() { if (!isDisposed) { onError(CanceledByUserException()) } } fun <T> SingleEmitter<T>.cancel() { if (!isDisposed) { onError(CanceledByUserException()) } } fun CompletableEmitter.createDestroyer(): Destroyer { val destroyer = Destroyer() setDisposable(object : Disposable { override fun dispose() { destroyer.destroy() } override fun isDisposed() = [email protected] }) return destroyer }
23
Kotlin
87
547
09eaa8438d452f95e73d57183b198c4b52d05789
819
HTTP-Shortcuts
MIT License
src/main/java/frc/robot/subsystems/Color.kt
HaywireRobotics
164,000,492
false
null
package frc.robot.subsystems enum class Color(val pwm: Double) { RAINBOW(-0.99), FIRE(-0.57), HOT_PINK(0.57), DARK_RED(0.59), RED(0.61), RED_ORANGE(0.63), ORANGE(0.65), GOLD(0.67), YELLOW(0.69), LAWN_GREEN(0.71), LIME(0.73), DARK_GREEN(0.75), GREEN(0.77), BLUE_GREEN(0.79), AQUA(0.81), SKY_BLUE(0.83), DARK_BLUE(0.85), BLUE(0.87), BLUE_VIOLET(0.89), VIOLET(0.91), BLACK(0.99), WHITE(0.93), GRAY(0.95), DARK_GRAY(0.97) }
0
Kotlin
0
1
c41ff0427754e85c02ba6bbef876d910eae71f4c
470
Haywire-1569-Deep-Space-2019
MIT License
graphene-writer/src/test/kotlin/com/graphene/writer/store/key/handler/TimeBasedLocalKeyCacheTest.kt
jacek-bakowski
231,624,180
true
{"Java": 400482, "Kotlin": 112616, "Shell": 3537, "Dockerfile": 2238, "Smarty": 2138, "ANTLR": 1632}
package com.graphene.writer.store.key.handler import com.graphene.writer.store.key.TimeBasedLocalKeyCache import kotlin.test.assertEquals import kotlin.test.assertNull import org.joda.time.DateTimeUtils import org.junit.jupiter.api.Test internal class TimeBasedLocalKeyCacheTest { @Test internal fun `should expire cache entry`() { // given val timeBasedCache = TimeBasedLocalKeyCache<String, Long>(1) // when DateTimeUtils.setCurrentMillisFixed(com.graphene.common.utils.DateTimeUtils.from("2019-01-01 10:00:00")) timeBasedCache.put(KEY, VALUE) // then DateTimeUtils.setCurrentMillisFixed(com.graphene.common.utils.DateTimeUtils.from("2019-01-01 10:01:01")) assertNull(timeBasedCache.get(KEY)) } @Test internal fun `shouldn't expire cache entry not yet expire interval`() { // given val timeBasedCache = TimeBasedLocalKeyCache<String, Long>(1) // when DateTimeUtils.setCurrentMillisFixed(com.graphene.common.utils.DateTimeUtils.from("2019-01-01 10:00:00")) timeBasedCache.put(KEY, VALUE) // then DateTimeUtils.setCurrentMillisFixed(com.graphene.common.utils.DateTimeUtils.from("2019-01-01 10:00:59")) assertEquals(timeBasedCache.get(KEY), VALUE) } companion object { const val KEY = "key1" const val VALUE = 1L } }
0
Java
0
0
657cd36a37c9bed4de87582ba6c4e0bebbe358c7
1,313
graphene
MIT License
app/src/main/java/com/example/practiceapplicationbrg/TierAdapter.kt
Hirenr12
860,945,068
false
{"Kotlin": 160983}
package com.example.practiceapplicationbrg import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class TierAdapter(private val tiers: List<Tier>) : RecyclerView.Adapter<TierAdapter.TierViewHolder>() { // ViewHolder class to hold references to the views for each list item class TierViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val tierImage: ImageView = itemView.findViewById(R.id.tierImage) val tierTitle: TextView = itemView.findViewById(R.id.tierTitle) val tierPoints: TextView = itemView.findViewById(R.id.tierPoints) } // Inflates the item layout and returns the ViewHolder override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TierViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.tier_item, parent, false) return TierViewHolder(view) } // Binds the data to the views in each item override fun onBindViewHolder(holder: TierViewHolder, position: Int) { val tier = tiers[position] holder.tierTitle.text = tier.name holder.tierPoints.text = "Points required: ${tier.requiredPoints}" holder.tierImage.setImageResource(tier.imageResId) // Handle touch event to scale the image holder.tierImage.setOnTouchListener { view, event -> when (event.action) { MotionEvent.ACTION_DOWN -> { // Scale up when pressed val scaleUp = AnimationUtils.loadAnimation(view.context, R.anim.scale_up) view.startAnimation(scaleUp) } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { // Scale down when released or canceled val scaleDown = AnimationUtils.loadAnimation(view.context, R.anim.scale_down) view.startAnimation(scaleDown) } } true } } // Returns the size of the data list override fun getItemCount(): Int { return tiers.size } }
0
Kotlin
0
0
a8fdad30a1f805d9557f105007217e7e9245dd52
2,290
BrainRotGame_OPSC7312POE
MIT License
app/src/main/java/com/soundai/azero/azeromobile/ui/activity/question/QuestionViewModel.kt
azerodeveloper
378,396,535
false
{"Kotlin": 740494, "Java": 208804, "AIDL": 1358}
package com.soundai.azero.azeromobile.ui.activity.question import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import com.azero.sdk.AzeroManager import com.azero.sdk.util.Utils import com.azero.sdk.util.log import com.google.gson.Gson import com.google.gson.JsonObject import com.soundai.azero.azeromobile.common.bean.question.* import org.json.JSONObject class QuestionViewModel( application: Application ) : AndroidViewModel(application) { val voteResultTemplate: MutableLiveData<VoteResultTemplate> = MutableLiveData() val sendQuestionTemplate: MutableLiveData<SendQuestionTemplate> = MutableLiveData() val voteTemplate: MutableLiveData<VoteTemplate> = MutableLiveData() val submitVoteTemplate: MutableLiveData<SubmitVoteTemplate> = MutableLiveData() val answerQuestionTemplate: MutableLiveData<AnswerQuestionTemplate> = MutableLiveData() val questionResultTemplate: MutableLiveData<QuestionResultTemplate> = MutableLiveData() val continueTemplate: MutableLiveData<ContinueTemplate> = MutableLiveData() val helpTemplate: MutableLiveData<QuestionHelperTemplate> = MutableLiveData() val timerStart: MutableLiveData<Int> = MutableLiveData() val ivHint: MutableLiveData<Int?> = MutableLiveData() var submitAnswer = "" var showQuestionInfoImmediately = false var isWatcher = false fun update(template: String?) { if (template == null) { return } val json = JSONObject(template) log.e("QuestionViewModel, update template, scene= ${json.getString("scene")}") when (json.getString("scene")) { "voteResult" -> onVoteResult(template) "answerQuestion" -> onAnswerQuestion(template) "questionResult" -> onQuestionResult(template) "sendQuestion" -> onSendQuestion(template) "continue" -> onContinue(template) "vote" -> onVote(template) "submitVote" -> onSubmitVote(template) "gameHelp" -> onHelper(template) } } fun sendSelect(option: String) { val payload = JsonObject().apply { addProperty("type", "answerGameSend") addProperty("value", option) } sendUserEvent(payload) } fun exitGame() { val payload = JsonObject().apply { addProperty("type", "answerGameEnd") } sendUserEvent(payload) } fun continueGame() { val payload = JsonObject().apply { addProperty("type", "answerGameContinue") } sendUserEvent(payload) } fun getHelp() { val payload = JsonObject().apply { addProperty("type", "answerGameHelp") } sendUserEvent(payload) } private fun sendUserEvent(payload: JsonObject) { val header = JsonObject().apply { addProperty("namespace", "AzeroExpress") addProperty("name", "UserEvent") addProperty("messageId", Utils.getUuid()) } val event = JsonObject().apply { add("event", JsonObject().also { event -> event.add("header", header) event.add("payload", payload) }) } AzeroManager.getInstance().customAgent.sendEvent(event.toString()) } private fun onSubmitVote(template: String) { submitVoteTemplate.postValue(Gson().fromJson(template, SubmitVoteTemplate::class.java)) } private fun onVote(template: String) { voteTemplate.postValue(Gson().fromJson(template, VoteTemplate::class.java)) } private fun onQuestionResult(template: String) { questionResultTemplate.postValue( Gson().fromJson( template, QuestionResultTemplate::class.java ) ) } private fun onSendQuestion(template: String) { sendQuestionTemplate.postValue(Gson().fromJson(template, SendQuestionTemplate::class.java)) } private fun onAnswerQuestion(template: String) { answerQuestionTemplate.postValue( Gson().fromJson( template, AnswerQuestionTemplate::class.java ) ) } private fun onVoteResult(template: String) { voteResultTemplate.postValue(Gson().fromJson(template, VoteResultTemplate::class.java)) } private fun onContinue(template: String) { continueTemplate.postValue(Gson().fromJson(template, ContinueTemplate::class.java)) } private fun onHelper(template: String) { if (helpTemplate.value == null) { helpTemplate.postValue(Gson().fromJson(template, QuestionHelperTemplate::class.java)) } } }
0
Kotlin
2
1
f30ab0e62a9ca6431ea4a8e6ba82b6f4a18028a1
4,758
AzeroMobile
Apache License 2.0
core/src/main/java/org/kerala/core/consensus/messages/AppendEntriesResponse.kt
elkd
150,052,974
false
null
package org.kerala.core.consensus.messages data class AppendEntriesResponse( val term: Int, val isSuccessful: Boolean, val prevLogIndex: Long = 0 )
1
null
1
1
f3b6d1781bfa60acc1932dfc352071532ebf1a3d
161
elkd
MIT License
plugins/cloudopt-next-health/src/main/kotlin/net/cloudopt/next/health/HealthChecksPlugin.kt
cloudoptlab
117,033,346
false
{"Kotlin": 438045, "HTML": 4325, "Python": 163, "Handlebars": 149, "FreeMarker": 148, "CSS": 23}
/* * Copyright 2017-2021 Cloudopt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.cloudopt.next.health import net.cloudopt.next.core.ConfigManager import net.cloudopt.next.core.Plugin import net.cloudopt.next.web.NextServer /** * This plugin provides a simple way to expose health checks. Health checks are used to express the current state of the * application in very simple terms: UP or DOWN. * * If also enabled in the settings, the /health interface is automatically opened and you can get the status of all used * plugins via json. */ class HealthChecksPlugin : Plugin { override fun start(): Boolean { /** * Loading configuration files. */ HealthChecksManager.config = ConfigManager.initObject("healthChecks", HealthChecksConfig::class) as HealthChecksConfig HealthChecksManager.report()["applicationName"] = HealthChecksManager.config.applicationName NextServer.registerResourceTable(url = HealthChecksManager.config.accessPath, HealthChecksController::class) /** * */ HealthChecksManager.creatTimer() return true } override fun stop(): Boolean { if (HealthChecksManager.timerId > 0) { HealthChecksManager.stopTimer() } return true } }
3
Kotlin
49
335
b6d8f934357a68fb94ef511109a1a6043af4b5b6
1,838
cloudopt-next
Apache License 2.0
app/src/main/java/android/project/auction/data/local/dao/FavoritesDao.kt
RavanSA
515,232,661
false
{"Kotlin": 429676}
package android.project.auction.data.local.dao import android.project.auction.data.local.entity.Favorites import androidx.room.* import kotlinx.coroutines.flow.Flow @Dao interface FavoritesDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun addItemToFavorites(fav: Favorites) @Delete suspend fun deleteItem(fav: Favorites) @Query("SELECT * FROM Favorites WHERE user_id =:userId") fun getFavoriteItems(userId: String): Flow<List<Favorites>> @Query("SELECT * FROM Favorites WHERE item_id=:id AND user_id = :userId") suspend fun getItemFromFavoritesById(id: String, userId: String): Favorites? @Query("SELECT EXISTS (SELECT 1 FROM Favorites WHERE item_id=:id)") suspend fun isItemAddedtoFavorites(id: String): Int? }
0
Kotlin
1
3
c5914b4870d6b004152c45d6d41d7bd6c99eb9e6
776
AuctionProject
MIT License
core/local/database/src/main/java/city/zouitel/database/mapper/NoteAndMediaMapper.kt
City-Zouitel
576,223,915
false
{"Kotlin": 570765}
package city.zouitel.database.mapper import city.zouitel.repository.model.NoteAndMedia import city.zouitel.database.model.NoteAndMediaEntity as InNoteAndMedia import city.zouitel.repository.model.NoteAndMedia as OutNoteAndMedia class NoteAndMediaMapper { fun toRepo(notesAndMedia: List<InNoteAndMedia>) = notesAndMedia.map { toRepo(it) } fun toRepo(noteAndMedia: InNoteAndMedia) = OutNoteAndMedia( noteUid = noteAndMedia.noteUid, mediaId = noteAndMedia.mediaId ) fun fromRepo(noteAndMedia: OutNoteAndMedia) = InNoteAndMedia( noteUid = noteAndMedia.noteUid, mediaId = noteAndMedia.mediaId ) }
40
Kotlin
13
120
72d036d49995f0a9bffa1b4dd9aee2657f4b8398
648
JetNote
Apache License 2.0
plugin/src/main/kotlin/se/ade/mc/cubematic/CubematicPlugin.kt
ade
651,206,426
false
{"Kotlin": 61789}
package se.ade.mc.cubematic import se.ade.mc.cubematic.breaking.BreakerAspect import se.ade.mc.cubematic.crafting.DispenseCraftingTableAspect import se.ade.mc.cubematic.crafting.SequenceInputDropperAspect import se.ade.mc.cubematic.placing.PlacingAspect import org.bukkit.NamespacedKey import org.bukkit.plugin.java.JavaPlugin import se.ade.mc.cubematic.config.CubeConfig import se.ade.mc.cubematic.config.CubeConfigProvider import se.ade.mc.cubematic.portals.PortalAspect class CubematicPlugin: JavaPlugin() { private val cubeConfigProvider by lazy { CubeConfigProvider(this) } val config: CubeConfig get() = cubeConfigProvider.current val namespaceKeys = Namespaces( craftingDropper = createNamespacedKey("crafting_dropper"), dropSlot = createNamespacedKey("drop_slot"), placerBlockTag = createNamespacedKey("placer") ) override fun onEnable() { super.onEnable() //server.pluginManager.registerEvents(DebugAspect(this), this) server.pluginManager.registerEvents(DispenseCraftingTableAspect(this), this) server.pluginManager.registerEvents(SequenceInputDropperAspect(this), this) server.pluginManager.registerEvents(BreakerAspect(this), this) server.pluginManager.registerEvents(PlacingAspect(this), this) server.pluginManager.registerEvents(PortalAspect(this), this) //server.pluginManager.registerEvents(ShriekerTest(this), this) if(config.debug) { logger.info("Initialized with debug mode enabled") } } fun scheduleRun(delayTicks: Long = 0L, block: () -> Unit) { server.scheduler.runTaskLater(this, Runnable { block() }, delayTicks) } private fun createNamespacedKey(entry: String) = NamespacedKey.fromString("$namespace:$entry".lowercase(), this)!! companion object { const val namespace = "cubematic" } } data class Namespaces( val craftingDropper: NamespacedKey, val dropSlot: NamespacedKey, val placerBlockTag: NamespacedKey, )
0
Kotlin
0
0
d0ef311929c27eae8f115cfbfa3c72f40711a3c5
2,065
Cubematic
MIT License
kommons-core/src/test/kotlin/io/kommons/utils/memorizer/AbstractMemorizerTest.kt
debop
235,066,649
false
null
package io.kommons.utils.memorizer import org.amshove.kluent.shouldBeGreaterOrEqualTo import org.amshove.kluent.shouldEqualTo import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertTimeout import java.time.Duration import kotlin.system.measureTimeMillis abstract class AbstractMemorizerTest { abstract val factorial: FactorialProvider abstract val fibonacci: FibonacciProvider abstract val heavyFunc: (Int) -> Int @Test fun `run fibonacci`() { val x1 = fibonacci.calc(500) assertTimeout(Duration.ofMillis(500)) { fibonacci.calc(500) } shouldEqualTo x1 } @Test fun `run factorial`() { val f1 = factorial.calc(100) assertTimeout(Duration.ofMillis(500)) { factorial.calc(100) } shouldEqualTo f1 } @Test fun `call heavy function`() { measureTimeMillis { heavyFunc(10) shouldEqualTo 100 } shouldBeGreaterOrEqualTo 100 assertTimeout(Duration.ofMillis(500)) { heavyFunc(10) shouldEqualTo 100 } } }
0
Kotlin
11
53
c00bcc0542985bbcfc4652d0045f31e5c1304a70
1,089
kotlin-design-patterns
Apache License 2.0
app/src/main/java/com/grarak/ytfetcher/views/recyclerview/RecyclerViewItem.kt
Grarak
130,748,417
false
null
package com.grarak.ytfetcher.views.recyclerview import android.support.annotation.LayoutRes import android.support.v7.widget.RecyclerView abstract class RecyclerViewItem { @get:LayoutRes abstract val layoutXml: Int abstract fun bindViewHolder(viewHolder: RecyclerView.ViewHolder) }
1
null
2
1
8b7f85608dd2cc4d2e8c748bbc7b1e8a512e3191
298
YTFetcher
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/ecs/patterns/NetworkListenerPropsDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.ecs.patterns import cloudshift.awscdk.common.CdkDslMarker import kotlin.Number import kotlin.String import software.amazon.awscdk.services.ecs.patterns.NetworkListenerProps /** * Properties to define an network listener. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ecs.patterns.*; * NetworkListenerProps networkListenerProps = NetworkListenerProps.builder() * .name("name") * // the properties below are optional * .port(123) * .build(); * ``` */ @CdkDslMarker public class NetworkListenerPropsDsl { private val cdkBuilder: NetworkListenerProps.Builder = NetworkListenerProps.builder() /** @param name Name of the listener. */ public fun name(name: String) { cdkBuilder.name(name) } /** @param port The port on which the listener listens for requests. */ public fun port(port: Number) { cdkBuilder.port(port) } public fun build(): NetworkListenerProps = cdkBuilder.build() }
4
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,337
awscdk-dsl-kotlin
Apache License 2.0
ethereumkit/src/main/java/org/p2p/ethereumkit/internal/api/core/WebSocketRpcSyncer.kt
p2p-org
306,035,988
false
null
package org.p2p.ethereumkit.internal.api.core import com.google.gson.Gson import org.p2p.core.rpc.JsonRpc import org.p2p.ethereumkit.internal.api.jsonrpc.SubscribeJsonRpc import org.p2p.ethereumkit.internal.api.jsonrpcsubscription.NewHeadsRpcSubscription import org.p2p.ethereumkit.internal.api.jsonrpcsubscription.RpcSubscription import org.p2p.ethereumkit.internal.core.EthereumKit import io.reactivex.Single import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger import java.util.logging.Logger import org.p2p.core.rpc.IRpcSyncer import org.p2p.core.rpc.IRpcSyncerListener import org.p2p.core.rpc.IRpcWebSocket import org.p2p.core.rpc.IRpcWebSocketListener import org.p2p.core.rpc.RpcHandler import org.p2p.core.rpc.RpcResponse import org.p2p.core.rpc.RpcSubscriptionResponse import org.p2p.core.rpc.SubscriptionHandler import org.p2p.core.rpc.SyncerState import org.p2p.core.rpc.WebSocketState class WebSocketRpcSyncer( private val rpcSocket: IRpcWebSocket, private val gson: Gson ) : IRpcSyncer, IRpcWebSocketListener { private val logger = Logger.getLogger("WebSocketRpcSyncer") private var currentRpcId = AtomicInteger(0) private var rpcHandlers = ConcurrentHashMap<Int, RpcHandler>() private var subscriptionHandlers = ConcurrentHashMap<String, SubscriptionHandler>() //region IRpcSyncer override var listener: IRpcSyncerListener? = null override val source = "WebSocket ${rpcSocket.source}" override var state: SyncerState = SyncerState.NotReady(EthereumKit.SyncError.NotStarted()) private set(value) { if (value != field) { field = value listener?.didUpdateSyncerState(value) } } override fun start() { state = SyncerState.Preparing rpcSocket.start() } override fun stop() { state = SyncerState.NotReady(EthereumKit.SyncError.NotStarted()) rpcSocket.stop() } override fun <P,T> single(rpc: JsonRpc<P, T>): Single<T> { return Single.create { emitter -> send( rpc = rpc, onSuccess = { emitter.onSuccess(it) }, onError = { emitter.onError(it) } ) } } //endregion //region IRpcWebSocketListener override fun didUpdate(socketState: WebSocketState) { when (socketState) { WebSocketState.Connecting -> { state = SyncerState.Preparing } WebSocketState.Connected -> { state = SyncerState.Ready subscribeToNewHeads() } is WebSocketState.Disconnected -> { rpcHandlers.forEach { (_, rpcHandler) -> rpcHandler.onError(socketState.error) } rpcHandlers.clear() subscriptionHandlers.clear() state = SyncerState.NotReady(socketState.error) } } } override fun didReceive(response: RpcResponse) { rpcHandlers.remove(response.id)?.let { rpcHandler -> rpcHandler.onSuccess(response) } } override fun didReceive(response: RpcSubscriptionResponse) { subscriptionHandlers[response.params.subscriptionId]?.invoke(response) } //endregion private fun <P,T> send(rpc: JsonRpc<P, T>, handler: RpcHandler) { rpc.id = currentRpcId.addAndGet(1) rpcSocket.send(rpc) rpcHandlers[rpc.id] = handler } private fun <P,T> send(rpc: JsonRpc<P, T>, onSuccess: (T) -> Unit, onError: (Throwable) -> Unit) { try { val rpcHandler = RpcHandler( onSuccess = { response -> try { onSuccess(rpc.parseResponse(response, gson)) } catch (error: Throwable) { onError(error) } }, onError = onError ) send(rpc, rpcHandler) } catch (error: Throwable) { onError(error) } } private fun <T> subscribe(subscription: RpcSubscription<T>, onSubscribeSuccess: () -> Unit, onSubscribeError: (Throwable) -> Unit, successHandler: (T) -> Unit, errorHandler: (Throwable) -> Unit) { send( rpc = SubscribeJsonRpc(subscription.params), onSuccess = { subscriptionId -> subscriptionHandlers[subscriptionId] = { response -> try { successHandler(subscription.parse(response, gson)) } catch (error: Throwable) { errorHandler(error) } } onSubscribeSuccess() }, onError = { error -> onSubscribeError(error) } ) } private fun subscribeToNewHeads() { subscribe( subscription = NewHeadsRpcSubscription(), onSubscribeSuccess = { }, onSubscribeError = { }, successHandler = { header -> listener?.didUpdateLastBlockHeight(lastBlockHeight = header.number) }, errorHandler = { error -> logger.warning("NewHeads Handle Failed: ${error.javaClass.simpleName}") } ) } }
8
Kotlin
16
28
71b282491cdafd26be1ffc412a971daaa9c06c61
5,635
key-app-android
MIT License
app/src/main/java/com/mnnit/moticlubs/domain/usecase/channel/AddChannel.kt
CC-MNNIT
576,708,897
false
{"Kotlin": 563214, "Shell": 212}
package com.mnnit.moticlubs.domain.usecase.channel import com.mnnit.moticlubs.domain.model.Channel import com.mnnit.moticlubs.domain.repository.Repository import com.mnnit.moticlubs.domain.util.Resource import com.mnnit.moticlubs.domain.util.ResponseStamp import com.mnnit.moticlubs.domain.util.mapFromDomain import com.mnnit.moticlubs.domain.util.mapToDomain import com.mnnit.moticlubs.domain.util.networkResource import kotlinx.coroutines.flow.Flow class AddChannel(private val repository: Repository) { operator fun invoke(channel: Channel): Flow<Resource<Channel>> = repository.networkResource( "Unable to create channel", stampKey = ResponseStamp.CHANNEL, query = { channel }, apiCall = { apiService, auth, stamp -> apiService.createChannel(auth, stamp, channel.mapFromDomain()) }, saveResponse = { _, new -> repository.insertOrUpdateChannel(new.mapToDomain()) }, remoteRequired = true, ) }
0
Kotlin
1
1
6be5e334b94b0bc89c3f33bd6f581fd739e14786
955
MotiClubs
MIT License
app/src/main/java/org/simple/clinic/registration/name/RegistrationNameEffect.kt
simpledotorg
132,515,649
false
null
package org.simple.clinic.registration.name import org.simple.clinic.user.OngoingRegistrationEntry sealed class RegistrationNameEffect data class ValidateEnteredName(val name: String) : RegistrationNameEffect() sealed class RegistrationNameViewEffect : RegistrationNameEffect() data class PrefillFields(val entry: OngoingRegistrationEntry) : RegistrationNameViewEffect() data class ProceedToPinEntry(val entry: OngoingRegistrationEntry) : RegistrationNameViewEffect()
13
null
73
236
ff699800fbe1bea2ed0492df484777e583c53714
474
simple-android
MIT License
android/app/src/main/java/com/jaino/napped/employment/adapter/CompanyAdapter.kt
pknu-wap
678,705,868
false
{"Kotlin": 61778}
package com.jaino.napped.employment.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.jaino.domain.model.Company import com.jaino.domain.model.Favorite import com.jaino.napped.databinding.ItemCompanyBinding class CompanyAdapter( private val onChecked: (Favorite) -> Unit ): ListAdapter<Company, CompanyAdapter.CompanyDataViewHolder>(callback) { companion object{ val callback = object : DiffUtil.ItemCallback<Company>(){ override fun areItemsTheSame(oldItem: Company, newItem: Company): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: Company, newItem: Company): Boolean { return oldItem.company == newItem.company } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CompanyDataViewHolder { return CompanyDataViewHolder(ItemCompanyBinding.inflate( LayoutInflater.from(parent.context), parent, false)) } override fun onBindViewHolder(holder: CompanyDataViewHolder, position: Int) { holder.bind(currentList[position]) } inner class CompanyDataViewHolder(private val binding: ItemCompanyBinding) : RecyclerView.ViewHolder(binding.root){ fun bind(item : Company){ binding.company = item binding.cbCompanyItem.setOnCheckedChangeListener { _, isChecked -> if(isChecked){ onChecked(item.toFavorite()) } } } } private fun Company.toFavorite() = Favorite( company = company, kind = kind, location = location ) }
0
Kotlin
1
7
ff32b4608bba47ca50c4a68e07744dee0e06321c
1,843
2023_RDC_NAPPED
MIT License
core/ui/src/main/kotlin/dev/yacsa/ui/composable/content/LoadingContent.kt
andrew-malitchuk
589,720,124
false
null
package dev.yacsa.ui.composable.content import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import com.google.accompanist.systemuicontroller.rememberSystemUiController import dev.yacsa.ui.theme.YacsaTheme import io.github.serpro69.kfaker.Faker @Composable fun ContentIsLoading( modifier: Modifier = Modifier, ) { val composition by rememberLottieComposition(LottieCompositionSpec.Asset("lottie_loading_accent.json")) val systemUiController = rememberSystemUiController() systemUiController.apply { setSystemBarsColor( color = YacsaTheme.colors.background, ) setNavigationBarColor( color = YacsaTheme.colors.background, ) } Box( modifier = modifier .fillMaxSize() .background(YacsaTheme.colors.background), contentAlignment = Alignment.Center, ) { LottieAnimation( modifier = Modifier.height(256.dp).width(256.dp), composition = composition, iterations = LottieConstants.IterateForever, ) } } @Preview(showBackground = true) @Composable fun Preview_ContentIsLoading_Light() { val faker = Faker() YacsaTheme(false) { ContentIsLoading() } } @Preview(showBackground = true) @Composable fun Preview_ContentIsLoading_Dark() { val faker = Faker() YacsaTheme(true) { ContentIsLoading() } }
0
Kotlin
0
0
e35620cf1c66b4f76f0ed30d9c6d499acd134403
2,052
yet-another-compose-showcase-app
MIT License
MarvelApp/commons/src/main/java/io/github/brunogabriel/commons/activity/BaseActivity.kt
brunogabriel
293,145,767
false
null
package io.github.brunogabriel.commons.activity import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar open class BaseActivity : AppCompatActivity() { fun setToolbar(toolbar: Toolbar?) { toolbar?.let { setSupportActionBar(it) } } }
0
Kotlin
0
0
62aee501df142e47fdbe0671d4a2e153e4221d97
303
android-marvel-app
MIT License
example/android/app/src/main/kotlin/com/yuxiaor/flutter/g_faraday_example/fragment/TestFragment.kt
gfaraday
299,574,522
false
{"Dart": 178306, "Objective-C": 4588, "Ruby": 3569, "C": 104}
package com.yuxiaor.flutter.g_faraday_example.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import com.yuxiaor.flutter.g_faraday_example.R /** * Author: Edward * Date: 2020-09-07 * Description: */ class TestFragment : Fragment() { companion object { fun newInstance(text: String): TestFragment { return TestFragment().apply { arguments = Bundle().apply { putString("text", text) } } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.frag_test, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val textView = view.findViewById<TextView>(R.id.fragText) textView.text = arguments?.getString("text") } }
9
Dart
21
142
f6f73d59812bb73fbdb5af1ad6d60c4bd2017d0b
1,093
g_faraday
MIT License
shared/src/commonMain/kotlin/io/github/alaksion/unsplashwrapper/api/models/user/data/profile/UserBadgeResponse.kt
Alaksion
738,783,181
false
{"Kotlin": 106664, "Ruby": 2207}
package io.github.alaksion.unsplashwrapper.api.models.user.data.profile import kotlinx.serialization.Serializable @Serializable internal data class UserBadgeResponse( val link: String, val primary: Boolean, val slug: String, val title: String )
0
Kotlin
0
0
1d2242da35a1df10c85c49977dc52fb3b1ab3d3a
263
UnsplashWrapper
MIT License
app/src/main/java/ar/com/instafood/adapters/CheckAdapter.kt
UTN-FRBA-Mobile
147,246,060
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Kotlin": 38, "XML": 53, "Java": 3}
package ar.com.instafood.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import ar.com.instafood.activities.R import ar.com.instafood.models.Check import ar.com.instafood.models.Product import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.check_card.view.* class CheckAdapter(val checks: ArrayList<Check>) : RecyclerView.Adapter<CheckAdapter.CheckViewHolder>() { class CheckViewHolder(val card: View): RecyclerView.ViewHolder(card) override fun onBindViewHolder(holder: CheckViewHolder, p1: Int) { if (holder != null) { //holder.card.txtxUsername.text = checks[p1].name for (item: Product in checks[p1].products) { Picasso.get().load(item.resource).into(holder.card.iv_icon_image) holder.card.txtProduct.text = item.title holder.card.txtCantidad.text = 1.toString() holder.card.txtTotal.text = item.price.toString() } } } override fun onCreateViewHolder(parent: ViewGroup, p1: Int): CheckViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.check_card,parent,false) return CheckViewHolder(view) } override fun getItemCount(): Int = checks.size }
1
null
1
1
958e0fe9fd94235106facb5a191945c8660d4a42
1,350
Instafood
MIT License
data/src/test/java/com/example/data/PokemonDatabaseTest.kt
Kovah101
595,638,079
false
{"Kotlin": 136781}
package com.example.data import android.content.Context import androidx.room.Room import androidx.test.core.app.ApplicationProvider import com.example.data.network.retrofit.PokemonDto import com.example.database.Pokemon import com.example.database.PokemonDAO import com.example.database.PokemonDatabase import com.example.database.PokemonRegion import com.example.database.PokemonType import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.junit.Assert.* import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE) class PokemonDatabaseTest { private lateinit var pokemonDAO: PokemonDAO private lateinit var db: PokemonDatabase private val dummyPokemonDtoList = listOf( PokemonDto(name = "Electabuzz", url = "electabuzz.com"), PokemonDto(name = "Rhydon", url = "rhydon.com"), PokemonDto(name = "Lapras", url = "lapras.com"), PokemonDto(name = "Arcanine", url = "arcanine.com"), PokemonDto(name = "Exeggutor", url = "exeggutor.com"), PokemonDto(name = "Aerodactyl", url = "aerodactyl.com"), ) private val dummyKantoPokemonList = listOf( Pokemon( id = 1, name = "Electabuzz", url = "electabuzz.com", height = 4.0, weight = 14.5, types = listOf(PokemonType.ELECTRIC).toMutableList(), region = PokemonRegion.KANTO, description = "An electric pokemon", stats = listOf(80, 70, 68, 72, 110, 120), sprite = "www.electabuzz.com" ), Pokemon( id = 2, name = "Rhydon", url = "rhydon.com", height = 5.0, weight = 15.5, types = listOf(PokemonType.GROUND, PokemonType.ROCK).toMutableList(), region = PokemonRegion.KANTO, description = "A ground pokemon", stats = listOf(105, 130, 120, 45, 45, 40), sprite = "www.rhydon.com" ), Pokemon( id = 3, name = "Lapras", url = "lapras.com", height = 6.0, weight = 16.5, types = listOf(PokemonType.WATER, PokemonType.ICE).toMutableList(), region = PokemonRegion.KANTO, description = "A water pokemon", stats = listOf(130, 85, 80, 85, 95, 60), sprite = "www.lapras.com" ), Pokemon( id = 4, name = "Arcanine" , url = "arcanine.com", height = 7.0, weight = 17.5, types = listOf(PokemonType.FIRE).toMutableList(), region = PokemonRegion.KANTO, description = "A fire pokemon", stats = listOf(110, 80, 80, 100, 80, 95), sprite = "www.arcanine.com" ), Pokemon( id = 5, name = "Exeggutor", url = "exeggutor.com", height = 8.0, weight = 18.5, types = listOf(PokemonType.GRASS, PokemonType.PSYCHIC).toMutableList(), region = PokemonRegion.KANTO, description = "A grass pokemon", stats = listOf(95, 95, 85, 125, 65, 55), sprite = "www.exeggutor.com" ), Pokemon( id = 6, name = "Aerodactyl", url = "aerodactyl.com", height = 9.0, weight = 19.5, types = listOf(PokemonType.ROCK, PokemonType.FLYING).toMutableList(), region = PokemonRegion.KANTO, description = "A rock pokemon", stats = listOf(105, 65, 130, 60, 75, 130), sprite = "www.aerodactyl.com" ), ) private val dummyJohtoPokemonList = listOf( Pokemon( id = 7, name = "Pichu", url = "pichu.com", height = 4.0, weight = 14.5, types = listOf(PokemonType.ELECTRIC).toMutableList(), region = PokemonRegion.JOHTO, description = "An electric pokemon", stats = listOf(80, 70, 68, 72, 110, 120), sprite = "www.pichu.com" ), Pokemon( id = 8, name = "Donphan", url = "donphan.com", height = 5.0, weight = 15.5, types = listOf(PokemonType.GROUND).toMutableList(), region = PokemonRegion.JOHTO, description = "A ground pokemon", stats = listOf(105, 130, 120, 45, 45, 40), sprite = "www.donphan.com" ), Pokemon( id = 9, name = "Lanturn", url = "lanturn.com", height = 6.0, weight = 16.5, types = listOf(PokemonType.WATER, PokemonType.ELECTRIC).toMutableList(), region = PokemonRegion.JOHTO, description = "A water pokemon", stats = listOf(130, 85, 80, 85, 95, 60), sprite = "www.lanturn.com" ), Pokemon( id = 10, name = "Houndoom" , url = "houndoom.com", height = 7.0, weight = 17.5, types = listOf(PokemonType.FIRE, PokemonType.DARK).toMutableList(), region = PokemonRegion.JOHTO, description = "A fire pokemon", stats = listOf(110, 80, 80, 100, 80, 95), sprite = "www.houndoom.com" ), Pokemon( id = 11, name = "Meganium", url = "meganium.com", height = 8.0, weight = 18.5, types = listOf(PokemonType.GRASS).toMutableList(), region = PokemonRegion.JOHTO, description = "A grass pokemon", stats = listOf(95, 95, 85, 125, 65, 55), sprite = "www.meganium.com" ), Pokemon( id = 12, name = "Skarmory", url = "skarmory.com", height = 9.0, weight = 19.5, types = listOf(PokemonType.STEEL, PokemonType.FLYING).toMutableList(), region = PokemonRegion.JOHTO, description = "A steel pokemon", stats = listOf(105, 65, 130, 60, 75, 130), sprite = "www.skarmory.com" ), ) private val dummyPokemon = Pokemon( id = 0, name = "Dragonite", url = "www.dragonite.com", height = 14.0, weight = 43.5, types = listOf(PokemonType.DRAGON, PokemonType.FLYING).toMutableList(), region = PokemonRegion.KANTO, description = "A dragon pokemon", stats = listOf(100, 100, 100, 100, 100, 100), sprite = "www.dragonite.com" ) @Before fun setUp() { val context = ApplicationProvider.getApplicationContext<Context>() db = Room.inMemoryDatabaseBuilder(context, PokemonDatabase::class.java) .build() pokemonDAO = db.pokemonDao() } @After fun tearDown() { db.close() } @Test @Throws(Exception::class) fun `getPokemonById returns specific Kanto pokemon by id from db`() { var pokemon: Pokemon runBlocking { withContext(Dispatchers.IO) { pokemonDAO.insertAllPokemon(dummyKantoPokemonList) pokemon = pokemonDAO.getPokemonById(id = 1).first() } } assert(pokemon.name == dummyKantoPokemonList[0].name) } @Test @Throws(Exception::class) fun `getPokemonByName returns specific Kanto pokemon by name from db`() { var pokemon: Pokemon runBlocking { withContext(Dispatchers.IO) { pokemonDAO.insertAllPokemon(dummyKantoPokemonList) pokemon = pokemonDAO.getPokemonByName(name = "Lapras").first() } } assert(pokemon.url == dummyKantoPokemonList[2].url) } @Test @Throws(Exception::class) fun `insertPokemon correctly adds new pokemon to db`() { var pokemon: Pokemon runBlocking { withContext(Dispatchers.IO) { pokemonDAO.insertPokemon(dummyPokemon) pokemon = pokemonDAO.getPokemonById(id = 0).first() } } assert(pokemon == dummyPokemon) } @Test @Throws(Exception::class) fun `deleteAllPokemon clears db`() { var pokemonNumber: Int runBlocking { withContext(Dispatchers.IO) { pokemonDAO.getKantoPokemon() pokemonDAO.deleteAllPokemon() pokemonNumber = pokemonDAO.pokemonCount() } } assert(pokemonNumber == 0) } }
1
Kotlin
0
0
aa45f730c3aa5522e3c362d235ed125b2dfa947c
8,939
TDD-Network-Pokedex
MIT License
app/src/test/java/com/appunite/loudius/analytics/EventParametersConverterTest.kt
appunite
604,044,782
false
{"Kotlin": 381740, "Python": 9529}
/* * Copyright 2023 AppUnite S.A. * * 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.appunite.loudius.analytics import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import strikt.api.expectThat import strikt.assertions.isEqualTo @RunWith(RobolectricTestRunner::class) @Config(sdk = [28]) // Use the desired Android SDK version. class EventParametersConverterTest { private val converter = EventParametersConverter() @Test fun testConvert() { val result = converter.convert( listOf( EventParameter.String("param_name1", "string_value1"), EventParameter.String("param_name2", "string_value2"), EventParameter.Boolean("param_name3", true) ) ) expectThat(result.getString("param_name1")).isEqualTo("string_value1") expectThat(result.getString("param_name2")).isEqualTo("string_value2") expectThat(result.getBoolean("param_name3")).isEqualTo(true) } }
6
Kotlin
0
12
d7196e614528a1d1989739ce21889fbdac149dee
1,592
Loudius
Apache License 2.0
app/src/main/java/com/skullper/apexlegendsmateapp/MainActivity.kt
Skullper
507,640,394
false
null
package com.skullper.apexlegendsmateapp import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowCompat import com.skullper.account_repo.AccountRepository import com.skullper.account_repo.data.PlatformType import com.skullper.apexlegendsmateapp.databinding.ActivityMainBinding import kotlinx.coroutines.runBlocking import org.koin.android.ext.android.get class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { WindowCompat.setDecorFitsSystemWindows(window, false) super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) binding.fab.setOnClickListener { _ -> runBlocking { val player = get<AccountRepository>() val info = player.getAccountInfo("SkuIIper", PlatformType.PC) Log.e("TAGA", "Info: $info \n\n\n") player.getLegendsInfo().forEach { Log.e("TAGA", "Legend: $it") } } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } }
0
Kotlin
0
0
4ca2d5277fbc953994044da753d6b51a590d40bd
1,936
ApexLegendsMateApp
Apache License 2.0
app/src/main/java/com/kodedynamic/recipeoracle/features/recipechat/presentation/models/MessageModel.kt
kushal2011
836,607,411
false
{"Kotlin": 238994}
package com.kodedynamic.recipeoracle.features.recipechat.presentation.models data class MessageModel( val message: String, val isMessageByUser: Boolean )
0
Kotlin
0
0
83a4ff53b21f2d225b7b3b2f29e7c24488dd661d
163
Recipe-Oracle
MIT License
app/src/main/java/ru/vafeen/habitschedule/noui/log/LogExecutor.kt
vafeen
769,265,588
false
{"Kotlin": 58241}
package ru.vafeen.habitschedule.noui.log import android.util.Log fun logExecutor(suffixTag: String? = null , message: String) { // "when" for switching on/off some types of logs :) when (suffixTag) { LogType.Database.value -> { Log.e(LogType.defaultName + suffixTag, message) } else -> { Log.e(suffixTag, message) } } }
0
Kotlin
0
0
a2cbf2992710e404b50563954a9d3cc010e52afe
396
HabitSchedule
Apache License 2.0
app/src/test/java/com/abidria/data/experience/ExperienceRepositoryTest.kt
TonyTangAndroid
115,438,401
true
{"Kotlin": 203035}
package com.abidria.data.experience import com.abidria.data.common.Result import com.abidria.data.common.ResultStreamFactory import io.reactivex.Flowable import io.reactivex.observers.TestObserver import io.reactivex.schedulers.Schedulers import io.reactivex.subscribers.TestSubscriber import org.junit.Assert import org.junit.Assert.assertEquals import org.junit.Test import org.mockito.BDDMockito import org.mockito.Mock import org.mockito.MockitoAnnotations class ExperienceRepositoryTest { @Test fun test_experiences_flowable_return_stream_flowable_connected_with_api_request() { given { an_experiences_stream_factory_that_returns_stream() an_api_repo_that_returns_experiences_flowable_with_an_experience() } whenn { experiences_flowable_is_called() } then { should_return_flowable_created_by_factory() should_connect_api_experiences_flowable_on_next_to_replace_all_experiences_observer() } } @Test fun test_on_refresh_experiences_asks_again_to_api_repo_and_emits_new_result_through_replace_all() { given { an_experiences_stream_factory_that_returns_stream() an_api_repo_that_returns_experiences_flowable_with_an_experience() } whenn { experiences_flowable_is_called() } given { an_api_repo_that_returns_experiences_flowable_with_another_experience() } whenn { refresh_experiences_is_called() } then { should_emit_first_and_second_experience_through_replace_all() } } @Test fun test_same_experience_experiences_flowable_call_returns_same_flowable() { given { an_experiences_stream_factory_that_returns_stream() an_experiences_stream_factory_that_returns_another_stream_when_called_again() an_api_repo_that_returns_experiences_flowable_with_an_experience() } whenn { experiences_flowable_is_called() experiences_flowable_is_called_again() } then { first_result_should_be_experiences_flowable() second_result_should_be_same_experiences_flowable() } } @Test fun test_experience_flowable_returns_experiences_flowable_filtering_desired_experience() { given { an_experience_id() an_experiences_stream_factory_that_returns_stream_with_several_experiences() an_api_repo_that_returns_experiences_flowable_with_an_experience() } whenn { experience_flowable_is_called_with_experience_id() } then { only_experience_with_experience_id_should_be_received() } } @Test fun test_create_experience_calls_api_repo_and_emits_through_add_observer_the_new_experience() { given { an_experience_id() an_experience() an_experiences_stream_factory_that_returns_stream() an_api_repo_that_returns_experiences_flowable_with_an_experience() an_api_repo_that_returns_created_experience() } whenn { experiences_flowable_is_called_with_experience_id() create_experience_is_called() } then { should_call_api_created_experience() should_emit_created_experience_through_add_or_update_experiences_observer() } } @Test fun test_upload_experience_picture_calls_api_repo_with_delegate_to_emit_through_update_observer() { given { an_experience_id() an_experience() a_cropped_image_uri_string() an_experiences_stream_factory_that_returns_stream() an_api_repo_that_returns_experiences_flowable_with_an_experience() } whenn { experiences_flowable_is_called_with_experience_id() upload_experience_picture_is_called() } then { should_call_api_upload_experience_picture_with_experience_id_and_image_uri_string() } whenn { delegate_is_called_with_experience() } then { delegate_param_should_emit_experience_through_add_or_update_observer() } } private fun given(func: ScenarioMaker.() -> Unit) = ScenarioMaker().start(func) class ScenarioMaker { lateinit var repository: ExperienceRepository @Mock lateinit var mockApiRepository: ExperienceApiRepository @Mock lateinit var mockExperiencesStreamFactory: ResultStreamFactory<Experience> var experienceId = "" var croppedImageUriString = "" lateinit var experience: Experience lateinit var secondExperience: Experience lateinit var experiencesFlowable: Flowable<Result<List<Experience>>> lateinit var addOrUpdateObserver: TestObserver<Result<Experience>> lateinit var replaceAllObserver: TestObserver<Result<List<Experience>>> lateinit var secondExperiencesFlowable: Flowable<Result<List<Experience>>> lateinit var secondAddOrUpdateObserver: TestObserver<Result<Experience>> lateinit var secondReplaceAllObserver: TestObserver<Result<List<Experience>>> lateinit var apiExperiencesFlowable: Flowable<Result<List<Experience>>> lateinit var experiencesFlowableResult: Flowable<Result<List<Experience>>> lateinit var experienceFlowableResult: Flowable<Result<Experience>> lateinit var createdExperienceFlowableResult: Flowable<Result<Experience>> fun buildScenario(): ScenarioMaker { MockitoAnnotations.initMocks(this) repository = ExperienceRepository(mockApiRepository, mockExperiencesStreamFactory) return this } fun an_experience_id() { experienceId = "1" } fun an_experience() { experience = Experience(id = "", title = "Title", description = "some desc.", picture = null) } fun a_cropped_image_uri_string() { croppedImageUriString = "image_uri" } fun an_api_repo_that_returns_created_experience() { val createdExperienceFlowable = Flowable.just(Result(experience, null)) BDDMockito.given(mockApiRepository.createExperience(experience)).willReturn(createdExperienceFlowable) } fun an_experiences_stream_factory_that_returns_stream() { replaceAllObserver = TestObserver.create() replaceAllObserver.onSubscribe(replaceAllObserver) addOrUpdateObserver = TestObserver.create() addOrUpdateObserver.onSubscribe(addOrUpdateObserver) experiencesFlowable = Flowable.never() BDDMockito.given(mockExperiencesStreamFactory.create()).willReturn( ResultStreamFactory.ResultStream(replaceAllObserver, addOrUpdateObserver, experiencesFlowable)) } fun an_experiences_stream_factory_that_returns_another_stream_when_called_again() { secondReplaceAllObserver = TestObserver.create() secondReplaceAllObserver.onSubscribe(replaceAllObserver) secondAddOrUpdateObserver = TestObserver.create() secondAddOrUpdateObserver.onSubscribe(addOrUpdateObserver) secondExperiencesFlowable = Flowable.never() BDDMockito.given(mockExperiencesStreamFactory.create()).willReturn( ResultStreamFactory.ResultStream(secondReplaceAllObserver, secondAddOrUpdateObserver, secondExperiencesFlowable)) } fun an_experiences_stream_factory_that_returns_stream_with_several_experiences() { val experienceA = Experience(id = "1", title = "T", description = "desc", picture = null) val experienceB = Experience(id = "2", title = "T", description = "desc", picture = null) replaceAllObserver = TestObserver.create() addOrUpdateObserver = TestObserver.create() experiencesFlowable = Flowable.just(Result(listOf(experienceA, experienceB), null)) BDDMockito.given(mockExperiencesStreamFactory.create()).willReturn( ResultStreamFactory.ResultStream(replaceAllObserver, addOrUpdateObserver, experiencesFlowable)) } fun an_api_repo_that_returns_experiences_flowable_with_an_experience() { experience = Experience("2", "T", "d", null) apiExperiencesFlowable = Flowable.just(Result(listOf(experience), null)) BDDMockito.given(mockApiRepository.experiencesFlowable()).willReturn(apiExperiencesFlowable) } fun an_api_repo_that_returns_experiences_flowable_with_another_experience() { secondExperience = Experience("4", "Y", "g", null) BDDMockito.given(mockApiRepository.experiencesFlowable()) .willReturn(Flowable.just(Result(listOf(secondExperience), null))) } fun experiences_flowable_is_called() { experiencesFlowableResult = repository.experiencesFlowable() } fun experiences_flowable_is_called_with_experience_id() { experienceFlowableResult = repository.experienceFlowable(experienceId) } fun refresh_experiences_is_called() { repository.refreshExperiences() } fun create_experience_is_called() { createdExperienceFlowableResult = repository.createExperience(experience) } fun delegate_is_called_with_experience() { repository.emitThroughAddOrUpdate.invoke(Result(experience, null)) } fun experiences_flowable_is_called_again() { secondExperiencesFlowable = repository.experiencesFlowable() } fun experience_flowable_is_called_with_experience_id() { experienceFlowableResult = repository.experienceFlowable(experienceId) } fun upload_experience_picture_is_called() { repository.uploadExperiencePicture(experienceId, croppedImageUriString) } fun should_return_flowable_created_by_factory() { Assert.assertEquals(experiencesFlowable, experiencesFlowableResult) } fun should_connect_api_experiences_flowable_on_next_to_replace_all_experiences_observer() { replaceAllObserver.onComplete() replaceAllObserver.assertResult(Result(listOf(experience), null)) } fun should_emit_first_and_second_experience_through_replace_all() { replaceAllObserver.onComplete() replaceAllObserver.assertResult(Result(listOf(experience), null), Result(listOf(secondExperience), null)) } fun first_result_should_be_experiences_flowable() { Assert.assertEquals(experiencesFlowable, experiencesFlowableResult) } fun second_result_should_be_same_experiences_flowable() { Assert.assertEquals(secondExperiencesFlowable, experiencesFlowableResult) } fun only_experience_with_experience_id_should_be_received() { val testSubscriber = TestSubscriber.create<Result<Experience>>() experienceFlowableResult.subscribeOn(Schedulers.trampoline()).subscribe(testSubscriber) testSubscriber.awaitCount(1) val result = testSubscriber.events.get(0).get(0) as Result<*> val receivedExperience = result.data as Experience assertEquals(experienceId, receivedExperience.id) } fun should_call_api_upload_experience_picture_with_experience_id_and_image_uri_string() { BDDMockito.then(mockApiRepository).should() .uploadExperiencePicture(experienceId, croppedImageUriString, repository.emitThroughAddOrUpdate) } fun delegate_param_should_emit_experience_through_add_or_update_observer() { addOrUpdateObserver.onComplete() addOrUpdateObserver.assertResult(Result(experience, null)) } fun should_call_api_created_experience() { BDDMockito.then(mockApiRepository).should().createExperience(experience) } fun should_emit_created_experience_through_add_or_update_experiences_observer() { createdExperienceFlowableResult.subscribeOn(Schedulers.trampoline()).subscribe() addOrUpdateObserver.onComplete() addOrUpdateObserver.assertResult(Result(experience, null)) } infix fun start(func: ScenarioMaker.() -> Unit) = buildScenario().given(func) infix fun given(func: ScenarioMaker.() -> Unit) = apply(func) infix fun whenn(func: ScenarioMaker.() -> Unit) = apply(func) infix fun then(func: ScenarioMaker.() -> Unit) = apply(func) } }
0
Kotlin
0
0
9ad533e44910cd3534b85d23e42da671c6d48502
12,799
abidria-android
Apache License 2.0
app/src/main/java/io/github/emaccaull/hotmic/AudioDeviceInfo.kt
emaccaull
522,409,894
false
{"Kotlin": 22527, "C++": 11446, "Java": 2883, "C": 1569, "CMake": 492}
package io.github.emaccaull.hotmic import android.media.AudioDeviceInfo val AudioDeviceInfo.typeString: String get() { return when (type) { AudioDeviceInfo.TYPE_AUX_LINE -> "auxiliary line-level connectors" AudioDeviceInfo.TYPE_BLUETOOTH_A2DP -> "Bluetooth device supporting the A2DP profile" AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> "Bluetooth device typically used for telephony" AudioDeviceInfo.TYPE_BUILTIN_EARPIECE -> "built-in earphone speaker" AudioDeviceInfo.TYPE_BUILTIN_MIC -> "built-in microphone" AudioDeviceInfo.TYPE_BUILTIN_SPEAKER -> "built-in speaker" AudioDeviceInfo.TYPE_BUS -> "BUS" AudioDeviceInfo.TYPE_DOCK -> "DOCK" AudioDeviceInfo.TYPE_FM -> "FM" AudioDeviceInfo.TYPE_FM_TUNER -> "FM tuner" AudioDeviceInfo.TYPE_HDMI -> "HDMI" AudioDeviceInfo.TYPE_HDMI_ARC -> "HDMI audio return channel" AudioDeviceInfo.TYPE_IP -> "IP" AudioDeviceInfo.TYPE_LINE_ANALOG -> "line analog" AudioDeviceInfo.TYPE_LINE_DIGITAL -> "line digital" AudioDeviceInfo.TYPE_TELEPHONY -> "telephony" AudioDeviceInfo.TYPE_TV_TUNER -> "TV tuner" AudioDeviceInfo.TYPE_USB_ACCESSORY -> "USB accessory" AudioDeviceInfo.TYPE_USB_DEVICE -> "USB device" AudioDeviceInfo.TYPE_WIRED_HEADPHONES -> "wired headphones" AudioDeviceInfo.TYPE_WIRED_HEADSET -> "wired headset" AudioDeviceInfo.TYPE_UNKNOWN -> "unknown" else -> "unknown" } } val AudioDeviceInfo.friendlyName: String get() = "$productName $typeString"
0
Kotlin
0
0
709e1496366a56e6a751791a81acb58001b66d69
1,695
hotmic
Apache License 2.0
converter/src/main/java/com/epicadk/hapiprotoconverter/converter/AnnotationConverter.kt
epicadk
402,074,793
false
{"Kotlin": 2405480}
package com.epicadk.hapiprotoconverter.converter import com.epicadk.hapiprotoconverter.converter.DateTimeConverter.toHapi import com.epicadk.hapiprotoconverter.converter.DateTimeConverter.toProto import com.epicadk.hapiprotoconverter.converter.ExtensionConverter.toHapi import com.epicadk.hapiprotoconverter.converter.ExtensionConverter.toProto import com.epicadk.hapiprotoconverter.converter.MarkdownConverter.toHapi import com.epicadk.hapiprotoconverter.converter.MarkdownConverter.toProto import com.epicadk.hapiprotoconverter.converter.ReferenceConverter.toHapi import com.epicadk.hapiprotoconverter.converter.ReferenceConverter.toProto import com.epicadk.hapiprotoconverter.converter.StringConverter.toHapi import com.epicadk.hapiprotoconverter.converter.StringConverter.toProto import com.google.fhir.r4.core.Annotation import com.google.fhir.r4.core.String import java.lang.IllegalArgumentException import org.hl7.fhir.r4.model.Reference import org.hl7.fhir.r4.model.StringType import org.hl7.fhir.r4.model.Type public object AnnotationConverter { private fun Annotation.AuthorX.annotationAuthorToHapi(): Type { if (hasReference()) { return (this.getReference()).toHapi() } if (hasStringValue()) { return (this.getStringValue()).toHapi() } throw IllegalArgumentException("Invalid Type for Annotation.author[x]") } private fun Type.annotationAuthorToProto(): Annotation.AuthorX { val protoValue = Annotation.AuthorX.newBuilder() if (this is Reference) { protoValue.setReference(this.toProto()) } if (this is StringType) { protoValue.setStringValue(this.toProto()) } return protoValue.build() } public fun Annotation.toHapi(): org.hl7.fhir.r4.model.Annotation { val hapiValue = org.hl7.fhir.r4.model.Annotation() if (hasId()) { hapiValue.id = id.value } if (extensionCount > 0) { hapiValue.setExtension(extensionList.map { it.toHapi() }) } if (hasAuthor()) { hapiValue.setAuthor(author.annotationAuthorToHapi()) } if (hasTime()) { hapiValue.setTimeElement(time.toHapi()) } if (hasText()) { hapiValue.setTextElement(text.toHapi()) } return hapiValue } public fun org.hl7.fhir.r4.model.Annotation.toProto(): Annotation { val protoValue = Annotation.newBuilder() if (hasId()) { protoValue.setId(String.newBuilder().setValue(id)) } if (hasExtension()) { protoValue.addAllExtension(extension.map { it.toProto() }) } if (hasAuthor()) { protoValue.setAuthor(author.annotationAuthorToProto()) } if (hasTime()) { protoValue.setTime(timeElement.toProto()) } if (hasText()) { protoValue.setText(textElement.toProto()) } return protoValue.build() } }
1
Kotlin
0
3
2abe5967a905f6a29ed5736c75e8ffb2cf6d3e78
2,789
hapi-proto-converter
Apache License 2.0
core/src/main/java/io/github/andraantariksa/meal/core/util/Theme.kt
andraantariksa
520,939,121
false
{"Kotlin": 57149}
package io.github.andraantariksa.meal.core.util enum class Theme { Default, Light, Dark }
0
Kotlin
0
0
6256837393e7dd97359b68a7dd42f38b6f60e663
102
sistema-meals
MIT License
source/sdk/src/test/java/com/stytch/sdk/consumer/oauth/GoogleOneTapImplTest.kt
stytchauth
314,556,359
false
{"Kotlin": 1797666, "Java": 6554, "HTML": 545}
package com.stytch.sdk.consumer.oauth import android.app.Activity import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential import com.stytch.sdk.common.EncryptionManager import com.stytch.sdk.common.StytchDispatchers import com.stytch.sdk.common.StytchResult import com.stytch.sdk.common.errors.UnexpectedCredentialType import com.stytch.sdk.common.sessions.SessionAutoUpdater import com.stytch.sdk.consumer.NativeOAuthResponse import com.stytch.sdk.consumer.network.StytchApi import com.stytch.sdk.consumer.sessions.ConsumerSessionStorage import io.mockk.MockKAnnotations import io.mockk.clearAllMocks import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.just import io.mockk.mockk import io.mockk.mockkObject import io.mockk.mockkStatic import io.mockk.runs import io.mockk.spyk import io.mockk.unmockkAll import io.mockk.verify import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test internal class GoogleOneTapImplTest { @MockK private lateinit var mockApi: StytchApi.OAuth @MockK private lateinit var mockSessionStorage: ConsumerSessionStorage @MockK private lateinit var mockGoogleCredentialManagerProvider: GoogleCredentialManagerProvider private lateinit var impl: GoogleOneTapImpl private val dispatcher = Dispatchers.Unconfined private val mockActivity: Activity = mockk() private val startParameters = OAuth.GoogleOneTap.StartParameters( context = mockActivity, clientId = "clientId", ) @Before fun before() { MockKAnnotations.init(this, true, true) mockkObject(SessionAutoUpdater) every { SessionAutoUpdater.startSessionUpdateJob(any(), any(), any()) } just runs mockkStatic("com.stytch.sdk.consumer.extensions.StytchResultExtKt") mockkObject(EncryptionManager) every { EncryptionManager.generateCodeChallenge() } returns "code-challenge" every { EncryptionManager.encryptCodeChallenge(any()) } returns "encrypted-code-challenge" impl = GoogleOneTapImpl( externalScope = TestScope(), dispatchers = StytchDispatchers(dispatcher, dispatcher), sessionStorage = mockSessionStorage, api = mockApi, credentialManagerProvider = mockGoogleCredentialManagerProvider, ) } @After fun after() { unmockkAll() clearAllMocks() } @Test fun `GoogleOneTapImpl start returns error if nonce fails to generate`() = runTest { every { EncryptionManager.generateCodeChallenge() } throws RuntimeException("Testing") val result = impl.start(startParameters) assert(result is StytchResult.Error) } @Test fun `GoogleOneTapImpl start with callback calls callback method`() { // short circuit every { EncryptionManager.generateCodeChallenge() } throws RuntimeException("Testing") val spy = spyk<(NativeOAuthResponse) -> Unit>() impl.start(startParameters, spy) verify { spy.invoke(any()) } } @Test fun `GoogleOneTapImpl start returns error if returned an unexpected credential type`() = runTest { coEvery { mockGoogleCredentialManagerProvider.getSignInWithGoogleCredential( any(), any(), any(), any(), any(), ) } returns mockk { every { credential } returns mockk { every { type } returns "Something Weird" } } val result = impl.start(startParameters) require(result is StytchResult.Error) assert(result.exception is UnexpectedCredentialType) } @Test fun `GoogleOneTapImpl start returns error if create credential fails`() = runTest { coEvery { mockGoogleCredentialManagerProvider.getSignInWithGoogleCredential( any(), any(), any(), any(), any(), ) } returns mockk { every { credential } returns mockk { every { type } returns GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL } } every { mockGoogleCredentialManagerProvider.createTokenCredential( any(), ) } throws RuntimeException("Testing") val result = impl.start(startParameters) require(result is StytchResult.Error) } @Test fun `GoogleOneTapImpl delegates to api if everything is successful`() = runTest { coEvery { mockGoogleCredentialManagerProvider.getSignInWithGoogleCredential( any(), any(), any(), any(), any(), ) } returns mockk { every { credential } returns mockk { every { type } returns GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL every { data } returns mockk(relaxed = true) } } every { mockGoogleCredentialManagerProvider.createTokenCredential( any(), ) } returns mockk(relaxed = true) { every { idToken } returns "my-id-token" } coEvery { mockApi.authenticateWithGoogleIdToken(any(), any(), any()) } returns StytchResult.Success(mockk(relaxed = true)) val result = impl.start(startParameters) assert(result is StytchResult.Success) coVerify { mockApi.authenticateWithGoogleIdToken("my-id-token", any(), any()) } } }
2
Kotlin
2
23
865260973aac09402c6fb624b0a1549224b9dbf8
6,416
stytch-android
MIT License
mbcarkit/src/main/java/com/daimler/mbcarkit/business/model/vehicle/unit/DistanceUnit.kt
Daimler
199,815,262
false
null
package com.daimler.mbcarkit.business.model.vehicle.unit enum class DistanceUnit { UNSPECIFIED_DISTANCE_UNIT, /** * distance unit: km */ KILOMETERS, /** * distance unit: miles */ MILES }
1
null
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
230
MBSDK-Mobile-Android
MIT License
ktfx-layouts/src/test/kotlin/javafx/scene/web/WebViewTest.kt
hanggrian
102,934,147
false
null
package ktfx.layouts import com.hanggrian.ktfx.test.LayoutsStyledTest import javafx.scene.web.WebView import kotlin.test.Ignore /** Error on [child1], [child2] and [child3] because creating [WebView] must be in FX thread. */ @Ignore class WebViewTest : LayoutsStyledTest<KtfxPane, WebView>() { override fun manager() = KtfxPane() override fun KtfxPane.childCount() = children.size override fun child1() = webView {} override fun KtfxPane.child2() = webView() override fun child3() = styledWebView(styleClass = arrayOf("style")) override fun KtfxPane.child4() = styledWebView(styleClass = arrayOf("style")) }
1
null
2
19
6e5ec9fedf8359423c31a2ba64cd175bc9864cd2
639
ktfx
Apache License 2.0
lib/src/main/kotlin/io/github/pasteleiros/nortlulib/dto/UsuarioDto.kt
pasteleiros
372,655,925
false
null
package io.github.pasteleiros.nortlulib.dto data class UsuarioDto(var id: Long?, val nome: String, val cpf: String, val email: String, val telefone: String, val enderecos: List<EnderecoDto>):BaseDto()
0
Kotlin
0
0
389b6c8c16cb8f84f4fabb926028fbe3e445caa3
286
nortlu-lib
Apache License 2.0
src/test/java/hannesdorfmann/ex4/RepositoryEx4Test.kt
ExpensiveBelly
104,675,798
false
null
package hannesdorfmann.ex4 import hannesdorfmann.types.Person import io.reactivex.Observable import io.reactivex.observers.TestObserver import io.reactivex.subjects.PublishSubject import org.junit.Assert import org.junit.Test class RepositoryEx4Test { @Test fun loadPersons() { val search = PublishSubject.create<String>() val view = object : ViewEx4 { override fun onSearchTextchanged(): Observable<String> = search.doOnNext { println("User input: '$it'") } } val backend = TestBackendEx4() val subscriber = TestObserver<List<Person>>() val repo = RepositoryEx4(view, backend) repo.search().subscribeWith(subscriber) search.onNext("H") search.onNext("Ha") Thread.sleep(400) search.onNext("H") search.onNext("") search.onNext("F") search.onNext("Fr") search.onNext("Fra") search.onNext("Fran") search.onNext("Franz") Thread.sleep(800) search.onNext("Fran") search.onNext("Fra") search.onNext("Fr") search.onNext("Fran") search.onNext("Fra") search.onNext("Franz") Thread.sleep(800) search.onNext("Franzis") Thread.sleep(400) search.onNext("Thom") Thread.sleep(1000) search.onComplete() subscriber.awaitTerminalEvent() subscriber.assertComplete() subscriber.assertNoErrors() Assert.assertEquals(listOf("Franz", "Franzis", "Thom"), backend.queries) val msg = "Expected searchresults: [" + backend.search("Franz").niceString() + "] and [" + backend.search("Thom").niceString() + "] but got the following search results: " + subscriber.values().niceStringList() Assert.assertEquals( listOf(backend.search("Franz"), backend.search("Thom")), subscriber.values() ) } private fun List<Person>.niceString() = map { it.toString() } .fold("") { old, new -> old + new } private fun List<List<Person>>.niceStringList(): String { return map { "[${it.niceString()}] , " } .fold("") { old, new -> old + new } } }
1
Kotlin
11
19
e07a3aea09f9235077d6d0dd553af2cfe782b393
2,256
RxKata
MIT License
sample/src/main/java/com/sanogueralorenzo/sample/domain/TrendingGifsUseCase.kt
chhabra-dhiraj
266,473,243
true
{"Kotlin": 39489}
package com.sanogueralorenzo.sample.domain import com.sanogueralorenzo.sample.data.GifsRepository import io.reactivex.Single import javax.inject.Inject /** * Subjective: * Does it make sense to have an empty use case that just calls the repository? * Alternative, inject the repository directly to the ViewModel (until there is some business logic) */ class TrendingGifsUseCase @Inject constructor( private val repository: GifsRepository ) : (Int) -> Single<List<Gif>> { override fun invoke(offset: Int): Single<List<Gif>> = repository.loadTrending(offset) }
0
null
0
0
e66d50349f308cb24fc38c324f9cf52df346ea9f
574
Android-Kotlin-Clean-Architecture
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/adjustments/api/model/AdditionalDaysAwardedDto.kt
ministryofjustice
607,762,818
false
{"Kotlin": 413740, "Shell": 1421, "Dockerfile": 1364}
package uk.gov.justice.digital.hmpps.adjustments.api.model import io.swagger.v3.oas.annotations.media.Schema @Schema(description = "The details of an additional days awarded (ADA) adjustment") data class AdditionalDaysAwardedDto( @Schema(description = "The id of the adjudication that resulted in the ADA") val adjudicationId: List<String>, val prospective: Boolean, )
5
Kotlin
0
0
408fe31df924fee63cd089c9699a3647d9a52ff5
377
hmpps-adjustments-api
MIT License
src/main/kotlin/com/housing/movie/features/resource/controller/ResourcesController.kt
thinhlh
431,658,207
false
null
package com.housing.movie.features.resource.controller import com.housing.movie.base.BaseController import com.housing.movie.base.BaseResponse import com.housing.movie.features.resource.domain.usecase.GenerateObjectLinkUseCase import com.housing.movie.features.resource.domain.usecase.UploadVideoUseCase import io.swagger.v3.oas.annotations.tags.Tag import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import org.springframework.web.multipart.MultipartFile import java.net.URL @RestController @Tag( name = "Resources") class ResourcesController( private val uploadVideoUseCase: UploadVideoUseCase, private val generateObjectLinkUseCase: GenerateObjectLinkUseCase, ) : BaseController() { @PostMapping("/upload", consumes = ["multipart/form-data"]) fun uploadVideo(file: MultipartFile): ResponseEntity<BaseResponse<String>> { return successResponse(uploadVideoUseCase(file)) } @GetMapping("/download") fun generateDownloadVideo(@RequestParam path: String): ResponseEntity<BaseResponse<URL>> { return successResponse(generateObjectLinkUseCase(path)) } }
0
Kotlin
0
0
f88c15909040f54baf9be3f2adf47429eeccfac5
1,337
oo-movie-backend
MIT License
src/main/kotlin/com/labco/raytracer/camera/Sensor.kt
R-Sai
543,716,549
false
{"Kotlin": 24538}
package com.labco.raytracer.camera import com.labco.raytracer.material.FloatColor data class Sensor(val width: Float, val height: Float, val resolutionX: Int, val resolutionY: Int) { val pixels: Array<Array<FloatColor>> = Array(resolutionX) { Array(resolutionY) { FloatColor.BLACK } } }
0
Kotlin
0
1
b1d2974589d9ae187ebca29f20c2b458a088d372
294
RayTracer
Apache License 2.0
src/main/kotlin/com/example/gungjeonjegwa/domain/bread/repository/SellDeliveryTypeRepository.kt
gungjeonjegwa
579,803,041
false
null
package com.example.gungjeonjegwa.domain.bread.repository import com.example.gungjeonjegwa.domain.delivery.data.entity.SellDeliveryType import org.springframework.data.jpa.repository.JpaRepository interface SellDeliveryTypeRepository : JpaRepository<SellDeliveryType, Long> { }
0
Kotlin
0
0
30a77ac8c8ec594a6d1267ae36df365f1622f250
279
GGJG-Backend
MIT License
src/main/kotlin/com/bbbang/license/cmd/UnInstallCmd.kt
laifugroup
749,306,751
false
{"Kotlin": 12939}
package com.bbbang.license.cmd import com.bbbang.parent.keymgr.LicenseManager import global.namespace.`fun`.io.bios.BIOS import io.micronaut.http.HttpStatus import picocli.CommandLine import java.io.FileInputStream import java.util.concurrent.Callable @CommandLine.Command(name = "uninstall",description=["卸载指令"]) class UnInstallCmd : Callable<Any> { @Throws(Exception::class) override fun call(): Any { try { LicenseManager.standard.uninstall() }catch (e:Exception){ //no-null }finally { val uninstallSuccess="----卸载成功----" println("\n") println(uninstallSuccess) println("\n") } return "----卸载成功----" } }
0
Kotlin
0
0
844b1b3c99c377348998fb37368c1e1b4076daff
735
license
Blue Oak Model License 1.0.0
app/src/main/java/com/swapnildroid/pet/support/ui/main/viewmodels/BaseViewModel.kt
swapnildroid
552,133,047
false
null
package com.swapnildroid.pet.support.ui.main.viewmodels import android.view.View import androidx.databinding.ObservableInt import androidx.lifecycle.ViewModel import com.swapnildroid.pet.support.ui.main.interaction.ErrorInterface open class BaseViewModel : ViewModel() { val isBusyLiveData: ObservableInt = ObservableInt(View.VISIBLE) var errorInterface: ErrorInterface? = null protected var isBusy: Boolean = false set(value) { isBusyLiveData.set(if (value) View.VISIBLE else View.GONE) field = value } }
0
Kotlin
0
0
68c92ae19232b42abb9fd3e2f69ea8e2f0574e22
563
PET-Support-Demo
MIT License
AtomicKotlin/Appendices/Java Interoperability/Examples/src/KotlinWrapper.kt
fatiq123
726,462,263
false
{"Kotlin": 370528, "HTML": 6544, "JavaScript": 5252, "Java": 4416, "CSS": 3780, "Assembly": 94}
// interoperability/KotlinWrapper.kt package interop fun main() { // Generates a primitive int: val i = 10 // Generates wrapper types: val iOrNull: Int? = null val list: List<Int> = listOf(1, 2, 3) }
0
Kotlin
0
0
3d351652ebe1dd7ef5f93e054c8f2692c89a144e
210
AtomicKotlinCourse
MIT License
plugin/src/main/kotlin/net/siggijons/gradle/graphuntangler/graph/IsolatedSubgraphDetails.kt
siggijons
615,653,143
false
null
package net.siggijons.gradle.graphuntangler.graph import org.jgrapht.graph.AbstractGraph data class IsolatedSubgraphDetails( val vertex: DependencyNode, val isolatedDag: AbstractGraph<DependencyNode, DependencyEdge>, val reducedDag: AbstractGraph<DependencyNode, DependencyEdge>, val isolatedDagSize: Int, val fullGraphSize: Int )
3
Kotlin
1
7
5cd3d4fc0df5321da5f0fb45c73ca52a0b46dc37
352
graph-untangler-plugin
Apache License 2.0
tools/src/main/java/ru/mintrocket/lib/mintpermissions/tools/ext/ActivityExt.kt
mintrocket
503,334,946
false
{"Kotlin": 111822}
package ru.mintrocket.lib.mintpermissions.tools.ext import androidx.activity.ComponentActivity import androidx.activity.result.contract.ActivityResultContract import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume /* * The filter can be useful in cases where the result is returned several times and you need to * catch only valid data. * * For example, if you make a request for permissions and rotate the screen, then invalid data * may be returned. In this case, if the user gives permission, then valid data will be returned. * */ public suspend fun <I, O> ComponentActivity.awaitActivityResult( contract: ActivityResultContract<I, O>, key: String, input: I, resultFilter: ((O) -> Boolean)? = null ): O = suspendCancellableCoroutine { continuation -> val launcher = activityResultRegistry.register(key, contract) { result -> val isPassedByFilter = resultFilter?.invoke(result) ?: true if (!continuation.isActive || !isPassedByFilter) { return@register } continuation.resume(result) } launcher.launch(input) continuation.invokeOnCancellation { launcher.unregister() } }
1
Kotlin
3
68
2de0d97454e7ab330418e53d9d1a2b899ca06ad0
1,194
MintPermissions
MIT License
app/src/main/java/com/jxareas/xpensor/features/transactions/domain/model/CategoryWithDetails.kt
jxareas
540,284,293
false
{"Kotlin": 260827, "Python": 1602, "Shell": 695}
package com.jxareas.xpensor.features.transactions.domain.model data class CategoryWithDetails( val category: Category, val amount: Double, )
0
Kotlin
3
35
c8639526a7fdd710e485668093ce627e0fa1e8e5
150
Xpensor
MIT License
app/src/main/java/nerd/tuxmobil/fahrplan/congress/validation/MetaValidation.kt
johnjohndoe
12,616,092
false
null
package nerd.tuxmobil.fahrplan.congress.validation import info.metadude.android.eventfahrplan.network.models.Meta import org.threeten.bp.DateTimeException import org.threeten.bp.ZoneId import org.threeten.bp.zone.ZoneRulesException /** * Validation routines to ensure that data received from the network contains values which can * actually processed further. */ object MetaValidation { /** * Returns a [Meta] object which has its [timeZoneName][Meta.timeZoneName] successfully * validated or set to `null`. */ fun Meta.validate(): Meta { val timeZoneNameIsValid = try { ZoneId.of(timeZoneName) true } catch (e: NullPointerException) { false } catch (e: DateTimeException) { false } catch (e: ZoneRulesException) { false } return if (timeZoneNameIsValid) this else copy(timeZoneName = null) } }
63
null
99
27
4b91d7dcdfbc8de965a928b3ebfbfe595ec06b3f
937
CampFahrplan
Apache License 2.0
scripts/src/main/java/io/github/fate_grand_automata/scripts/modules/ConnectionRetry.kt
Fate-Grand-Automata
245,391,245
false
null
package io.github.fate_grand_automata.scripts.modules import io.github.fate_grand_automata.scripts.IFgoAutomataApi import io.github.fate_grand_automata.scripts.Images import io.github.lib_automata.dagger.ScriptScope import javax.inject.Inject import kotlin.time.Duration.Companion.seconds @ScriptScope class ConnectionRetry @Inject constructor( api: IFgoAutomataApi ) : IFgoAutomataApi by api { fun needsToRetry() = images[Images.Retry] in locations.retryRegion fun retry() { locations.retryRegion.click() 2.seconds.wait() } }
160
Kotlin
187
993
eb630b8efcdb56782f796de2e17b36fdf9e19f3b
570
FGA
MIT License
01-basic-websocket-server/src/main/kotlin/com/example/websocket/config/WebSocketConfig.kt
bkjam
487,783,785
false
{"Kotlin": 25580}
package com.example.websocket.config import org.springframework.context.annotation.Configuration import org.springframework.messaging.simp.config.MessageBrokerRegistry import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker import org.springframework.web.socket.config.annotation.StompEndpointRegistry import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer @Configuration @EnableWebSocketMessageBroker class WebSocketConfig: WebSocketMessageBrokerConfigurer { override fun registerStompEndpoints(registry: StompEndpointRegistry) { registry.addEndpoint("/stomp").setAllowedOrigins("*") } override fun configureMessageBroker(registry: MessageBrokerRegistry) { registry.enableSimpleBroker("/topic") registry.setApplicationDestinationPrefixes("/app") } }
0
Kotlin
10
24
92f437b892945a4285ef25fc704f514d14488eb5
857
websocket-microservice
Apache License 2.0
app/src/main/kotlin/aap/bot/oppgavestyring/Testbruker.kt
navikt
552,766,690
false
null
package aap.bot.oppgavestyring enum class Testbruker(val epost: String, val ident: String) { VEILEDER_GAMLEOSLO_NAVKONTOR("<EMAIL><EMAIL>", "Z994559"), // Lokalkontor SAKSBEHANDLER("<EMAIL><EMAIL>", "Z994554"), // NAY SAKSBEHANDLER_STRENGT_FORTROLIG("<EMAIL><EMAIL>", "Z994553"), FATTER("<EMAIL><EMAIL>", "Z994439"), // Kvalitetssikrer lokalkontor BESLUTTER("<EMAIL><EMAIL>", "Z994524"), // Kvalitetssikrer NAY SAKSBEHANDLER_FORTROLIG("<EMAIL><EMAIL>", "Z994169"), SAKSBEHANDLER_OG_VEILEDER_ALLE_NAVKONTOR("<EMAIL><EMAIL>", "Z990203"), BESLUTTER_OG_FATTER_ALLE_NAVKONTOR("<EMAIL><EMAIL>", "Z990252"), }
1
Kotlin
0
0
71f703349db2e259de4437fafbbf4e9bb96c7fba
636
aap-bot
MIT License
Utils/azuretools-core/src/com/microsoft/azuretools/core/mvp/model/database/AzureSqlDatabaseMvpModel.kt
Bhanditz
168,934,079
true
{"Java": 6667145, "Kotlin": 684156, "Scala": 106981, "JavaScript": 98350, "Gherkin": 75651, "HTML": 22998, "CSS": 21770, "Shell": 17990, "XSLT": 7141, "Batchfile": 1345}
/** * Copyright (c) 2018 JetBrains s.r.o. * <p/> * All rights reserved. * <p/> * MIT License * <p/> * 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: * <p/> * The above copyright notice and this permission notice shall be included in all copies or substantial portions of * the Software. * <p/> * 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 com.microsoft.azuretools.core.mvp.model.database import com.microsoft.azure.management.sql.SqlDatabase import com.microsoft.azure.management.sql.SqlServer import com.microsoft.azuretools.authmanage.AuthMethodManager import com.microsoft.azuretools.core.mvp.model.AzureMvpModel import com.microsoft.azuretools.core.mvp.model.ResourceEx import java.io.IOException import java.util.* import java.util.concurrent.ConcurrentHashMap object AzureSqlDatabaseMvpModel { private val sqlServerToSqlDatabasesMap = ConcurrentHashMap<SqlServer, List<SqlDatabase>>() fun listSqlDatabasesByServerId(subscriptionId: String, sqlServerId: String): List<SqlDatabase> { try { val azure = AuthMethodManager.getInstance().getAzureClient(subscriptionId) val sqlServer = azure.sqlServers().getById(sqlServerId) return sqlServer.databases().list() } catch (e: Throwable) { e.printStackTrace() } return ArrayList() } fun listSqlDatabasesBySubscriptionId(subscriptionId: String): List<ResourceEx<SqlDatabase>> { val sqlDatabaseList = ArrayList<ResourceEx<SqlDatabase>>() try { val azure = AuthMethodManager.getInstance().getAzureClient(subscriptionId) val sqlServers = azure.sqlServers().list() for (sqlServer in sqlServers) { val sqlDatabases = sqlServer.databases().list() for (sqlDatabase in sqlDatabases) { sqlDatabaseList.add(ResourceEx(sqlDatabase, subscriptionId)) } } } catch (e: IOException) { e.printStackTrace() } return sqlDatabaseList } fun listSqlDatabases(): List<ResourceEx<SqlDatabase>> { val sqlDatabases = ArrayList<ResourceEx<SqlDatabase>>() val subscriptions = AzureMvpModel.getInstance().selectedSubscriptions for (subscription in subscriptions) { sqlDatabases.addAll(listSqlDatabasesBySubscriptionId(subscription.subscriptionId())) } return sqlDatabases } fun deleteDatabase(subscriptionId: String, databaseId: String) { val sqlDatabases = listSqlDatabasesBySubscriptionId(subscriptionId) for (sqlDatabaseRes in sqlDatabases) { val sqlDatabase = sqlDatabaseRes.resource if (sqlDatabase.id() == databaseId) { sqlDatabase.delete() return } } } }
0
Java
0
0
f6a0b217e1147663a77cbc6f1a76c5b56bcf97ff
3,671
azure-tools-for-intellij
MIT License
ftc_app-3.5/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/game/RelicRecoveryConstants.kt
GotRobotFTC5037
100,045,718
false
{"Java": 1047885, "HTML": 176214, "Kotlin": 105682, "CSS": 12842, "JavaScript": 827}
package org.firstinspires.ftc.teamcode.game object RelicRecoveryConstants { const val LEADING_FRONT_CRYPTO_BOX_DISTANCE = 49.0 const val CENTER_FRONT_CRYPTO_BOX_DISTANCE = LEADING_FRONT_CRYPTO_BOX_DISTANCE + 17.0 const val TRAILING_FRONT_CRYPTO_BOX_DISTANCE = CENTER_FRONT_CRYPTO_BOX_DISTANCE + 18.0 const val LEADING_SIDE_CRYPTO_BOX_DISTANCE = 106.0 const val CENTER_SIDE_CRYPTO_BOX_DISTANCE = LEADING_SIDE_CRYPTO_BOX_DISTANCE + 17.0 const val TRAILING_SIDE_CRYPTO_BOX_DISTANCE = CENTER_SIDE_CRYPTO_BOX_DISTANCE + 18.0 }
1
Java
1
2
72983d1cefc29cd4cfbbffd43e907ca96d54668c
547
Relic-Recovery-2018
MIT License
ftc_app-3.5/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/game/RelicRecoveryConstants.kt
GotRobotFTC5037
100,045,718
false
{"Java": 1047885, "HTML": 176214, "Kotlin": 105682, "CSS": 12842, "JavaScript": 827}
package org.firstinspires.ftc.teamcode.game object RelicRecoveryConstants { const val LEADING_FRONT_CRYPTO_BOX_DISTANCE = 49.0 const val CENTER_FRONT_CRYPTO_BOX_DISTANCE = LEADING_FRONT_CRYPTO_BOX_DISTANCE + 17.0 const val TRAILING_FRONT_CRYPTO_BOX_DISTANCE = CENTER_FRONT_CRYPTO_BOX_DISTANCE + 18.0 const val LEADING_SIDE_CRYPTO_BOX_DISTANCE = 106.0 const val CENTER_SIDE_CRYPTO_BOX_DISTANCE = LEADING_SIDE_CRYPTO_BOX_DISTANCE + 17.0 const val TRAILING_SIDE_CRYPTO_BOX_DISTANCE = CENTER_SIDE_CRYPTO_BOX_DISTANCE + 18.0 }
1
Java
1
2
72983d1cefc29cd4cfbbffd43e907ca96d54668c
547
Relic-Recovery-2018
MIT License
src/client/kotlin/dev/hybridlabs/aquatic/client/gui/SeaMessageBookContents.kt
hybridlabs
661,391,321
false
{"Kotlin": 892890, "Java": 69899}
package dev.hybridlabs.aquatic.client.gui import dev.hybridlabs.aquatic.block.SeaMessage import net.minecraft.client.gui.screen.ingame.BookScreen.Contents import net.minecraft.client.resource.language.I18n import net.minecraft.text.StringVisitable /** * Custom book contents for Sea Message books. */ class SeaMessageBookContents(message: SeaMessage) : Contents { private val text = I18n.translate(message.translationKey) override fun getPageCount(): Int { return 1 } override fun getPageUnchecked(index: Int): StringVisitable { return StringVisitable.plain(text) } }
6
Kotlin
0
4
82c3b26d6697d2e5666b173101ade38505a3fe4c
610
hybrid-aquatic
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Skating.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.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.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.Outline.Skating: ImageVector get() { if (_skating != null) { return _skating!! } _skating = Builder(name = "Skating", 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(21.0f, 2.5f) arcTo(2.5f, 2.5f, 0.0f, true, true, 18.5f, 0.0f) arcTo(2.5f, 2.5f, 0.0f, false, true, 21.0f, 2.5f) close() moveTo(8.219f, 15.293f) lineTo(3.4f, 20.112f) lineTo(2.2f, 18.888f) lineToRelative(-1.428f, 1.4f) lineToRelative(2.8f, 2.857f) arcToRelative(2.978f, 2.978f, 0.0f, false, false, 2.112f, 0.9f) horizontalLineToRelative(0.031f) arcToRelative(2.982f, 2.982f, 0.0f, false, false, 2.1f, -0.857f) lineToRelative(-1.4f, -1.429f) arcToRelative(1.007f, 1.007f, 0.0f, false, true, -0.71f, 0.286f) arcToRelative(0.994f, 0.994f, 0.0f, false, true, -0.7f, -0.3f) lineToRelative(-0.2f, -0.2f) lineToRelative(4.834f, -4.833f) close() moveTo(17.0f, 21.0f) horizontalLineToRelative(2.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, -3.0f, 3.0f) horizontalLineTo(12.0f) verticalLineTo(22.0f) horizontalLineToRelative(2.0f) verticalLineTo(18.274f) lineTo(8.8f, 13.333f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, -0.055f, -4.3f) lineTo(11.781f, 6.0f) horizontalLineTo(4.0f) verticalLineTo(4.0f) horizontalLineToRelative(9.959f) lineToRelative(2.062f, 1.723f) arcTo(3.009f, 3.009f, 0.0f, false, true, 17.0f, 7.9f) arcToRelative(2.976f, 2.976f, 0.0f, false, true, -0.879f, 2.158f) horizontalLineToRelative(0.0f) lineTo(12.29f, 13.891f) lineTo(16.0f, 17.416f) verticalLineTo(22.0f) arcTo(1.0f, 1.0f, 0.0f, false, false, 17.0f, 21.0f) close() moveTo(9.866f, 11.171f) arcToRelative(0.985f, 0.985f, 0.0f, false, false, 0.31f, 0.712f) lineToRelative(0.663f, 0.63f) lineToRelative(3.868f, -3.867f) arcTo(1.816f, 1.816f, 0.0f, false, false, 15.0f, 7.927f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -0.31f, -0.713f) lineToRelative(-0.706f, -0.588f) lineToRelative(-3.825f, 3.825f) arcTo(0.989f, 0.989f, 0.0f, false, false, 9.866f, 11.171f) close() } } .build() return _skating!! } private var _skating: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,756
icons
MIT License
src/com/softwaret/kpdf/db/tables/publication/PublicationTile.kt
Softwaret
277,790,397
false
null
package com.softwaret.kpdf.db.tables.publication import com.softwaret.kpdf.db.tables.metadata.MetadataTile import com.softwaret.kpdf.db.tables.pdf.PdfTile import com.softwaret.kpdf.db.tables.user.UserTile data class PublicationTile( var name: String, var author: UserTile, val pdf: PdfTile, val metadata: MetadataTile )
8
Kotlin
0
16
5bc4f5e2ed85d5a63a0fb95919fe22ad1450f5a2
338
kpdf
MIT License
src/main/kotlin/FrameCounter.kt
fracassi-marco
465,222,214
false
null
class FrameCounter { fun count(rolls: List<Point>): Int { var sum = 0.0 return rolls.takeWhile { sum += it.frameSpan() sum <= 10.0 }.count() } }
0
Kotlin
0
0
0c9bbcfcae32a673420c242a1e6525e472d462dd
200
Bowling-Score-Kata
Apache License 2.0
build-logic/convention/src/main/kotlin/io/github/japskiddin/android/core/buildlogic/DependenciesExtension.kt
Japskiddin
643,089,658
false
{"Kotlin": 35170}
package io.github.japskiddin.android.core.buildlogic import org.gradle.api.Project import org.gradle.api.artifacts.MinimalExternalModuleDependency import org.gradle.api.provider.Provider import org.gradle.kotlin.dsl.DependencyHandlerScope fun DependencyHandlerScope.implementation(dependency: Provider<MinimalExternalModuleDependency>) { add("implementation", dependency) } fun DependencyHandlerScope.detektPlugins(provider: Provider<MinimalExternalModuleDependency>) { add("detektPlugins", provider) } fun DependencyHandlerScope.ksp(provider: Provider<MinimalExternalModuleDependency>) { add("ksp", provider) } fun DependencyHandlerScope.androidTestImplementation(provider: Provider<MinimalExternalModuleDependency>) { add("androidTestImplementation", provider) } fun DependencyHandlerScope.testImplementation(provider: Provider<MinimalExternalModuleDependency>) { add("testImplementation", provider) } fun DependencyHandlerScope.implementation(project: Project) { add("implementation", project) } fun DependencyHandlerScope.api(project: Project) { add("api", project) }
0
Kotlin
0
0
94b70e0b7cbf8373e11ce824ef81596f1bdf5535
1,108
ScreenRecorder
Apache License 2.0
app/src/main/java/com/example/osen/activity/Restore.kt
maulanarasoky
272,947,464
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Kotlin": 35, "XML": 83, "Java": 1}
package com.example.osen.activity import android.content.ContentValues import android.content.Context import android.net.ConnectivityManager import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import cn.pedant.SweetAlert.SweetAlertDialog import com.example.osen.R import com.example.osen.database.database import com.example.osen.model.* import com.google.firebase.auth.FirebaseAuth import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageException import com.google.firebase.storage.StorageReference import kotlinx.android.synthetic.main.activity_restore.* import org.json.JSONArray import org.json.JSONException import java.io.* class Restore : AppCompatActivity() { lateinit var auth: FirebaseAuth lateinit var storage: StorageReference lateinit var dialog: SweetAlertDialog override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_restore) auth = FirebaseAuth.getInstance() storage = FirebaseStorage.getInstance().reference restoreClasses.setOnClickListener { downloadFile("Osen_Classes.json", "Kelas") } restoreStudents.setOnClickListener { downloadFile("Osen_Students.json", "Murid") } restoreAbsents.setOnClickListener { downloadFile("Osen_Absents.json", "Absen") } restoreScores.setOnClickListener { downloadFile("Osen_Scores.json", "Nilai") } restoreCategories.setOnClickListener { downloadFile("Osen_Categories.json", "Kategori") } } private fun downloadFile(fileName: String, restoreName: String) { if (!isNetworkConnected()) { dialog = SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE) dialog.setCancelable(false) dialog.titleText = "Pastikan Anda terhubung ke Internet" dialog.show() return } dialog = SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE) dialog.setCancelable(false) dialog.show() try { val folder = storage.child("${auth.currentUser?.email}/${fileName}") val location = File.createTempFile("application", ".json") folder.getFile(location) .addOnSuccessListener { when (restoreName) { "Kelas" -> importClasses(location.toString(), restoreName) "Murid" -> importStudent(location.toString(), restoreName) "Absen" -> importAbsents(location.toString(), restoreName) "Nilai" -> importScores(location.toString(), restoreName) "Kategori" -> importCategories(location.toString(), restoreName) } } .addOnFailureListener { dialog.changeAlertType(SweetAlertDialog.ERROR_TYPE) dialog.confirmText = "OK" dialog.titleText = "Anda belum melakukan backup data $restoreName" } } catch (e: StorageException) { e.printStackTrace() Log.d("ERROR", e.message.toString()) } } @Throws(IOException::class) private fun readJsonFile(data: String): String { val builder = StringBuilder() var inputStream: InputStream? = null try { var jsonDataString: String? inputStream = FileInputStream(data) val bufferReader = BufferedReader(InputStreamReader(inputStream, "UTF-8")) while (bufferReader.readLine().also { jsonDataString = it } != null) { builder.append(jsonDataString) } } catch (e: UnsupportedEncodingException) { e.printStackTrace() } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } finally { inputStream?.close() } Log.d("OUTPUT", builder.toString()) return String(builder) } @Throws(IOException::class, JSONException::class) fun importClasses(data: String, restoreName: String) { val ID_ = "ID_" val IMAGE = "IMAGE" val NAME = "NAME" val TYPE = "TYPE" val CATEGORY = "CATEGORY" val START_DATE = "START_DATE" val END_DATE = "END_DATE" val START_TIME = "START_TIME" val END_TIME = "END_TIME" val DAY = "DAY" val TEACHER_ID = "TEACHER_ID" try { val jsonDataString = readJsonFile(data) if (jsonDataString == "[]") { dialog.changeAlertType(SweetAlertDialog.WARNING_TYPE) dialog.titleText = "Data $restoreName kosong" dialog.confirmText = "OK" return } val menuItemJsonArray = JSONArray(jsonDataString) for (i in 0 until menuItemJsonArray.length()) { val jsonObject = menuItemJsonArray.getJSONObject(i) val contentValue = ContentValues() contentValue.put(ID_, jsonObject.getString(ID_)) contentValue.put(IMAGE, jsonObject.getString(IMAGE)) contentValue.put(NAME, jsonObject.getString(NAME)) contentValue.put(TYPE, jsonObject.getString(TYPE)) contentValue.put(CATEGORY, jsonObject.getString(CATEGORY)) contentValue.put(START_DATE, jsonObject.getString(START_DATE)) contentValue.put(END_DATE, jsonObject.getString(END_DATE)) contentValue.put(START_TIME, jsonObject.getString(START_TIME)) contentValue.put(END_TIME, jsonObject.getString(END_TIME)) contentValue.put(DAY, jsonObject.getString(DAY)) contentValue.put(TEACHER_ID, jsonObject.getString(TEACHER_ID)) database.use { val insert = insert(Classroom.TABLE_CLASSROOM, null, contentValue) if (insert > 0) { dialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE) dialog.titleText = "Data $restoreName berhasil di restore" dialog.confirmText = "OK" } } Log.d("IMPORT CLASSES SUCCESS", contentValue.toString()) } } catch (e: JSONException) { Log.e("ERROR", e.message.toString()) e.printStackTrace() } } @Throws(IOException::class, JSONException::class) fun importStudent(data: String, restoreName: String) { val ID_ = "ID_" val NAME = "NAME" val CLASS_NAME = "CLASS" val GENDER = "GENDER" val SCORE = "SCORE" val TEACHER_ID = "TEACHER_ID" try { val jsonDataString = readJsonFile(data) if (jsonDataString == "[]") { dialog.changeAlertType(SweetAlertDialog.WARNING_TYPE) dialog.titleText = "Data $restoreName kosong" dialog.confirmText = "OK" return } val menuItemJsonArray = JSONArray(jsonDataString) for (i in 0 until menuItemJsonArray.length()) { val jsonObject = menuItemJsonArray.getJSONObject(i) val contentValue = ContentValues() contentValue.put(ID_, jsonObject.getString(ID_)) contentValue.put(NAME, jsonObject.getString(NAME)) contentValue.put(CLASS_NAME, jsonObject.getString(CLASS_NAME)) contentValue.put(GENDER, jsonObject.getString(GENDER)) contentValue.put(SCORE, jsonObject.getString(SCORE)) contentValue.put(TEACHER_ID, jsonObject.getString(TEACHER_ID)) database.use { val insert = insert(Student.TABLE_STUDENT, null, contentValue) if (insert > 0) { dialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE) dialog.titleText = "Data $restoreName berhasil di restore" dialog.confirmText = "OK" } } Log.d("IMPORT STUDENTS SUCCESS", contentValue.toString()) } } catch (e: JSONException) { Log.e("ERROR", e.message.toString()) e.printStackTrace() } } @Throws(IOException::class, JSONException::class) fun importAbsents(data: String, restoreName: String) { val ID_ = "ID_" val STUDENT_ID = "STUDENT_ID" val HADIR = "HADIR" val IZIN = "IZIN" val SAKIT = "SAKIT" val ALFA = "ALFA" val CLASS = "CLASS" val TEACHER_ID = "TEACHER_ID" try { val jsonDataString = readJsonFile(data) if (jsonDataString == "[]") { dialog.changeAlertType(SweetAlertDialog.WARNING_TYPE) dialog.titleText = "Data $restoreName kosong" dialog.confirmText = "OK" return } val menuItemJsonArray = JSONArray(jsonDataString) for (i in 0 until menuItemJsonArray.length()) { val jsonObject = menuItemJsonArray.getJSONObject(i) val contentValue = ContentValues() contentValue.put(ID_, jsonObject.getString(ID_)) contentValue.put(STUDENT_ID, jsonObject.getString(STUDENT_ID)) contentValue.put(HADIR, jsonObject.getString(HADIR)) contentValue.put(IZIN, jsonObject.getString(IZIN)) contentValue.put(SAKIT, jsonObject.getString(SAKIT)) contentValue.put(ALFA, jsonObject.getString(ALFA)) contentValue.put(CLASS, jsonObject.getString(CLASS)) contentValue.put(TEACHER_ID, jsonObject.getString(TEACHER_ID)) database.use { val insert = insert(Absent.TABLE_ABSENT, null, contentValue) if (insert > 0) { dialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE) dialog.titleText = "Data $restoreName berhasil di restore" dialog.confirmText = "OK" } } Log.d("IMPORT ABSENTS SUCCESS", contentValue.toString()) } } catch (e: JSONException) { Log.e("ERROR", e.message.toString()) e.printStackTrace() } } @Throws(IOException::class, JSONException::class) fun importScores(data: String, restoreName: String) { val ID_ = "ID_" val STUDENT_ID = "STUDENT_ID" val UTS = "UTS" val PERSENTASE_UTS = "PERSENTASE_UTS" val UAS = "UAS" val PERSENTASE_UAS = "PERSENTASE_UAS" val ASSESSMENT_1 = "ASSESSMENT_1" val PERSENTASE_ASSESSMENT_1 = "PERSENTASE_ASSESSMENT_1" val ASSESSMENT_2 = "ASSESSMENT_2" val PERSENTASE_ASSESSMENT_2 = "PERSENTASE_ASSESSMENT_2" val ASSESSMENT_3 = "ASSESSMENT_3" val PERSENTASE_ASSESSMENT_3 = "PERSENTASE_ASSESSMENT_3" val CLASS_NAME = "CLASS" val TEACHER_ID = "TEACHER_ID" try { val jsonDataString = readJsonFile(data) if (jsonDataString == "[]") { dialog.changeAlertType(SweetAlertDialog.WARNING_TYPE) dialog.titleText = "Data $restoreName kosong" dialog.confirmText = "OK" return } val menuItemJsonArray = JSONArray(jsonDataString) for (i in 0 until menuItemJsonArray.length()) { val jsonObject = menuItemJsonArray.getJSONObject(i) val contentValue = ContentValues() contentValue.put(ID_, jsonObject.getString(ID_)) contentValue.put(STUDENT_ID, jsonObject.getString(STUDENT_ID)) contentValue.put(UTS, jsonObject.getString(UTS)) contentValue.put(PERSENTASE_UTS, jsonObject.getString(PERSENTASE_UTS)) contentValue.put(UAS, jsonObject.getString(UAS)) contentValue.put(PERSENTASE_UAS, jsonObject.getString(PERSENTASE_UAS)) contentValue.put(ASSESSMENT_1, jsonObject.getString(ASSESSMENT_1)) contentValue.put( PERSENTASE_ASSESSMENT_1, jsonObject.getString(PERSENTASE_ASSESSMENT_1) ) contentValue.put(ASSESSMENT_2, jsonObject.getString(ASSESSMENT_2)) contentValue.put( PERSENTASE_ASSESSMENT_2, jsonObject.getString(PERSENTASE_ASSESSMENT_2) ) contentValue.put(ASSESSMENT_3, jsonObject.getString(ASSESSMENT_3)) contentValue.put( PERSENTASE_ASSESSMENT_3, jsonObject.getString(PERSENTASE_ASSESSMENT_3) ) contentValue.put(CLASS_NAME, jsonObject.getString(CLASS_NAME)) contentValue.put(TEACHER_ID, jsonObject.getString(TEACHER_ID)) database.use { val insert = insert(Score.TABLE_SCORE, null, contentValue) if (insert > 0) { dialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE) dialog.titleText = "Data $restoreName berhasil di restore" dialog.confirmText = "OK" } } Log.d("IMPORT SCORES SUCCESS", contentValue.toString()) } } catch (e: JSONException) { Log.e("ERROR", e.message.toString()) e.printStackTrace() } } @Throws(IOException::class, JSONException::class) fun importCategories(data: String, restoreName: String) { val ID_: String = "ID_" val NAME: String = "NAME" val TEACHER_ID: String = "TEACHER_ID" try { val jsonDataString = readJsonFile(data) if (jsonDataString == "[]") { dialog.changeAlertType(SweetAlertDialog.WARNING_TYPE) dialog.titleText = "Data $restoreName kosong" dialog.confirmText = "OK" return } val menuItemJsonArray = JSONArray(jsonDataString) for (i in 0 until menuItemJsonArray.length()) { val jsonObject = menuItemJsonArray.getJSONObject(i) val contentValue = ContentValues() contentValue.put(ID_, jsonObject.getString(ID_)) contentValue.put(NAME, jsonObject.getString(NAME)) contentValue.put(TEACHER_ID, jsonObject.getString(TEACHER_ID)) database.use { val insert = insert(Category.TABLE_CATEGORY, null, contentValue) if (insert > 0) { dialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE) dialog.titleText = "Data $restoreName berhasil di restore" dialog.confirmText = "OK" } } Log.d("IMPORT CATEGORY SUCCESS", contentValue.toString()) } } catch (e: JSONException) { Log.e("ERROR", e.message.toString()) e.printStackTrace() } } private fun isNetworkConnected(): Boolean { val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return connectivityManager.activeNetworkInfo != null && connectivityManager.activeNetworkInfo.isConnected } }
0
Kotlin
0
0
56555265c46b0a443d81a7b489ed7e190e6c25c7
15,795
OSEN
MIT License
app/src/main/java/com/usama/ridekaro/views/OTPSecondActivity.kt
griffin-k
812,767,826
false
{"Kotlin": 153876, "Java": 33458}
package com.usama.ridekaro.views import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.froyo.usama.R import com.google.firebase.FirebaseException import com.google.firebase.FirebaseTooManyRequestsException import com.google.firebase.auth.* import kotlinx.android.synthetic.main.activity_otpsecond.* class OTPSecondActivity : AppCompatActivity() { private var mVerificationId: String? = null lateinit var mAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_otpsecond) lateinit var mobileNumber: String // support_otp_val.setOnClickListener { // val i = Intent(this, HomeActivity::class.java) // startActivity(i) // } if (intent != null && intent.extras != null) { mobileNumber = intent.getStringExtra("mobileNumber").toString() } mAuth = FirebaseAuth.getInstance() PhoneAuthProvider.getInstance().verifyPhoneNumber( "+91$mobileNumber", // Phone number to verify 60, // Timeout duration java.util.concurrent.TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback binding) callbacks ) // OnVerificationStateChangedCallbacks verifyButton.setOnClickListener { if (!otpTextField.text.isNullOrEmpty()) { verifyVerificationCode(otpTextField.text.toString()) } // startActivity(Intent(this, HomeActivity::class.java)) // finish() } } private val callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { override fun onVerificationCompleted(phoneAuthCredential: PhoneAuthCredential) { Log.d("TAG", "onVerificationCompleted:$phoneAuthCredential") signInWithPhoneAuthCredential(phoneAuthCredential) } override fun onVerificationFailed(e: FirebaseException) { // This callback is invoked in an invalid request for verification is made, // for instance if the the phone number format is not valid. if (e is FirebaseAuthInvalidCredentialsException) { Toast.makeText(this@OTPSecondActivity, e.message, Toast.LENGTH_LONG).show() } else if (e is FirebaseTooManyRequestsException) { Toast.makeText(this@OTPSecondActivity, e.message, Toast.LENGTH_LONG).show() } } override fun onCodeSent( s: String, forceResendingToken: PhoneAuthProvider.ForceResendingToken ) { super.onCodeSent(s, forceResendingToken) mVerificationId = s } } private fun verifyVerificationCode(code: String) { //creating the credential val credential = mVerificationId?.let { PhoneAuthProvider.getCredential(it, code) } //signing the user if (credential != null) { signInWithPhoneAuthCredential(credential) } } private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) { mAuth?.signInWithCredential(credential) ?.addOnCompleteListener(this) { task -> if (task.isSuccessful) { val i = Intent(this, HomeActivity::class.java) startActivity(i) } else { Toast.makeText(this, "Failed", Toast.LENGTH_LONG).show() } } } }
0
Kotlin
0
0
670861b4324b66a6e744326847a71fd50de7fc7a
3,784
Health-And-Rescue
MIT License
AsteriodRadar/app/src/main/java/github/informramiz/asteriodradar/view/overview/AsteroidItemViewHolder.kt
informramiz
256,688,156
false
null
package github.informramiz.asteriodradar.view.overview import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import github.informramiz.asteriodradar.databinding.ListItemAsteroidBinding import github.informramiz.asteriodradar.model.respository.domain.Asteroid /** * Created by <NAME> on 19/04/2020 */ class AsteroidItemViewHolder(private val binding: ListItemAsteroidBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(asteroid: Asteroid, clickListener: AsteroidClickListener) { binding.asteroid = asteroid binding.clickListener = clickListener //apply changes immediately as the view may get reused very quick binding.executePendingBindings() } companion object { fun create(parent: ViewGroup): AsteroidItemViewHolder { return AsteroidItemViewHolder(ListItemAsteroidBinding.inflate(LayoutInflater.from(parent.context), parent, false)) } } } class AsteroidClickListener(val clickListener: (asteroid: Asteroid) -> Unit) { fun onClick(asteroid: Asteroid) = clickListener(asteroid) }
0
Kotlin
0
0
6fe2d816faa5304c831ab83a4c31957034e1b39e
1,157
NASA-NearEarthObjects-Radar
MIT License
src/rider/main/kotlin/fr/socolin/rider/plugins/hsf/settings/storage/HsfProjectSettingsState.kt
Socolin
585,032,170
false
null
package fr.socolin.rider.plugins.hsf.settings.storage import com.intellij.util.xmlb.annotations.OptionTag import fr.socolin.rider.plugins.hsf.settings.models.HsfRuleConfiguration import fr.socolin.rider.plugins.hsf.settings.storage.converters.ProjectHsfRuleConfigurationConverter class HsfProjectSettingsState { @OptionTag(converter = ProjectHsfRuleConfigurationConverter::class) val rules = ArrayList<HsfRuleConfiguration>() }
0
Kotlin
0
0
ef40f6144973d8842135f4b640b0c5bd4281585f
437
HighlightSpecialFiles
MIT License
app/src/main/java/com/babestudios/ganbb/data/network/GanBbRepositoryContract.kt
herrbert74
321,043,716
false
null
package com.babestudios.ganbb.data.network import com.babestudios.ganbb.model.Character import com.github.michaelbull.result.Result interface GanBbRepositoryContract { suspend fun getCharacters(): Result<List<Character>, Throwable> }
0
Kotlin
0
0
e18dc6596ebb04ee6373fa4df0524c03644c951e
239
GanBreakingBad
MIT License
src/main/kotlin/JSONArmor.kt
lindsaygelle
833,228,388
false
{"Kotlin": 78925}
package dqbb import kotlinx.serialization.Serializable @Serializable data class JSONArmor( val armorType: ArmorType?, val defense: Int = 1 ) { fun build(): Armor { return when (this.armorType) { ArmorType.CHAIN_MAIL -> ArmorChainMail ArmorType.CLOTHES -> ArmorClothes ArmorType.ERDRICK -> ArmorErdrick ArmorType.FULL_PLATE -> ArmorFullPlate ArmorType.HALF_PLATE -> ArmorHalfPlate ArmorType.LEATHER -> ArmorLeather ArmorType.MAGIC -> ArmorMagic else -> Armor( armorType = ArmorType.CUSTOM, defense = defense, ) } } }
0
Kotlin
0
0
e4faa308e3a40ed0e0888a1c54043476a5d6f277
690
dqbb
MIT License
plugin-unity-agent/src/main/kotlin/jetbrains/buildServer/unity/logging/PlayerStatisticsBlock.kt
JetBrains
159,985,216
false
{"Kotlin": 255626, "ANTLR": 53548, "Java": 28778, "C#": 4090, "Shell": 2924, "Batchfile": 1180}
package jetbrains.buildServer.unity.logging class PlayerStatisticsBlock : LogBlock { override val name = "Player statistics" override val logFirstLine = LogType.Outside override val logLastLine = LogType.Outside override fun isBlockStart(text: String) = blockStart.containsMatchIn(text) override fun isBlockEnd(text: String) = blockEnd.containsMatchIn(text) override fun getText(text: String) = text companion object { private val blockStart = Regex("\\*\\*\\*Player size statistics\\*\\*\\*") private val blockEnd = Regex("Unloading.*") } }
41
Kotlin
39
80
cbcd38a34aa45c0d10ffd0f722776cb405ebdb08
600
teamcity-unity-plugin
Apache License 2.0
data/repository/src/main/java/com/luan/teste/data/repository/repositories/model/RepositoryMapper.kt
luangs7
475,285,813
false
null
package com.luan.teste.data.repository.repositories.model import com.luan.teste.domain.model.repositories.Owner import com.luan.teste.domain.model.repositories.Repository fun RepositoryData.toDomain(): Repository { return Repository( id = id, name = name, fullName = fullName, owner = owner.toDomain(), description = description, starCount= starCount ) } fun OwnerData.toDomain(): Owner { return Owner( username = login, id = id, avatar = avatarUrl ) } fun Repository.toRepo(): RepositoryData { return RepositoryData( id = id, name = name, fullName = fullName, owner = owner.toRepo(), description = description, starCount = starCount ) } fun Owner.toRepo(): OwnerData { return OwnerData( login = username, id = id, avatarUrl = avatar, type = "user", url = String() ) }
0
Kotlin
0
0
af40cb051d592fbaab59154a499ba98aab0c4a2f
966
GithubComposable
Apache License 2.0
webserver/src/main/kotlin/cz/vutbr/fit/knot/enticing/webserver/controller/GlobalControllerExceptionHandler.kt
d-kozak
180,137,313
false
{"Kotlin": 1104829, "TypeScript": 477922, "Python": 23617, "Shell": 19609, "HTML": 8510, "ANTLR": 2005, "CSS": 1432}
package cz.vutbr.fit.knot.enticing.webserver.controller import cz.vutbr.fit.knot.enticing.api.ComponentNotAccessibleException import cz.vutbr.fit.knot.enticing.dto.utils.toJson import cz.vutbr.fit.knot.enticing.eql.compiler.EqlCompilerException import cz.vutbr.fit.knot.enticing.log.LoggerFactory import cz.vutbr.fit.knot.enticing.log.error import cz.vutbr.fit.knot.enticing.log.logger import cz.vutbr.fit.knot.enticing.query.processor.QueryDispatcherException import cz.vutbr.fit.knot.enticing.webserver.exception.InvalidPasswordException import cz.vutbr.fit.knot.enticing.webserver.exception.InvalidSearchSettingsException import cz.vutbr.fit.knot.enticing.webserver.exception.ValueNotUniqueException import org.hibernate.exception.JDBCConnectionException import org.springframework.dao.DataIntegrityViolationException import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.ResponseStatus import javax.servlet.http.HttpServletResponse @ControllerAdvice class GlobalControllerExceptionHandler(loggerFactory: LoggerFactory) { val logger = loggerFactory.logger { } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(JDBCConnectionException::class) fun jDBCConnectionException(e: Exception) { logger.error(e) } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(QueryDispatcherException::class) fun queryDispatcherException(e: Exception) { logger.error(e) } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(IllegalArgumentException::class) fun illegalArgumentException(e: Exception) { logger.error(e) } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(ComponentNotAccessibleException::class) fun componentNotAccessibleException(e: Exception) { logger.error(e) } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(DataIntegrityViolationException::class) fun handleConstrainViolation(e: Exception) { logger.error(e) } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(InvalidSearchSettingsException::class) fun invalidSearchSettings(exception: InvalidSearchSettingsException) { logger.error(exception) } @ExceptionHandler(EqlCompilerException::class) fun eqlCompilerException(exception: EqlCompilerException, response: HttpServletResponse) { logger.error(exception) response.sendError(HttpStatus.BAD_REQUEST.value(), exception.message) } @ExceptionHandler(InvalidPasswordException::class) fun invalidPasswordException(exception: InvalidPasswordException, response: HttpServletResponse) { logger.error(exception) val messageMap = mapOf("errors" to listOf(mapOf("field" to "oldPassword", "defaultMessage" to exception.message))) response.sendError(HttpStatus.BAD_REQUEST.value(), messageMap.toJson()) } @ExceptionHandler(ValueNotUniqueException::class) fun handleValueNotUnique(exception: ValueNotUniqueException, response: HttpServletResponse) { logger.error(exception) val messageMap = mapOf("errors" to listOf(mapOf("field" to exception.field, "defaultMessage" to exception.message))) response.sendError(HttpStatus.BAD_REQUEST.value(), messageMap.toJson()) } }
0
Kotlin
0
0
1ea9f874c6d2e4ea158e20bbf672fc45bcb4a561
3,429
enticing
MIT License
Front/MyJetpackFront/app/src/main/java/com/example/myjetpackfront/ui/screens/StocksGridScreen.kt
Ramazuki
696,235,417
false
{"Kotlin": 76802}
package com.example.myjetpackfront.ui.screens import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.itemsIndexed import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.example.myjetpackfront.R import com.example.myjetpackfront.data.stock.Stock import com.example.myjetpackfront.navigation.AppRouter import com.example.myjetpackfront.navigation.ButtonHandler import com.example.myjetpackfront.navigation.Screens @Composable fun StocksGridScreen( stocks: List<Stock>, modifier: Modifier, onStockClick: (Stock) -> Unit ) { LazyVerticalGrid( columns = GridCells.Adaptive(150.dp), contentPadding = PaddingValues(4.dp), ) { itemsIndexed(stocks) { _, stock -> StocksCard(stock = stock, modifier, onStockClick) } } ButtonHandler { AppRouter.navigateTo(Screens.HomeScreens) } } @Composable fun StocksCard( stock: Stock, modifier: Modifier, onStockClick: (Stock) -> Unit ) { Card( modifier = modifier .padding(4.dp) .fillMaxWidth() .requiredHeight(296.dp) .clickable {onStockClick(stock)}, elevation = CardDefaults.cardElevation( defaultElevation = 8.dp ) ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { stock.name?.let { Text( text = it, textAlign = TextAlign.Center, modifier = modifier .padding(top = 4.dp, bottom = 8.dp) ) } AsyncImage( modifier = modifier.fillMaxWidth(), model = ImageRequest.Builder(context = LocalContext.current) .data(stock.imgLink?.replace("http", "https")) .crossfade(true) .build(), error = painterResource(id = R.drawable.stock_error), placeholder = painterResource(id = R.drawable.loading_img), contentDescription = stringResource(id = R.string.content_description), contentScale = ContentScale.Crop ) } } }
0
Kotlin
0
1
19217c0c2909bc56d5bbfd04cc0829f85f61093c
2,908
PRDInvest-Application
MIT License
app/src/main/java/com/panchalamitr/notificationreader/viewmodel/NotificationViewModel.kt
panchalamitr
616,993,035
false
null
package com.panchalamitr.notificationreader.viewmodel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.viewModelScope import com.panchalamitr.notificationreader.db.NotificationDb import com.panchalamitr.notificationreader.model.NotificationDao import com.panchalamitr.notificationreader.model.NotificationEntity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class NotificationViewModel(application: Application) : AndroidViewModel(application) { private val notificationDao: NotificationDao val notificationList: LiveData<List<NotificationEntity>> init { val database = NotificationDb.getInstance(application) notificationDao = database.notificationDao() notificationList = notificationDao.getNotifications() } }
0
Kotlin
0
1
cdcd96688d8f34b92395f098d03f64d5a1602b95
868
Android-Notification-Reader
MIT License
app/src/main/java/com/cellfishpool/sportsinventory/ui/student/InventoryCnfActivity.kt
gaurisingh98
292,079,960
false
null
package com.cellfishpool.sportsinventory.ui.student import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.cellfishpool.sportsinventory.databinding.ActivityInventoryCnfBinding import com.cellfishpool.sportsinventory.models.Student import com.google.firebase.database.FirebaseDatabase class InventoryCnfActivity : AppCompatActivity() { var database = FirebaseDatabase.getInstance() private lateinit var sportsName: String private lateinit var binding: ActivityInventoryCnfBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityInventoryCnfBinding.inflate(layoutInflater) sportsName = intent.getStringExtra("sportsName").toString() setContentView(binding.root) initToolbar() addListener() } private fun addListener() { with(binding) { btnConfirm.setOnClickListener { database.reference.child(etPhone.text.toString()).push() .setValue( Student( etEmail.text.toString(), etPhone.text.toString(), sportsName, "pending", null, null ) ) } btnDismiss.setOnClickListener { startActivity(Intent(this@InventoryCnfActivity, StudentActivity::class.java)) } } } private fun initToolbar() { with(binding.appBar.toolbar) { title = "Inventory Confirmation" } } }
0
Kotlin
0
0
5475491fb048e4187ed0844aa77e1f7c94838c0e
1,721
Sports-Inventory
MIT License
app/src/main/java/com/heng/ku/jnitest/VideoPlayActivity.kt
Jiaoshichun
261,649,251
false
null
package com.heng.ku.jnitest import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.heng.ku.jnitest.media.decoder.* import kotlinx.android.synthetic.main.activity_video_play.* class VideoPlayActivity : AppCompatActivity() { private val TAG = "MainActivity" private var videoDecoder: VideoDecoder? = null private var audioDecoder: AudioDecoder? = null private var pos = -1L private var isStart = false private var isPause = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_video_play) videoDecoder = VideoDecoder(VIDEO_FILE1, surfaceView) audioDecoder = AudioDecoder(VIDEO_FILE1) videoDecoder?.start() audioDecoder?.start() videoDecoder!!.mStateListener=object :DefDecodeStateListener{ override fun decoderStop(decodeJob: BaseDecoder?) { start.text = "开始" isStart = false isPause = false } override fun decoderRunning(decodeJob: BaseDecoder?) { if (pos != -1L) { videoDecoder!!.seekTo(pos) audioDecoder!!.seekTo(pos) pos = -1L } } } start.setOnClickListener { isStart = !isStart if (isStart) { videoDecoder!!.start() audioDecoder!!.start() start.text = "停止" } else { videoDecoder!!.stop() audioDecoder!!.stop() start.text = "开始" } } pause.setOnClickListener { if (!isStart) return@setOnClickListener isPause = !isPause if (isPause) { videoDecoder!!.pause() audioDecoder!!.pause() pause.text = "继续" } else { videoDecoder!!.resume() audioDecoder!!.resume() pause.text = "暂停" } } } override fun onStop() { super.onStop() pos = videoDecoder!!.getCurTimeStamp() audioDecoder?.stop() videoDecoder?.stop() } override fun onStart() { super.onStart() if (pos != -1L) { audioDecoder!!.start() videoDecoder!!.start() } } override fun onDestroy() { super.onDestroy() audioDecoder?.stop() videoDecoder?.stop() } }
0
null
1
3
efe9cb6cefed596a50a50c1b041a43e040ff4ba1
2,585
VideoAndOpenGL
Apache License 2.0
simpleBleClient/src/main/java/com/bortxapps/simplebleclient/api/data/BleCharacteristic.kt
neoBortx
735,979,951
false
{"Kotlin": 227695, "Java": 572}
package com.bortxapps.simplebleclient.api.data import java.util.UUID /** * Represents a BLE characteristic IDs. * * @param serviceUUID The UUID of the service that contains the characteristic. * @param characteristicUUID The UUID of the characteristic. */ public data class BleCharacteristic(public val serviceUUID: UUID, public val characteristicUUID: UUID)
0
Kotlin
0
4
d34efdb10c159091426d0bc126ad8789127b7414
365
SimpleBleClient
MIT License
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/DistributeVertical.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.cssggicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.CssGgIcons public val CssGgIcons.DistributeVertical: ImageVector get() { if (_distributeVertical != null) { return _distributeVertical!! } _distributeVertical = Builder(name = "DistributeVertical", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeAlpha = 0.5f, strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 11.0f) horizontalLineTo(15.0f) verticalLineTo(13.0f) horizontalLineTo(9.0f) verticalLineTo(11.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.0f, 7.0f) horizontalLineTo(5.0f) verticalLineTo(5.0f) horizontalLineTo(19.0f) verticalLineTo(7.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.0f, 19.0f) horizontalLineTo(5.0f) verticalLineTo(17.0f) horizontalLineTo(19.0f) verticalLineTo(19.0f) close() } } .build() return _distributeVertical!! } private var _distributeVertical: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,582
compose-icons
MIT License
api_generator/tests/references/kotlin_dsl/EntityWithOptionalStringEnumProperty.kt
divkit
523,491,444
false
{"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
// Generated code. Do not modify. package com.yandex.api_generator.test import java.net.URI import com.fasterxml.jackson.annotation.* import com.yandex.div.dsl.* import com.yandex.div.dsl.context.* import com.yandex.div.dsl.type.* import com.yandex.div.dsl.util.* class EntityWithOptionalStringEnumProperty internal constructor( @JsonIgnore val property: Property<Property>?, ) : Entity { @JsonProperty("type") override val type = "entity_with_optional_string_enum_property" @JsonAnyGetter internal fun properties(): Map<String, Any> { return propertyMapOf( "property" to property, ) } enum class Property(@JsonValue val value: String) { FIRST("first"), SECOND("second"), } } fun <T> TemplateContext<T>.entityWithOptionalStringEnumProperty(): LiteralProperty<EntityWithOptionalStringEnumProperty> { return value(EntityWithOptionalStringEnumProperty( property = null, )) } fun <T> TemplateContext<T>.entityWithOptionalStringEnumProperty( property: Property<EntityWithOptionalStringEnumProperty.Property>? = null, ): LiteralProperty<EntityWithOptionalStringEnumProperty> { return value(EntityWithOptionalStringEnumProperty( property = property, )) } fun <T> TemplateContext<T>.entityWithOptionalStringEnumProperty( property: EntityWithOptionalStringEnumProperty.Property? = null, ): LiteralProperty<EntityWithOptionalStringEnumProperty> { return value(EntityWithOptionalStringEnumProperty( property = optionalValue(property), )) } fun CardContext.entityWithOptionalStringEnumProperty(): EntityWithOptionalStringEnumProperty { return EntityWithOptionalStringEnumProperty( property = null, ) } fun CardContext.entityWithOptionalStringEnumProperty( property: ValueProperty<EntityWithOptionalStringEnumProperty.Property>? = null, ): EntityWithOptionalStringEnumProperty { return EntityWithOptionalStringEnumProperty( property = property, ) } fun CardContext.entityWithOptionalStringEnumProperty( property: EntityWithOptionalStringEnumProperty.Property? = null, ): EntityWithOptionalStringEnumProperty { return EntityWithOptionalStringEnumProperty( property = optionalValue(property), ) }
5
Kotlin
128
2,240
dd102394ed7b240ace9eaef9228567f98e54d9cf
2,278
divkit
Apache License 2.0
app/src/main/java/ru/debajo/reader/rss/domain/article/ClearArticlesUseCase.kt
devDebajo
436,756,058
false
{"Kotlin": 289301}
package ru.debajo.reader.rss.domain.article import ru.debajo.reader.rss.data.converter.toDomain import ru.debajo.reader.rss.domain.channel.ChannelsRepository import ru.debajo.reader.rss.ui.channels.model.UiChannelUrl class ClearArticlesUseCase( private val newArticlesRepository: NewArticlesRepository, private val articlesRepository: ArticlesRepository, private val channelsRepository: ChannelsRepository, ) { suspend fun clear(channelUrl: UiChannelUrl) { newArticlesRepository.remove(channelUrl.toDomain()) articlesRepository.removeFromDb(channelUrl.toDomain()) channelsRepository.removeFromDb(channelUrl.toDomain()) } }
0
Kotlin
0
4
5a86b47d31744424afeced3e65e162b509e524f2
670
sreeeder
Apache License 2.0
sample/src/main/java/com/github/rmielnik/demo/SampleViewHolder.kt
rmielnik
286,580,967
false
null
package com.github.rmielnik.demo import android.content.Intent import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.github.rmielnik.list.AbstractViewHolder class SampleViewHolder(view: View) : AbstractViewHolder<SampleItem>(view) { private val title = view.findViewById<TextView>(R.id.title) private val description = view.findViewById<TextView>(R.id.description) override fun bind(item: SampleItem) { title.text = item.title description.text = item.description itemView.setOnClickListener { if (adapterPosition != RecyclerView.NO_POSITION) { with(itemView.context) { startActivity(Intent(this, item.targetActivityClass)) } } } } }
0
Kotlin
0
6
bcc0f5483f980a8d1284968f6d6635a4246e8080
823
SimplerRecyclerView
Apache License 2.0
openrndr-utils/src/commonMain/kotlin/collections/Stack.kt
openrndr
122,222,767
false
null
package org.openrndr.collections fun <E> ArrayDeque<E>.push(item: E) : E { addLast(item) return item } fun <E> ArrayDeque<E>.pop() : E { return removeLast() }
21
null
73
880
2ef3c463ecb66701771dc0cf8fb3364e960a5e3c
172
openrndr
BSD 2-Clause FreeBSD License
platform/platform-api/src/com/intellij/ide/ui/ThemeListProvider.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.ui import com.intellij.ide.ui.laf.UIThemeLookAndFeelInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.editor.colors.Groups import org.jetbrains.annotations.ApiStatus /** * Provides all available LaFs sorted and grouped for popups/combobox lists */ @ApiStatus.Internal interface ThemeListProvider { companion object { fun getInstance(): ThemeListProvider = ApplicationManager.getApplication().service<ThemeListProvider>() } /** * Provides all available themes. * Themes are divided to groups, groups should be split by separators in all UIs */ fun getShownThemes(): Groups<UIThemeLookAndFeelInfo> }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
858
intellij-community
Apache License 2.0
app/src/main/java/com/k/k/validation/validation/BindingAdapter.kt
k-kawajiri
219,539,280
false
null
package com.k.k.validation.validation import android.widget.EditText import androidx.databinding.BindingAdapter /** * バリデーションエラーメッセージを表示する. */ @BindingAdapter("errorMessage") fun setErrorMessage(editText: EditText, data: ValidateLiveData) { val errorMessage = when (data.isError) { true -> { val context = editText.context data.messageMap.map { context.getString(it.key, *it.value) } .joinToString(separator = "\n") } else -> null } editText.error = errorMessage }
0
Kotlin
0
0
b9bcb56736740b93e72b4962dc5a0447787adecc
545
android-validation
The Unlicense
app/src/main/kotlin/y2k/rssreader/components/SubscriptionComponent.kt
y2k
65,879,889
false
null
package y2k.rssreader.components import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ListView import android.widget.TextView import y2k.rssreader.Provider.selectSubscription import y2k.rssreader.RssSubscription import y2k.rssreader.getSubscriptions import y2k.rssreader.toLiveCycleObservable /** * Created by y2k on 21/08/16. */ class SubscriptionComponent(context: Context, attrs: AttributeSet?) : ListView(context, attrs) { init { getSubscriptions() .toLiveCycleObservable(context) .subscribe { subs -> adapter = object : BaseAdapter() { override fun getView(index: Int, view: View?, parent: ViewGroup?): View { val v = view ?: View.inflate(context, android.R.layout.simple_list_item_2, null) val i = subs[index] (v.findViewById(android.R.id.text1) as TextView).text = i.title (v.findViewById(android.R.id.text2) as TextView).text = i.url return v } override fun getCount() = subs.size override fun getItemId(index: Int) = index.toLong() override fun getItem(index: Int) = TODO() } } setOnItemClickListener { adapterView, view, index, id -> selectSubscription(adapter.getItem(index) as RssSubscription) } } }
0
Kotlin
0
0
0002a22087efcbd277d70539c8e4585054cc7765
1,573
RssReader
MIT License
composeApp/src/commonMain/kotlin/ru/rznnike/demokmp/data/preference/Preference.kt
RznNike
834,057,164
false
{"Kotlin": 147652}
package ru.rznnike.demokmp.data.preference import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import kotlinx.coroutines.flow.first import ru.rznnike.demokmp.domain.model.common.Language import ru.rznnike.demokmp.domain.model.common.Theme import ru.rznnike.demokmp.domain.utils.toDoubleOrNullSmart sealed class Preference<Type>( private val dataStore: DataStore<Preferences>, key: String, private val defaultValue: Type ) { private val typedKey = stringPreferencesKey(key) protected abstract fun Type.serialize(): String protected abstract fun String.deserialize(): Type? suspend fun get(): Type = dataStore.data.first()[typedKey]?.deserialize() ?: defaultValue suspend fun set(newValue: Type) { dataStore.edit { it[typedKey] = newValue.serialize() } } class StringPreference( dataStore: DataStore<Preferences>, key: String, defaultValue: String = "" ) : Preference<String>(dataStore, key, defaultValue) { override fun String.serialize() = this override fun String.deserialize() = this } class IntPreference( dataStore: DataStore<Preferences>, key: String, defaultValue: Int = 0 ) : Preference<Int>(dataStore, key, defaultValue) { override fun Int.serialize() = toString() override fun String.deserialize() = toIntOrNull() } class LongPreference( dataStore: DataStore<Preferences>, key: String, defaultValue: Long = 0 ) : Preference<Long>(dataStore, key, defaultValue) { override fun Long.serialize() = toString() override fun String.deserialize() = toLongOrNull() } class DoublePreference( dataStore: DataStore<Preferences>, key: String, defaultValue: Double = 0.0 ) : Preference<Double>(dataStore, key, defaultValue) { override fun Double.serialize() = toString() override fun String.deserialize() = toDoubleOrNullSmart() } class BooleanPreference( dataStore: DataStore<Preferences>, key: String, defaultValue: Boolean = false ) : Preference<Boolean>(dataStore, key, defaultValue) { override fun Boolean.serialize() = toString() override fun String.deserialize() = toBooleanStrictOrNull() } class LanguagePreference( dataStore: DataStore<Preferences>, key: String, defaultValue: Language ) : Preference<Language>(dataStore, key, defaultValue) { override fun Language.serialize() = tag override fun String.deserialize() = Language[this] } class ThemePreference( dataStore: DataStore<Preferences>, key: String, defaultValue: Theme ) : Preference<Theme>(dataStore, key, defaultValue) { override fun Theme.serialize() = id.toString() override fun String.deserialize() = Theme[toIntOrNull() ?: 0] } }
0
Kotlin
0
0
3009e10aff2f846ae11d79e1ab63ffbf02c820cc
3,081
DemoKMP
MIT License
app/src/main/java/de/dizcza/fundu_moto_joystick/fragment/LogsFragment.kt
dizcza
194,525,625
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Markdown": 1, "Proguard": 1, "XML": 28, "Kotlin": 14}
package de.dizcza.fundu_moto_joystick.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.ImageButton import android.widget.TextView import androidx.fragment.app.Fragment import de.dizcza.fundu_moto_joystick.R import de.dizcza.fundu_moto_joystick.util.Constants import java.util.Arrays import java.util.Collections class LogsFragment : Fragment() { private val mStatusView = LogsView() private val mSentView = LogsView() private val mReceivedView = LogsView() private var mJoystickFragment: JoystickFragment? = null private class LogsView { var view: TextView? = null val logs = StringBuilder() } fun setJoystickFragment(joystickFragment: JoystickFragment?) { mJoystickFragment = joystickFragment } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) retainInstance = true } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.logs_fragment, container, false) mStatusView.view = view.findViewById(R.id.logs_status) mSentView.view = view.findViewById(R.id.logs_sent) mReceivedView.view = view.findViewById(R.id.logs_received) val commandView = view.findViewById<EditText>(R.id.send_text) val sendCmdButton = view.findViewById<ImageButton>(R.id.send_btn) sendCmdButton.setOnClickListener { v: View? -> val command = commandView.text.toString() if (mJoystickFragment!!.send(command.toByteArray())) { mSentView.view!!.append(command + Constants.NEW_LINE) } } return view } private val views: Iterable<LogsView> private get() = Arrays.asList(mStatusView, mSentView, mReceivedView) override fun onResume() { super.onResume() for (logsView in views) { val text = logsView.logs.toString() val textLines = Arrays.asList( *text.split(Constants.NEW_LINE.toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray()) Collections.reverse(textLines) val textReversed = java.lang.String.join(Constants.NEW_LINE, textLines) logsView.view!!.text = textReversed } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_logs, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val idSelected = item.itemId return if (idSelected == R.id.clear) { for (logsView in views) { logsView.view!!.text = "" logsView.logs.setLength(0) } true } else { super.onOptionsItemSelected(item) } } fun appendStatus(text: String?) { mStatusView.logs.append(text) } fun appendSent(text: String?) { mSentView.logs.append(text) } fun appendReceived(text: String?) { mReceivedView.logs.append(text) } }
1
null
1
1
e35d5fd21497314d5b0f24460b57ef56cb6b3ca2
3,379
FunduMotoJoystick
MIT License
plugins/kotlin/base/fir/analysis-api-providers/src/org/jetbrains/kotlin/idea/base/fir/analysisApiProviders/FirIdeForwardDeclarationsServiceFactories.kt
cljohnso
74,039,733
false
{"Text": 9802, "INI": 515, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 634, "Markdown": 752, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 261, "XML": 7903, "SVG": 4545, "Kotlin": 59866, "Java": 84192, "HTML": 3795, "Java Properties": 216, "Gradle": 462, "Maven POM": 95, "JavaScript": 231, "CSS": 79, "JSON": 1426, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 732, "Groovy": 3109, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 72, "GraphQL": 125, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17077, "C": 109, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.fir.analysisApiProviders import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.analysis.project.structure.KtModule import org.jetbrains.kotlin.analysis.providers.KotlinDeclarationProvider import org.jetbrains.kotlin.analysis.providers.KotlinForwardDeclarationsPackageProviderFactory import org.jetbrains.kotlin.analysis.providers.KotlinForwardDeclarationProviderFactory import org.jetbrains.kotlin.analysis.providers.KotlinPackageProvider import org.jetbrains.kotlin.analysis.providers.createDeclarationProvider import org.jetbrains.kotlin.analysis.providers.createPackageProvider import org.jetbrains.kotlin.idea.base.projectStructure.KtNativeKlibLibraryModuleByModuleInfo /** * FIR IDE declaration provider factory implementation for Kotlin/Native forward declarations. * Delegates to the regular factory, but uses a narrow [GlobalSearchScope] that contains only generated declarations of the [KtModule]. * * @see [org.jetbrains.kotlin.idea.base.projectStructure.fwdDeclaration.KotlinForwardDeclarationsFileGenerator] */ class FirIdeForwardDeclarationProviderFactory : KotlinForwardDeclarationProviderFactory() { override fun createDeclarationProvider(ktModule: KtModule): KotlinDeclarationProvider? { if (ktModule !is KtNativeKlibLibraryModuleByModuleInfo) return null return ktModule.project.createDeclarationProvider(ktModule.fwdDeclarationsScope, ktModule) } } /** * FIR IDE package provider factory for Kotlin/Native forward declarations. * Delegates to the regular factory, but uses a narrow [GlobalSearchScope] that contains only generated declarations of the [KtModule]. * * @see [org.jetbrains.kotlin.idea.base.projectStructure.fwdDeclaration.KotlinForwardDeclarationsFileGenerator] */ class FirIdeForwardDeclarationPackageProviderFactory : KotlinForwardDeclarationsPackageProviderFactory() { override fun createPackageProvider(ktModule: KtModule): KotlinPackageProvider? { if (ktModule !is KtNativeKlibLibraryModuleByModuleInfo) return null return ktModule.project.createPackageProvider(ktModule.fwdDeclarationsScope) } }
1
null
1
1
175348b0f14b79441e9cae26cc28c3beb11ac389
2,281
intellij-community
Apache License 2.0
fc-webflux/webflux-examples/examples/kotlin-coroutine/src/main/kotlin/com/grizz/wooman/coroutine/orderexample/blocking/OrderBlockingService.kt
devYSK
461,887,647
false
{"Java": 3507759, "JavaScript": 659549, "Kotlin": 563136, "HTML": 455168, "CSS": 446825, "Shell": 57444, "Groovy": 54414, "Batchfile": 47890, "Go": 26805, "Python": 9963, "Handlebars": 8554, "Makefile": 7837, "Vue": 5706, "TypeScript": 5172, "Dockerfile": 436, "Vim Snippet": 362, "Assembly": 278, "Procfile": 199}
package com.grizz.wooman.coroutine.orderexample.blocking import com.grizz.wooman.coroutine.orderexample.common.Customer import com.grizz.wooman.coroutine.orderexample.common.DeliveryAddress import com.grizz.wooman.coroutine.orderexample.common.Product import com.grizz.wooman.coroutine.orderexample.common.Store class OrderBlockingService { fun createOrder( customer: Customer, products: List<Product>, deliveryAddress: DeliveryAddress, stores: List<Store>, ): Order { return Order( stores = stores, products = products, customer = customer, deliveryAddress = deliveryAddress, ) } }
1
null
1
1
7a7c6b1bab3dc2c84527f8c528b06b9408872635
692
study_repo
MIT License
app/src/main/java/com/cuidedacidade/di/AppModuleBinds.kt
daniloabranches
281,368,825
false
null
package com.cuidedacidade.di import com.cuidedacidade.core.router.AppRouter import com.cuidedacidade.core.router.Router import com.cuidedacidade.core.task.AppSchedulerProvider import com.cuidedacidade.core.task.SchedulerProvider import com.cuidedacidade.data.repository.CategoryDataRepository import com.cuidedacidade.data.repository.RequestDataRepository import com.cuidedacidade.domain.repository.CategoryRepository import com.cuidedacidade.domain.repository.RequestRepository import dagger.Binds import dagger.Module import javax.inject.Singleton @Module abstract class AppModuleBinds { @Binds abstract fun bindSchedulerProvider(schedulerProvider: AppSchedulerProvider): SchedulerProvider @Singleton @Binds abstract fun bindRequestRepository(requestDataRepository: RequestDataRepository): RequestRepository @Singleton @Binds abstract fun bindCategoryRepository(categoryDataRepository: CategoryDataRepository): CategoryRepository @Binds abstract fun bindRouter(appRouter: AppRouter): Router }
0
Kotlin
0
1
ee646396e98595aad72d048b80beaec9712e56a2
1,039
app-cuide-cidade-igti
MIT License
Manga/app/src/main/java/nhdphuong/com/manga/ApplicationComponent.kt
duyphuong5126
140,096,962
false
null
package nhdphuong.com.manga import dagger.Component import nhdphuong.com.manga.data.RepositoryModule import nhdphuong.com.manga.features.about.AboutUsComponent import nhdphuong.com.manga.features.about.AboutUsModule import nhdphuong.com.manga.features.admin.AdminComponent import nhdphuong.com.manga.features.admin.AdminModule import nhdphuong.com.manga.features.comment.CommentThreadComponent import nhdphuong.com.manga.features.comment.CommentThreadModule import nhdphuong.com.manga.features.downloaded.DownloadedBooksComponent import nhdphuong.com.manga.features.downloaded.DownloadedBooksModule import nhdphuong.com.manga.features.downloading.DownloadingBooksComponent import nhdphuong.com.manga.features.downloading.DownloadingBooksModule import nhdphuong.com.manga.features.header.HeaderModule import nhdphuong.com.manga.features.home.HomeComponent import nhdphuong.com.manga.features.home.HomeModule import nhdphuong.com.manga.features.preview.BookPreviewComponent import nhdphuong.com.manga.features.preview.BookPreviewModule import nhdphuong.com.manga.features.reader.ReaderComponent import nhdphuong.com.manga.features.reader.ReaderModule import nhdphuong.com.manga.features.recent.RecentComponent import nhdphuong.com.manga.features.recent.RecentModule import nhdphuong.com.manga.features.setting.SettingsComponent import nhdphuong.com.manga.features.setting.SettingsModule import nhdphuong.com.manga.features.tags.TagsComponent import nhdphuong.com.manga.features.tags.TagsModule import nhdphuong.com.manga.service.BookDeletingService import nhdphuong.com.manga.service.BookDownloadingService import nhdphuong.com.manga.service.RecentFavoriteMigrationService import nhdphuong.com.manga.service.TagsDownloadingService import nhdphuong.com.manga.service.TagsUpdateService import nhdphuong.com.manga.usecase.UseCaseModule import javax.inject.Singleton /* * Created by nhdphuong on 3/21/18. */ @Singleton @Component(modules = [ApplicationModule::class, RepositoryModule::class, UseCaseModule::class]) interface ApplicationComponent { fun plus(homeModule: HomeModule, headerModule: HeaderModule): HomeComponent fun plus(bookPreviewModule: BookPreviewModule): BookPreviewComponent fun plus(readerModule: ReaderModule): ReaderComponent fun plus(tagsModule: TagsModule, headerModule: HeaderModule): TagsComponent fun plus(recentModule: RecentModule): RecentComponent fun plus(adminModule: AdminModule): AdminComponent fun plus(downloadedBooksModule: DownloadedBooksModule): DownloadedBooksComponent fun plus(downloadedBooksModule: DownloadingBooksModule): DownloadingBooksComponent fun plus(commentThreadModule: CommentThreadModule): CommentThreadComponent fun plus(settingsModule: SettingsModule): SettingsComponent fun plus(aboutUsModule: AboutUsModule): AboutUsComponent fun inject(service: TagsUpdateService) fun inject(bookDownloadingService: BookDownloadingService) fun inject(recentFavoriteMigrationService: RecentFavoriteMigrationService) fun inject(bookDeletingService: BookDeletingService) fun inject(tagsDownloadingService: TagsDownloadingService) fun inject(nHentaiApp: NHentaiApp) }
4
Kotlin
0
3
8cbd6b2246726944e8cde96be8a4124feabe1baf
3,173
H-Manga
Apache License 2.0
src/main/kotlin/com/coxautodev/graphql/tools/ResolverInfo.kt
jflorencio
102,769,945
true
{"Kotlin": 77982, "Groovy": 33746, "Java": 7896}
package com.coxautodev.graphql.tools import org.apache.commons.lang3.reflect.TypeUtils import java.lang.reflect.ParameterizedType internal abstract class ResolverInfo { abstract fun getFieldSearches(): List<FieldResolverScanner.Search> } internal class NormalResolverInfo(val resolver: GraphQLResolver<*>, private val options: SchemaParserOptions): ResolverInfo() { val resolverType = resolver.javaClass val dataClassType = findDataClass() private fun findDataClass(): Class<*> { // Grab the parent interface with type GraphQLResolver from our resolver and get its first type argument. val interfaceType = GenericType(resolverType, options).getGenericInterface(GraphQLResolver::class.java) if(interfaceType == null || interfaceType !is ParameterizedType) { error("${GraphQLResolver::class.java.simpleName} interface was not parameterized for: ${resolverType.name}") } val type = TypeUtils.determineTypeArguments(resolverType, interfaceType)[GraphQLResolver::class.java.typeParameters[0]] if(type == null || type !is Class<*>) { throw ResolverError("Unable to determine data class for resolver '${resolverType.name}' from generic interface! This is most likely a bug with graphql-java-tools.") } if(type == Void::class.java) { throw ResolverError("Resolvers may not have ${Void::class.java.name} as their type, use a real type or use a root resolver interface.") } return type } override fun getFieldSearches(): List<FieldResolverScanner.Search> { return listOf( FieldResolverScanner.Search(resolverType, this, resolver, dataClassType), FieldResolverScanner.Search(dataClassType, this, null) ) } } internal class RootResolverInfo(val resolvers: List<GraphQLRootResolver>): ResolverInfo() { override fun getFieldSearches(): List<FieldResolverScanner.Search> { return resolvers.map { FieldResolverScanner.Search(it.javaClass, this, it) } } } internal class DataClassResolverInfo(val dataClass: Class<*>): ResolverInfo() { override fun getFieldSearches(): List<FieldResolverScanner.Search> { return listOf(FieldResolverScanner.Search(dataClass, this, null)) } } internal class MissingResolverInfo: ResolverInfo() { override fun getFieldSearches(): List<FieldResolverScanner.Search> = listOf() } class ResolverError(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
0
Kotlin
1
0
14101cbc3f6f67088736422fe95871ff7b2c6fdb
2,523
graphql-java-tools
MIT License
app/src/main/java/com/quizapp/data/datasource/remote/category/api/CategoryApi.kt
AhmetOcak
591,704,302
false
null
package com.quizapp.data.datasource.remote.category.api import com.quizapp.data.datasource.remote.category.entity.CategoriesDto import retrofit2.http.GET interface CategoryApi { @GET("api/Category/GetAll") suspend fun getCategories() : CategoriesDto }
0
Kotlin
0
5
cc9d467fcd37cc88c9bbac315bd9aae920722bac
262
QuizApp
MIT License
src/test/kotlin/com/jazavac/taskmanager/api/PriorityTest.kt
bmudric
352,116,386
false
{"Kotlin": 31666}
package com.jazavac.taskmanager.api import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.collections.shouldContainExactly class PriorityTest : ShouldSpec({ context("sorting a Priority list") { val unsorted = listOf(Priority.MEDIUM, Priority.HIGH, Priority.LOW) context("ascending") { should("return in order from low to high") { val sorted = unsorted.sorted() sorted shouldContainExactly listOf(Priority.LOW, Priority.MEDIUM, Priority.HIGH) } } context("descending") { should("return in order from high to low") { val sorted = unsorted.sortedDescending() sorted shouldContainExactly listOf(Priority.HIGH, Priority.MEDIUM, Priority.LOW) } } } })
0
Kotlin
0
0
08062b9b67bff37ad98ea56f642811e71818105c
826
task-manager
The Unlicense
Divide and Conquer/Median in Two Sorted Lists/test/Tests.kt
jetbrains-academy
515,621,972
false
null
import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class Test { @Test fun sample1() { val first = listOf(1, 2, 5) val second = listOf(3, 4, 6) val actual = getMedian(first, second) assertEquals(3, actual) } @Test fun sample2() { val first = listOf("a", "z", "zz") val second = listOf("a", "a", "zz") val actual = getMedian(first, second) assertEquals("a", actual) } }
1
Kotlin
0
2
fda85c9eb54f81c4c5d528425cceaf9370e0a11d
494
algo-challenges-in-kotlin
MIT License
app/src/main/java/com/zj/weather/utils/permission/LocationUtils.kt
zhujiang521
422,904,634
false
null
package com.zj.weather.utils.permission import android.annotation.SuppressLint import android.content.Context import android.location.* import android.os.Build import android.os.CancellationSignal import android.os.Looper import com.zj.weather.ui.view.weather.viewmodel.WeatherViewModel import com.zj.weather.utils.XLog import java.util.* import java.util.function.Consumer @SuppressLint("MissingPermission") fun getLocation(context: Context, weatherViewModel: WeatherViewModel) { val locationManager: LocationManager? val locationProvider: String? //1.获取位置管理器 locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager //2.获取位置提供器,GPS或是NetWork val providers: List<String> = locationManager.getProviders(true) XLog.e("getLocation: providers:$providers") when { providers.contains(LocationManager.NETWORK_PROVIDER) -> { //如果是Network locationProvider = LocationManager.NETWORK_PROVIDER XLog.d("定位方式Network") } providers.contains(LocationManager.GPS_PROVIDER) -> { //如果是GPS locationProvider = LocationManager.GPS_PROVIDER XLog.d("定位方式GPS") } else -> { XLog.e("getLocation: 没有可用的位置提供器") return } } //3.获取当前位置,R以上的版本需要使用getCurrentLocation // 之前的版本可以可用requestSingleUpdate if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { locationManager.getCurrentLocation( locationProvider, CancellationSignal(), context.mainExecutor, Consumer { location -> getAddress(context, location, weatherViewModel) }) } else { locationManager.requestSingleUpdate( locationProvider, LocationListener { location -> getAddress(context, location, weatherViewModel) }, Looper.getMainLooper() ) } } //获取地址信息:城市、街道等信息 private fun getAddress( context: Context, location: Location?, weatherViewModel: WeatherViewModel, ): List<Address?>? { XLog.e( "获取当前位置-经纬度:" + location?.longitude .toString() + " " + location?.latitude ) var result: List<Address?>? = null if (location == null) return result val gc = Geocoder(context, Locale.getDefault()) result = gc.getFromLocation( location.latitude, location.longitude, 1 ) weatherViewModel.updateCityInfo(location, result) XLog.e("获取地址信息:${result}") return result }
1
Kotlin
18
94
b64976949fdf79adbd8da903c72d4c99161a0544
2,553
PlayWeather
MIT License
core/src/main/kotlin/be/jameswilliams/preso/slides/Slides.kt
jwill
116,086,860
false
null
package be.jameswilliams.preso.slides import be.jameswilliams.preso.* import be.jameswilliams.preso.templates.* import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.math.Interpolation import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.ui.Image import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.Table import com.badlogic.gdx.scenes.scene2d.ui.VerticalGroup import com.badlogic.gdx.utils.Scaling import com.badlogic.gdx.utils.Scaling.fit import com.badlogic.gdx.utils.Scaling.stretchY import com.badlogic.gdx.utils.viewport.ScreenViewport import com.rafaskoberg.gdx.typinglabel.TypingConfig import ktx.app.KtxScreen import ktx.app.clearScreen import ktx.app.use import ktx.collections.gdxArrayOf import ktx.scene2d.slider import ktx.scene2d.table // This is where slides live until they deserve // their own file class Slide0() : KtxScreen, Slide { var table = Table() var verticalGroup = VerticalGroup() val batch = SpriteBatch() var stage: Stage init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { val title = headerLabel("Demystifying ConstraintLayout") val texture = Texture(Gdx.files.internal("images/james-emoji-circular.png")) val image = Image(texture) val name = bodyLabel("<NAME>") val twitterId = bodyLabel("@ecspike") val twitterIcon = iconLabel("\uf099") twitterIcon.setFontScale(0.5f) title.centerLabel() name.centerLabel() name.y -= name.height * 2 twitterId.centerLabel() twitterId.y -= (twitterId.height * 3) image.setSize(150f, 150f) image.x = name.x - 200f image.y = name.y - 80f with(stage) { addActor(image) addActor(title) addActor(name) //addActor(twitterIcon) addActor(twitterId) } } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) stage.act() stage.draw() } override fun nextPressed() { Presentation.setScreen(Slide1::class.java) } override fun backPressed() { // NO OP } } class Slide1 : KtxScreen, Slide { var table = Table() var verticalGroup = VerticalGroup() val batch = SpriteBatch() lateinit var udacityLogo: Texture var stage: Stage lateinit var label: Label init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { udacityLogo = Texture(Gdx.files.internal("images/udacity-240-white.jpg")) label = headerLabel("I work at Udacity. I'm Curriculum Lead for Android.") label.centerLabel() stage.addActor(label) } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) stage.act() stage.draw() batch.use { var x = (Gdx.graphics.width - udacityLogo.width) / 2f it.draw(udacityLogo, x, (Gdx.graphics.height / 2 - (2 * label.height + 50))) } } override fun dispose() { // Will be automatically disposed of by the game instance. batch.dispose() } override fun nextPressed() { Presentation.setScreen(Slide2::class.java) } override fun backPressed() { Presentation.setScreen(Slide0::class.java) } } class Slide2 : HeadlineSlide("The Android View Rendering Cycle", Slide1::class.java, Slide3::class.java) class Slide3 : BulletsSlide("The Android View Rendering Cycle", listOf("Measure Pass", "Layout Pass", "Drawing The Things", "")) { override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide5::class.java) } } override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide2::class.java) } } } class Slide5 : HeadlineSlide("Measuring A View", Slide3::class.java, Slide6::class.java) class Slide6 : HeadlineSlide("onMeasure(widthMeasureSpec, heightMeasureSpec)", Slide5::class.java, Slide7::class.java) class Slide7 : BulletsSlide("MeasureSpec", listOf("mode", "size", "")) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide6::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide8::class.java) } } } class Slide8 : BulletsSlide("MeasureSpec Modes", listOf("EXACTLY", "AT MOST", "UNSPECIFIED", "")) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide7::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide10::class.java) } } } class Slide10 : HeadlineSlide("Double Taxation", Slide8::class.java, Slide10A::class.java) val slide10A_definition = "Android has to do multiple measure passes to" + " determine the final positions of a View" class Slide10A : DefinitionSlide("What is double taxation?", slide10A_definition, Slide10::class.java, Slide11::class.java) class Slide11 : HeadlineSlide("Why is this Important?", Slide10A::class.java, Slide12::class.java) class Slide12 : HeadlineSlide("16ms*", Slide11::class.java, Slide13::class.java) class Slide13 : HeadlineSlide("What layouts are prone to double taxation?", Slide12::class.java, Slide13A::class.java) //Vertical LinearLayout class Slide13A : KtxScreen, Slide { val renderer = ShapeRenderer() val batch = SpriteBatch() var stage: Stage val texture = Texture(Gdx.files.internal("images/device.png")) val startingWidth = 300f val endingWidth = 580f var currentWidth = startingWidth val boxHeight = 150f val windowWidth = Gdx.graphics.width val windowHeight = Gdx.graphics.height init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) batch.use { it.draw(texture, 0f, 0f, Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat()) } currentWidth += (delta * 100f) if (currentWidth >= endingWidth) { currentWidth = startingWidth } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(Color.LIGHT_GRAY) translate(windowWidth / 2f - 300, windowHeight / 2f, 0f) rect(0f, 0f, currentWidth, boxHeight) end() } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(Color.LIGHT_GRAY) translate(windowWidth / 2f - 300, windowHeight / 2f - boxHeight - 16f, 0f) rect(0f, 0f, currentWidth, boxHeight) end() } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(Color.RED) translate(windowWidth / 2f - 300, windowHeight / 2f - boxHeight * 2 - 16f * 2, 0f) rect(0f, 0f, endingWidth, boxHeight) end() } stage.act() stage.draw() } override fun dispose() { // Will be automatically disposed of by the game instance. renderer.dispose() batch.dispose() } override fun nextPressed() { Presentation.setScreen(Slide13B::class.java) } override fun backPressed() { Presentation.setScreen(Slide13::class.java) } } class Slide13B : KtxScreen, Slide { val renderer = ShapeRenderer() val batch = SpriteBatch() var stage: Stage val texture = Texture(Gdx.files.internal("images/device.png")) val staticWidth = 100f val startingWidth = 100f val endingWidth = 350f var currentWidth = startingWidth val boxHeight = 150f val windowWidth = Gdx.graphics.width val windowHeight = Gdx.graphics.height init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) batch.use { it.draw(texture, 0f, 0f, Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat()) } currentWidth += (delta * 100f) if (currentWidth >= endingWidth) { currentWidth = startingWidth } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(Color.LIGHT_GRAY) translate(windowWidth / 2f - 300, windowHeight / 2f, 0f) rect(0f, 0f, staticWidth, boxHeight) end() } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 1f) translate(windowWidth / 2f - 300 + 16 + staticWidth, windowHeight / 2f, 0f) rect(0f, 0f, currentWidth, boxHeight) end() } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(Color.LIGHT_GRAY) translate(windowWidth / 2f - 300 + 16 + staticWidth + currentWidth + 16, windowHeight / 2f, 0f) rect(0f, 0f, staticWidth, boxHeight) end() } stage.act() stage.draw() } override fun dispose() { // Will be automatically disposed of by the game instance. renderer.dispose() batch.dispose() } override fun nextPressed() { Presentation.setScreen(Slide13C::class.java) } override fun backPressed() { Presentation.setScreen(Slide13A::class.java) } } class Slide13C : HeadlineSlide("RelativeLayout", Slide13B::class.java, Slide14::class.java) // TODO Insert Relative and Linear combined example. class Slide14 : HeadlineSlide("GridLayout", Slide13C::class.java, Slide15::class.java) class Slide15 : HeadlineSlide("What is ConstraintLayout?", Slide14::class.java, Slide16::class.java) class Slide16 : BulletsSlide("ConstraintLayout", listOf("Support library", "Available on API 9+ (Gingerbread)", "")) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide15::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide17::class.java) } } } class Slide17 : HeadlineSlide("What are constraints?", Slide16::class.java, Slide18::class.java) val definition = "A restriction or limitation on the properties of a View that the layout attempts to respect" class Slide18 : DefinitionSlide("What is a constraint?", definition, Slide17::class.java, Slide18A::class.java) class Slide18A : KtxScreen, Slide { override fun backPressed() = Presentation.setScreen(Slide18::class.java) override fun nextPressed() = Presentation.setScreen(Slide19::class.java) val textures = gdxArrayOf<Texture>( Texture("images/device.png"), Texture("images/device2.png"), Texture("images/device3.png"), Texture("images/device4.png")) var animation: Animation<Texture> var batch = SpriteBatch() var currentTime = 0f init { animation = Animation<Texture>(0.333f, textures, Animation.PlayMode.LOOP) setSlideContent() } override fun setSlideContent() {} override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) currentTime += delta val currentFrame = animation.getKeyFrame(currentTime, true) batch.use { it.draw(currentFrame, 0f, 0f, Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat()) } } override fun dispose() { // Will be automatically disposed of by the game instance. batch.dispose() } } class Slide19 : BulletsSlide("The New Layout Editor", listOf("Design View", "Blueprint View", "")) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide18A::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide20::class.java) } } } class Slide20 : BackgroundImageSlide(Gdx.files.internal("images/design-view.png"), stretchY, Slide19::class.java, Slide21::class.java) class Slide21 : BackgroundImageSlide(Gdx.files.internal("images/blueprint-view.png"), fit, Slide20::class.java, Slide22::class.java) class Slide22 : BackgroundImageSlide(Gdx.files.internal("images/attributes-view.png"), fit, Slide21::class.java, Slide22A::class.java) // Constraint labels class Slide22A() : KtxScreen, Slide { override fun backPressed() { if (showBaselineRectangle) { showBaselineRectangle = false labelBaseline.isVisible = false } else if (showBottomRectangle) { showBottomRectangle = false labelBottom.isVisible = false } else if (showTopRectangle) { showTopRectangle = false labelTop.isVisible = false } else { // Advance to previous slide Presentation.setScreen(Slide22::class.java) } } override fun nextPressed() { if (showTopRectangle == false) { showTopRectangle = true labelTop.isVisible = true } else if (showBottomRectangle == false) { showBottomRectangle = true labelBottom.isVisible = true } else if (showBaselineRectangle == false) { showBaselineRectangle = true labelBaseline.isVisible = true } else { // Advance to next slide Presentation.setScreen(Slide22B::class.java) } } var stage: Stage var renderer = ShapeRenderer() val label = headerLabel("[BLUE]A[]") val labelTop = bodyLabel("[YELLOW]top[]") val labelBottom = bodyLabel("[YELLOW]bottom[]") val labelBaseline = bodyLabel("[YELLOW]baseline[]") var showTopRectangle = false var showBottomRectangle = false var showBaselineRectangle = false val offset = 300f val halfWindowWidth = Gdx.graphics.width / 2f - offset val halfWindowHeight = Gdx.graphics.height / 2f val boxHeight = 250f val boxWidth = 500f init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { val titleLabel = headerLabel("Relative Positioning Constraints") TypingConfig.FORCE_COLOR_MARKUP_BY_DEFAULT = true titleLabel.centerX() titleLabel.y = Gdx.graphics.height - titleLabel.height - 16f // Position A label label.centerLabel() label.x = halfWindowWidth label.x += boxWidth / 2 label.y += boxHeight / 2 labelBottom.x = halfWindowWidth - labelBottom.width labelBottom.y = halfWindowHeight - labelBottom.height / 2 labelTop.x = halfWindowWidth - labelTop.width - 40f labelTop.y = halfWindowHeight - labelTop.height / 2 + 240f labelBaseline.x = halfWindowWidth + labelBaseline.width + 250f labelBaseline.y = halfWindowHeight - labelBaseline.height / 2 + 81f labelBottom.setFontScale(0.9f) labelTop.setFontScale(0.9f) labelBaseline.setFontScale(0.9f) labelBaseline.isVisible = false labelBottom.isVisible = false labelTop.isVisible = false with(stage) { addActor(titleLabel) addActor(label) // add labels and hide them addActor(labelBaseline) addActor(labelBottom) addActor(labelTop) } } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) // Draw the initial box with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(0f, 1f, 0f, 1f) translate(halfWindowWidth, halfWindowHeight, 0f) rect(0f, 0f, boxWidth, boxHeight) end() } if (showBottomRectangle) { // Draw bottom rectangle with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 0.5f) translate(halfWindowWidth, halfWindowHeight, 0f) rect(0f, 0f, boxWidth, boxHeight / 8.3333f) end() } } if (showTopRectangle) { // Draw top rectangle with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 0.5f) translate(halfWindowWidth, halfWindowHeight + 220f, 0f) rect(0f, 0f, 500f, 30f) end() } } if (showBaselineRectangle) { // Draw baseline with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 0.5f) translate(halfWindowWidth, halfWindowHeight + 61f, 0f) rect(0f, 0f, boxWidth, boxHeight / 8.3333f) end() } } stage.act() stage.draw() } override fun dispose() { // Will be automatically disposed of by the game instance. stage.dispose() renderer.dispose() } } class Slide22B() : KtxScreen, Slide { override fun backPressed() { if (showRightRectangle == true) { showRightRectangle = false labelRight.isVisible = false labelEnd.isVisible = false } else if (showLeftRectangle == true) { showLeftRectangle = false labelLeft.isVisible = false labelStart.isVisible = false } else { // Advance to previous slide Presentation.setScreen(Slide22A::class.java) } } override fun nextPressed() { if (showLeftRectangle == false) { showLeftRectangle = true labelLeft.isVisible = true labelStart.isVisible = true } else if (showRightRectangle == false) { showRightRectangle = true labelRight.isVisible = true labelEnd.isVisible = true } else { // Advance to next slide Presentation.setScreen(Slide22C::class.java) } } var stage: Stage var renderer = ShapeRenderer() val label = headerLabel("[BLUE]A[]") val labelLeft = bodyLabel("[YELLOW]left[]") val labelStart = bodyLabel("[YELLOW]start[]") val labelRight = bodyLabel("[YELLOW]right[]") val labelEnd = bodyLabel("[YELLOW]end[]") var showLeftRectangle = false var showRightRectangle = false val offset = 300f val halfWindowWidth = Gdx.graphics.width / 2f - offset val halfWindowHeight = Gdx.graphics.height / 2f val boxHeight = 250f val boxWidth = 500f init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { val titleLabel = headerLabel("Relative Positioning Constraints") TypingConfig.FORCE_COLOR_MARKUP_BY_DEFAULT = true titleLabel.centerX() titleLabel.y = Gdx.graphics.height - titleLabel.height - 16f // Position A label label.centerLabel() label.x = halfWindowWidth label.x += boxWidth / 2 label.y += boxHeight / 2 labelLeft.centerLabel() labelLeft.x = halfWindowWidth - labelLeft.width labelLeft.y = halfWindowHeight - labelLeft.height / 2 labelStart.centerLabel() labelStart.x = halfWindowWidth - labelStart.width labelStart.y = halfWindowHeight - labelStart.height / 2 - 90f labelRight.centerLabel() labelRight.x = halfWindowWidth - labelRight.width + boxWidth + 180f labelRight.y = halfWindowHeight - labelRight.height / 2 labelEnd.centerLabel() labelEnd.x = halfWindowWidth - labelEnd.width + boxWidth + 180f labelEnd.y = halfWindowHeight - labelEnd.height / 2 - 90f labelLeft.setFontScale(0.9f) labelRight.setFontScale(0.9f) labelStart.setFontScale(0.9f) labelEnd.setFontScale(0.9f) labelLeft.isVisible = false labelStart.isVisible = false labelEnd.isVisible = false labelRight.isVisible = false with(stage) { addActor(titleLabel) addActor(label) // add labels and hide them addActor(labelLeft) addActor(labelStart) addActor(labelEnd) addActor(labelRight) } } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) // Draw the initial box with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(0f, 1f, 0f, 1f) translate(halfWindowWidth, halfWindowHeight, 0f) rect(0f, 0f, boxWidth, boxHeight) end() } if (showLeftRectangle) { // Draw bottom rectangle with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 0.5f) translate(halfWindowWidth, halfWindowHeight, 0f) rect(0f, 0f, boxWidth / (8.3333f * 2), boxHeight) end() } } if (showRightRectangle) { // Draw top rectangle with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 0.5f) translate(halfWindowWidth + 470f, halfWindowHeight, 0f) rect(0f, 0f, boxWidth / (8.3333f * 2), boxHeight) end() } } stage.act() stage.draw() } override fun dispose() { // Will be automatically disposed of by the game instance. stage.dispose() renderer.dispose() } } class Slide22C() : BulletsSlide("Relative Positioning Constraints", listOf<String>( "layout_constraint[GREEN]SourceConstraint[]_to[RED]TargetConstraint[]Of", "layout_constraintStart_toEndOf", "layout_constraintRight_toRightOf", "" )) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide22B::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide23::class.java) } } } // Removing a constraint class Slide23 : HeadlineSlide("Clearing Constraints", Slide22C::class.java, Slide24::class.java) class Slide24 : BackgroundImageSlide(Gdx.files.internal("images/show-initial-constraints.png"), fit, Slide23::class.java, Slide25::class.java) class Slide25 : BackgroundImageSlide(Gdx.files.internal("images/delete-connection.png"), fit, Slide24::class.java, Slide26::class.java) class Slide26 : BackgroundImageSlide(Gdx.files.internal("images/delete-left-constraint.png"), fit, Slide25::class.java, Slide27::class.java) // Adding a constraint class Slide27 : HeadlineSlide("Adding Constraints", Slide26::class.java, Slide28::class.java) class Slide28 : BackgroundImageSlide(Gdx.files.internal("images/add-constraint1.png"), fit, Slide27::class.java, Slide29::class.java) class Slide29 : BackgroundImageSlide(Gdx.files.internal("images/add-constraint2.png"), fit, Slide28::class.java, Slide30::class.java) class Slide30 : BackgroundImageSlide(Gdx.files.internal("images/add-constraint3.png"), fit, Slide29::class.java, Slide31::class.java) class Slide31 : BackgroundImageSlide(Gdx.files.internal("images/add-constraint4.png"), fit, Slide30::class.java, Slide32::class.java) class Slide32 : BackgroundImageSlide(Gdx.files.internal("images/add-constraint5.png"), fit, Slide31::class.java, Slide33::class.java) class Slide33 : HeadlineSlide("Understanding The New Attributes View", Slide32::class.java, Slide34::class.java) class Slide34 : ConstraintSlide(AttributeBuilder.defaultConstraints, "wrap_content", "wrap_content", Slide33::class.java, Slide35::class.java) { override fun render(delta: Float) { super.render(delta) with(shapeRenderer) { begin(ShapeRenderer.ShapeType.Filled) setColor(Color.PINK) rect(400f, halfY, 200f, 80f) end() } // AttributeBuilder.drawSquigglyPipe(Vector2(5f, halfY + 20f),Vector2(250f, 50f), color=Color.YELLOW) // AttributeBuilder.drawSquigglyPipe(Vector2(505f, halfY + 20f),Vector2(250f, 50f), color=Color.YELLOW) // Constraint Handles AttributeBuilder.drawConstraintHandle(Vector2(380f, halfY + 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(580f, halfY + 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY + 60f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY - 20f), radius = 20f, color2 = Color.BLUE) } } val constraints = arrayOf(AttributeBuilder.ConstraintType.WRAP_CONTENT, AttributeBuilder.ConstraintType.WRAP_CONTENT, AttributeBuilder.ConstraintType.EXACT_SIZE, AttributeBuilder.ConstraintType.EXACT_SIZE ) class Slide35 : ConstraintSlide(constraints, "wrap_content", "19dp", Slide34::class.java, Slide36::class.java) { override fun render(delta: Float) { super.render(delta) with(shapeRenderer) { begin(ShapeRenderer.ShapeType.Filled) setColor(Color.PINK) rect(400f, halfY, 200f, 80f) end() } // AttributeBuilder.drawSquigglyPipe(Vector2(5f, halfY + 20f),Vector2(250f, 50f), color=Color.YELLOW) // AttributeBuilder.drawSquigglyPipe(Vector2(505f, halfY + 20f),Vector2(250f, 50f), color=Color.YELLOW) // Constraint Handles AttributeBuilder.drawConstraintHandle(Vector2(380f, halfY + 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(580f, halfY + 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY + 60f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY - 20f), radius = 20f, color2 = Color.BLUE) } } class Slide36 : ConstraintSlide(constraints, "wrap_content", "19dp", Slide35::class.java, Slide37::class.java) { override fun render(delta: Float) { super.render(delta) with(shapeRenderer) { begin(ShapeRenderer.ShapeType.Filled) setColor(Color.PINK) rect(400f, halfY, 200f, 80f) end() } // Constraint Handles AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY + 60f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY - 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawSquigglyPipe(Vector2(5f, halfY + 20f), Vector2(395f, 50f), color = Color.YELLOW) AttributeBuilder.drawSquigglyPipe(Vector2(600f, halfY + 20f), Vector2(420f, 50f), color = Color.YELLOW) } } val slide37_constraints = arrayOf( AttributeBuilder.ConstraintType.CONSTRAINT, AttributeBuilder.ConstraintType.CONSTRAINT, AttributeBuilder.ConstraintType.EXACT_SIZE, AttributeBuilder.ConstraintType.EXACT_SIZE ) class Slide37 : ConstraintSlide(slide37_constraints, "match_constraint", "19dp ", Slide36::class.java, Slide38::class.java) { override fun render(delta: Float) { super.render(delta) with(shapeRenderer) { begin(ShapeRenderer.ShapeType.Filled) setColor(Color.PINK) rect(65f, halfY, 900f, 80f) end() } // Constraint Handles AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY + 60f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY - 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawSquigglyPipe(Vector2(5f, halfY + 20f), Vector2(60f, 50f), color = Color.YELLOW) AttributeBuilder.drawSquigglyPipe(Vector2(965f, halfY + 20f), Vector2(55f, 50f), color = Color.YELLOW) } } class Slide38 : HeadlineSlide("A word about MATCH_PARENT", Slide37::class.java, Slide40::class.java) class Slide40 : HeadlineSlide("Chains", Slide38::class.java, Slide40A::class.java) class Slide40A : DefinitionSlide("Chains", "Views linked together with bidirectional positional constraints. Can replace LinearLayouts in many cases.", Slide40::class.java, Slide41::class.java) class Slide41 : ConstraintSlide(constraints, "wrap_content", "19dp", Slide40A::class.java, Slide43::class.java) { override fun render(delta: Float) { super.render(delta) with(shapeRenderer) { begin(ShapeRenderer.ShapeType.Filled) setColor(Color.PINK) rect(300f, halfY, 150f, 80f) rect(700f, halfY, 150f, 80f) end() } ChainBuilder.makeChainLink(250f, 35f, Vector2(450f, halfY+30f),color2 = uiBackgroundColor) // Constraint Handles //AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY + 60f), radius = 20f, color2 = Color.BLUE) //AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY - 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawSquigglyPipe(Vector2(5f, halfY + 20f), Vector2(295f, 50f), color = Color.YELLOW) AttributeBuilder.drawSquigglyPipe(Vector2(850f, halfY + 20f), Vector2(170f, 50f), color = Color.YELLOW) } } class Slide43 : BackgroundImageSlide(Gdx.files.internal("images/chain-types.png"), fit, Slide41::class.java, Slide45::class.java) class Slide45 : HeadlineSlide("Virtual Helper Objects", Slide43::class.java, Slide46::class.java) class Slide46 : BulletsSlide("Virtual Helper Objects", listOf("Guidelines", "Barriers", "Groups", "")) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide45::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide47::class.java) } } } class Slide47 : HeadlineSlide("Guidelines", Slide46::class.java, Slide47A::class.java) val slide47A_definition = "Allow multiple widgets to be aligned from a single virtual object" class Slide47A : DefinitionSlide("Guidelines", slide47A_definition, Slide47::class.java, Slide48::class.java) class Slide48 : BackgroundImageSlide(Gdx.files.internal("images/guidelines-blueprint.png"), fit, Slide47A::class.java, Slide49::class.java) val codeString = Gdx.files.internal("code/guidelines.txt.out").readString() class Slide49 : CodeSlide("Guidelines", codeString, Slide48::class.java, Slide50::class.java) class Slide50 : HeadlineSlide("Barriers", Slide49::class.java, Slide51::class.java) val slide51_definition = "Allows widgets to be aligned based on the one with the largest value" class Slide51 : DefinitionSlide("Barriers", slide51_definition, Slide50::class.java, Slide52::class.java) val slide52_code = Gdx.files.internal("code/barrier-code.txt.out").readString() class Slide52 : CodeSlide("Barriers", slide52_code, Slide51::class.java, Slide53::class.java) class Slide53 : HeadlineSlide("Groups", Slide52::class.java, Slide53A::class.java) val slide53A_definition = "Control the visibility of a set of widgets." class Slide53A : DefinitionSlide("Groups", slide53A_definition, Slide53::class.java, Slide54::class.java) class Slide54 : BackgroundImageSlide(Gdx.files.internal("images/groups-example.png"), Scaling.fillY, Slide53A::class.java, Slide54A::class.java) val slide54_code = Gdx.files.internal("code/groups-code.txt.out").readString() class Slide54A : CodeSlide("Groups", slide54_code, Slide54::class.java, Slide55::class.java) val slide55_code = Gdx.files.internal("code/groups-detail.txt.out").readString() class Slide55 : CodeSlide("Groups", slide55_code, Slide54::class.java, Slide56::class.java) class Slide56 : HeadlineSlide("Placeholders", Slide55::class.java, Slide57::class.java) class Slide57 : HeadlineSlide("setContentId(...)", Slide56::class.java, Slide59::class.java) class Slide59 : HeadlineSlide("Circular Positioning", Slide57::class.java, Slide60::class.java) class Slide60 : KtxScreen, Slide { var stage: Stage var shapeRenderer = ShapeRenderer() var degrees = 0f init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { val label = headerLabel("Circular Positioning") label.centerLabel() stage.addActor(label) } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) shapeRenderer.setAutoShapeType(true) shapeRenderer.begin(ShapeRenderer.ShapeType.Filled) shapeRenderer.setColor(Color.ORANGE) shapeRenderer.identity() // Place circle in center shapeRenderer.translate(Gdx.graphics.width / 2f, Gdx.graphics.height / 2f, 0f) shapeRenderer.circle(0f, 0f, 50f) shapeRenderer.end() // Draw earth shapeRenderer.begin(ShapeRenderer.ShapeType.Filled) shapeRenderer.identity() degrees += (delta * 30f) if (degrees > 360f) degrees = 0f shapeRenderer.translate(Gdx.graphics.width / 2f, Gdx.graphics.height / 2f, 0f) shapeRenderer.rotate(0f, 0f, 1f, degrees) shapeRenderer.setColor(Color.CYAN) shapeRenderer.circle(250f, 0f, 10f) shapeRenderer.end() stage.act() stage.draw() } override fun dispose() { // Will be automatically disposed of by the game instance. shapeRenderer.dispose() } override fun backPressed() { Presentation.setScreen(Slide59::class.java) } override fun nextPressed() { Presentation.setScreen(Slide61::class.java) } } class Slide61 : CodeSlide("Circular Positioning", Gdx.files.internal("code/circular-code.txt.out").readString(), Slide60::class.java, Slide62::class.java) class Slide62 : HeadlineSlide("Udacity is hiring!",Slide61::class.java, EndSlide::class.java) class EndSlide : HeadlineSlide("Any Questions?", Slide62::class.java)
0
Kotlin
1
0
33b4e797f69988bd33deb3277fc6866159f3afd1
36,359
refactored-robot
MIT License
core/src/main/kotlin/be/jameswilliams/preso/slides/Slides.kt
jwill
116,086,860
false
null
package be.jameswilliams.preso.slides import be.jameswilliams.preso.* import be.jameswilliams.preso.templates.* import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.math.Interpolation import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.ui.Image import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.Table import com.badlogic.gdx.scenes.scene2d.ui.VerticalGroup import com.badlogic.gdx.utils.Scaling import com.badlogic.gdx.utils.Scaling.fit import com.badlogic.gdx.utils.Scaling.stretchY import com.badlogic.gdx.utils.viewport.ScreenViewport import com.rafaskoberg.gdx.typinglabel.TypingConfig import ktx.app.KtxScreen import ktx.app.clearScreen import ktx.app.use import ktx.collections.gdxArrayOf import ktx.scene2d.slider import ktx.scene2d.table // This is where slides live until they deserve // their own file class Slide0() : KtxScreen, Slide { var table = Table() var verticalGroup = VerticalGroup() val batch = SpriteBatch() var stage: Stage init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { val title = headerLabel("Demystifying ConstraintLayout") val texture = Texture(Gdx.files.internal("images/james-emoji-circular.png")) val image = Image(texture) val name = bodyLabel("<NAME>") val twitterId = bodyLabel("@ecspike") val twitterIcon = iconLabel("\uf099") twitterIcon.setFontScale(0.5f) title.centerLabel() name.centerLabel() name.y -= name.height * 2 twitterId.centerLabel() twitterId.y -= (twitterId.height * 3) image.setSize(150f, 150f) image.x = name.x - 200f image.y = name.y - 80f with(stage) { addActor(image) addActor(title) addActor(name) //addActor(twitterIcon) addActor(twitterId) } } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) stage.act() stage.draw() } override fun nextPressed() { Presentation.setScreen(Slide1::class.java) } override fun backPressed() { // NO OP } } class Slide1 : KtxScreen, Slide { var table = Table() var verticalGroup = VerticalGroup() val batch = SpriteBatch() lateinit var udacityLogo: Texture var stage: Stage lateinit var label: Label init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { udacityLogo = Texture(Gdx.files.internal("images/udacity-240-white.jpg")) label = headerLabel("I work at Udacity. I'm Curriculum Lead for Android.") label.centerLabel() stage.addActor(label) } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) stage.act() stage.draw() batch.use { var x = (Gdx.graphics.width - udacityLogo.width) / 2f it.draw(udacityLogo, x, (Gdx.graphics.height / 2 - (2 * label.height + 50))) } } override fun dispose() { // Will be automatically disposed of by the game instance. batch.dispose() } override fun nextPressed() { Presentation.setScreen(Slide2::class.java) } override fun backPressed() { Presentation.setScreen(Slide0::class.java) } } class Slide2 : HeadlineSlide("The Android View Rendering Cycle", Slide1::class.java, Slide3::class.java) class Slide3 : BulletsSlide("The Android View Rendering Cycle", listOf("Measure Pass", "Layout Pass", "Drawing The Things", "")) { override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide5::class.java) } } override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide2::class.java) } } } class Slide5 : HeadlineSlide("Measuring A View", Slide3::class.java, Slide6::class.java) class Slide6 : HeadlineSlide("onMeasure(widthMeasureSpec, heightMeasureSpec)", Slide5::class.java, Slide7::class.java) class Slide7 : BulletsSlide("MeasureSpec", listOf("mode", "size", "")) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide6::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide8::class.java) } } } class Slide8 : BulletsSlide("MeasureSpec Modes", listOf("EXACTLY", "AT MOST", "UNSPECIFIED", "")) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide7::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide10::class.java) } } } class Slide10 : HeadlineSlide("Double Taxation", Slide8::class.java, Slide10A::class.java) val slide10A_definition = "Android has to do multiple measure passes to" + " determine the final positions of a View" class Slide10A : DefinitionSlide("What is double taxation?", slide10A_definition, Slide10::class.java, Slide11::class.java) class Slide11 : HeadlineSlide("Why is this Important?", Slide10A::class.java, Slide12::class.java) class Slide12 : HeadlineSlide("16ms*", Slide11::class.java, Slide13::class.java) class Slide13 : HeadlineSlide("What layouts are prone to double taxation?", Slide12::class.java, Slide13A::class.java) //Vertical LinearLayout class Slide13A : KtxScreen, Slide { val renderer = ShapeRenderer() val batch = SpriteBatch() var stage: Stage val texture = Texture(Gdx.files.internal("images/device.png")) val startingWidth = 300f val endingWidth = 580f var currentWidth = startingWidth val boxHeight = 150f val windowWidth = Gdx.graphics.width val windowHeight = Gdx.graphics.height init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) batch.use { it.draw(texture, 0f, 0f, Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat()) } currentWidth += (delta * 100f) if (currentWidth >= endingWidth) { currentWidth = startingWidth } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(Color.LIGHT_GRAY) translate(windowWidth / 2f - 300, windowHeight / 2f, 0f) rect(0f, 0f, currentWidth, boxHeight) end() } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(Color.LIGHT_GRAY) translate(windowWidth / 2f - 300, windowHeight / 2f - boxHeight - 16f, 0f) rect(0f, 0f, currentWidth, boxHeight) end() } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(Color.RED) translate(windowWidth / 2f - 300, windowHeight / 2f - boxHeight * 2 - 16f * 2, 0f) rect(0f, 0f, endingWidth, boxHeight) end() } stage.act() stage.draw() } override fun dispose() { // Will be automatically disposed of by the game instance. renderer.dispose() batch.dispose() } override fun nextPressed() { Presentation.setScreen(Slide13B::class.java) } override fun backPressed() { Presentation.setScreen(Slide13::class.java) } } class Slide13B : KtxScreen, Slide { val renderer = ShapeRenderer() val batch = SpriteBatch() var stage: Stage val texture = Texture(Gdx.files.internal("images/device.png")) val staticWidth = 100f val startingWidth = 100f val endingWidth = 350f var currentWidth = startingWidth val boxHeight = 150f val windowWidth = Gdx.graphics.width val windowHeight = Gdx.graphics.height init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) batch.use { it.draw(texture, 0f, 0f, Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat()) } currentWidth += (delta * 100f) if (currentWidth >= endingWidth) { currentWidth = startingWidth } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(Color.LIGHT_GRAY) translate(windowWidth / 2f - 300, windowHeight / 2f, 0f) rect(0f, 0f, staticWidth, boxHeight) end() } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 1f) translate(windowWidth / 2f - 300 + 16 + staticWidth, windowHeight / 2f, 0f) rect(0f, 0f, currentWidth, boxHeight) end() } with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(Color.LIGHT_GRAY) translate(windowWidth / 2f - 300 + 16 + staticWidth + currentWidth + 16, windowHeight / 2f, 0f) rect(0f, 0f, staticWidth, boxHeight) end() } stage.act() stage.draw() } override fun dispose() { // Will be automatically disposed of by the game instance. renderer.dispose() batch.dispose() } override fun nextPressed() { Presentation.setScreen(Slide13C::class.java) } override fun backPressed() { Presentation.setScreen(Slide13A::class.java) } } class Slide13C : HeadlineSlide("RelativeLayout", Slide13B::class.java, Slide14::class.java) // TODO Insert Relative and Linear combined example. class Slide14 : HeadlineSlide("GridLayout", Slide13C::class.java, Slide15::class.java) class Slide15 : HeadlineSlide("What is ConstraintLayout?", Slide14::class.java, Slide16::class.java) class Slide16 : BulletsSlide("ConstraintLayout", listOf("Support library", "Available on API 9+ (Gingerbread)", "")) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide15::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide17::class.java) } } } class Slide17 : HeadlineSlide("What are constraints?", Slide16::class.java, Slide18::class.java) val definition = "A restriction or limitation on the properties of a View that the layout attempts to respect" class Slide18 : DefinitionSlide("What is a constraint?", definition, Slide17::class.java, Slide18A::class.java) class Slide18A : KtxScreen, Slide { override fun backPressed() = Presentation.setScreen(Slide18::class.java) override fun nextPressed() = Presentation.setScreen(Slide19::class.java) val textures = gdxArrayOf<Texture>( Texture("images/device.png"), Texture("images/device2.png"), Texture("images/device3.png"), Texture("images/device4.png")) var animation: Animation<Texture> var batch = SpriteBatch() var currentTime = 0f init { animation = Animation<Texture>(0.333f, textures, Animation.PlayMode.LOOP) setSlideContent() } override fun setSlideContent() {} override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) currentTime += delta val currentFrame = animation.getKeyFrame(currentTime, true) batch.use { it.draw(currentFrame, 0f, 0f, Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat()) } } override fun dispose() { // Will be automatically disposed of by the game instance. batch.dispose() } } class Slide19 : BulletsSlide("The New Layout Editor", listOf("Design View", "Blueprint View", "")) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide18A::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide20::class.java) } } } class Slide20 : BackgroundImageSlide(Gdx.files.internal("images/design-view.png"), stretchY, Slide19::class.java, Slide21::class.java) class Slide21 : BackgroundImageSlide(Gdx.files.internal("images/blueprint-view.png"), fit, Slide20::class.java, Slide22::class.java) class Slide22 : BackgroundImageSlide(Gdx.files.internal("images/attributes-view.png"), fit, Slide21::class.java, Slide22A::class.java) // Constraint labels class Slide22A() : KtxScreen, Slide { override fun backPressed() { if (showBaselineRectangle) { showBaselineRectangle = false labelBaseline.isVisible = false } else if (showBottomRectangle) { showBottomRectangle = false labelBottom.isVisible = false } else if (showTopRectangle) { showTopRectangle = false labelTop.isVisible = false } else { // Advance to previous slide Presentation.setScreen(Slide22::class.java) } } override fun nextPressed() { if (showTopRectangle == false) { showTopRectangle = true labelTop.isVisible = true } else if (showBottomRectangle == false) { showBottomRectangle = true labelBottom.isVisible = true } else if (showBaselineRectangle == false) { showBaselineRectangle = true labelBaseline.isVisible = true } else { // Advance to next slide Presentation.setScreen(Slide22B::class.java) } } var stage: Stage var renderer = ShapeRenderer() val label = headerLabel("[BLUE]A[]") val labelTop = bodyLabel("[YELLOW]top[]") val labelBottom = bodyLabel("[YELLOW]bottom[]") val labelBaseline = bodyLabel("[YELLOW]baseline[]") var showTopRectangle = false var showBottomRectangle = false var showBaselineRectangle = false val offset = 300f val halfWindowWidth = Gdx.graphics.width / 2f - offset val halfWindowHeight = Gdx.graphics.height / 2f val boxHeight = 250f val boxWidth = 500f init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { val titleLabel = headerLabel("Relative Positioning Constraints") TypingConfig.FORCE_COLOR_MARKUP_BY_DEFAULT = true titleLabel.centerX() titleLabel.y = Gdx.graphics.height - titleLabel.height - 16f // Position A label label.centerLabel() label.x = halfWindowWidth label.x += boxWidth / 2 label.y += boxHeight / 2 labelBottom.x = halfWindowWidth - labelBottom.width labelBottom.y = halfWindowHeight - labelBottom.height / 2 labelTop.x = halfWindowWidth - labelTop.width - 40f labelTop.y = halfWindowHeight - labelTop.height / 2 + 240f labelBaseline.x = halfWindowWidth + labelBaseline.width + 250f labelBaseline.y = halfWindowHeight - labelBaseline.height / 2 + 81f labelBottom.setFontScale(0.9f) labelTop.setFontScale(0.9f) labelBaseline.setFontScale(0.9f) labelBaseline.isVisible = false labelBottom.isVisible = false labelTop.isVisible = false with(stage) { addActor(titleLabel) addActor(label) // add labels and hide them addActor(labelBaseline) addActor(labelBottom) addActor(labelTop) } } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) // Draw the initial box with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(0f, 1f, 0f, 1f) translate(halfWindowWidth, halfWindowHeight, 0f) rect(0f, 0f, boxWidth, boxHeight) end() } if (showBottomRectangle) { // Draw bottom rectangle with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 0.5f) translate(halfWindowWidth, halfWindowHeight, 0f) rect(0f, 0f, boxWidth, boxHeight / 8.3333f) end() } } if (showTopRectangle) { // Draw top rectangle with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 0.5f) translate(halfWindowWidth, halfWindowHeight + 220f, 0f) rect(0f, 0f, 500f, 30f) end() } } if (showBaselineRectangle) { // Draw baseline with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 0.5f) translate(halfWindowWidth, halfWindowHeight + 61f, 0f) rect(0f, 0f, boxWidth, boxHeight / 8.3333f) end() } } stage.act() stage.draw() } override fun dispose() { // Will be automatically disposed of by the game instance. stage.dispose() renderer.dispose() } } class Slide22B() : KtxScreen, Slide { override fun backPressed() { if (showRightRectangle == true) { showRightRectangle = false labelRight.isVisible = false labelEnd.isVisible = false } else if (showLeftRectangle == true) { showLeftRectangle = false labelLeft.isVisible = false labelStart.isVisible = false } else { // Advance to previous slide Presentation.setScreen(Slide22A::class.java) } } override fun nextPressed() { if (showLeftRectangle == false) { showLeftRectangle = true labelLeft.isVisible = true labelStart.isVisible = true } else if (showRightRectangle == false) { showRightRectangle = true labelRight.isVisible = true labelEnd.isVisible = true } else { // Advance to next slide Presentation.setScreen(Slide22C::class.java) } } var stage: Stage var renderer = ShapeRenderer() val label = headerLabel("[BLUE]A[]") val labelLeft = bodyLabel("[YELLOW]left[]") val labelStart = bodyLabel("[YELLOW]start[]") val labelRight = bodyLabel("[YELLOW]right[]") val labelEnd = bodyLabel("[YELLOW]end[]") var showLeftRectangle = false var showRightRectangle = false val offset = 300f val halfWindowWidth = Gdx.graphics.width / 2f - offset val halfWindowHeight = Gdx.graphics.height / 2f val boxHeight = 250f val boxWidth = 500f init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { val titleLabel = headerLabel("Relative Positioning Constraints") TypingConfig.FORCE_COLOR_MARKUP_BY_DEFAULT = true titleLabel.centerX() titleLabel.y = Gdx.graphics.height - titleLabel.height - 16f // Position A label label.centerLabel() label.x = halfWindowWidth label.x += boxWidth / 2 label.y += boxHeight / 2 labelLeft.centerLabel() labelLeft.x = halfWindowWidth - labelLeft.width labelLeft.y = halfWindowHeight - labelLeft.height / 2 labelStart.centerLabel() labelStart.x = halfWindowWidth - labelStart.width labelStart.y = halfWindowHeight - labelStart.height / 2 - 90f labelRight.centerLabel() labelRight.x = halfWindowWidth - labelRight.width + boxWidth + 180f labelRight.y = halfWindowHeight - labelRight.height / 2 labelEnd.centerLabel() labelEnd.x = halfWindowWidth - labelEnd.width + boxWidth + 180f labelEnd.y = halfWindowHeight - labelEnd.height / 2 - 90f labelLeft.setFontScale(0.9f) labelRight.setFontScale(0.9f) labelStart.setFontScale(0.9f) labelEnd.setFontScale(0.9f) labelLeft.isVisible = false labelStart.isVisible = false labelEnd.isVisible = false labelRight.isVisible = false with(stage) { addActor(titleLabel) addActor(label) // add labels and hide them addActor(labelLeft) addActor(labelStart) addActor(labelEnd) addActor(labelRight) } } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) // Draw the initial box with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(0f, 1f, 0f, 1f) translate(halfWindowWidth, halfWindowHeight, 0f) rect(0f, 0f, boxWidth, boxHeight) end() } if (showLeftRectangle) { // Draw bottom rectangle with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 0.5f) translate(halfWindowWidth, halfWindowHeight, 0f) rect(0f, 0f, boxWidth / (8.3333f * 2), boxHeight) end() } } if (showRightRectangle) { // Draw top rectangle with(renderer) { begin(ShapeRenderer.ShapeType.Filled) identity() setColor(1f, 0f, 0f, 0.5f) translate(halfWindowWidth + 470f, halfWindowHeight, 0f) rect(0f, 0f, boxWidth / (8.3333f * 2), boxHeight) end() } } stage.act() stage.draw() } override fun dispose() { // Will be automatically disposed of by the game instance. stage.dispose() renderer.dispose() } } class Slide22C() : BulletsSlide("Relative Positioning Constraints", listOf<String>( "layout_constraint[GREEN]SourceConstraint[]_to[RED]TargetConstraint[]Of", "layout_constraintStart_toEndOf", "layout_constraintRight_toRightOf", "" )) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide22B::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide23::class.java) } } } // Removing a constraint class Slide23 : HeadlineSlide("Clearing Constraints", Slide22C::class.java, Slide24::class.java) class Slide24 : BackgroundImageSlide(Gdx.files.internal("images/show-initial-constraints.png"), fit, Slide23::class.java, Slide25::class.java) class Slide25 : BackgroundImageSlide(Gdx.files.internal("images/delete-connection.png"), fit, Slide24::class.java, Slide26::class.java) class Slide26 : BackgroundImageSlide(Gdx.files.internal("images/delete-left-constraint.png"), fit, Slide25::class.java, Slide27::class.java) // Adding a constraint class Slide27 : HeadlineSlide("Adding Constraints", Slide26::class.java, Slide28::class.java) class Slide28 : BackgroundImageSlide(Gdx.files.internal("images/add-constraint1.png"), fit, Slide27::class.java, Slide29::class.java) class Slide29 : BackgroundImageSlide(Gdx.files.internal("images/add-constraint2.png"), fit, Slide28::class.java, Slide30::class.java) class Slide30 : BackgroundImageSlide(Gdx.files.internal("images/add-constraint3.png"), fit, Slide29::class.java, Slide31::class.java) class Slide31 : BackgroundImageSlide(Gdx.files.internal("images/add-constraint4.png"), fit, Slide30::class.java, Slide32::class.java) class Slide32 : BackgroundImageSlide(Gdx.files.internal("images/add-constraint5.png"), fit, Slide31::class.java, Slide33::class.java) class Slide33 : HeadlineSlide("Understanding The New Attributes View", Slide32::class.java, Slide34::class.java) class Slide34 : ConstraintSlide(AttributeBuilder.defaultConstraints, "wrap_content", "wrap_content", Slide33::class.java, Slide35::class.java) { override fun render(delta: Float) { super.render(delta) with(shapeRenderer) { begin(ShapeRenderer.ShapeType.Filled) setColor(Color.PINK) rect(400f, halfY, 200f, 80f) end() } // AttributeBuilder.drawSquigglyPipe(Vector2(5f, halfY + 20f),Vector2(250f, 50f), color=Color.YELLOW) // AttributeBuilder.drawSquigglyPipe(Vector2(505f, halfY + 20f),Vector2(250f, 50f), color=Color.YELLOW) // Constraint Handles AttributeBuilder.drawConstraintHandle(Vector2(380f, halfY + 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(580f, halfY + 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY + 60f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY - 20f), radius = 20f, color2 = Color.BLUE) } } val constraints = arrayOf(AttributeBuilder.ConstraintType.WRAP_CONTENT, AttributeBuilder.ConstraintType.WRAP_CONTENT, AttributeBuilder.ConstraintType.EXACT_SIZE, AttributeBuilder.ConstraintType.EXACT_SIZE ) class Slide35 : ConstraintSlide(constraints, "wrap_content", "19dp", Slide34::class.java, Slide36::class.java) { override fun render(delta: Float) { super.render(delta) with(shapeRenderer) { begin(ShapeRenderer.ShapeType.Filled) setColor(Color.PINK) rect(400f, halfY, 200f, 80f) end() } // AttributeBuilder.drawSquigglyPipe(Vector2(5f, halfY + 20f),Vector2(250f, 50f), color=Color.YELLOW) // AttributeBuilder.drawSquigglyPipe(Vector2(505f, halfY + 20f),Vector2(250f, 50f), color=Color.YELLOW) // Constraint Handles AttributeBuilder.drawConstraintHandle(Vector2(380f, halfY + 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(580f, halfY + 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY + 60f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY - 20f), radius = 20f, color2 = Color.BLUE) } } class Slide36 : ConstraintSlide(constraints, "wrap_content", "19dp", Slide35::class.java, Slide37::class.java) { override fun render(delta: Float) { super.render(delta) with(shapeRenderer) { begin(ShapeRenderer.ShapeType.Filled) setColor(Color.PINK) rect(400f, halfY, 200f, 80f) end() } // Constraint Handles AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY + 60f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY - 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawSquigglyPipe(Vector2(5f, halfY + 20f), Vector2(395f, 50f), color = Color.YELLOW) AttributeBuilder.drawSquigglyPipe(Vector2(600f, halfY + 20f), Vector2(420f, 50f), color = Color.YELLOW) } } val slide37_constraints = arrayOf( AttributeBuilder.ConstraintType.CONSTRAINT, AttributeBuilder.ConstraintType.CONSTRAINT, AttributeBuilder.ConstraintType.EXACT_SIZE, AttributeBuilder.ConstraintType.EXACT_SIZE ) class Slide37 : ConstraintSlide(slide37_constraints, "match_constraint", "19dp ", Slide36::class.java, Slide38::class.java) { override fun render(delta: Float) { super.render(delta) with(shapeRenderer) { begin(ShapeRenderer.ShapeType.Filled) setColor(Color.PINK) rect(65f, halfY, 900f, 80f) end() } // Constraint Handles AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY + 60f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY - 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawSquigglyPipe(Vector2(5f, halfY + 20f), Vector2(60f, 50f), color = Color.YELLOW) AttributeBuilder.drawSquigglyPipe(Vector2(965f, halfY + 20f), Vector2(55f, 50f), color = Color.YELLOW) } } class Slide38 : HeadlineSlide("A word about MATCH_PARENT", Slide37::class.java, Slide40::class.java) class Slide40 : HeadlineSlide("Chains", Slide38::class.java, Slide40A::class.java) class Slide40A : DefinitionSlide("Chains", "Views linked together with bidirectional positional constraints. Can replace LinearLayouts in many cases.", Slide40::class.java, Slide41::class.java) class Slide41 : ConstraintSlide(constraints, "wrap_content", "19dp", Slide40A::class.java, Slide43::class.java) { override fun render(delta: Float) { super.render(delta) with(shapeRenderer) { begin(ShapeRenderer.ShapeType.Filled) setColor(Color.PINK) rect(300f, halfY, 150f, 80f) rect(700f, halfY, 150f, 80f) end() } ChainBuilder.makeChainLink(250f, 35f, Vector2(450f, halfY+30f),color2 = uiBackgroundColor) // Constraint Handles //AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY + 60f), radius = 20f, color2 = Color.BLUE) //AttributeBuilder.drawConstraintHandle(Vector2(480f, halfY - 20f), radius = 20f, color2 = Color.BLUE) AttributeBuilder.drawSquigglyPipe(Vector2(5f, halfY + 20f), Vector2(295f, 50f), color = Color.YELLOW) AttributeBuilder.drawSquigglyPipe(Vector2(850f, halfY + 20f), Vector2(170f, 50f), color = Color.YELLOW) } } class Slide43 : BackgroundImageSlide(Gdx.files.internal("images/chain-types.png"), fit, Slide41::class.java, Slide45::class.java) class Slide45 : HeadlineSlide("Virtual Helper Objects", Slide43::class.java, Slide46::class.java) class Slide46 : BulletsSlide("Virtual Helper Objects", listOf("Guidelines", "Barriers", "Groups", "")) { override fun backPressed() { var result = super.bullets.goBack() if (result == false) { Presentation.setScreen(Slide45::class.java) } } override fun nextPressed() { var result = super.bullets.showNext() if (result == false) { Presentation.setScreen(Slide47::class.java) } } } class Slide47 : HeadlineSlide("Guidelines", Slide46::class.java, Slide47A::class.java) val slide47A_definition = "Allow multiple widgets to be aligned from a single virtual object" class Slide47A : DefinitionSlide("Guidelines", slide47A_definition, Slide47::class.java, Slide48::class.java) class Slide48 : BackgroundImageSlide(Gdx.files.internal("images/guidelines-blueprint.png"), fit, Slide47A::class.java, Slide49::class.java) val codeString = Gdx.files.internal("code/guidelines.txt.out").readString() class Slide49 : CodeSlide("Guidelines", codeString, Slide48::class.java, Slide50::class.java) class Slide50 : HeadlineSlide("Barriers", Slide49::class.java, Slide51::class.java) val slide51_definition = "Allows widgets to be aligned based on the one with the largest value" class Slide51 : DefinitionSlide("Barriers", slide51_definition, Slide50::class.java, Slide52::class.java) val slide52_code = Gdx.files.internal("code/barrier-code.txt.out").readString() class Slide52 : CodeSlide("Barriers", slide52_code, Slide51::class.java, Slide53::class.java) class Slide53 : HeadlineSlide("Groups", Slide52::class.java, Slide53A::class.java) val slide53A_definition = "Control the visibility of a set of widgets." class Slide53A : DefinitionSlide("Groups", slide53A_definition, Slide53::class.java, Slide54::class.java) class Slide54 : BackgroundImageSlide(Gdx.files.internal("images/groups-example.png"), Scaling.fillY, Slide53A::class.java, Slide54A::class.java) val slide54_code = Gdx.files.internal("code/groups-code.txt.out").readString() class Slide54A : CodeSlide("Groups", slide54_code, Slide54::class.java, Slide55::class.java) val slide55_code = Gdx.files.internal("code/groups-detail.txt.out").readString() class Slide55 : CodeSlide("Groups", slide55_code, Slide54::class.java, Slide56::class.java) class Slide56 : HeadlineSlide("Placeholders", Slide55::class.java, Slide57::class.java) class Slide57 : HeadlineSlide("setContentId(...)", Slide56::class.java, Slide59::class.java) class Slide59 : HeadlineSlide("Circular Positioning", Slide57::class.java, Slide60::class.java) class Slide60 : KtxScreen, Slide { var stage: Stage var shapeRenderer = ShapeRenderer() var degrees = 0f init { stage = Stage(ScreenViewport()) setSlideContent() } override fun setSlideContent() { val label = headerLabel("Circular Positioning") label.centerLabel() stage.addActor(label) } override fun render(delta: Float) { val bg = Presentation.theme.backgroundColor clearScreen(bg.r, bg.g, bg.b, bg.a) shapeRenderer.setAutoShapeType(true) shapeRenderer.begin(ShapeRenderer.ShapeType.Filled) shapeRenderer.setColor(Color.ORANGE) shapeRenderer.identity() // Place circle in center shapeRenderer.translate(Gdx.graphics.width / 2f, Gdx.graphics.height / 2f, 0f) shapeRenderer.circle(0f, 0f, 50f) shapeRenderer.end() // Draw earth shapeRenderer.begin(ShapeRenderer.ShapeType.Filled) shapeRenderer.identity() degrees += (delta * 30f) if (degrees > 360f) degrees = 0f shapeRenderer.translate(Gdx.graphics.width / 2f, Gdx.graphics.height / 2f, 0f) shapeRenderer.rotate(0f, 0f, 1f, degrees) shapeRenderer.setColor(Color.CYAN) shapeRenderer.circle(250f, 0f, 10f) shapeRenderer.end() stage.act() stage.draw() } override fun dispose() { // Will be automatically disposed of by the game instance. shapeRenderer.dispose() } override fun backPressed() { Presentation.setScreen(Slide59::class.java) } override fun nextPressed() { Presentation.setScreen(Slide61::class.java) } } class Slide61 : CodeSlide("Circular Positioning", Gdx.files.internal("code/circular-code.txt.out").readString(), Slide60::class.java, Slide62::class.java) class Slide62 : HeadlineSlide("Udacity is hiring!",Slide61::class.java, EndSlide::class.java) class EndSlide : HeadlineSlide("Any Questions?", Slide62::class.java)
0
Kotlin
1
0
33b4e797f69988bd33deb3277fc6866159f3afd1
36,359
refactored-robot
MIT License
src/main/kotlin/com/hkmod/soluna/common/util/DevUtil.kt
HKMOD
525,047,786
false
{"Kotlin": 27261}
package com.hkmod.soluna.common.util import com.hkmod.soluna.Soluna import net.minecraftforge.fml.loading.FMLEnvironment fun devException(message: String) { if (FMLEnvironment.production) { Soluna.LOGGER.error(message) } else { throw IllegalStateException(message) } }
0
Kotlin
0
1
596423f0cbf7eaca09f3eb340458b9f7face640e
298
Soluna
MIT License
kotlin/Learning/range.kt
Ethic41
131,386,984
false
null
fun main(args: Array<String>){ val y = 9 for (i in 1..y+1){ print("fits") println(" in") } checkOutOfRange() } fun checkOutOfRange(){ val items = listOf('a', 'b', 'c') if (-1 !in 0..items.lastIndex){ println("item is out of range") } if (items.size !in items.indices){ println("list size is out of valid list indices range too") } last() } fun last(){ for (x in 1..5){ println(x) } for (x in 1..10 step 2){ print(x) } println() for (x in 9 downTo 0 step 3){ println(x) } }
0
Python
0
1
865658ac267336846e78a63b0214fb1535e17df3
541
codes
MIT License
app/src/main/java/github/informramiz/com/androidapiintegration/model/repositories/randogrepository/RandogRepository.kt
informramiz
195,990,984
false
null
package github.informramiz.com.androidapiintegration.model.repositories.randogrepository import github.informramiz.com.androidapiintegration.model.models.responses.BreedRandomImageResponse import github.informramiz.com.androidapiintegration.model.models.responses.BreedsListResponse import github.informramiz.com.androidapiintegration.model.repositories.utils.CommonInfo import github.informramiz.com.androidapiintegration.model.repositories.utils.NetworkBoundResource import github.informramiz.com.androidapiintegration.model.repositories.utils.Resource import retrofit2.Response import javax.inject.Inject /** * Created by <NAME> on 2019-07-23 */ class RandogRepository @Inject constructor(private val commonInfo: CommonInfo, private val randogAPI: RandogAPI) { suspend fun listBreeds(): Resource<BreedsListResponse> { return ListBreedsNetworkResource(commonInfo, randogAPI).start() } suspend fun fetchRandomImage(breedName: String): Resource<BreedRandomImageResponse> { return FetchRandomImageResource(commonInfo, randogAPI, breedName).start() } }
0
Kotlin
0
0
17e2991766086dbf15458c37c8a3a2ed54bd60c7
1,130
android-api-integration
Apache License 2.0
core/database/src/main/kotlin/com/ngapps/phototime/core/database/model/RecentSearchQueryEntity.kt
ngapp-dev
752,386,763
false
{"Kotlin": 1833486, "Shell": 10136}
/* * Copyright 2024 NGApps Dev (https://github.com/ngapp-dev). All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ngapps.phototime.core.database.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.datetime.Instant /** * Defines an database entity that stored recent search queries. */ @Entity(tableName = "recentSearchQueries") data class RecentSearchQueryEntity( @PrimaryKey val query: String, @ColumnInfo val queriedDate: Instant, )
0
Kotlin
0
3
bc1990bccd9674c6ac210fa72a56ef5318bf7241
1,058
phototime
Apache License 2.0