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
visualization/src/main/kotlin/com/enigmashowdown/visual/LevelVisualization.kt
EnigmaShowdown
682,837,285
false
{"Kotlin": 168601, "Java": 233}
package com.enigmashowdown.visual import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.utils.viewport.ExtendViewport import com.enigmashowdown.game.conquest.map.LevelMap import com.enigmashowdown.game.conquest.state.ConquestStateView import com.enigmashowdown.game.conquest.state.EntityType import com.enigmashowdown.message.broadcast.LevelStateBroadcast import com.enigmashowdown.util.add import com.enigmashowdown.util.getLogger import com.enigmashowdown.visual.render.DisposeRenderable import com.enigmashowdown.visual.render.RenderObject import com.enigmashowdown.visual.render.Renderable import com.enigmashowdown.visual.render.RenderableMultiplexer import com.enigmashowdown.visual.render.RenderableReference import com.enigmashowdown.visual.render.StageRenderable import com.enigmashowdown.visual.render.TiledMapRenderable import com.enigmashowdown.visual.render.ViewportResizerRenderable import com.enigmashowdown.visual.update.Updatable import kotlin.math.max import kotlin.math.min private const val VIEW_WIDTH = 30f private const val VIEW_HEIGHT = 20f /** * This class should be called by [com.enigmashowdown.visual.screens.GameScreen]. * * This should be used to contain all map rendering logic and any logic for the actual visualization of the state of the game */ class LevelVisualization( private val renderObject: RenderObject, map: LevelMap, private val doReturnHome: () -> Unit, private val doRestartLevel: () -> Unit, ) : Updatable { /** The size in pixels of a single tile */ private val tileSize = map.tileSize private val levelCountdown = LevelCountdown(renderObject) private var endDisplay: LevelEndDisplay? = null private val entitySpriteManager: EntitySpriteManager private val healthBar = HealthClassManager(renderObject) val renderable: Renderable private val stageViewport: ExtendViewport private val tiledViewport: ExtendViewport private val stage: Stage /** Represents how far to zoom. 10 is 100% zoom (normal). 20 is 200% zoom, etc*/ private var zoomValue: Int = 10 init { val tiledMap = map.tiledMap val tiledCamera = OrthographicCamera() stageViewport = ExtendViewport(VIEW_WIDTH, VIEW_HEIGHT) tiledViewport = ExtendViewport(VIEW_WIDTH * tileSize, VIEW_HEIGHT * tileSize, tiledCamera) // let this viewport handle the camera stage = Stage(stageViewport, renderObject.batch) entitySpriteManager = EntitySpriteManager(renderObject, stage) // stage.isDebugAll = true // turn on if you are having trouble figuring out what the bounds of your actor is renderable = RenderableMultiplexer( listOf( ViewportResizerRenderable(tiledViewport), // we need a resizer for tiledViewport because it is not managed by a stage like stageViewport is TiledMapRenderable(tiledMap, tiledCamera, intArrayOf(map.backgroundLayerIndex, map.floorLayerIndex, map.foregroundLayerIndex)), StageRenderable(stage), TiledMapRenderable(tiledMap, tiledCamera, intArrayOf(map.topLayerIndex)), levelCountdown.renderable, RenderableReference { endDisplay?.renderable }, DisposeRenderable { map.tiledMap.dispose() }, DisposeRenderable(entitySpriteManager::dispose), healthBar.renderable, ), ) renderable.resize(Gdx.graphics.width, Gdx.graphics.height) } override fun update(delta: Float, previousState: LevelStateBroadcast, currentState: LevelStateBroadcast, percent: Float) { if (Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Input.Keys.CONTROL_RIGHT)) { if (Gdx.input.isKeyJustPressed(Input.Keys.EQUALS)) { // plus zoomValue++ } if (Gdx.input.isKeyJustPressed(Input.Keys.MINUS)) { zoomValue-- } if (Gdx.input.isKeyJustPressed(Input.Keys.NUM_0)) { zoomValue = 10 } zoomValue = max(2, min(20, zoomValue)) scale(zoomValue / 10.0f) } // logger.info("Tick: {} with percent: {}", previousState.gameStateView.tick - previousState.ticksUntilBegin, percent) val cameraPosition = averagePlayerPosition(previousState.gameStateView as ConquestStateView) cameraPosition.lerp(averagePlayerPosition(currentState.gameStateView as ConquestStateView), percent) tiledViewport.camera.position.set(cameraPosition.x * tileSize, cameraPosition.y * tileSize, 0f) stageViewport.camera.position.set(cameraPosition.x, cameraPosition.y, 0f) tiledViewport.apply() stageViewport.apply() levelCountdown.update(delta, previousState, currentState, percent) entitySpriteManager.update(delta, previousState, currentState, percent) val gameState = (previousState.gameStateView as ConquestStateView) for (entity in gameState.entities) { if (entity.entityType == EntityType.PLAYER) { healthBar.update(entity.health!!.health, entity.health!!.totalHealth) } } if (endDisplay == null && gameState.levelEndStatistics.isNotEmpty()) { require(gameState.levelEndStatistics.size == 1) { "We currently don't have logic implemented for multiple level end statistics" } val statistic = gameState.levelEndStatistics[0] var damageTaken = 0 for (entity in gameState.entities) { if (entity.entityType == EntityType.PLAYER) { damageTaken = entity.health!!.totalHealth - entity.health!!.health } } endDisplay = LevelEndDisplay(renderObject, statistic.status, statistic.tickEndedOn, damageTaken, 0, 0, doReturnHome, doRestartLevel) } else if (endDisplay != null && gameState.levelEndStatistics.isEmpty()) { endDisplay = null } endDisplay?.let { endDisplay -> endDisplay.update(delta, previousState, currentState, percent) Gdx.input.inputProcessor = endDisplay.inputProcessor } } private fun averagePlayerPosition(state: ConquestStateView): Vector2 { var playerCount = 0 val playerLocationSum = Vector2() for (entity in state.entities) { if (entity.entityType == EntityType.PLAYER) { playerLocationSum.add(entity.position) playerCount++ } } if (playerCount == 0) { // We don't ever expect players to be empty, but in the off chance that it is, we'll just return this. // If in the future this is a case we need to properly handle, we may consider giving the level a "default camera position" or just not move the camera at all in this case return Vector2() } return playerLocationSum.set(playerLocationSum.x / playerCount, playerLocationSum.y / playerCount) } private fun scale(zoom: Float) { tiledViewport.minWorldWidth = VIEW_WIDTH * tileSize / zoom tiledViewport.minWorldHeight = VIEW_HEIGHT * tileSize / zoom stageViewport.minWorldWidth = VIEW_WIDTH / zoom stageViewport.minWorldHeight = VIEW_HEIGHT / zoom tiledViewport.update(Gdx.graphics.width, Gdx.graphics.height) stageViewport.update(Gdx.graphics.width, Gdx.graphics.height) } private companion object { val logger = getLogger() } }
1
Kotlin
0
1
105d93d2e1a1081ff5d52abd2da0fe847cc2e898
7,702
enigmashowdown
MIT License
tool/src/main/java/com/hq/tool/widget/view/swipe/adapters/BaseSwipeAdapter.kt
wwan12
174,499,736
false
{"Java": 2297969, "Kotlin": 721771, "CMake": 22693, "C++": 20727, "C": 1709, "Lua": 67}
package com.hq.tool.widget.view.swipe.adapters import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import com.hq.tool.widget.view.swipe.SwipeLayout import com.hq.tool.widget.view.swipe.implments.SwipeItemMangerImpl import com.hq.tool.widget.view.swipe.interfaces.SwipeAdapterInterface import com.hq.tool.widget.view.swipe.interfaces.SwipeItemMangerInterface import com.hq.tool.widget.view.swipe.util.Attributes abstract class BaseSwipeAdapter : BaseAdapter(), SwipeItemMangerInterface, SwipeAdapterInterface { protected var mItemManger = SwipeItemMangerImpl(this) /** * return the [com.hq.tool.model.swipe.SwipeLayout] resource id, int the view item. * @param position * @return */ abstract override fun getSwipeLayoutResourceId(position: Int): Int /** * generate a new view item. * Never bind SwipeListener or fill values here, every item has a chance to fill value or bind * listeners in fillValues. * to fill it in `fillValues` method. * @param position * @param parent * @return */ abstract fun generateView(position: Int, parent: ViewGroup?): View /** * fill values or bind listeners to the view. * @param position * @param convertView */ abstract fun fillValues(position: Int, convertView: View?) override fun notifyDatasetChanged() { super.notifyDataSetChanged() } override fun getView(position: Int, convertView: View, parent: ViewGroup): View { var v = convertView if (v == null) { v = generateView(position, parent) } mItemManger.bind(v, position) fillValues(position, v) return v } override fun openItem(position: Int) { mItemManger.openItem(position) } override fun closeItem(position: Int) { mItemManger.closeItem(position) } override fun closeAllExcept(layout: SwipeLayout) { mItemManger.closeAllExcept(layout) } override fun closeAllItems() { mItemManger.closeAllItems() } override val openItems: List<Int?>? get() = mItemManger.openItems override val openLayouts: List<SwipeLayout?>? get() = mItemManger.openLayouts override fun removeShownLayouts(layout: SwipeLayout?) { mItemManger.removeShownLayouts(layout) } override fun isOpen(position: Int): Boolean { return mItemManger.isOpen(position) } override fun Mode(): Attributes.Mode? { return mItemManger.mode } override fun Mode(mode: Attributes.Mode) { mItemManger.mode = mode } }
0
Java
0
0
af206e0e6c6029d8f7024bc1c432031e8545df93
2,645
SimpleExample_v1
Apache License 2.0
src/main/kotlin/com/deflatedpickle/intellij/concurnas/gutter/ConcurnasLineMarkerProvider.kt
DeflatedPickle
255,972,485
false
null
package com.deflatedpickle.intellij.concurnas.gutter import com.deflatedpickle.intellij.concurnas.psi.subtree.ConcurnasPSIClassSubtree import com.deflatedpickle.intellij.concurnas.psi.subtree.ConcurnasPSIFunctionSubtree import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.icons.AllIcons import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiElement class ConcurnasLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? = when (element) { // is ConcurnasPSIFileRoot -> // LineMarkerInfo( // element, // element.textRange, // AllIcons.Actions.Execute, // { "" }, // { mouseEvent: MouseEvent, // concurnasPSIFileRoot: ConcurnasPSIFileRoot -> // }, // GutterIconRenderer.Alignment.RIGHT // ) is ConcurnasPSIClassSubtree -> LineMarkerInfo( element, element.textRange, AllIcons.Nodes.Class, { "" }, null, GutterIconRenderer.Alignment.RIGHT ) is ConcurnasPSIFunctionSubtree -> LineMarkerInfo( element, element.parent.textRange, AllIcons.Nodes.Function, { "" }, null, GutterIconRenderer.Alignment.RIGHT ) else -> null } }
1
null
1
1
87d6c5123549611d7f324c80afa18ba0064ff1cf
1,962
intellij-concurnas
MIT License
app/src/main/java/co/nikavtech/anote/screens/adapters/category/CategoryAdapter.kt
dousthagh
358,625,557
false
null
package co.nikavtech.anote.screens.adapters.category import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import co.nikavtech.anote.R import co.nikavtech.anote.database.entities.CategoryEntity class CategoryAdapter(var diffCallback: DiffUtil.ItemCallback<CategoryEntity?>) : ListAdapter<CategoryEntity?, CategoryAdapter.CategoryAdapterViewHolder?>(diffCallback) { private var listener: OnItemClickListener? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryAdapterViewHolder { return CategoryAdapterViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.category_item, parent, false) ) } override fun onBindViewHolder(holder: CategoryAdapterViewHolder, position: Int) { holder.Bind(getItem(position)) } fun getCategoryAt(position: Int): CategoryEntity? { return getItem(position) } fun setOnItemClickListener(listener: OnItemClickListener?) { this.listener = listener } interface OnItemClickListener { fun onItemClick(category: CategoryEntity?) } inner class CategoryAdapterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { internal fun Bind(category: CategoryEntity?) { if (category != null) { itemView.findViewById<TextView>(R.id.tv_category_title).text = category.title } } init { itemView.setOnClickListener { v: View? -> if (listener != null && adapterPosition != RecyclerView.NO_POSITION) listener!!.onItemClick( getItem(adapterPosition) ) } } } companion object { val DIFF_CALLBACK: DiffUtil.ItemCallback<CategoryEntity?> = object : DiffUtil.ItemCallback<CategoryEntity?>() { override fun areItemsTheSame(oldItem: CategoryEntity, newItem: CategoryEntity): Boolean { return oldItem.id === newItem.id } override fun areContentsTheSame(oldItem: CategoryEntity, newItem: CategoryEntity): Boolean { return oldItem.title == newItem.title } } } }
0
Kotlin
0
1
bf4abb48e52923a55221d09b2690268f27318739
2,460
aNote
MIT License
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/indexedProperty/IndexedPropertyReferenceSearchExecutor.kt
androidports
115,100,208
false
null
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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 org.jetbrains.plugins.groovy.transformations.indexedProperty import com.intellij.openapi.application.runReadAction import com.intellij.psi.PsiReference import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.util.Processor import com.intellij.util.QueryExecutor import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField class IndexedPropertyReferenceSearchExecutor : QueryExecutor<PsiReference, ReferencesSearch.SearchParameters> { override fun execute(queryParameters: ReferencesSearch.SearchParameters, consumer: Processor<PsiReference>): Boolean { val field = queryParameters.elementToSearch if (field is GrField) { runReadAction { findIndexedPropertyMethods(field) }?.forEach { method -> MethodReferencesSearch.searchOptimized(method, queryParameters.effectiveSearchScope, true, queryParameters.optimizer, consumer) } } return true } }
6
null
0
4
6e4f7135c5843ed93c15a9782f29e4400df8b068
1,600
intellij-community
Apache License 2.0
app/src/main/java/com/wbrawner/simplemarkdown/view/activity/MarkdownInfoActivity.kt
mario2100
265,338,651
true
{"Kotlin": 60947}
package com.wbrawner.simplemarkdown.view.activity import android.content.res.Configuration import android.os.Bundle import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import com.wbrawner.simplemarkdown.MarkdownApplication import com.wbrawner.simplemarkdown.R import com.wbrawner.simplemarkdown.utility.readAssetToString import com.wbrawner.simplemarkdown.utility.toHtml import kotlinx.android.synthetic.main.activity_markdown_info.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext class MarkdownInfoActivity : AppCompatActivity(), CoroutineScope { override val coroutineContext: CoroutineContext = Dispatchers.Main override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_markdown_info) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) val title = intent?.getStringExtra(EXTRA_TITLE) val fileName = intent?.getStringExtra(EXTRA_FILE) if (title.isNullOrBlank() || fileName.isNullOrBlank()) { finish() return } val isNightMode = AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES || resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES val defaultCssId = if (isNightMode) { R.string.pref_custom_css_default_dark } else { R.string.pref_custom_css_default } val css: String? = getString(defaultCssId) launch { try { val html = assets?.readAssetToString(fileName) ?.toHtml() ?: throw RuntimeException("Unable to open stream to $fileName") infoWebview.loadDataWithBaseURL(null, String.format(FORMAT_CSS, css) + html, "text/html", "UTF-8", null ) } catch (e: Exception) { (application as MarkdownApplication).errorHandler.reportException(e) Toast.makeText(this@MarkdownInfoActivity, R.string.file_load_error, Toast.LENGTH_SHORT).show() finish() } } } override fun onDestroy() { coroutineContext[Job]?.cancel() super.onDestroy() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } companion object { const val FORMAT_CSS = "<style>" + "%s" + "</style>" const val EXTRA_TITLE = "title" const val EXTRA_FILE = "file" } }
0
Kotlin
0
0
7df867b88520f01460da8629a4aea9d9ac928491
3,059
SimpleMarkdown
Apache License 2.0
client-core/src/main/kotlin/org/sinou/pydia/client/core/util/BackStackAdapter.kt
bsinou
434,248,316
false
{"Kotlin": 2133584, "Java": 10237}
package org.sinou.pydia.client.core.util import android.util.Log import androidx.activity.OnBackPressedCallback import androidx.fragment.app.FragmentManager import androidx.navigation.NavController import org.sinou.pydia.sdk.transport.StateID /** * Tweak back navigation to force target state to be the root of the account when navigating back * from the first level, typically, workspace root, bookmarks or accounts, otherwise we will be * redirected back to where we are by the logic that is launched base on the state when the * workspace list fragment resumes. */ class BackStackAdapter(enabled: Boolean = false) : OnBackPressedCallback(enabled) { private var accountID: StateID? = null private lateinit var manager: FragmentManager private lateinit var navController: NavController fun initializeBackNavigation( manager: FragmentManager, navController: NavController, stateID: StateID ) { this.manager = manager this.navController = navController if (stateID.isWorkspaceRoot) { isEnabled = true accountID = StateID.fromId(stateID.accountId) } } override fun handleOnBackPressed() { accountID?.let { Log.i("BackStackAdapter", "Setting custom state before navigating back") // CellsApp.instance.setCurrentState(it) navController.navigateUp() } } companion object { fun initialised( manager: FragmentManager, navController: NavController, stateID: StateID ): BackStackAdapter { val backPressedCallback = BackStackAdapter() backPressedCallback.initializeBackNavigation(manager, navController, stateID) return backPressedCallback } } }
0
Kotlin
0
1
51a128c49a24eedef1baf2d4f295f14aa799b5d3
1,814
pydia
Apache License 2.0
kmp-observableviewmodel-core/src/nonAndroidxMain/kotlin/com/rickclephas/kmp/observableviewmodel/ViewModel.kt
rickclephas
568,920,097
false
{"Kotlin": 24143, "Swift": 19928, "Ruby": 2145, "Objective-C": 693}
package com.rickclephas.kmp.observableviewmodel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.cancel /** * A Kotlin Multiplatform Mobile ViewModel. */ public actual abstract class ViewModel { /** * The [ViewModelScope] containing the [CoroutineScope] of this ViewModel. */ public actual val viewModelScope: ViewModelScope internal val closeables: Closeables public actual constructor(): this(DefaultCoroutineScope()) @OptIn(ExperimentalStdlibApi::class) public actual constructor(coroutineScope: CoroutineScope) { viewModelScope = ViewModelScope(coroutineScope) closeables = Closeables() } @OptIn(ExperimentalStdlibApi::class) public actual constructor(vararg closeables: AutoCloseable): this(DefaultCoroutineScope(), *closeables) @OptIn(ExperimentalStdlibApi::class) public actual constructor( coroutineScope: CoroutineScope, vararg closeables: AutoCloseable ) { viewModelScope = ViewModelScope(coroutineScope) this.closeables = Closeables(closeables.toMutableSet()) } /** * Called when this ViewModel is no longer used and will be destroyed. */ public actual open fun onCleared() { } /** * Should be called to clear the ViewModel once it's no longer being used. */ public fun clear() { viewModelScope.coroutineScope.cancel() closeables.close() onCleared() } } /** * Adds an [AutoCloseable] resource with an associated [key] to this [ViewModel]. * The resource will be closed right before the [onCleared][ViewModel.onCleared] method is called. * * If the [key] already has a resource associated with it, the old resource will be replaced and closed immediately. * * If [onCleared][ViewModel.onCleared] has already been called, * the provided resource will not be added and will be closed immediately. */ @OptIn(ExperimentalStdlibApi::class) public actual fun ViewModel.addCloseable(key: String, closeable: AutoCloseable) { closeables[key] = closeable } /** * Adds an [AutoCloseable] resource to this [ViewModel]. * The resource will be closed right before the [onCleared][ViewModel.onCleared] method is called. * * If [onCleared][ViewModel.onCleared] has already been called, * the provided resource will not be added and will be closed immediately. */ @OptIn(ExperimentalStdlibApi::class) public actual fun ViewModel.addCloseable(closeable: AutoCloseable) { closeables += closeable } /** * Returns the [AutoCloseable] resource associated to the given [key], * or `null` if such a [key] is not present in this [ViewModel]. */ @OptIn(ExperimentalStdlibApi::class) @Suppress("UNCHECKED_CAST") public actual fun <T : AutoCloseable> ViewModel.getCloseable(key: String): T? = closeables[key] as T?
8
Kotlin
28
578
805c41ff1305b02909c3b50a7e34a46b3c029c04
2,833
KMP-ObservableViewModel
MIT License
app/src/main/java/no/kasperi/matoppskrifter/viewModel/HjemViewModel.kt
Keezpaa
554,308,183
false
null
package no.kasperi.matoppskrifter.viewModel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import no.kasperi.matoppskrifter.pojo.* import no.kasperi.matoppskrifter.retrofit.RetrofitInstance import retrofit2.Call import retrofit2.Callback import retrofit2.Response const val TAG = "HjemViewModel" class HjemViewModel:ViewModel() { private val mutableKategori = MutableLiveData<KategoriRespons>() private val mutableTilfeldigOppskrift = MutableLiveData<TilfeldigOppskriftRespons>() private val mutableOppskriftEtterKategori = MutableLiveData<OppskriftRespons>() init { hentTilfeldigOppskrift() hentAlleKategorier() hentOppskriftEtterKategori() } private fun hentAlleKategorier() { RetrofitInstance.api.hentKategorier().enqueue(object : Callback<KategoriRespons> { override fun onResponse(call: Call<KategoriRespons>, response: Response<KategoriRespons>) { mutableKategori.value = response.body() } override fun onFailure(call: Call<KategoriRespons>, t: Throwable) { Log.d(TAG, t.message.toString()) } }) } private fun hentTilfeldigOppskrift() { RetrofitInstance.api.hentTilfeldigOppskrift().enqueue(object : Callback<TilfeldigOppskriftRespons> { override fun onResponse(call: Call<TilfeldigOppskriftRespons>, response: Response<TilfeldigOppskriftRespons>) { mutableTilfeldigOppskrift.value = response.body() } override fun onFailure(call: Call<TilfeldigOppskriftRespons>, t: Throwable) { Log.e(TAG, t.message.toString()) } }) } private fun hentOppskriftEtterKategori() { RetrofitInstance.api.hentOppskriftEtterKategori("chicken").enqueue(object : Callback<OppskriftRespons> { override fun onResponse(call: Call<OppskriftRespons>, response: Response<OppskriftRespons>) { mutableOppskriftEtterKategori.value = response.body() } override fun onFailure(call: Call<OppskriftRespons>, t: Throwable) { Log.e(TAG, t.message.toString()) } }) } fun observerOppskriftEtterKategori(): LiveData<OppskriftRespons> { return mutableOppskriftEtterKategori } fun observerTilfeldigOppskrift(): LiveData<TilfeldigOppskriftRespons> { return mutableTilfeldigOppskrift } fun observerKategorier(): LiveData<KategoriRespons> { return mutableKategori } }
0
Kotlin
0
0
4d6f9f320a26dd1ed0c2a3497b0ee4beb3a337ae
2,641
MatOppskrifter
MIT License
src/main/kotlin/de/handler/gdg/data/GdgEntity.kt
luckyhandler
314,615,422
false
null
package de.handler.gdg.data import com.google.gson.annotations.SerializedName data class GdgEntity( var id: String, @SerializedName("result_type") val resultType: ResultType, val picture: Picture, val title: String, val country: String, val url: String, val city: String )
0
Kotlin
0
1
14da1af7922f43195b4a03aa3b8fe0896c2797e2
306
demo_kotlin_spring_boot
Apache License 2.0
forge/src/main/java/com/tkisor/upd8r/forge/Upd8rForge.kt
Tki-sor
638,110,305
false
null
package com.tkisor.upd8r.forge import com.tkisor.upd8r.Upd8r import com.tkisor.upd8r.Upd8r.init import com.tkisor.upd8r.forge.event.JoinWorld import net.minecraftforge.common.MinecraftForge import net.minecraftforge.fml.common.Mod @Mod(Upd8r.MOD_ID) class Upd8rForge { init { init() MinecraftForge.EVENT_BUS.register(Upd8rCommand) MinecraftForge.EVENT_BUS.register(JoinWorld) // MinecraftForge.EVENT_BUS.register(ModEventSubscriber) } }
2
Kotlin
0
0
9770f228f06d35bc1dec8161273c4bb0afac7272
480
Upd8r
MIT License
src/main/java/me/shadowalzazel/mcodyssey/phenomenon/solar_phenomena/SlimeShower.kt
ShadowAlzazel
511,383,377
false
{"Kotlin": 896208}
package me.shadowalzazel.mcodyssey.phenomenon.solar_phenomena import me.shadowalzazel.mcodyssey.phenomenon.base.OdysseyPhenomenon import me.shadowalzazel.mcodyssey.phenomenon.base.PhenomenonType import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.TextColor import org.bukkit.World import org.bukkit.entity.EntityType import org.bukkit.entity.Slime import org.bukkit.potion.PotionEffect import org.bukkit.potion.PotionEffectType object SlimeShower : OdysseyPhenomenon("Slime Shower", PhenomenonType.LUNAR, 70, 5, 15, 55, Component.text("There are strange flashes in the sky...")) { override fun successfulActivation(someWorld: World) { super.successfulActivation(someWorld) someWorld.players.forEach { it.sendMessage(Component.text("Slime is falling from the sky?", TextColor.color(107, 162, 105))) } } override fun persistentPlayerActives(someWorld: World) { // Effects val fallingSlimeEffects = listOf( PotionEffect(PotionEffectType.SLOW_FALLING, 20 * 30, 1), PotionEffect(PotionEffectType.REGENERATION, 20 * 600, 1), PotionEffect(PotionEffectType.RESISTANCE, 20 * 600, 1), PotionEffect(PotionEffectType.HEALTH_BOOST, 20 * 600, 1)) // someWorld.players.forEach { if ((0..10).random() > 9) { if (it.location.block.lightFromSky > 9 && it.location.y > 63.0) { (it.world.spawnEntity(it.location.clone().add((-16..16).random().toDouble(), 32.0, (-16..16).random().toDouble()), EntityType.SLIME) as Slime).also { slime -> slime.addPotionEffects(fallingSlimeEffects) slime.health += 8.0 } } } } } }
0
Kotlin
0
3
5e85f15a3a4184e110c45200f32d7158a827ec99
1,836
MinecraftOdyssey
MIT License
CRM/src/main/kotlin/org/example/crm/validators/ContactBody.kt
M4tT3d
874,249,564
false
{"Kotlin": 354206, "TypeScript": 180680, "JavaScript": 3610, "Dockerfile": 2844, "CSS": 2078, "HTML": 302}
package org.example.crm.validators import jakarta.validation.Constraint import jakarta.validation.ConstraintValidator import jakarta.validation.ConstraintValidatorContext import jakarta.validation.Payload import org.example.crm.dtos.request.create.CContactDTO import org.example.crm.dtos.request.update.UContactDTO import org.example.crm.utils.enums.Category import kotlin.reflect.KClass @MustBeDocumented @Constraint(validatedBy = [CBodyValidator::class, UBodyValidator::class]) @Target(AnnotationTarget.CLASS) annotation class ContactBody( val message: String = "Invalid body", val groups: Array<KClass<*>> = [], val payload: Array<KClass<out Payload>> = [] ) class CBodyValidator : ConstraintValidator<ContactBody, CContactDTO> { override fun isValid(requestBody: CContactDTO, context: ConstraintValidatorContext): Boolean { return when (requestBody.category) { Category.CUSTOMER -> { if (requestBody.customer == null) { context.disableDefaultConstraintViolation() context.buildConstraintViolationWithTemplate("Customer data cannot be null") .addPropertyNode("customer") .addConstraintViolation() return false } return true } Category.PROFESSIONAL -> { if (requestBody.professional == null) { context.disableDefaultConstraintViolation() context.buildConstraintViolationWithTemplate("Professional data cannot be null") .addPropertyNode("professional") .addConstraintViolation() return false } if (requestBody.professional.dailyRate <= 0f) { context.disableDefaultConstraintViolation() context.buildConstraintViolationWithTemplate("Rate must be greater than 0") .addPropertyNode("rate") .addConstraintViolation() return false } return true } Category.UNKNOWN -> true } } } class UBodyValidator : ConstraintValidator<ContactBody, UContactDTO> { override fun isValid(requestBody: UContactDTO, context: ConstraintValidatorContext): Boolean { if (requestBody.category == null) return true return when (requestBody.category) { Category.CUSTOMER -> { if (requestBody.customer == null) { context.disableDefaultConstraintViolation() context.buildConstraintViolationWithTemplate("Customer data cannot be null") .addPropertyNode("customer") .addConstraintViolation() return false } return true } Category.PROFESSIONAL -> { if (requestBody.professional == null) { context.disableDefaultConstraintViolation() context.buildConstraintViolationWithTemplate("Professional data cannot be null") .addPropertyNode("professional") .addConstraintViolation() return false } if (requestBody.professional.dailyRate == null) return true if (requestBody.professional.dailyRate <= 0f) { context.disableDefaultConstraintViolation() context.buildConstraintViolationWithTemplate("Rate must be greater than 0") .addPropertyNode("rate") .addConstraintViolation() return false } return true } Category.UNKNOWN -> true } } }
0
Kotlin
0
0
ccad8f0a41e77e03935e548b4f03969fc051a61f
3,908
wa2-project-job-placement
MIT License
increase-java-core/src/main/kotlin/com/increase/api/services/async/simulations/WireTransferServiceAsync.kt
Increase
614,596,462
false
{"Kotlin": 14644217, "Shell": 1257}
@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 package com.increase.api.services.async.simulations import com.increase.api.core.RequestOptions import com.increase.api.models.SimulationWireTransferCreateInboundParams import com.increase.api.models.WireTransferSimulation import java.util.concurrent.CompletableFuture interface WireTransferServiceAsync { /** Simulates an inbound Wire Transfer to your account. */ @JvmOverloads fun createInbound( params: SimulationWireTransferCreateInboundParams, requestOptions: RequestOptions = RequestOptions.none() ): CompletableFuture<WireTransferSimulation> }
1
Kotlin
0
1
d7e09a56f02cea352df4e06d67db2a3809fbd13c
678
increase-java
Apache License 2.0
library/modules/themes/src/main/java/com/michaelflisar/composethemer/themes/themes/ThemeBigStoneTulip.kt
MFlisar
713,865,489
false
{"Kotlin": 206429}
package com.michaelflisar.composethemer.themes.themes import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.ui.graphics.Color import com.michaelflisar.composethemer.ComposeTheme /** * Theme taken from the default themes from https://rydmike.com/flexcolorscheme/themesplayground-latest/ * * FlexColor Theme Name: "Big Stone Tulip" */ object ThemeBigStoneTulip { const val KEY = "Big Stone Tulip" fun get() = ComposeTheme.Theme( key = KEY, colorSchemeLight = Light, colorSchemeDark = Dark ) private val Light = lightColorScheme( primary = Color(0xff1a2c42), onPrimary = Color(0xffffffff), primaryContainer = Color(0xffb1c0dd), onPrimaryContainer = Color(0xff0f1012), secondary = Color(0xffe59a18), onSecondary = Color(0xff000000), secondaryContainer = Color(0xffe0bd80), onSecondaryContainer = Color(0xff13100b), tertiary = Color(0xfff0b03f), onTertiary = Color(0xff000000), tertiaryContainer = Color(0xffe9cfa1), onTertiaryContainer = Color(0xff13110e), error = Color(0xffb00020), onError = Color(0xffffffff), errorContainer = Color(0xfffcd8df), onErrorContainer = Color(0xff141213), background = Color(0xfff8f9f9), onBackground = Color(0xff090909), surface = Color(0xfff8f9f9), onSurface = Color(0xff090909), surfaceVariant = Color(0xffe2e3e4), onSurfaceVariant = Color(0xff111111), outline = Color(0xff7c7c7c), outlineVariant = Color(0xffc8c8c8), scrim = Color(0xff000000), inverseSurface = Color(0xff111112), inverseOnSurface = Color(0xfff5f5f5), inversePrimary = Color(0xff9eacbd), surfaceTint = Color(0xff1a2c42), ) private val Dark = darkColorScheme( primary = Color(0xff60748a), onPrimary = Color(0xfff6f8f9), primaryContainer = Color(0xff1a2c42), onPrimaryContainer = Color(0xffe3e6ea), secondary = Color(0xffebb251), onSecondary = Color(0xff14110a), secondaryContainer = Color(0xffd48608), onSecondaryContainer = Color(0xfffff4e1), tertiary = Color(0xfff4ca7e), onTertiary = Color(0xff14130d), tertiaryContainer = Color(0xffc68e2d), onTertiaryContainer = Color(0xfffef6e6), error = Color(0xffcf6679), onError = Color(0xff140c0d), errorContainer = Color(0xffb1384e), onErrorContainer = Color(0xfffbe8ec), background = Color(0xff151617), onBackground = Color(0xffececec), surface = Color(0xff151617), onSurface = Color(0xffececec), surfaceVariant = Color(0xff36383a), onSurfaceVariant = Color(0xffdfdfe0), outline = Color(0xff797979), outlineVariant = Color(0xff2d2d2d), scrim = Color(0xff000000), inverseSurface = Color(0xfff6f7f9), inverseOnSurface = Color(0xff131313), inversePrimary = Color(0xff38404a), surfaceTint = Color(0xff60748a), ) }
0
Kotlin
0
1
bd690a973f2aca0162dc4f48c92a9b6a2383a895
3,156
ComposeThemer
Apache License 2.0
korge-core/test/korlibs/io/lang/WStringTest.kt
korlibs
80,095,683
false
{"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41}
package korlibs.io.lang import kotlin.test.Test import kotlin.test.assertEquals class WStringTest { @Test fun smokeTest() { val string = WString("\uD83D\uDE00") // 😀 U+1F600 // "😀".codePointAt(0).toString(16) assertEquals(1, string.length) assertEquals(128512, string[0].codePoint) assertEquals(1, WString("😀").length) assertEquals(128512, WString("😀")[0].codePoint) assertEquals(WString("😀"), WString("😀").toString().toWString()) assertEquals(WString("G"), WString("G").toString().toWString()) } }
444
WebAssembly
121
2,207
dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a
569
korge
Apache License 2.0
domain/src/test/kotlin/com/cheise_proj/domain/usecase/users/GetProfileTaskTest.kt
marshall219
249,870,132
true
{"Kotlin": 788935}
package com.cheise_proj.domain.usecase.users import com.cheise_proj.domain.repository.UserRepository import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations import utils.TestUserGenerator @RunWith(JUnit4::class) class GetProfileTaskTest { companion object { const val PARENT = "Parent" const val TEACHER = "teacher" } @Mock lateinit var userRepository: UserRepository private lateinit var getProfileTask: GetProfileTask @Before fun setUp() { MockitoAnnotations.initMocks(this) getProfileTask = GetProfileTask(userRepository, Schedulers.trampoline(), Schedulers.trampoline()) } @Test fun `Get parent profile success`() { val actual = TestUserGenerator.getProfile() val params = getProfileTask.ProfileParams(PARENT,"test parent") Mockito.`when`(userRepository.getStudentProfile(params.identifier)).thenReturn(Observable.just(actual)) getProfileTask.buildUseCase(params).test() .assertSubscribed() .assertValueCount(1) .assertValue { it == actual } .assertComplete() } @Test fun `Get teacher profile success`() { val params = getProfileTask.ProfileParams(TEACHER,"test teacher") val actual = TestUserGenerator.getProfile() Mockito.`when`(userRepository.getTeacherProfile(params.identifier)).thenReturn(Observable.just(actual)) getProfileTask.buildUseCase(params).test() .assertSubscribed() .assertValueCount(1) .assertValue { it == actual } .assertComplete() } @Test(expected = IllegalArgumentException::class) fun `Get profile with unknown role throws an exception`() { val params = getProfileTask.ProfileParams("unknown","test") getProfileTask.buildUseCase(params).test() } @Test(expected = IllegalArgumentException::class) fun `Get profile with null params throws an exception`() { getProfileTask.buildUseCase().test() } }
0
null
0
0
0183ab6165a42be83691dd7281efc6d738ebe88c
2,311
Nagies-Edu-Center
Apache License 2.0
src/test/kotlin/net/andreinc/serverneat/responses/RouteResponseResourceTest.kt
nomemory
255,720,445
false
null
package net.andreinc.serverneat.responses import io.vertx.core.buffer.Buffer import io.vertx.core.http.HttpMethod import io.vertx.ext.web.client.WebClient import io.vertx.junit5.VertxTestContext import io.vertx.junit5.web.TestRequest.* import net.andreinc.serverneat.abstraction.RouteResponseAbstractTest import net.andreinc.serverneat.server.server import org.junit.jupiter.api.Test private val currentServer = server { httpOptions { host = "localhost" port = 17880 } globalHeaders { header("Content-Type", "application/text") } routes { get { path = "/resource/response/get" response { header("/resource/response/get", "get") statusCode = 200 resource { path = "api-data/get-response.txt" } } } post { path = "/resource/response/post" response { header("/resource/response/post", "post") statusCode = 200 resource { path = "api-data/post-response.txt" } } } put { path = "/resource/response/put" response { header("/resource/response/put", "put") statusCode = 200 resource { path = "api-data/put-response.txt" } } } patch { path = "/resource/response/patch" response { header("/resource/response/patch", "patch") statusCode = 200 resource { path = "api-data/patch-response.txt" } } } delete { path = "/resource/response/delete" response { header("/resource/response/delete", "delete") statusCode = 200 resource { path = "api-data/delete-response.txt" } } } } } class RouteResponseResourceTest : RouteResponseAbstractTest(currentServer) { @Test fun `Test if a GET route with Resource response works correctly (status, body, header) ` (webClient: WebClient, testContext: VertxTestContext) { testRequest(webClient, HttpMethod.GET, "/resource/response/get") .expect( statusCode(200), responseHeader("/resource/response/get", "get"), bodyResponse(Buffer.buffer("Hello, Get!"), "application/text") ) .send(testContext) } @Test fun `Test if a POST route with Resource response works correctly (status, body, header) ` (webClient: WebClient, testContext: VertxTestContext) { testRequest(webClient, HttpMethod.POST, "/resource/response/post") .expect( statusCode(200), responseHeader("/resource/response/post", "post"), bodyResponse(Buffer.buffer("Hello, Post!"), "application/text") ) .send(testContext) } @Test fun `Test if a PUT route with Resource response works correctly (status, body, header) ` (webClient: WebClient, testContext: VertxTestContext) { testRequest(webClient, HttpMethod.PUT, "/resource/response/put") .expect( statusCode(200), responseHeader("/resource/response/put", "put"), bodyResponse(Buffer.buffer("Hello, Put!"), "application/text") ) .send(testContext) } @Test fun `Test if a PATCH route with Resource response works correctly (status, body, header) ` (webClient: WebClient, testContext: VertxTestContext) { testRequest(webClient, HttpMethod.PATCH, "/resource/response/patch") .expect( statusCode(200), responseHeader("/resource/response/patch", "patch"), bodyResponse(Buffer.buffer("Hello, Patch!"), "application/text") ) .send(testContext) } @Test fun `Test if a DELETE route with Resource response works correctly (status, body, header) ` (webClient: WebClient, testContext: VertxTestContext) { testRequest(webClient, HttpMethod.DELETE, "/resource/response/delete") .expect( statusCode(200), responseHeader("/resource/response/delete", "delete"), bodyResponse(Buffer.buffer("Hello, Delete!"), "application/text") ) .send(testContext) } }
11
Kotlin
0
18
13e34a1e4cab05dade445f1ad5495cb3956e97fc
4,626
serverneat
Apache License 2.0
app/src/main/java/com/dreamsoftware/saborytv/ui/screens/instructions/InstructionsDetailScreenContent.kt
sergio11
527,221,243
false
{"Kotlin": 558422}
package com.dreamsoftware.saborytv.ui.screens.instructions import androidx.compose.runtime.Composable import com.dreamsoftware.saborytv.R import com.dreamsoftware.saborytv.ui.core.components.SupportPreviewContentGrid @Composable fun InstructionsDetailScreenContent( uiState: InstructionsDetailUiState, actionListener: IIngredientsDetailScreenActionListener ) { with(uiState) { SupportPreviewContentGrid( mainTitleRes = R.string.instructions_main_title_text, secondaryTitleRes = R.string.instructions_main_secondary_text, confirmButtonTextRes = R.string.instructions_confirm_button_text, imageUrl = recipeImageUrl, contentList = instructions, onErrorAccepted = actionListener::onErrorMessageCleared, onAccepted = actionListener::onCompleted ) } }
0
Kotlin
1
1
93b8bc2fffd10601d5015621da0caeda114a6cce
865
saborytv_android
MIT License
app/src/main/java/com/heyanle/easybangumi4/ui/main/star/CoverStarViewModel.kt
easybangumiorg
413,723,669
false
null
package com.heyanle.easybangumi4.ui.main.star import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.heyanle.easy_i18n.R import com.heyanle.easybangumi4.cartoon.entity.CartoonInfo import com.heyanle.easybangumi4.cartoon.repository.db.dao.CartoonInfoDao import com.heyanle.easybangumi4.case.CartoonInfoCase import com.heyanle.easybangumi4.source_api.entity.CartoonCover import com.heyanle.easybangumi4.source_api.entity.toIdentify import com.heyanle.easybangumi4.ui.common.moeSnackBar import com.heyanle.easybangumi4.utils.stringRes import com.heyanle.injekt.core.Injekt import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.yield /** * CartoonCover 的 star 逻辑抽取 * Created by heyanlin on 2023/8/4. * https://github.com/heyanLE */ class CoverStarViewModel : ViewModel() { private val cartoonInfoDao: CartoonInfoDao by Injekt.injectLazy() val starFlow = cartoonInfoDao.flowAllStar() val setFlow = starFlow.map { val set = mutableSetOf<String>() it.forEach { set.add(it.toIdentify()) } set } fun star(cartoonCover: CartoonCover) { viewModelScope.launch { val old = cartoonInfoDao.getByCartoonSummary(cartoonCover.id, cartoonCover.source, cartoonCover.url) if(old == null){ cartoonInfoDao.insert(CartoonInfo.fromCartoonCover(cartoonCover).copy(starTime = System.currentTimeMillis())) }else{ if(old.starTime > 0){ cartoonInfoDao.modify(old.copy(starTime = 0, tags = "", upTime = 0)) }else{ cartoonInfoDao.modify(old.copy(starTime = System.currentTimeMillis())) } } } } }
7
null
60
2,233
f9077823be7ab77109759211ad70c53ad72b2e9a
2,124
EasyBangumi
Apache License 2.0
skiko/src/iosMain/kotlin/org/jetbrains/skiko/SkikoViewController.kt
JetBrains
282,864,178
false
null
package org.jetbrains.skiko import kotlinx.cinterop.CValue import kotlinx.cinterop.ExportObjCClass import kotlinx.cinterop.useContents import platform.CoreGraphics.CGRect import platform.CoreGraphics.CGRectMake import platform.Foundation.NSCoder import platform.UIKit.UIEvent import platform.UIKit.UITouch import platform.UIKit.UIScreen import platform.UIKit.UIView import platform.UIKit.UIViewController import platform.UIKit.setFrame import platform.UIKit.contentScaleFactor import platform.UIKit.UIKeyInputProtocol import platform.UIKit.UIPress import platform.UIKit.UIPressesEvent @ExportObjCClass class SkikoViewController : UIViewController { @OverrideInit constructor() : super(nibName = null, bundle = null) @OverrideInit constructor(coder: NSCoder) : super(coder) constructor(skikoUIView: SkikoUIView) : this() { this.skikoUIView = skikoUIView } private var skikoUIView: SkikoUIView? = null override fun loadView() { if (skikoUIView == null) { super.loadView() } else { this.view = skikoUIView!!.load() } } // viewDidUnload() is deprecated and not called. override fun viewDidDisappear(animated: Boolean) { skikoUIView?.detach() } } @ExportObjCClass class SkikoUIView : UIView, UIKeyInputProtocol { @OverrideInit constructor(frame: CValue<CGRect>) : super(frame) @OverrideInit constructor(coder: NSCoder) : super(coder) private var skiaLayer: SkiaLayer? = null constructor(skiaLayer: SkiaLayer, frame: CValue<CGRect> = CGRectMake(0.0, 0.0, 1.0, 1.0)) : super(frame) { this.skiaLayer = skiaLayer } fun detach() = skiaLayer?.detach() fun load(): SkikoUIView { val (width, height) = UIScreen.mainScreen.bounds.useContents { this.size.width to this.size.height } setFrame(CGRectMake(0.0, 0.0, width, height)) contentScaleFactor = UIScreen.mainScreen.scale skiaLayer?.let { layer -> layer.attachTo(this) layer.initGestures() } return this } fun showScreenKeyboard() = becomeFirstResponder() fun hideScreenKeyboard() = resignFirstResponder() fun isScreenKeyboardOpen() = isFirstResponder var keyEvent: UIPress? = null private var inputText: String = "" override fun hasText(): Boolean { return inputText.length > 0 } override fun insertText(theText: String) { inputText += theText skiaLayer?.skikoView?.onInputEvent(toSkikoTypeEvent(theText, keyEvent)) } override fun deleteBackward() { inputText = inputText.dropLast(1) } override fun canBecomeFirstResponder() = true override fun pressesBegan(presses: Set<*>, withEvent: UIPressesEvent?) { if (withEvent != null) { for (press in withEvent.allPresses) { keyEvent = press as UIPress skiaLayer?.skikoView?.onKeyboardEvent( toSkikoKeyboardEvent(press, SkikoKeyboardEventKind.DOWN) ) } } super.pressesBegan(presses, withEvent) } override fun pressesEnded(presses: Set<*>, withEvent: UIPressesEvent?) { if (withEvent != null) { for (press in withEvent.allPresses) { keyEvent = press as UIPress skiaLayer?.skikoView?.onKeyboardEvent( toSkikoKeyboardEvent(press, SkikoKeyboardEventKind.UP) ) } } super.pressesEnded(presses, withEvent) } override fun touchesBegan(touches: Set<*>, withEvent: UIEvent?) { super.touchesBegan(touches, withEvent) val events: MutableList<SkikoTouchEvent> = mutableListOf() for (touch in touches) { val event = touch as UITouch val (x, y) = event.locationInView(null).useContents { x to y } val timestamp = (event.timestamp * 1_000).toLong() events.add( SkikoTouchEvent(x, y, SkikoTouchEventKind.STARTED, timestamp, event) ) } skiaLayer?.skikoView?.onTouchEvent(events.toTypedArray()) } override fun touchesEnded(touches: Set<*>, withEvent: UIEvent?) { super.touchesEnded(touches, withEvent) val events: MutableList<SkikoTouchEvent> = mutableListOf() for (touch in touches) { val event = touch as UITouch val (x, y) = event.locationInView(null).useContents { x to y } val timestamp = (event.timestamp * 1_000).toLong() events.add( SkikoTouchEvent(x, y, SkikoTouchEventKind.ENDED, timestamp, event) ) } skiaLayer?.skikoView?.onTouchEvent(events.toTypedArray()) } override fun touchesMoved(touches: Set<*>, withEvent: UIEvent?) { super.touchesMoved(touches, withEvent) val events: MutableList<SkikoTouchEvent> = mutableListOf() for (touch in touches) { val event = touch as UITouch val (x, y) = event.locationInView(null).useContents { x to y } val timestamp = (event.timestamp * 1_000).toLong() events.add( SkikoTouchEvent(x, y, SkikoTouchEventKind.MOVED, timestamp, event) ) } skiaLayer?.skikoView?.onTouchEvent(events.toTypedArray()) } override fun touchesCancelled(touches: Set<*>, withEvent: UIEvent?) { super.touchesCancelled(touches, withEvent) val events: MutableList<SkikoTouchEvent> = mutableListOf() for (touch in touches) { val event = touch as UITouch val (x, y) = event.locationInView(null).useContents { x to y } val timestamp = (event.timestamp * 1_000).toLong() events.add( SkikoTouchEvent(x, y, SkikoTouchEventKind.CANCELLED, timestamp, event) ) } skiaLayer?.skikoView?.onTouchEvent(events.toTypedArray()) } }
42
null
43
840
cf67c819f15ffcd8b6ecee3edb29ae2cdce1f2fe
5,999
skiko
Apache License 2.0
app/src/main/kotlin/com/juniperphoton/myersplash/repo/DownloadItemsRepo.kt
JuniperPhoton
67,424,471
false
null
package com.juniperphoton.myersplash.repo import androidx.lifecycle.LiveData import com.juniperphoton.myersplash.db.DownloadItemDao import com.juniperphoton.myersplash.model.DownloadItem import javax.inject.Inject class DownloadItemsRepo @Inject constructor( private val dao: DownloadItemDao ) { val downloadItems: LiveData<List<DownloadItem>> get() = dao.getAll() suspend fun deleteByStatus(status: Int) { dao.deleteByStatus(status) } suspend fun updateStatus(id: String, status: Int) { dao.setStatusById(id, status) } suspend fun resetStatus(id: String) { dao.resetStatus(id) } suspend fun deleteById(id: String) { dao.deleteById(id) } }
27
Kotlin
23
93
d2e6da91c20b638445c60b089e9aa789c646d22b
729
MyerSplash.Android
MIT License
src/main/kotlin/org/sampl/codegen/ToKotlinCompiler.kt
SamChou19815
134,309,719
false
{"Kotlin": 282544, "ANTLR": 7823}
package org.sampl.codegen import org.sampl.EASTER_EGG import org.sampl.TOP_LEVEL_PROGRAM_NAME import org.sampl.ast.common.BinaryOperator import org.sampl.ast.common.FunctionCategory.USER_DEFINED import org.sampl.ast.common.Literal import org.sampl.ast.decorated.DecoratedClassFunction import org.sampl.ast.decorated.DecoratedClassMember import org.sampl.ast.decorated.DecoratedExpression import org.sampl.ast.decorated.DecoratedPattern import org.sampl.ast.decorated.DecoratedProgram import org.sampl.ast.type.TypeDeclaration import org.sampl.ast.type.TypeExpr import org.sampl.ast.type.TypeIdentifier import org.sampl.ast.type.boolTypeExpr import org.sampl.ast.type.charTypeExpr import org.sampl.ast.type.floatTypeExpr import org.sampl.ast.type.intTypeExpr import org.sampl.ast.type.stringArrayTypeExpr import org.sampl.ast.type.stringTypeExpr import org.sampl.ast.type.unitTypeExpr import org.sampl.util.joinToGenericsInfoString import java.io.BufferedReader import java.io.InputStreamReader import java.util.LinkedList /** * [ToKotlinCompiler] is responsible for compiling the given AST node to valid Kotlin Code. */ internal class ToKotlinCompiler private constructor() : AstToCodeConverter { /** * [q] is the only indentation queue used in this class. */ private val q: IdtQueue = IdtQueue(strategy = IdtStrategy.FOUR_SPACES) // Helper Methods /** * [CodeConvertible.toOneLineCode] returns the one-liner form of the [CodeConvertible]. */ private fun CodeConvertible.toOneLineCode(): String = ToKotlinCompiler().apply { acceptConversion(converter = this) } .q.toOneLineCode() /** * [DecoratedExpression.toOneLineCode] returns the one-liner form of [DecoratedExpression]. * * This method is expression node specific. It will consider the precedence between this node * and its [parent] to decide whether to add parenthesis. */ private fun DecoratedExpression.toOneLineCode(parent: DecoratedExpression): String = toOneLineCode().let { code -> if (hasLowerPrecedence(parent = parent)) "($code)" else code } /** * [TypeExpr.toKotlinType] converts a [TypeExpr] to string form of Kotlin type expression. */ private fun TypeExpr.toKotlinType(): String = when (this) { is TypeExpr.Identifier -> when { this == unitTypeExpr -> "Unit" this == intTypeExpr -> "Long" this == floatTypeExpr -> "Double" this == boolTypeExpr -> "Boolean" this == charTypeExpr -> "Char" this == stringTypeExpr -> "String" this == stringArrayTypeExpr -> "Array<String>" genericsInfo.isEmpty() -> type else -> type + genericsInfo.joinToGenericsInfoString() } is TypeExpr.Function -> { val argumentStrings = argumentTypes.joinToString(separator = ", ") { it.toKotlinType() } val returnTypeString = returnType.toKotlinType() "($argumentStrings) -> $returnTypeString" } } // Visitor Methods override fun convert(node: DecoratedProgram) { q.addLine(line = """@file:JvmName(name = "$TOP_LEVEL_PROGRAM_NAME")""") q.addEmptyLine() // Add some nice easter egg :)) q.addLine(line = "/*") q.addLine(line = " * $EASTER_EGG") q.addLine(line = " */") q.addEmptyLine() // Include provided library, if exists node.providedRuntimeLibrary?.let { providedLibrary -> q.addLine(line = "import ${providedLibrary::class.java.canonicalName}") q.addEmptyLine() } // Include primitive library this::class.java.getResourceAsStream("/PrimitiveRuntimeLibrary.kt") .let { BufferedReader(InputStreamReader(it)) } .lineSequence() .forEach { q.addLine(line = it) } q.addEmptyLine() // Convert main members node.members.convert(isTopLevel = true) // Add main if exists node.members.asSequence().mapNotNull { member -> member as? DecoratedClassMember.FunctionGroup }.mapNotNull { functionGroup -> functionGroup.functions.filter { it.category == USER_DEFINED }.firstOrNull { f -> f.isPublic && f.identifier == "main" && f.arguments.isEmpty() } }.firstOrNull() ?: return q.addLine(line = "fun main(args: Array<String>) {") q.indentAndApply { addLine(line = "println(main())") } q.addLine(line = "}") } /** * [convert] converts a list of [DecoratedClassMember] to code. * * @param isTopLevel tells whether the members are at top level. Default to false. */ private fun List<DecoratedClassMember>.convert(isTopLevel: Boolean = false) { val constants = LinkedList<DecoratedClassMember.Constant>() val functionGroups = LinkedList<DecoratedClassMember.FunctionGroup>() val classes = LinkedList<DecoratedClassMember.Clazz>() for (member in this) { when (member) { is DecoratedClassMember.Constant -> constants.add(member) is DecoratedClassMember.FunctionGroup -> functionGroups.add(member) is DecoratedClassMember.Clazz -> classes.add(member) } } if (isTopLevel) { constants.forEach { convert(node = it) } functionGroups.forEach { convert(node = it) } } else { q.addLine(line = "companion object {") q.indentAndApply { constants.forEach { convert(node = it) } functionGroups.forEach { convert(node = it) } } q.addLine(line = "}") q.addEmptyLine() } classes.forEach { convert(node = it) } } override fun convert(node: DecoratedClassMember.Constant) { val public = if (node.isPublic) "" else "private " q.addLine(line = "${public}val ${node.identifier}: ${node.type.toKotlinType()} = run {") q.indentAndApply { node.expr.acceptConversion(converter = this@ToKotlinCompiler) } q.addLine(line = "}") q.addEmptyLine() } override fun convert(node: DecoratedClassMember.FunctionGroup): Unit = node.functions.filter { it.category == USER_DEFINED }.forEach { convert(node = it) } override fun convert(node: DecoratedClassMember.Clazz) { val i = node.identifier val m = node.members val d = node.declaration when (d) { is TypeDeclaration.Variant -> convertClass(identifier = i, members = m, declaration = d) is TypeDeclaration.Struct -> convertClass(identifier = i, members = m, declaration = d) } q.addEmptyLine() } /** * [convertClass] converts a class with [identifier] [members] and [declaration] to well * formatted Kotlin code. */ private fun convertClass(identifier: TypeIdentifier, members: List<DecoratedClassMember>, declaration: TypeDeclaration.Variant) { val classRawName = identifier.name val classType = if (identifier.genericsInfo.isEmpty()) classRawName else { classRawName + identifier.genericsInfo.joinToString( separator = ", ", prefix = "<", postfix = ">") { "out $it" } } q.addLine(line = "sealed class $classType {") q.indentAndApply { val map = declaration.map val genericsInfo = identifier.genericsInfo for ((name, associatedType) in map) { val (genericsInfoStr, genericsInfoForVariant) = when { genericsInfo.isEmpty() -> "" to "" associatedType == null -> { val all = arrayListOf<TypeExpr>() repeat(times = genericsInfo.size) { all.add(TypeExpr.Identifier(type = "Nothing")) } all.joinToString(separator = ",", prefix = "<", postfix = ">") { t -> t.toKotlinType() } to "" } else -> { val all = arrayListOf<TypeExpr>() val forVariant = arrayListOf<TypeExpr>() for (genericPlaceholder in genericsInfo) { if (associatedType.containsIdentifier(genericPlaceholder)) { all.add(TypeExpr.Identifier(type = genericPlaceholder)) forVariant.add(TypeExpr.Identifier(type = genericPlaceholder)) } else { all.add(TypeExpr.Identifier(type = "Nothing")) } } val allString = all .joinToString(separator = ",", prefix = "<", postfix = ">") { t -> t.toKotlinType() } val forVariantString = forVariant .joinToString(separator = ",", prefix = "<", postfix = ">") { t -> t.toKotlinType() } allString to forVariantString } } if (associatedType == null) { // No Args addLine(line = "object $name: ${identifier.name}$genericsInfoStr()") addEmptyLine() } else { // Single Arg val dataType = associatedType.toKotlinType() val nameCode = name + genericsInfoForVariant val inheritanceCode = identifier.name + genericsInfoStr addLine(line = "data class $nameCode(val data: $dataType): $inheritanceCode()") } } members.convert() } q.addLine(line = "}") } /** * [convertClass] converts a class with [identifier] [members] and [declaration] to well * formatted Kotlin code. */ private fun convertClass(identifier: TypeIdentifier, members: List<DecoratedClassMember>, declaration: TypeDeclaration.Struct) { if (declaration.map.isEmpty()) { q.addLine(line = "class $identifier {") } else { q.addLine(line = "data class $identifier (") q.indentAndApply { val map = declaration.map val l = map.size var i = 1 for ((name, expr) in map) { if (i == l) { q.addLine(line = "val $name: ${expr.toKotlinType()}") } else { q.addLine(line = "val $name: ${expr.toKotlinType()},") } i++ } } q.addLine(line = ") {") } q.indentAndApply { if (declaration.map.isEmpty()) { q.addLine(line = "fun copy(): $identifier = this") q.addEmptyLine() } members.convert() } q.addLine(line = "}") } override fun convert(node: DecoratedClassFunction) { val public = if (node.isPublic) "" else "private " val generics = node.genericsDeclaration .takeIf { it.isNotEmpty() } ?.joinToGenericsInfoString() ?.let { " $it" } ?: "" val id = node.identifier val argumentsString = node.arguments .joinToString(separator = ", ") { (i, t) -> "$i: ${t.toKotlinType()}" } val r = node.returnType.toKotlinType() q.addLine(line = "${public}fun$generics $id($argumentsString): $r = run {") q.indentAndApply { node.body.acceptConversion(converter = this@ToKotlinCompiler) } q.addLine(line = "}") q.addEmptyLine() } override fun convert(node: DecoratedExpression.Literal) { q.addLine(line = when (node.literal) { Literal.Unit -> "Unit" is Literal.Int -> node.literal.toString() + "L" else -> node.literal.toString() }) } override fun convert(node: DecoratedExpression.VariableIdentifier) { if (!node.isClassFunction) { if (node.genericInfo.isNotEmpty()) { error(message = "Impossible!") } q.addLine(line = node.variable) return } // Node is function. Must write in terms of function lambda in Kotlin val functionNodeType = node.type as TypeExpr.Function val argsWithType = functionNodeType.argumentTypes.mapIndexed { i, typeExpr -> "_temp$i: ${typeExpr.toKotlinType()}" } val argsIdOnly = argsWithType.mapIndexed { i, _ -> "_temp$i" } .joinToString(separator = ", ", prefix = "${node.variable}(", postfix = ")") argsWithType.joinToString(separator = ", ", prefix = "{ ", postfix = " -> $argsIdOnly }") .let { q.addLine(line = it) } } override fun convert(node: DecoratedExpression.Constructor) { when (node) { is DecoratedExpression.Constructor.NoArgVariant -> q.addLine( line = "${node.typeName}.${node.variantName}" ) is DecoratedExpression.Constructor.OneArgVariant -> { val dataStr = node.data.toOneLineCode() q.addLine(line = "${node.typeName}.${node.variantName}(run { $dataStr })") } is DecoratedExpression.Constructor.Struct -> { val args = node.declarations.map { (n, e) -> "$n = run { ${e.toOneLineCode()} }" }.joinToString(separator = ", ") q.addLine(line = "${node.typeName}($args)") } is DecoratedExpression.Constructor.StructWithCopy -> { val oldStr = node.old.toOneLineCode() val args = node.newDeclarations.map { (n, e) -> "$n = run { ${e.toOneLineCode()} }" }.joinToString(separator = ", ") q.addLine(line = "($oldStr).copy($args)") } } } override fun convert(node: DecoratedExpression.StructMemberAccess) { val s = node.structExpr.toOneLineCode() q.addLine(line = "($s).${node.memberName}") } override fun convert(node: DecoratedExpression.Not) { q.addLine(line = "!(${node.expr.toOneLineCode()})") } override fun convert(node: DecoratedExpression.Binary) { val left = node.left.toOneLineCode() val right = node.right.toOneLineCode() q.addLine(line = "($left) ${node.op.toKotlinForm()} ($right)") } /** * [BinaryOperator.toKotlinForm] maps the binary operator to its form in Kotlin */ private fun BinaryOperator.toKotlinForm(): String = when (this) { BinaryOperator.LAND -> "and" BinaryOperator.LOR -> "or" BinaryOperator.F_MUL -> "*" BinaryOperator.F_DIV -> "/" BinaryOperator.F_PLUS -> "+" BinaryOperator.F_MINUS -> "-" BinaryOperator.STR_CONCAT -> "+" else -> symbol } override fun convert(node: DecoratedExpression.Throw) { val e = node.expr.toOneLineCode() q.addLine(line = "throw PLException($e)") } override fun convert(node: DecoratedExpression.IfElse) { val c = node.condition.toOneLineCode() q.addLine(line = "if ($c) {") q.indentAndApply { node.e1.acceptConversion(converter = this@ToKotlinCompiler) } q.addLine(line = "} else {") q.indentAndApply { node.e2.acceptConversion(converter = this@ToKotlinCompiler) } q.addLine(line = "}") } override fun convert(node: DecoratedExpression.Match) { val matchedStr = node.exprToMatch.toOneLineCode() q.addLine(line = "with($matchedStr){ when(this) {") q.indentAndApply { for ((pattern, expr) in node.matchingList) { when (pattern) { is DecoratedPattern.Variant -> { addLine(line = "is ${pattern.variantIdentifier} -> {") indentAndApply { pattern.associatedVariable?.let { v -> addLine(line = "val $v = data;") } expr.acceptConversion(converter = this@ToKotlinCompiler) } } is DecoratedPattern.Variable -> { addLine(line = "else -> {") indentAndApply { addLine(line = "val ${pattern.identifier} = data;") expr.acceptConversion(converter = this@ToKotlinCompiler) } } is DecoratedPattern.WildCard -> { addLine(line = "else -> {") indentAndApply { expr.acceptConversion(converter = this@ToKotlinCompiler) } } } addLine(line = "}") } } q.addLine(line = "}}") } override fun convert(node: DecoratedExpression.FunctionApplication) { val funType = node.functionExpr.type as TypeExpr.Function val funStr = node.functionExpr.toFunctionOneLineCodeInFunctionApplication(parent = node) val shorterLen = node.arguments.size val longerLen = funType.argumentTypes.size if (longerLen == shorterLen) { // perfect application val args = node.arguments.joinToString(separator = ", ") { it.toOneLineCode() } q.addLine(line = "$funStr($args)") } else { // currying val argsInsideLambdaBuilder = StringBuilder() for (i in 0 until shorterLen) { argsInsideLambdaBuilder.append(node.arguments[i].toOneLineCode()).append(", ") } argsInsideLambdaBuilder.setLength(argsInsideLambdaBuilder.length - 2) for (i in shorterLen until longerLen) { argsInsideLambdaBuilder.append(", _tempV").append(i) } val lambdaArgsBuilder = StringBuilder() for (i in shorterLen until longerLen) { lambdaArgsBuilder.append("_tempV").append(i).append(": ") .append(funType.argumentTypes[i].toKotlinType()) .append(", ") } lambdaArgsBuilder.setLength(lambdaArgsBuilder.length - 2) q.addLine(line = "{ $lambdaArgsBuilder ->") q.indentAndApply { addLine(line = "$funStr($argsInsideLambdaBuilder)") } q.addLine(line = "}") } } /** * [DecoratedExpression.toFunctionOneLineCodeInFunctionApplication] converts the given * function expression to one line code in function application context and with [parent]. */ private fun DecoratedExpression.toFunctionOneLineCodeInFunctionApplication( parent: DecoratedExpression.FunctionApplication ): String { if (this !is DecoratedExpression.VariableIdentifier || !isClassFunction) { return toOneLineCode(parent = parent) } val genericInfo = genericInfo.takeIf { it.isNotEmpty() } ?.joinToString(separator = ", ", prefix = "<", postfix = ">") { it.toKotlinType() } ?: "" return variable + genericInfo } override fun convert(node: DecoratedExpression.Function) { val args = node.arguments.asSequence().joinToString(separator = ", ") { (name, typeExpr) -> "$name: ${typeExpr.toKotlinType()}" } q.addLine(line = "{ $args ->") q.indentAndApply { node.body.acceptConversion(converter = this@ToKotlinCompiler) } q.addLine(line = "}") } override fun convert(node: DecoratedExpression.TryCatch) { q.addLine(line = "try {") q.indentAndApply { node.tryExpr.acceptConversion(converter = this@ToKotlinCompiler) } q.addLine(line = "} catch (_e: PLException) {") q.indentAndApply { addLine(line = "val ${node.exception} = _e.m;") node.catchHandler.acceptConversion(converter = this@ToKotlinCompiler) } q.addLine(line = "}") } override fun convert(node: DecoratedExpression.Let) { val letLine = if (node.identifier == null) "run {" else { "val ${node.identifier}: ${node.e1.type.toKotlinType()} = run {" } q.addLine(line = letLine) q.indentAndApply { node.e1.acceptConversion(converter = this@ToKotlinCompiler) } q.addLine(line = "};") node.e2.acceptConversion(converter = this) } companion object { /** * [compile] returns the given [node] as well-formatted Kotlin code in string. */ @JvmStatic fun compile(node: CodeConvertible): String = ToKotlinCompiler() .apply { node.acceptConversion(converter = this) } .q.toIndentedCode() } }
0
Kotlin
0
1
766f7b8e5c35eb788b75c636c443eca07a0051a1
21,503
sampl
MIT License
arrow-optics/src/test/kotlin/arrow/optics/data/ListInstancesTest.kt
dbartel
115,580,561
true
{"Kotlin": 1282882, "CSS": 115129, "HTML": 8390, "JavaScript": 6941, "Java": 4423, "Shell": 3077}
package arrow.optics import io.kotlintest.KTestJUnitRunner import io.kotlintest.properties.Gen import arrow.Eq import arrow.IsoLaws import arrow.ListKWMonadCombineInstance import arrow.ListKWMonoidInstanceImplicits import arrow.NonEmptyListSemigroupInstanceImplicits import arrow.OptionMonoidInstanceImplicits import arrow.OptionalLaws import arrow.UnitSpec import arrow.genFunctionAToB import arrow.genNonEmptyList import arrow.genOption import arrow.isos import arrow.k import org.junit.runner.RunWith @RunWith(KTestJUnitRunner::class) class ListInstancesTest : UnitSpec() { init { testLaws( OptionalLaws.laws( optional = listHead(), aGen = Gen.list(Gen.int()), bGen = Gen.int(), funcGen = genFunctionAToB(Gen.int()), EQA = Eq.any(), EQB = Eq.any(), EQOptionB = Eq.any()), OptionalLaws.laws( optional = listTail(), aGen = Gen.list(Gen.int()), bGen = Gen.list(Gen.int()), funcGen = genFunctionAToB(Gen.list(Gen.int())), EQA = Eq.any(), EQB = Eq.any(), EQOptionB = Eq.any()), IsoLaws.laws( iso = listToOptionNel(), aGen = Gen.list(Gen.int()), bGen = genOption(genNonEmptyList(Gen.int())), funcGen = genFunctionAToB(genOption(genNonEmptyList(Gen.int()))), EQA = Eq.any(), EQB = Eq.any(), bMonoid = OptionMonoidInstanceImplicits.instance(NonEmptyListSemigroupInstanceImplicits.instance<Int>())), IsoLaws.laws( iso = listToListKW(), aGen = Gen.list(Gen.int()), bGen = Gen.create { Gen.list(Gen.int()).generate().k() }, funcGen = genFunctionAToB(Gen.create { Gen.list(Gen.int()).generate().k() }), EQA = Eq.any(), EQB = Eq.any(), bMonoid = ListKWMonoidInstanceImplicits.instance()) ) } }
0
Kotlin
0
0
4750bd6dafd57baec61329c68d2b7ec8a59916f6
2,113
arrow
Apache License 2.0
GhostInTheCell/src/main/kotlin/org/neige/codingame/ghostinthecell/Action.kt
CedrickFlocon
106,032,469
false
null
package org.neige.codingame.ghostinthecell abstract class Action { abstract fun play(): String } object Waiting : Action() { override fun play(): String { return "WAIT" } } class Messaging(private val message: String) : Action() { override fun play(): String { return "MSG $message" } }
0
Kotlin
0
4
8d3ba5436af69a603127755613612c3540ed23a2
330
Codingame
Do What The F*ck You Want To Public License
src/main/kotlin/ar/edu/unq/ttip/grupo1s12022/OdontoTTIPbackend/service/TurnoService.kt
mlucas94
480,573,619
false
{"Kotlin": 7079}
package ar.edu.unq.ttip.grupo1s12022.OdontoTTIPbackend.service import ar.edu.unq.ttip.grupo1s12022.OdontoTTIPbackend.dto.TurnoDTO import ar.edu.unq.ttip.grupo1s12022.OdontoTTIPbackend.model.Turno import ar.edu.unq.ttip.grupo1s12022.OdontoTTIPbackend.persistence.TurnoPersistence import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import org.springframework.web.server.ResponseStatusException @Service class TurnoService { @Autowired lateinit var turnoRepository: TurnoPersistence @Transactional(readOnly = true) fun getTurno(id: Long): TurnoDTO { var turno = turnoRepository.findById(id).orElseThrow { ResponseStatusException(HttpStatus.NOT_FOUND, "No se encontro el turno con el id $id") } return TurnoDTO().fromTurno(turno) } @Transactional(readOnly = true) fun getTurnos(): MutableIterable<Turno> = turnoRepository.findAll() @Transactional fun deleteTurno(id: Long) { turnoRepository.deleteById(id) } @Transactional fun saveTurno(turno: Turno): TurnoDTO { turno.validar() var result = TurnoDTO() var turnoGuardado = turnoRepository.save(turno) return result.fromTurno(turnoGuardado) } }
0
Kotlin
0
0
d52caa1339a0c86a44c22eab348a7268a035712e
1,398
OdontoTTIP-backend
MIT License
src/main/kotlin/com/tankobon/utils/Sha256.kt
AcetylsalicylicAcid
445,686,330
false
null
package com.tankobon.utils import java.nio.charset.StandardCharsets import java.security.MessageDigest fun sha256(str: String): ByteArray = MessageDigest.getInstance("SHA-256") .digest(str.toByteArray(StandardCharsets.UTF_8)) fun ByteArray.toHex() = joinToString(separator = "") { byte -> "%02x".format(byte) }
0
Kotlin
0
4
fa63eb8eed91dd4a9177a3644c105c66b8ca8c3d
330
tankobon-backend-kotlin
MIT License
app/src/main/java/com/bitshares/oases/ui/account_ktor/K_AccountViewModel.kt
huskcasaca
464,732,039
false
null
package com.bitshares.oases.ui.account_ktor import android.app.Application import android.content.Intent import androidx.lifecycle.* import bitshareskit.chain.ChainConfig import bitshareskit.extensions.* import bitshareskit.models.FullAccount import bitshareskit.models.PrivateKey import bitshareskit.models.PublicKey import bitshareskit.objects.* import com.bitshares.oases.chain.AccountBalance import com.bitshares.oases.chain.IntentParameters import com.bitshares.oases.chain.blockchainDatabaseScope import com.bitshares.oases.chain.resolveAccountPath import com.bitshares.oases.globalWalletManager import com.bitshares.oases.preference.old.Graphene import com.bitshares.oases.preference.old.Settings import com.bitshares.oases.provider.chain_repo.* import com.bitshares.oases.provider.local_repo.LocalUserRepository import com.bitshares.oases.ui.base.BaseViewModel import com.bitshares.oases.ui.base.getJson import graphene.chain.K102_AccountObject import graphene.protocol.* import graphene.rpc.DatabaseClientAPI import graphene.rpc.MultiClient import graphene.rpc.Node import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import modulon.extensions.livedata.* import java.math.BigDecimal open class K_AccountViewModel(application: Application) : BaseViewModel(application) { private val databaseApi by lazy { MultiClient().run { switch(Node("XN_DELEGATE", "wss://api.btsgo.net/ws")) DatabaseClientAPI(this) } } val accountUID = mutableLiveDataOf(0UL) val account = accountUID.mapSuspend { (databaseApi.getObject(it.toAccount()) as K102_AccountObject?).orEmpty() } override fun onActivityIntent(intent: Intent?) { super.onActivityIntent(intent) intent ?: return logcat("onActivityIntent", intent.action) when (intent.action) { Intent.ACTION_MAIN -> return Intent.ACTION_VIEW -> { val uri = intent.data?.normalizeScheme() if (uri != null) { viewModelScope.launch { val accountPath = uri.pathSegments.firstOrNull() val account = resolveAccountPath(accountPath) withContext(Dispatchers.Main) { accountUID.value = account.uid.toULong() } } } } null -> { val accountInstance = intent.getJson(IntentParameters.Account.KEY_UID, ChainConfig.EMPTY_INSTANCE) val chainId = intent.getJson(IntentParameters.Chain.KEY_CHAIN_ID, ChainConfig.EMPTY_STRING_ID) if (chainId != ChainConfig.EMPTY_STRING_ID) { // chainIdManual.value = chainId // accountUid.value = if (chainId == ChainPropertyRepository.chainId) accountInstance else ChainConfig.EMPTY_INSTANCE // userUid.value = accountInstance accountUID.value = accountInstance.toULong() } else { // accountUid.value = accountInstance // userUid.value = accountInstance accountUID.value = accountInstance.toULong() } } else -> return } } }
0
Kotlin
4
5
2522ec7169a5fd295225caf936bae2edf09b157e
3,303
bitshares-oases-android
MIT License
app/src/main/java/com/bitshares/oases/ui/account_ktor/K_AccountViewModel.kt
huskcasaca
464,732,039
false
null
package com.bitshares.oases.ui.account_ktor import android.app.Application import android.content.Intent import androidx.lifecycle.* import bitshareskit.chain.ChainConfig import bitshareskit.extensions.* import bitshareskit.models.FullAccount import bitshareskit.models.PrivateKey import bitshareskit.models.PublicKey import bitshareskit.objects.* import com.bitshares.oases.chain.AccountBalance import com.bitshares.oases.chain.IntentParameters import com.bitshares.oases.chain.blockchainDatabaseScope import com.bitshares.oases.chain.resolveAccountPath import com.bitshares.oases.globalWalletManager import com.bitshares.oases.preference.old.Graphene import com.bitshares.oases.preference.old.Settings import com.bitshares.oases.provider.chain_repo.* import com.bitshares.oases.provider.local_repo.LocalUserRepository import com.bitshares.oases.ui.base.BaseViewModel import com.bitshares.oases.ui.base.getJson import graphene.chain.K102_AccountObject import graphene.protocol.* import graphene.rpc.DatabaseClientAPI import graphene.rpc.MultiClient import graphene.rpc.Node import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import modulon.extensions.livedata.* import java.math.BigDecimal open class K_AccountViewModel(application: Application) : BaseViewModel(application) { private val databaseApi by lazy { MultiClient().run { switch(Node("XN_DELEGATE", "wss://api.btsgo.net/ws")) DatabaseClientAPI(this) } } val accountUID = mutableLiveDataOf(0UL) val account = accountUID.mapSuspend { (databaseApi.getObject(it.toAccount()) as K102_AccountObject?).orEmpty() } override fun onActivityIntent(intent: Intent?) { super.onActivityIntent(intent) intent ?: return logcat("onActivityIntent", intent.action) when (intent.action) { Intent.ACTION_MAIN -> return Intent.ACTION_VIEW -> { val uri = intent.data?.normalizeScheme() if (uri != null) { viewModelScope.launch { val accountPath = uri.pathSegments.firstOrNull() val account = resolveAccountPath(accountPath) withContext(Dispatchers.Main) { accountUID.value = account.uid.toULong() } } } } null -> { val accountInstance = intent.getJson(IntentParameters.Account.KEY_UID, ChainConfig.EMPTY_INSTANCE) val chainId = intent.getJson(IntentParameters.Chain.KEY_CHAIN_ID, ChainConfig.EMPTY_STRING_ID) if (chainId != ChainConfig.EMPTY_STRING_ID) { // chainIdManual.value = chainId // accountUid.value = if (chainId == ChainPropertyRepository.chainId) accountInstance else ChainConfig.EMPTY_INSTANCE // userUid.value = accountInstance accountUID.value = accountInstance.toULong() } else { // accountUid.value = accountInstance // userUid.value = accountInstance accountUID.value = accountInstance.toULong() } } else -> return } } }
0
Kotlin
4
5
2522ec7169a5fd295225caf936bae2edf09b157e
3,303
bitshares-oases-android
MIT License
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/contactdiary/storage/dao/ContactDiaryPersonDao.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.contactdiary.storage.dao import androidx.room.Dao import androidx.room.Query import de.rki.coronawarnapp.contactdiary.storage.entity.ContactDiaryPersonEntity import kotlinx.coroutines.flow.Flow @Dao abstract class ContactDiaryPersonDao : BaseRoomDao<ContactDiaryPersonEntity, ContactDiaryPersonEntity>() { @Query("SELECT * FROM persons") abstract override fun allEntries(): Flow<List<ContactDiaryPersonEntity>> @Query("SELECT * FROM persons WHERE personId = :id") abstract override suspend fun entityForId(id: Long): ContactDiaryPersonEntity @Query("DELETE FROM persons") abstract override suspend fun deleteAll() }
6
Kotlin
514
2,495
d3833a212bd4c84e38a1fad23b282836d70ab8d5
674
cwa-app-android
Apache License 2.0
shared/src/commonMain/kotlin/com/nimesh/vasani/melodybeatblastkmp/network/models/topfiftycharts/VideoThumbnail.kt
NimeshVasani
778,497,675
false
{"Kotlin": 1083587, "Swift": 1032, "HTML": 239, "Ruby": 228, "JavaScript": 152}
package com.nimesh.vasani.melodybeatblastkmp.network.models.topfiftycharts import com.arkivanov.essenty.parcelable.Parcelable import com.arkivanov.essenty.parcelable.Parcelize import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Parcelize @Serializable data class VideoThumbnail( @SerialName("url") val url: String? ):Parcelable
0
Kotlin
0
0
4c09e28cce471dbdb8ae0847ba92a1f13fdef131
369
melody_BeatBlast_KMP
Info-ZIP License
src/main/kotlin/me/theseems/crodl/entity/Article.kt
Crodl
385,952,098
false
null
package me.theseems.crodl.entity import me.theseems.crodl.entity.extensions.Users import javax.persistence.* import javax.validation.constraints.NotNull @Entity(name = "CrodlArticle") @Table(name = "crodl_articles") data class Article( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long = -1, @Column(nullable = false, length = 64) @NotNull val title: String = "", @ManyToOne(fetch = FetchType.EAGER) @NotNull var author: User = Users.default, @Column(nullable = false, length = 256) @NotNull val preText: String = "", @Column(nullable = false, length = 5096) @NotNull val fullText: String = "" )
11
Kotlin
0
4
68d4cb2e72c0360347a67bc9f7e0f965775fa1d4
680
crodl-backend
MIT License
app/src/main/java/dev/patrickgold/florisboard/setup/EnableImeFragment.kt
hosseinkhojany
356,598,539
false
null
package dev.patrickgold.florisboard.setup import android.content.Intent import android.os.Bundle import android.provider.Settings import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import dev.patrickgold.florisboard.databinding.SetupFragmentEnableImeBinding import dev.patrickgold.florisboard.ime.core.FlorisBoard class EnableImeFragment : Fragment() { private lateinit var binding: SetupFragmentEnableImeBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = SetupFragmentEnableImeBinding.inflate(inflater, container, false) binding.languageAndInputButton.setOnClickListener { val intent = Intent() intent.action = Settings.ACTION_INPUT_METHOD_SETTINGS intent.addCategory(Intent.CATEGORY_DEFAULT) startActivity(intent) } return binding.root } override fun onResume() { super.onResume() if (FlorisBoard.checkIfImeIsEnabled(requireContext())) { (activity as SetupActivity).changePositiveButtonState(true) binding.textAfterEnabled.visibility = View.VISIBLE } else { (activity as SetupActivity).changePositiveButtonState(false) binding.textAfterEnabled.visibility = View.INVISIBLE } } }
0
Kotlin
0
0
e9fc3246d834d626b073563c175a4a1445b739f1
1,452
KeyLogger
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/HTTPRequest.kt
ShalokShalom
343,354,086
true
{"Kotlin": 516486, "GDScript": 294955, "C++": 262753, "C#": 11670, "CMake": 2060, "Shell": 1628, "C": 959, "Python": 75}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName") package godot import godot.HTTPClient import godot.annotation.GodotBaseType import godot.core.GodotError import godot.core.PoolByteArray import godot.core.PoolStringArray import godot.core.TransferContext import godot.core.VariantType.BOOL import godot.core.VariantType.JVM_INT import godot.core.VariantType.LONG import godot.core.VariantType.NIL import godot.core.VariantType.POOL_STRING_ARRAY import godot.core.VariantType.STRING import godot.signals.Signal4 import godot.signals.signal import godot.util.VoidPtr import kotlin.Boolean import kotlin.Int import kotlin.Long import kotlin.String import kotlin.Suppress @GodotBaseType open class HTTPRequest : Node() { val requestCompleted: Signal4<Long, Long, PoolStringArray, PoolByteArray> by signal("result", "response_code", "headers", "body") open var bodySizeLimit: Long get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_GET_BODY_SIZE_LIMIT, LONG) return TransferContext.readReturnValue(LONG, false) as Long } set(value) { TransferContext.writeArguments(LONG to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_SET_BODY_SIZE_LIMIT, NIL) } open var downloadChunkSize: Long get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_GET_DOWNLOAD_CHUNK_SIZE, LONG) return TransferContext.readReturnValue(LONG, false) as Long } set(value) { TransferContext.writeArguments(LONG to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_SET_DOWNLOAD_CHUNK_SIZE, NIL) } open var downloadFile: String get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_GET_DOWNLOAD_FILE, STRING) return TransferContext.readReturnValue(STRING, false) as String } set(value) { TransferContext.writeArguments(STRING to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_SET_DOWNLOAD_FILE, NIL) } open var maxRedirects: Long get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_GET_MAX_REDIRECTS, LONG) return TransferContext.readReturnValue(LONG, false) as Long } set(value) { TransferContext.writeArguments(LONG to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_SET_MAX_REDIRECTS, NIL) } open var timeout: Long get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_GET_TIMEOUT, LONG) return TransferContext.readReturnValue(LONG, false) as Long } set(value) { TransferContext.writeArguments(LONG to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_SET_TIMEOUT, NIL) } open var useThreads: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_GET_USE_THREADS, BOOL) return TransferContext.readReturnValue(BOOL, false) as Boolean } set(value) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_SET_USE_THREADS, NIL) } override fun __new(): VoidPtr = TransferContext.invokeConstructor(ENGINECLASS_HTTPREQUEST) open fun _redirectRequest(arg0: String) { } open fun _requestDone( arg0: Long, arg1: Long, arg2: PoolStringArray, arg3: PoolByteArray ) { } open fun _timeout() { } open fun cancelRequest() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_CANCEL_REQUEST, NIL) } open fun getBodySize(): Long { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_GET_BODY_SIZE, LONG) return TransferContext.readReturnValue(LONG, false) as Long } open fun getDownloadedBytes(): Long { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_GET_DOWNLOADED_BYTES, LONG) return TransferContext.readReturnValue(LONG, false) as Long } open fun getHttpClientStatus(): HTTPClient.Status { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_GET_HTTP_CLIENT_STATUS, LONG) return HTTPClient.Status.values()[TransferContext.readReturnValue(JVM_INT) as Int] } open fun request( url: String, customHeaders: PoolStringArray = PoolStringArray(), sslValidateDomain: Boolean = true, method: Long = 0, requestData: String = "" ): GodotError { TransferContext.writeArguments(STRING to url, POOL_STRING_ARRAY to customHeaders, BOOL to sslValidateDomain, LONG to method, STRING to requestData) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_HTTPREQUEST_REQUEST, LONG) return GodotError.values()[TransferContext.readReturnValue(JVM_INT) as Int] } enum class Result( id: Long ) { RESULT_SUCCESS(0), RESULT_CHUNKED_BODY_SIZE_MISMATCH(1), RESULT_CANT_CONNECT(2), RESULT_CANT_RESOLVE(3), RESULT_CONNECTION_ERROR(4), RESULT_SSL_HANDSHAKE_ERROR(5), RESULT_NO_RESPONSE(6), RESULT_BODY_SIZE_LIMIT_EXCEEDED(7), RESULT_REQUEST_FAILED(8), RESULT_DOWNLOAD_FILE_CANT_OPEN(9), RESULT_DOWNLOAD_FILE_WRITE_ERROR(10), RESULT_REDIRECT_LIMIT_REACHED(11), RESULT_TIMEOUT(12); val id: Long init { this.id = id } companion object { fun from(value: Long) = values().single { it.id == value } } } companion object { final const val RESULT_BODY_SIZE_LIMIT_EXCEEDED: Long = 7 final const val RESULT_CANT_CONNECT: Long = 2 final const val RESULT_CANT_RESOLVE: Long = 3 final const val RESULT_CHUNKED_BODY_SIZE_MISMATCH: Long = 1 final const val RESULT_CONNECTION_ERROR: Long = 4 final const val RESULT_DOWNLOAD_FILE_CANT_OPEN: Long = 9 final const val RESULT_DOWNLOAD_FILE_WRITE_ERROR: Long = 10 final const val RESULT_NO_RESPONSE: Long = 6 final const val RESULT_REDIRECT_LIMIT_REACHED: Long = 11 final const val RESULT_REQUEST_FAILED: Long = 8 final const val RESULT_SSL_HANDSHAKE_ERROR: Long = 5 final const val RESULT_SUCCESS: Long = 0 final const val RESULT_TIMEOUT: Long = 12 } }
0
null
0
1
7b9b195de5be4a0b88b9831c3a02f9ca06aa399c
6,940
godot-jvm
MIT License
reactor/Core/src/jetbrains/mps/logic/reactor/core/internal/ProcessingStrategy.kt
JetBrains
94,222,533
false
null
/* * Copyright 2014-2020 JetBrains s.r.o. * * 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 jetbrains.mps.logic.reactor.core.internal import jetbrains.mps.logic.reactor.core.* import jetbrains.mps.logic.reactor.evaluation.EvaluationTrace import jetbrains.mps.logic.reactor.program.Constraint import jetbrains.mps.logic.reactor.program.IncrementalContractViolationException import jetbrains.mps.logic.reactor.program.IncrementalSpec import jetbrains.mps.logic.reactor.program.Rule /** * Facade interface for incremental processing. * * Specifies points in program evaluation where * incremental processing must be must be injected: * [offerMatch], [processMatch], [processOccurrenceMatches], * [processActivated], [processInvalidated]. * * Provides an entry point for evaluation: [run]. * * Provides additional session output through * [invalidatedFeedback] & [invalidatedRules]. */ internal interface ProcessingStrategy { /** * Output of incremental processing session. * * Specifies keys for invalid program feedback * so that caller could clear it. * * @return collection of invalid program feedback keys. */ fun invalidatedFeedback(): FeedbackKeySet /** * Output of incremental processing session. * * Specifies unique tags of principal rules which * matches were invalidated. From this rule information * it can be inferred which rule origins were affected. * * @return collection of unique tags of affected rules. */ fun invalidatedRules(): List<Any> /** * Entry point for processing session. */ fun run(processing: ConstraintsProcessing, controller: Controller, main: Constraint): FeedbackStatus /** * Injection point into program evaluation process. * * Called before [Controller.offerMatch]. * Allows to omit match (by returning `false`) * from usual evaluation process and handle it * in some special manner according to strategy. * * @return `true` if match isn't affected by the strategy, * `false` if it was and must be omitted. */ fun offerMatch(match: RuleMatchEx): Boolean /** * Injection point into program evaluation process. * * Pre-process [match] accepted by [Controller.offerMatch] * before general processing in [Controller.processBody]. * Aimed at processing heads of the [match], while [match] * itself is evaluated in a usual manner by [Controller]. */ fun processMatch(match: RuleMatchEx) /** * Injection point into program evaluation process. * * Processes [matches] of activated [Occurrence] * returned by [Dispatcher.DispatchingFront.matches]. * Allows to filter [matches] according to the strategy * e.g. postpone them or drop entirely. * * In contrast to [offerMatch], happens earlier and allows * to process all new matches of [active] at once. * * @return list of filtered [matches]. */ fun processOccurrenceMatches(active: Occurrence, matches: List<RuleMatchEx>): List<RuleMatchEx> /** * Injection point into program evaluation process. * * Called on new activated [Occurrence]. * Allows to handle program's logical state, * e.g. add processing-specific observers with [observable]. */ fun processActivated(active: Occurrence, observable: LogicalStateObservable) // fixme: essentially InvalidationStage.invalidateChunk redirects back here -- unnecessary circle /** * Injection point into program evaluation process. * * Called for invalidated [Occurrence]s. * It's a pair method for [processActivated] to discharge * its effects, e.g. to clear program logical state. */ fun processInvalidated(occ: Occurrence, observable: LogicalStateObservable) } /** * Default non-incremental processing with stubs. Does nothing. */ internal open class EmptyProcessing: ProcessingStrategy { override fun invalidatedFeedback(): FeedbackKeySet = emptySet() override fun invalidatedRules(): List<Any> = emptyList() /** * Entry point. Simply redirects evaluation to [Controller]. */ override fun run(processing: ConstraintsProcessing, controller: Controller, main: Constraint) = controller.activate(main) override fun offerMatch(match: RuleMatchEx): Boolean = true override fun processMatch(match: RuleMatchEx) {} override fun processOccurrenceMatches(active: Occurrence, matches: List<RuleMatchEx>): List<RuleMatchEx> = matches override fun processActivated(active: Occurrence, observable: LogicalStateObservable) {} override fun processInvalidated(occ: Occurrence, observable: LogicalStateObservable) {} }
0
Kotlin
5
26
a09dd24413a9f6650410af07684bf6062742e422
5,287
mps-coderules
Apache License 2.0
bellatrix.web/src/main/java/solutions/bellatrix/web/components/contracts/ComponentMax.kt
AutomateThePlanet
334,964,015
false
null
/* * Copyright 2021 Automate The Planet Ltd. * Author: <NAME> * Licensed under the Apache License, Version 2.0 (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package solutions.bellatrix.web.components.contracts import solutions.bellatrix.web.components.WebComponent import solutions.bellatrix.web.validations.ComponentValidator interface ComponentMax : Component { val max: Double? fun validateMaxIsSet() { defaultValidateAttributeNotNull(this as WebComponent, max, "max") } fun validateMaxNotSet() { defaultValidateAttributeIsNull(this as WebComponent, max, "max") } fun validateMaxIs(value: Number) { defaultValidateAttributeIs(this as WebComponent, max, value.toDouble(), "max") } companion object : ComponentValidator() }
1
Kotlin
1
1
5da5e705b47e12c66937d130b3031ac8703b8279
1,239
BELLATRIX-Kotlin
Apache License 2.0
app/src/main/java/ramble/sokol/sberafisha/model_request/TokenManager.kt
InverseTeam
674,135,722
false
null
package ramble.sokol.sberafisha.model_request import android.content.Context class TokenManager(context: Context) { companion object{ private const val PREF_TOKEN = "PREF_TOKEN" private const val USER_TOKEN = "USER_TOKEN" } private var sPref = context.getSharedPreferences(PREF_TOKEN, Context.MODE_PRIVATE) fun saveToken(token: String){ val editor = sPref.edit() editor.putString(USER_TOKEN, token) editor.apply() } fun getToken() : String? { return sPref.getString(USER_TOKEN, null) } }
0
Kotlin
0
1
f550e0b932106d6dd0181f86baa2cd627572085b
570
SberAfisha-Mobile
MIT License
examples/minecraft/sponge/kotlin/src/main/kotlin/com/asledgehammer/langpack/sponge/example/kotlin/ExamplePlugin.kt
asledgehammer
341,660,344
false
{"Text": 2, "Gradle": 14, "Markdown": 2, "INI": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Kotlin": 93, "YAML": 36, "JSON": 3, "Java": 3, "XML": 4}
package com.asledgehammer.langpack.sponge.example.kotlin import com.asledgehammer.langpack.core.objects.LangArg import com.asledgehammer.langpack.sponge.SpongeLangPack import org.spongepowered.api.Sponge import org.spongepowered.api.event.Listener import org.spongepowered.api.event.entity.living.humanoid.player.PlayerChangeClientSettingsEvent import org.spongepowered.api.event.game.state.GameInitializationEvent import org.spongepowered.api.event.game.state.GameStoppingServerEvent import org.spongepowered.api.event.network.ClientConnectionEvent import org.spongepowered.api.plugin.Dependency import org.spongepowered.api.plugin.Plugin import org.spongepowered.api.scheduler.Task import java.util.* /** * @author Jab */ @Plugin( id = "langpack_sponge_example_kotlin", name = "LangPack_Sponge_Example_Kotlin", version = "1.0.0", dependencies = [Dependency(id = "langpack")] ) class ExamplePlugin { private val greetMap = HashMap<UUID, Boolean>() private val pack = SpongeLangPack(this::class.java.classLoader) @Listener fun on(event: GameInitializationEvent) { pack.append("lang_example_kotlin", true) } @Listener fun on(event: GameStoppingServerEvent) { greetMap.clear() } @Listener fun on(event: PlayerChangeClientSettingsEvent) { val player = event.targetEntity val playerId = player.uniqueId if (greetMap.containsKey(playerId)) { greetMap.remove(playerId) // Delay for one tick to let the server apply the settings changes to the player. -Jab val tasks = Sponge.getRegistry().createBuilder(Task.Builder::class.java) tasks.delayTicks(1L) tasks.execute(Runnable { pack.broadcast("event.enter_server", LangArg("player", player.name)) }).submit(this) } } @Listener fun on(event: ClientConnectionEvent.Join) { event.isMessageCancelled = true val player = event.targetEntity // The server executes this event prior to the client sending the locale information. Log the information to be // processed only when the client settings are sent. -Jab greetMap[player.uniqueId] = true } @Listener fun on(event: ClientConnectionEvent.Disconnect) { event.isMessageCancelled = true val player = event.targetEntity val playerId = player.uniqueId if (greetMap.containsKey(playerId)) { greetMap.remove(playerId) return } pack.broadcast("event.leave_server", LangArg("player", player.name)) } }
2
Kotlin
0
0
f88aaddc0bcf24f7986fea44f46296d3d9e2d78b
2,624
LangPack
Apache License 2.0
src/test/kotlin/nl/dirkgroot/structurizr/dsl/parser/ElementsWithBlocksOfElementsTest.kt
dirkgroot
561,786,663
false
{"Kotlin": 75605, "Lex": 2479, "ASL": 463}
package nl.dirkgroot.structurizr.dsl.parser import nl.dirkgroot.structurizr.dsl.lexer.KEYWORDS_WITH_BLOCKS import nl.dirkgroot.structurizr.dsl.support.StructurizrDSLCodeInsightTest import org.junit.jupiter.api.DynamicTest.dynamicTest import org.junit.jupiter.api.TestFactory class ElementsWithBlocksOfElementsTest : StructurizrDSLCodeInsightTest() { @TestFactory fun `empty block`() = KEYWORDS_WITH_BLOCKS.map { (keyword, _) -> dynamicTest(keyword) { assertPsiTree( """ $keyword { } """.trimIndent(), """ BlockStatement Keyword $keyword Block {\n} """.trimIndent() ) } } @TestFactory fun `block with only empty lines inside`() = KEYWORDS_WITH_BLOCKS.map { (keyword, _) -> dynamicTest(keyword) { assertPsiTree( """ $keyword { } """.trimIndent(), """ BlockStatement Keyword $keyword Block {\n\n\n} """.trimIndent() ) } } @TestFactory fun `block with single line element inside`() = KEYWORDS_WITH_BLOCKS.map { (keyword, _) -> dynamicTest(keyword) { val (elementKeyword, _) = KEYWORDS_WITH_BLOCKS.random() assertPsiTree( """ $keyword { $elementKeyword arg1 } """.trimIndent(), """ BlockStatement Keyword $keyword Block SingleLineStatement Keyword $elementKeyword Argument arg1 """.trimIndent() ) } } @TestFactory fun `block with multiple single line elements inside`() = KEYWORDS_WITH_BLOCKS.map { (keyword, _) -> dynamicTest(keyword) { val (elementKeyword, _) = KEYWORDS_WITH_BLOCKS.random() assertPsiTree( """ $keyword { $elementKeyword arg1 $elementKeyword arg2 $elementKeyword arg3 } """.trimIndent(), """ BlockStatement Keyword $keyword Block SingleLineStatement Keyword $elementKeyword Argument arg1 SingleLineStatement Keyword $elementKeyword Argument arg2 SingleLineStatement Keyword $elementKeyword Argument arg3 """.trimIndent() ) } } @TestFactory fun `nested blocks`() = KEYWORDS_WITH_BLOCKS.map { (keyword, _) -> dynamicTest(keyword) { val (elementKeyword, _) = KEYWORDS_WITH_BLOCKS.random() assertPsiTree( """ $keyword { $elementKeyword arg1 { } $elementKeyword arg2 { } } """.trimIndent(), """ BlockStatement Keyword $keyword Block BlockStatement Keyword $elementKeyword Argument arg1 Block {\n } BlockStatement Keyword $elementKeyword Argument arg2 Block {\n } """.trimIndent() ) } } }
6
Kotlin
1
37
660fec2b36b14b366cf9f7caae2d1b5788bb42f3
4,216
structurizr-dsl-intellij-plugin
MIT License
common/src/main/kotlin/dev/throwouterror/game/common/data/Block.kt
throw-out-error
277,902,461
false
null
package dev.throwouterror.game.common.data import dev.throwouterror.game.common.Transform class Block(var type: String, val transform: Transform) { }
1
Kotlin
0
0
02552c64b68560a5e5312aa779b1a41c3717024f
155
java-game
MIT License
app/src/main/java/de/fluchtwege/vocabulary/di/AppModule.kt
kaskasi
97,953,783
false
null
package de.fluchtwege.vocabulary.di import com.google.gson.GsonBuilder import dagger.Module import dagger.Provides import de.fluchtwege.vocabulary.Vocabulary import de.fluchtwege.vocabulary.analytics.Events import de.fluchtwege.vocabulary.analytics.FirebaseEvents import de.fluchtwege.vocabulary.configuration.Configuration import de.fluchtwege.vocabulary.configuration.FirebaseConfiguration import de.fluchtwege.vocabulary.lessons.LessonsController import de.fluchtwege.vocabulary.lessons.LessonsRepository import de.fluchtwege.vocabulary.lessons.RoomLessonsRepository import de.fluchtwege.vocabulary.persistance.RepositoryId import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.Executors @Module class AppModule(val vocabulary: Vocabulary) { private val baseUrl = "https://api.myjson.com/" private val subscribeOn = Schedulers.io() private val observeOn = AndroidSchedulers.mainThread() private var retrofit: Retrofit? = null @Provides fun provideRetrofit(): Retrofit { if (retrofit == null) { retrofit = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create())) .callbackExecutor(Executors.newCachedThreadPool()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(createHttpClient()) .baseUrl(baseUrl) .build() } return retrofit!! } private fun createHttpClient(): OkHttpClient { val builder = OkHttpClient.Builder() val logLevel = HttpLoggingInterceptor.Level.BODY val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = logLevel builder.addInterceptor(loggingInterceptor) return builder.build() } @Provides fun provideRepositoryUrl(): RepositoryId { return RepositoryId(vocabulary) } @Provides fun provideConfiguration(): Configuration { return FirebaseConfiguration() } @Provides fun provideEvents(): Events { return FirebaseEvents(vocabulary) } @Provides fun provideLessonsController(retrofit: Retrofit, repositoryId: RepositoryId): LessonsController { val lessonsApi = retrofit.create(LessonsController.LessonsApi::class.java) return LessonsController(lessonsApi, repositoryId) } @Provides fun provideLessonsRepository(lessonsController: LessonsController): LessonsRepository { return RoomLessonsRepository(lessonsController, vocabulary.database, observeOn, subscribeOn) } }
1
null
1
3
0026f31f4dfccdfb653ed8e34f63e1f1725df408
2,901
VocabularyTrainer
MIT License
common/api/src/commonMain/kotlin/com/denchic45/studiversity/api/submission/model/SubmissionByAuthor.kt
denchic45
435,895,363
false
{"Kotlin": 2110094, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.api.submission.model import kotlinx.serialization.Serializable @Serializable data class SubmissionByAuthor( val author: SubmissionAuthor, val submission: SubmissionResponse? )
0
Kotlin
0
7
293132d2f93ba3e42a3efe9b54deb07d7ff5ecf9
221
Studiversity
Apache License 2.0
src/main/kotlin/no/nav/helse/flex/brukernotifikasjon/Brukernotifikasjon.kt
navikt
495,745,215
false
{"Kotlin": 119326, "Dockerfile": 267}
package no.nav.helse.flex.brukernotifikasjon import io.micrometer.core.instrument.MeterRegistry import no.nav.helse.flex.kafka.MINSIDE_BRUKERVARSEL import no.nav.helse.flex.logger import no.nav.helse.flex.util.norskDateFormat import no.nav.tms.varsel.action.* import no.nav.tms.varsel.builder.VarselActionBuilder import org.apache.kafka.clients.producer.KafkaProducer import org.apache.kafka.clients.producer.ProducerRecord import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component import java.time.Instant import java.time.LocalDate import java.time.ZoneOffset.UTC @Component class Brukernotifikasjon( private val kafkaProducer: KafkaProducer<String, String>, @Value("\${INNTEKTSMELDING_MANGLER_URL}") private val inntektsmeldingManglerUrl: String, private val registry: MeterRegistry, ) { val log = logger() fun beskjedManglerInntektsmelding( fnr: String, eksternId: String, bestillingId: String, orgNavn: String, fom: LocalDate, synligFremTil: Instant, ) { registry.counter("brukernotifikasjon_mangler_inntektsmelding_beskjed_sendt").increment() val opprettVarsel = VarselActionBuilder.opprett { type = Varseltype.Beskjed varselId = bestillingId sensitivitet = Sensitivitet.High ident = fnr tekst = Tekst( spraakkode = "nb", tekst = "Vi mangler inntektsmeldingen fra $orgNavn for sykefraværet som startet ${ fom.format( norskDateFormat, ) }.", default = true, ) aktivFremTil = synligFremTil.atZone(UTC) link = inntektsmeldingManglerUrl eksternVarsling = null } kafkaProducer.send(ProducerRecord(MINSIDE_BRUKERVARSEL, bestillingId, opprettVarsel)).get() log.info("Bestilte beskjed for manglende inntektsmelding $eksternId") } fun sendDonemelding( fnr: String, eksternId: String, bestillingId: String, ) { registry.counter("brukernotifikasjon_done_sendt").increment() val inaktiverVarsel = VarselActionBuilder.inaktiver { varselId = bestillingId } kafkaProducer.send(ProducerRecord(MINSIDE_BRUKERVARSEL, bestillingId, inaktiverVarsel)).get() } }
4
Kotlin
0
0
df3897cf4fdd18af4b96de6f11232908b4426e88
2,587
flex-inntektsmelding-status
MIT License
app/src/main/java/com/angelomoroni/githubrepoexplorer/KoinModules.kt
chemickypes
154,942,353
false
null
package com.angelomoroni.githubrepoexplorer import android.app.Application import androidx.room.Room import com.angelomoroni.githubrepoexplorer.datalayer.UserDatabase import com.angelomoroni.githubrepoexplorer.datalayer.UserRepository import com.angelomoroni.githubrepoexplorer.ui.user.UserViewModel import org.koin.android.ext.android.startKoin import org.koin.android.ext.koin.androidApplication import org.koin.androidx.viewmodel.ext.koin.viewModel import org.koin.dsl.module.module val appModule = module { single { UserRepository(get()) } viewModel { UserViewModel(get()) } factory { Room.databaseBuilder(androidApplication(), UserDatabase::class.java, "users-db") .build() } //UserDao single { get<UserDatabase>().userDao() } } class GitHubExplorerApp: Application() { override fun onCreate() { super.onCreate() startKoin(this, listOf(appModule)) } }
0
Kotlin
0
1
cce3b20e224baad74d220394e0b73752e863fee1
960
GitHubRepoExplorer
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/PencilSearch.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.PencilSearch: ImageVector get() { if (_pencilSearch != null) { return _pencilSearch!! } _pencilSearch = Builder(name = "PencilSearch", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.0f, 11.0f) lineToRelative(1.5f, -1.5f) arcToRelative(2.828f, 2.828f, 0.0f, true, false, -4.0f, -4.0f) lineToRelative(-10.5f, 10.5f) verticalLineToRelative(4.0f) horizontalLineToRelative(4.0f) lineToRelative(3.0f, -3.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.5f, 6.5f) lineToRelative(4.0f, 4.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.0f, 18.0f) moveToRelative(-3.0f, 0.0f) arcToRelative(3.0f, 3.0f, 0.0f, true, false, 6.0f, 0.0f) arcToRelative(3.0f, 3.0f, 0.0f, true, false, -6.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.2f, 20.2f) lineToRelative(1.8f, 1.8f) } } .build() return _pencilSearch!! } private var _pencilSearch: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
2,973
compose-icon-collections
MIT License
app/src/main/java/com/msa/news_msa/data/remote/model/ArticleModel.kt
ALISCHILLER
380,240,811
false
null
package com.msa.news_msa.data.remote.model import com.google.gson.annotations.SerializedName data class ArticleModel( @SerializedName("source") val source: SourceModel? = null, @SerializedName("author") val author: String? = "", @SerializedName("title") val title: String? = "", @SerializedName("description") val description: String? = "", @SerializedName("url") val url: String? = "", @SerializedName("urlToImage") val urlToImage : String? = "", @SerializedName("publishedAt") val publishedAt: String? = "", @SerializedName("content") val content: String? = "" ) data class SourceModel( @SerializedName("name") val sourceName: String? = "" )
0
Kotlin
0
0
212790514624a5bb20d86e233c9db302c9ca0d3b
799
News_MsA
Apache License 2.0
RoomBasicDemo/app/src/main/java/com/example/room/MainActivity.kt
BennyZhang-Canviz
255,919,665
false
null
package com.example.room import android.app.TaskStackBuilder import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.ui.NavigationUI import androidx.recyclerview.widget.LinearLayoutManager import com.example.room.Room.AppViewModel import com.example.room.Room.User import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) navController = Navigation.findNavController(findViewById(R.id.fragment)) NavigationUI.setupActionBarWithNavController(this,navController) } override fun onSupportNavigateUp(): Boolean { navController.navigateUp() return super.onSupportNavigateUp() } } // private var userCard:Boolean = false // private val appViewModel : AppViewModel by lazy { // ViewModelProvider(this)[AppViewModel::class.java] // } // rvMain.layoutManager = LinearLayoutManager(this) // var adapter: UserAdapter = UserAdapter(appViewModel) // adapter.userCardView(userCard) // rvMain.adapter = adapter // // appViewModel.getAllUsers().observe(this,Observer<List<User>>{ // var temp = adapter.itemCount // adapter.setUsers(it) // if(it.count() !=temp){ // adapter.notifyDataSetChanged() // } // // }) // // btnInsert.setOnClickListener(){ // for(index in 1..10){ // var user: User = User("Hankers $index","Tom $index",index,true) // appViewModel.insert(user) // } // } // // btnCard.setOnClickListener(){ // userCard = !userCard // adapter.userCardView(userCard) // rvMain.adapter = adapter // } // // btnDelete.setOnClickListener(){ // appViewModel.deleteAll() // // }
0
Kotlin
0
0
55ae049d5c880b67251e40cf658c4535d52cd017
2,215
Android
Apache License 2.0
src/test/kotlin/com/cccc/essentials/Section03NullableTypesTest.kt
Cosmic-Coding-Community-Club
553,430,065
false
{"Kotlin": 42783}
package com.cccc.essentials import com.cccc.essentials.Section03NullableTypes.THE_BEST_PHRASE import com.cccc.essentials.Section03NullableTypes.USE_THIS_VALUE_TO_DEFAULT_LENGTH import com.cccc.essentials.Section03NullableTypes.USE_THIS_VALUE_TO_DEFAULT_PHRASE import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class Section03NullableTypesTest { @Test fun shouldReturnGreenWhenCheckTask1() { assertThat(Section03NullableTypes.task1() is String).isTrue assertThat(Section03NullableTypes.task1()).isNotNull assertThat(Section03NullableTypes.task1()).isIn(THE_BEST_PHRASE, USE_THIS_VALUE_TO_DEFAULT_PHRASE) } @Test fun shouldReturnGreenWhenCheckTask2() { assertThat(Section03NullableTypes.task2() is Int).isTrue assertThat(Section03NullableTypes.task2()).isNotNull assertThat(Section03NullableTypes.task2()).isIn(THE_BEST_PHRASE.length, USE_THIS_VALUE_TO_DEFAULT_LENGTH) } @Test fun shouldReturnGreenWhenCheckTask3() { assertThat(Section03NullableTypes.task3() is String).isTrue assertThat(Section03NullableTypes.task3()).isNotNull assertThat(Section03NullableTypes.task3()) .isIn(THE_BEST_PHRASE.lowercase(), USE_THIS_VALUE_TO_DEFAULT_PHRASE.lowercase()) } }
0
Kotlin
0
2
0a76599a0f416b59e4e653666e9d0ea3de7c34b0
1,314
essential-kotlin-course
Apache License 2.0
portfolio-android/src/main/java/com/venkatasudha/portfolio/android/data/LoginDataSource.kt
kanakamedala-rajesh
336,837,088
false
null
package com.venkatasudha.portfolio.android.data import com.google.firebase.FirebaseTooManyRequestsException import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException import com.google.firebase.auth.FirebaseAuthInvalidUserException import com.google.firebase.auth.FirebaseAuthRecentLoginRequiredException import com.venkatasudha.portfolio.android.entities.NetworkRequestStates import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.tasks.await import timber.log.Timber import javax.inject.Inject /** * Class that handles authentication w/ login credentials and retrieves user information. */ class LoginDataSource @Inject constructor(private val auth: FirebaseAuth) { suspend fun emailLogin(email: String, password: String) = flow { emit(NetworkRequestStates.Loading) val loginResultTask = auth.signInWithEmailAndPassword(email, password).await() Timber.i("Login Success") emit(NetworkRequestStates.Success(data = loginResultTask.user!!)) }.catch { Timber.e("Login Failed Exception $it") emit( NetworkRequestStates.Failed( it as Exception, when (it) { is FirebaseAuthInvalidCredentialsException -> NetworkRequestStates.NetworkFailureCauses.LOGIN_FAILURE_INVALID_CREDENTIALS is FirebaseAuthInvalidUserException -> NetworkRequestStates.NetworkFailureCauses.LOGIN_FAILURE_INVALID_USER is FirebaseAuthRecentLoginRequiredException -> NetworkRequestStates.NetworkFailureCauses.LOGIN_FAILURE_RE_AUTHENTICATE is FirebaseTooManyRequestsException -> NetworkRequestStates.NetworkFailureCauses.LOGIN_FAILURE_TOO_MANY_REQUESTS else -> { NetworkRequestStates.NetworkFailureCauses.LOGIN_FAILURE_OTHER } } ) ) }.flowOn(Dispatchers.IO) fun logout() { // TODO: revoke authentication } }
0
Kotlin
0
1
118e7da9eaecc566501dcb5b16d9c8bad8b74dd6
2,153
portfolio-android-deprecated-
MIT License
foryouandme/src/main/java/com/foryouandme/ui/auth/onboarding/step/screening/page/ScreeningPageFragment.kt
4YouandMeData
610,425,317
false
null
package com.foryouandme.ui.auth.onboarding.step.screening.page import android.os.Bundle import android.view.View import androidx.navigation.fragment.navArgs import com.foryouandme.R import com.foryouandme.core.arch.flow.observeIn import com.foryouandme.core.arch.flow.unwrapEvent import com.foryouandme.core.arch.navigation.AnywhereToWeb import com.foryouandme.core.ext.setStatusBar import com.foryouandme.core.ext.showBackSecondaryButton import com.foryouandme.core.view.page.EPageType import com.foryouandme.databinding.ScreeningPageBinding import com.foryouandme.ui.auth.onboarding.step.screening.ScreeningSectionFragment import com.foryouandme.ui.auth.onboarding.step.screening.ScreeningStateUpdate import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.onEach @AndroidEntryPoint class ScreeningPageFragment : ScreeningSectionFragment(R.layout.screening_page) { private val args: ScreeningPageFragmentArgs by navArgs() private val binding: ScreeningPageBinding? get() = view?.let { ScreeningPageBinding.bind(it) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.stateUpdate .unwrapEvent(name) .onEach { when (it) { is ScreeningStateUpdate.Screening -> applyData() else -> Unit } } .observeIn(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupView() applyData() } override fun onConfigurationChange() { super.onConfigurationChange() applyData() } private fun setupView() { screeningFragment().binding ?.toolbar ?.showBackSecondaryButton(imageConfiguration) { back() } } private fun applyData() { val viewBinding = binding val config = configuration val screening = viewModel.state.screening if (viewBinding != null && config != null && screening != null) { setStatusBar(config.theme.secondaryColor.color()) viewBinding.root.setBackgroundColor(config.theme.secondaryColor.color()) screeningFragment().showAbort(config.theme.primaryColorEnd.color()) screening.pages.firstOrNull { it.id == args.id } ?.let { data -> viewBinding.page.applyData( config, data, EPageType.INFO, { if (it == null) questions(false) else page(it.id, false) }, {}, { navigator.navigateTo(rootNavController(), AnywhereToWeb(it)) } ) } } } }
0
Kotlin
0
0
bc82972689db5052344365ac07c8f6711f5ad7fa
2,937
4YouandMeAndroid
MIT License
feature-tests/src/test/kotlin/fi/vauhtijuoksu/vauhtijuoksuapi/featuretest/DonationFlowTest.kt
Vauhtijuoksu
394,707,727
false
null
package fi.vauhtijuoksu.vauhtijuoksuapi.featuretest import io.vertx.core.Vertx import io.vertx.core.buffer.Buffer import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import io.vertx.ext.auth.authentication.UsernamePasswordCredentials import io.vertx.ext.web.client.HttpRequest import io.vertx.ext.web.client.WebClient import io.vertx.junit5.VertxExtension import io.vertx.junit5.VertxTestContext import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.MethodOrderer import org.junit.jupiter.api.Order import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestMethodOrder import org.junit.jupiter.api.extension.ExtendWith import java.util.UUID @TestMethodOrder(MethodOrderer.OrderAnnotation::class) @ExtendWith(VertxExtension::class) class DonationFlowTest { private val newIncentive = """{ "game_id": null, "title": "Tetrispalikan nimi", "end_time": "2021-09-21T19:08:47.000+00:00", "type": "open", "open_char_limit": 10, "info": "Nimeä tetrispalikka poggers" } """ private val donationSum = 10.0 private val newDonation = """ { "timestamp": "2021-09-21T15:05:47.000+00:00", "name": "jsloth", "read": false, "amount": $donationSum, "external_id": "a non unique string" } """ private lateinit var client: WebClient companion object { private lateinit var incentiveId: UUID private lateinit var incentiveCode: String } @BeforeEach fun setup() { client = WebClient.create(Vertx.vertx()) } private fun authenticatedPost(url: String): HttpRequest<Buffer> { return client.post(url) .putHeader("Origin", "http://localhost") .authentication(UsernamePasswordCredentials("vauhtijuoksu", "vauhtijuoksu")) } @Test @Order(1) fun `an admin can create an incentive`(testContext: VertxTestContext) { authenticatedPost("/incentives/") .sendJson(JsonObject(newIncentive)) .onFailure(testContext::failNow) .onSuccess { res -> testContext.verify { assertEquals(201, res.statusCode()) } incentiveId = UUID.fromString(res.bodyAsJsonObject().getString("id")) testContext.completeNow() } } @Test @Order(2) fun `a user can generate an incentive code for the incentive`(testContext: VertxTestContext) { client.post("/generate-incentive-code") .putHeader("Origin", "http://localhost") .sendJson(JsonArray().add(JsonObject().put("id", incentiveId.toString()).put("parameter", "neliö"))) .onFailure(testContext::failNow) .onSuccess { testContext.verify { assertEquals(201, it.statusCode()) val body = it.bodyAsJsonObject() assertEquals(1, body.size()) incentiveCode = body.getString("code") } testContext.completeNow() } } @Test @Order(3) fun `then the user makes a donation using the generated code`(testContext: VertxTestContext) { authenticatedPost("/donations") .sendJson(JsonObject(newDonation).put("message", "ota tää :D 🤔🤔: $incentiveCode")) .onFailure(testContext::failNow) .onSuccess { testContext.completeNow() } } @Test @Order(4) fun `the user checks incentives, and sees their donation money in the status`(testContext: VertxTestContext) { client.get("/incentives/$incentiveId") .send() .onFailure(testContext::failNow) .onSuccess { testContext.verify { val incentive = it.bodyAsJsonObject() val total = incentive.getDouble("total_amount") assertEquals(donationSum, total) val statuses = incentive.getJsonArray("status") assertEquals(1, statuses.size()) val expectedStatus = JsonObject() expectedStatus.put("type", "option") expectedStatus.put("option", "neliö") expectedStatus.put("amount", donationSum) val status = statuses.getJsonObject(0) assertEquals(expectedStatus, status) } testContext.completeNow() } } }
7
null
0
2
c90951dd845d388ef8149f44ce816c586c6c0606
4,587
vauhtijuoksu-api
MIT License
1er Corte/TALLER02/src/taller02/Solucion_problemasKtTest.kt
BrayanTorres2
197,484,467
false
null
package taller02 import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test internal class Solucion_problemasKtTest internal class TallerKtTest { @Test fun ProbarEjecicioA() { var datos = ejercicio(2500.0, 100) var numbicis = datos.first var total = datos.second assertEquals(50, numbicis) assertEquals(125000.0, total) } @Test fun probarejer() { assertEquals(81, DANE(1000)) } @Test fun probarArea() { assertEquals(2.0, areadeltriangulo(2.0, 2.0)) } @Test fun cambio() { assertEquals(28320000.0, convercion(10000.0, 2832.0)) } @Test fun volumencono() { assertEquals(20.943951023931955, volumencono(2.0, 5.0)) } @Test fun edadmenorde(){ var datos2=edadandnombre("brayan","sebastian","camilo",12,18,18) var nombre=datos2.first var edad=datos2.second assertEquals("brayan",nombre) assertEquals(12,edad) } @Test fun pintorcobra(){ assertEquals( 10000.0,pintor(1000.0,10.0)) } @Test fun valorpresente(){ assertEquals(2.0176569459262645E-8, valor_presente(1.22,5,10)) } @Test fun descuenyo_iva(){ var datos3= precio_articulo(1000.0) var des=datos3.first var pt=datos3.second assertEquals(950.0,des) assertEquals(180.5,pt) } @Test fun litros(){ assertEquals(70000.0, litros_contaminados(100)) } @Test fun cables(){ assertEquals(87, computadores_cables(88)) } @Test fun edad(){ assertEquals(19,edad1(2018,1999)) } @Test fun estaciona(){ assertEquals(15000.0, estacionamiento(3000.0,5)) } @Test fun definitiva(){ assertEquals(67.5, notasfinal(20.0,50.0,100.0)) } @Test fun mujermm(){ var datos4= mujermaravilla(5120.0) var mts=datos4.first var s=datos4.second assertEquals(21,mts) assertEquals(33,s) } @Test fun timpos(){ assertEquals(2, tiempo(50.0,100.0)) } @Test fun bequitas(){ assertEquals("2000.00", becas(19,95.0)) } }
0
Kotlin
0
0
70d5579685691f6142fde45ae7bd01f8d74fa749
2,213
Estructura-de-Datos-Kotlin
MIT License
bc-gateway/bc-gateway-core/src/main/kotlin/co/nilin/opex/bcgateway/core/api/InfoService.kt
opexdev
370,411,517
false
null
package co.nilin.opex.bcgateway.core.api import co.nilin.opex.bcgateway.core.model.CurrencyInfo interface InfoService { suspend fun countReservedAddresses(): Long suspend fun getCurrencyInfo(): CurrencyInfo }
29
null
22
51
fedf3be46ee7fb85ca7177ae91b13dbc6f2e8a73
218
core
MIT License
app/src/main/java/com/example/kodegoskillsimulatorapp/observer/SkillBarObserver.kt
jamesdev23
619,404,462
false
null
package com.example.kodegoskillsimulatorapp.observer import com.example.kodegoskillsimulatorapp.model.Skill interface SkillBarObserver { fun getTotalProgress(list: MutableList<Int>) fun checkSkillPoints(list: MutableList<Int>) } interface SkillDataObserver { fun saveSkillData(skillData: ArrayList<Skill>) fun showSkillData(skillData: ArrayList<Skill>) }
0
Kotlin
0
0
f06933a1e56805b7a32632c92465cd5e28d16166
373
SkillSimulatorApp
Apache License 2.0
airsync-api/src/main/java/ffc/airsync/api/services/module/MobileHttpRestService.kt
porntipa
125,967,174
true
{"Kotlin": 89876, "Java": 34607}
/* * Copyright (c) 2561 NECTEC * National Electronics and Computer Technology Center, Thailand * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ffc.airsync.api.services.module import ffc.airsync.api.dao.DaoFactory import ffc.airsync.api.dao.MobileDao import ffc.airsync.api.dao.PcuDao import ffc.airsync.api.websocket.module.PcuEventService import ffc.model.* import java.util.* class MobileHttpRestService : MobileServices { var mobileDao: MobileDao = DaoFactory().buildMobileDao() var pcuDao: PcuDao = DaoFactory().buildPcuDao() override fun getAll(): List<Pcu> { val pculist = ArrayList<Pcu>() pculist.addAll(pcuDao.find()) return pculist } override fun getMyPcu(ipAddress: String): List<Pcu> { val pculist = ArrayList<Pcu>() pculist.add(pcuDao.findByIpAddress(ipAddress)) return pculist } override fun <T> sendToPcu(message: Message<T>) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun registerMobile(mobileUserAuth: MobileUserAuth): Message<MobileUserAuth> { val message = Message(mobileUserAuth.mobileUuid, mobileUserAuth.pcu.uuid, Message.Status.DEFAULT, Message.Action.REGISTER, mobileUserAuth.toJson()) var messageReturn :Message<MobileUserAuth> = Message(UUID.randomUUID(), UUID.randomUUID(), Message.Status.ERROR, Message.Action.DEFAULT) println("registerMobile \n Message =" + mobileUserAuth.toJson()) val pcu = pcuDao.findByUuid(mobileUserAuth.pcu.uuid) sendAndRecive(message, object : MobileServices.OnReceiveListener { override fun onReceive(message: String) { messageReturn = message.fromJson() if (messageReturn.status == Message.Status.SUCC) { mobileDao.insert(Mobile(messageReturn.to, pcu)) println("Register Mobile " + messageReturn.to.toString()) } } }, pcu) return messageReturn } override fun <T> sendAndRecive(message: Message<T>, onReceiveListener: MobileServices.OnReceiveListener, pcu: Pcu) { val pcu2: Pcu println("sendAndRecive") println("Pcu = "+pcu.toJson()) if (pcu.code.equals("099912")) { pcu2 = mobileDao.findByUuid(message.from).pcu } else { pcu2 = pcu } println("Pcu2 = "+pcu2.toJson()) message.to = pcu2.uuid val pcuNetwork = PcuEventService.connectionMap.get(pcu2.session) println("Mobile find session Pcu = ") //print(pcuNetwork!!.remote.inetSocketAddress.hostName) if (pcuNetwork != null) { println("pcuNetwork Not Null") var waitReciveData = true var count = 0 PcuEventService.mobileHashMap.put(message.from, object : PcuEventService.onReciveMessage { override fun setOnReceiveMessage(message: String) { println("messageReceive") onReceiveListener.onReceive(message) waitReciveData = false } }) pcuNetwork.remote.sendString(message.toJson()) while (waitReciveData && count < 10) { count++ Thread.sleep(2000) println("Wait Count " + count) } } } }
0
Kotlin
0
0
638796977b3d9f8253c8e237f9b91cfddabe1751
3,938
airsync
Apache License 2.0
kotlin-react-router-dom/src/main/kotlin/react/router/dom/routingDsl.kt
LouisCAD
126,850,309
true
{"Kotlin": 109947}
package react.router.dom import react.* import kotlin.reflect.KClass fun RBuilder.hashRouter(handler: RHandler<RProps>) = child(HashRouterComponent::class, handler) fun RBuilder.browserRouter(handler: RHandler<RProps>) = child(BrowserRouterComponent::class, handler) fun RBuilder.switch(handler: RHandler<RProps>) = child(SwitchComponent::class, handler) fun RBuilder.route( path: String, component: KClass<out Component<*, *>>, exact: Boolean = false, strict: Boolean = false ): ReactElement { return child<RouteProps<RProps>, RouteComponent<RProps>> { attrs { this.path = path this.exact = exact this.strict = strict this.component = component.js.unsafeCast<RClass<RProps>>() } } } fun <T : RProps> RBuilder.route( path: String, exact: Boolean = false, strict: Boolean = false, render: (props: RouteResultProps<T>) -> ReactElement? ): ReactElement { return child<RouteProps<T>, RouteComponent<T>> { attrs { this.path = path this.exact = exact this.strict = strict this.render = render } } } fun RBuilder.route( path: String, exact: Boolean = false, strict: Boolean = false, render: () -> ReactElement? ): ReactElement { return child<RouteProps<RProps>, RouteComponent<RProps>> { attrs { this.path = path this.exact = exact this.strict = strict this.render = { render() } } } } fun RBuilder.routeLink(to: String, replace: Boolean = false, handler: RHandler<RProps>?) = child(LinkComponent::class) { attrs { this.to = to this.replace = replace } handler?.invoke(this) } fun RBuilder.redirect( from: String, to: String, push: Boolean = false, exact: Boolean = false, strict: Boolean = false ) = child(RedirectComponent::class) { attrs { this.from = from this.to = to this.push = push this.exact = exact this.strict = strict } }
0
Kotlin
0
0
b2595b2c899052769afa8baf635bf591779cf5b7
2,096
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/alirahimi/digikalaclone/data/db/BasketDao.kt
Aliiiw
612,510,322
false
null
package com.alirahimi.digikalaclone.data.db import androidx.room.* import com.alirahimi.digikalaclone.data.model.basket.BasketItem import com.alirahimi.digikalaclone.data.model.basket.CartStatus import com.alirahimi.digikalaclone.util.Constants.SHOPPING_CART_TABLE import kotlinx.coroutines.flow.Flow @Dao interface BasketDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertBasketItem(cart: BasketItem) @Query("SELECT * FROM $SHOPPING_CART_TABLE WHERE cartStatus=:status") fun getAllItems(status: CartStatus): Flow<List<BasketItem>> @Delete suspend fun removeFromBasket(item: BasketItem) @Query("UPDATE $SHOPPING_CART_TABLE SET cartStatus=:newCartStatus WHERE itemId=:id") suspend fun changeItemStatus(id: String, newCartStatus: CartStatus) @Query("UPDATE $SHOPPING_CART_TABLE SET count=:newCount WHERE itemId=:id") suspend fun changeCountBasketItem(id: String, newCount: Int) @Query("select total(count) as count from $SHOPPING_CART_TABLE where cartStatus=:status") fun getBasketItemsCount(status: CartStatus): Flow<Int> }
0
Kotlin
0
8
fca70301b84fe3c1030b313921656fb75b32113e
1,099
Digikala-clone
MIT License
app/src/main/java/com/sample/mvp/base/BaseActivity.kt
vntalking
335,137,059
false
null
package com.es.developine.ui import android.app.ProgressDialog import android.content.DialogInterface import android.os.Bundle import android.os.PersistableBundle import android.provider.Settings import android.support.annotation.LayoutRes import android.support.v7.app.AppCompatActivity import android.widget.Toast import com.es.developine.R import com.google.gson.Gson import retrofit2.HttpException import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException abstract class BaseActivity : AppCompatActivity(),IView { /** * A dialog showing a progress indicator and an optional text message or * view. */ protected var mProgressDialog: ProgressDialog?=null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(setLayout()) initialzeProgressDialoge() init(savedInstanceState) } fun initialzeProgressDialoge(){ if(mProgressDialog==null) { mProgressDialog = ProgressDialog(this) mProgressDialog!!.isIndeterminate = true mProgressDialog!!.setCancelable(false) } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) } override fun onResume() { super.onResume() } override fun onDestroy() { super.onDestroy() System.gc() System.runFinalization() dismissProgress() mProgressDialog=null } @LayoutRes abstract fun setLayout():Int abstract fun init(savedInstanceState: Bundle?) abstract fun onStartScreen() abstract fun stopScreen() fun showProgress(msgResId: Int, keyListener: DialogInterface.OnKeyListener?) { if (isFinishing) return if (mProgressDialog!!.isShowing) { return } if (msgResId != 0) { mProgressDialog?.setMessage(resources.getString(msgResId)) } if (keyListener != null) { mProgressDialog?.setOnKeyListener(keyListener) } else { mProgressDialog?.setCancelable(false) } mProgressDialog?.show() } /** * @param isCancel */ fun setCancelableProgress(isCancel: Boolean) { if (mProgressDialog != null) { mProgressDialog?.setCancelable(true) } } /** * cancel progress dialog. */ fun dismissProgress() { if (mProgressDialog != null && mProgressDialog!!.isShowing) { mProgressDialog?.dismiss() } } override fun hideLoading() { dismissProgress() } override fun showLoading() { showProgress(R.string.loading, null) } override fun loadError(e: Throwable) { showHttpError(e) } override fun loadError(msg: String) { Toast.makeText(this,msg,Toast.LENGTH_SHORT).show() } /* Improper handling in real case */ protected fun showHttpError(e: Throwable) { loadError(e.localizedMessage) } override fun onStop() { super.onStop() stopScreen() } }
0
Kotlin
1
0
c01dcf5f5e00b6eea5a0d3c3954db5ecbfd221ac
3,211
my_sample_mvp
Apache License 2.0
app/src/main/java/com/sawyer/component/startup/Dispatcher.kt
sawyer-lee
710,204,764
false
{"Kotlin": 58356, "Java": 15232}
package com.sawyer.component.startup import java.util.concurrent.Executor interface Dispatcher { //是否在主线程执行 fun callCreateOnMainThread(): Boolean //主线程是否需要等待该任务执行完成再开始执行 fun waitOnMainThread(): Boolean //等待 fun toWait() //有父任务执行完毕 fun toNotify() //线程池执行任务 fun executor(): Executor? //线程执行的优先级 fun getThreadPriority(): Int }
0
Kotlin
0
0
8c82e3daa8d97d1b35f26a7d16fbff7caad48887
373
KotlinComponentWanAndroid
Apache License 2.0
core/network/src/main/java/com/hellguy39/hellweather/core/network/HttpRoute.kt
HellGuy39
441,462,803
false
{"Kotlin": 113052}
package com.hellguy39.hellweather.core.network object HttpRoute { const val Current = "/v1/current.json" const val Forecast = "/v1/forecast.json" const val Search = "/v1/search.json" const val History = "/v1/history.json" const val Marine = "/v1/marine.json" const val Future = "/v1/future.json" const val Timezone = "/v1/timezone.json" const val Sports = "/v1/sports.json" const val Astronomy = "/v1/astronomy.json" const val IPLookup = "/v1/ip.json" }
0
Kotlin
0
2
ae8c16d2a594a807df3db3cdb0bbba805adf22e5
504
HellWeather
Apache License 2.0
app/src/main/java/com/satyajit/newsappnew/ui/screencountry/CountryRoute.kt
satyajitdas95
642,512,112
false
{"Kotlin": 109517}
package com.satyajit.newsappnew.ui.screencountry import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.viewmodel.compose.viewModel import com.satyajit.newsappnew.R import com.satyajit.newsappnew.di.component.ApplicationComponent @Composable fun CountryScreenRoute( onClickOfCountry: (countryCode: String) -> Unit, countryViewModel:CountryViewModel ) { // val countryViewModel: CountryViewModel = // viewModel(factory = applicationComponent.getCountriesViewModelFactory()) val uiStateCountry = countryViewModel.uiState.collectAsState().value val onClickOfRetry: () -> Unit = { countryViewModel.fetchAllCountries() } CountryScreen( uiStateCountry = uiStateCountry, onClickOfCountry = onClickOfCountry, onClickOfRetry = onClickOfRetry ) }
0
Kotlin
0
0
46c05a563d2ebbdc431a666c9124972851bd9119
908
NewsXKotlin
Apache License 2.0
app/src/main/java/com/example/newbiechen/ireader/model/repository/LeaderBoardRepository.kt
EiChinn
157,148,636
true
{"Kotlin": 718783, "Java": 2313}
package com.example.newbiechen.ireader.model.repository import androidx.lifecycle.MutableLiveData import com.chad.library.adapter.base.entity.MultiItemEntity import com.example.newbiechen.ireader.model.bean.LeaderBoardLabel import com.example.newbiechen.ireader.model.bean.LeaderBoardName import com.example.newbiechen.ireader.model.remote.RemoteRepository import com.example.newbiechen.ireader.viewmodel.BaseViewModelData import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers class LeaderBoardRepository private constructor(private val remoteRepository: RemoteRepository) { fun fetchLeaderBoard(): BaseViewModelData<List<MultiItemEntity>> { val isRequestInProgress = MutableLiveData<Boolean>() val toastMsg = MutableLiveData<String>() val data = MutableLiveData<List<MultiItemEntity>>() isRequestInProgress.postValue(true) remoteRepository.billboardPackage.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .map { response -> val list = mutableListOf<MultiItemEntity>() response.male?.let { male -> if (male.isNotEmpty()) { list.add(LeaderBoardLabel("男生")) val map = male.groupBy{ if (it.isCollapse) { "other" } else { "name" } } list.addAll(map["name"]!!) val otherLeaderBoard = LeaderBoardName("", "别人家的排行榜", "") otherLeaderBoard.subItems = map["other"] list.add(otherLeaderBoard) } } response.female?.let {femle -> if (femle.isNotEmpty()) { list.add(LeaderBoardLabel("女生")) val map = femle.groupBy{ if (it.isCollapse) { "other" } else { "name" } } list.addAll(map["name"]!!) val otherLeaderBoard = LeaderBoardName("", "别人家的排行榜", "") otherLeaderBoard.subItems = map["other"] list.add(otherLeaderBoard) } } list } .subscribe( {response -> isRequestInProgress.postValue(false) data.postValue(response) }, {error -> isRequestInProgress.postValue(false) toastMsg.postValue(error.toString()) } ) return BaseViewModelData(isRequestInProgress, toastMsg, data) } companion object { // For singleton instantiation @Volatile private var instance: LeaderBoardRepository? = null fun getInstance(remoteRepository: RemoteRepository) = instance ?: synchronized(this) { instance ?: LeaderBoardRepository(remoteRepository).also { instance = it } } } }
1
Kotlin
1
1
ab465c2cfc5af98c8da0927a81e4f6f27930fd32
3,645
NovelReader
MIT License
kexasol/ExaConstant.kt
badoo
307,729,424
false
null
package com.badoo.kexasol object ExaConstant { const val DRIVER_NAME: String = "KExasol" const val DRIVER_VERSION: String = "0.2.1" const val DEFAULT_CONNECTION_TIMEOUT: Long = 10 const val DEFAULT_SOCKET_TIMEOUT: Long = 30 const val DEFAULT_LOGGER_JSON_MAX_LENGTH: Int = 20000 const val DEFAULT_EXASOL_PORT: Int = 8563 const val DEFAULT_FETCH_SIZE: Long = 5 * 1024 * 1024 const val SNAPSHOT_EXECUTION_PREFIX: String = "/*snapshot execution*/" }
0
Kotlin
0
9
fa958c6a751f01eb93426b7be2c3b4598467f58c
483
kexasol
Apache License 2.0
app/src/main/java/eu/neilalexander/yggdrasil/GlobalApplication.kt
yggdrasil-network
377,590,278
false
{"Kotlin": 62823}
package eu.neilalexander.yggdrasil import android.app.* import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Build import android.service.quicksettings.TileService import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.preference.PreferenceManager const val PREF_KEY_ENABLED = "enabled" const val MAIN_CHANNEL_ID = "Yggdrasil Service" class GlobalApplication: Application(), YggStateReceiver.StateReceiver { private lateinit var config: ConfigurationProxy private var currentState: State = State.Disabled private var updaterConnections: Int = 0 override fun onCreate() { super.onCreate() config = ConfigurationProxy(applicationContext) val callback = NetworkStateCallback(this) callback.register() val receiver = YggStateReceiver(this) receiver.register(this) migrateDnsServers(this) } fun subscribe() { updaterConnections++ } fun unsubscribe() { if (updaterConnections > 0) { updaterConnections-- } } fun needUiUpdates(): Boolean { return updaterConnections > 0 } fun getCurrentState(): State { return currentState } @RequiresApi(Build.VERSION_CODES.N) override fun onStateChange(state: State) { if (state != currentState) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val componentName = ComponentName(this, YggTileService::class.java) TileService.requestListeningState(this, componentName) } if (state != State.Disabled) { val notification = createServiceNotification(this, state) val notificationManager: NotificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(SERVICE_NOTIFICATION_ID, notification) } currentState = state } } } fun migrateDnsServers(context: Context) { val preferences = PreferenceManager.getDefaultSharedPreferences(context) if (preferences.getInt(KEY_DNS_VERSION, 0) >= 1) { return } val serverString = preferences.getString(KEY_DNS_SERVERS, "") if (serverString!!.isNotEmpty()) { // Replacing old Revertron's servers by new ones val newServers = serverString .replace("fdf8:f53e:61e4::18", "fdf8:f53e:61e4::18") .replace("fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "fdf8:f53e:61e4::18") .replace("fdf8:f53e:61e4::18", "fc00:e968:6179::de52:7100") .replace("fdf8:f53e:61e4::18", "fc00:e968:6179::de52:7100") val editor = preferences.edit() editor.putInt(KEY_DNS_VERSION, 1) if (newServers != serverString) { editor.putString(KEY_DNS_SERVERS, newServers) } editor.apply() } } fun createServiceNotification(context: Context, state: State): Notification { createNotificationChannels(context) val intent = Intent(context, MainActivity::class.java).apply { this.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } var flags = PendingIntent.FLAG_UPDATE_CURRENT if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE } val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, flags) val text = when (state) { State.Disabled -> context.getText(R.string.tile_disabled) State.Enabled -> context.getText(R.string.tile_enabled) State.Connected -> context.getText(R.string.tile_connected) else -> context.getText(R.string.tile_disabled) } return NotificationCompat.Builder(context, MAIN_CHANNEL_ID) .setShowWhen(false) .setContentTitle(text) .setSmallIcon(R.drawable.ic_tile_icon) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_MIN) .build() } fun createPermissionMissingNotification(context: Context): Notification { createNotificationChannels(context) val intent = Intent(context, MainActivity::class.java).apply { this.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } var flags = PendingIntent.FLAG_UPDATE_CURRENT if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE } val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, flags) return NotificationCompat.Builder(context, MAIN_CHANNEL_ID) .setShowWhen(false) .setContentTitle(context.getText(R.string.app_name)) .setContentText(context.getText(R.string.permission_notification_text)) .setSmallIcon(R.drawable.ic_tile_icon) .setContentIntent(pendingIntent) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .build() } private fun createNotificationChannels(context: Context) { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = context.getString(R.string.channel_name) val descriptionText = context.getString(R.string.channel_description) val importance = NotificationManager.IMPORTANCE_MIN val channel = NotificationChannel(MAIN_CHANNEL_ID, name, importance).apply { description = descriptionText } // Register the channel with the system val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } }
21
Kotlin
19
122
e211111d60dcd833a1158f70fc2a19b0578dd956
5,982
yggdrasil-android
MIT License
platform/lib/common/src/main/kotlin/io/hamal/lib/common/hot/HotNode.kt
hamal-io
622,870,037
false
{"Kotlin": 2450833, "C": 1400046, "TypeScript": 323978, "Lua": 165691, "C++": 40651, "Makefile": 11728, "Java": 7564, "CMake": 2810, "JavaScript": 2640, "CSS": 1567, "Shell": 977, "HTML": 903}
package io.hamal.lib.common.hot import com.google.gson.JsonDeserializationContext import com.google.gson.JsonElement import com.google.gson.JsonSerializationContext import io.hamal.lib.common.serialization.GsonTransform import io.hamal.lib.common.serialization.JsonAdapter import java.lang.reflect.Type import java.math.BigDecimal import java.math.BigInteger sealed interface HotNode { val isArray get(): Boolean = false fun asArray(): HotArray = throw IllegalStateException("Not HotArray") val isBoolean get(): Boolean = false fun asBoolean(): HotBoolean = throw IllegalStateException("Not HotBoolean") val booleanValue get() : Boolean = throw IllegalStateException("Not boolean") val isNumber get(): Boolean = false fun asNumber(): HotNumber = throw IllegalStateException("Not HotNumber") val bigDecimalValue get() : BigDecimal = throw IllegalStateException("Not BigDecimal") val bigIntegerValue get() : BigInteger = throw IllegalStateException("Not BigInteger") val byteValue get() : Byte = throw IllegalStateException("Not byte") val doubleValue get() : Double = throw IllegalStateException("Not double") val floatValue get() : Float = throw IllegalStateException("Not float") val intValue get() : Int = throw IllegalStateException("Not int") val longValue get() : Long = throw IllegalStateException("Not long") val numberValue get() : Number = throw IllegalStateException("Not number") val shortValue get() : Short = throw IllegalStateException("Not short") val isNull get(): Boolean = false fun asNull(): HotNull = throw IllegalStateException("Not HotNull") val isObject get(): Boolean = false fun asObject(): HotObject = throw IllegalStateException("Not HotObject") val isString get(): Boolean = false fun asString(): HotString = throw IllegalStateException("Not HotString") val stringValue get(): String = throw IllegalStateException("Not string") val isTerminal get(): Boolean = false fun asTerminal(): HotTerminal = throw IllegalStateException("Not HotTerminal") fun deepCopy(): HotNode object Adapter : JsonAdapter<HotNode> { override fun serialize(src: HotNode, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return GsonTransform.fromNode(src) } override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): HotNode { return GsonTransform.toNode(json) } } }
38
Kotlin
0
0
7ead833ab99206c5a20bcb295103ee3642972423
2,503
hamal
Creative Commons Zero v1.0 Universal
app/src/main/java/com/uri/phone_native_resources/FormViewModel.kt
eduardo-ibarr
861,801,373
false
{"Kotlin": 13978}
package com.uri.phone_native_resources import android.content.Context import android.location.Location import androidx.lifecycle.ViewModel import com.google.android.gms.location.LocationServices import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow class FormViewModel(private val context: Context) : ViewModel() { private val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context) private val _currentLocation = MutableStateFlow<Location?>(null) val currentLocation: StateFlow<Location?> = _currentLocation fun saveFormData(name: String, email: String, comment: String, imagePath: String) { val dbHelper = FormDatabaseHelper(context) dbHelper.insertFormData(name, email, comment, imagePath) } fun getCurrentLocation() { if (androidx.core.content.ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) == android.content.pm.PackageManager.PERMISSION_GRANTED ) { fusedLocationClient.lastLocation.addOnSuccessListener { location -> _currentLocation.value = location } } } }
0
Kotlin
0
0
b80d7d56f87ba2fbc1282454c646b68dff082037
1,228
native-resources-app
MIT License
app/src/main/java/graph/ql/countries/data/repository/ApolloCountryClient.kt
hdmor
757,400,856
false
{"Kotlin": 16943}
package graph.ql.countries.data.repository import com.apollographql.apollo3.ApolloClient import com.example.CountriesQuery import com.example.CountryQuery import graph.ql.countries.data.mapper.toDetailedCountry import graph.ql.countries.data.mapper.toSimpleCountry import graph.ql.countries.domain.repository.CountryClient import graph.ql.countries.domain.model.DetailedCountry import graph.ql.countries.domain.model.SimpleCountry class ApolloCountryClient(private val apolloClient: ApolloClient) : CountryClient { override suspend fun getCountries(): List<SimpleCountry> = apolloClient.query(CountriesQuery()).execute().data?.countries?.map { it.toSimpleCountry() } ?: emptyList() override suspend fun getCountry(code: String): DetailedCountry? = apolloClient.query(CountryQuery(code)).execute().data?.country?.toDetailedCountry() }
0
Kotlin
0
0
3a19490b66d71edc65b873dfc915bf09ce3df3e7
861
GraphQLCountries
MIT License
shared/src/commonMain/kotlin/io/matrix/walletc/piv/PivTool.kt
kristoffer-paulsson
579,522,131
false
null
package io.matrix.walletc.piv expect class PivTool { fun piv() }
0
Kotlin
0
0
3a428b6bf0d986d3371d30f3e2d43499a2e38a94
69
WalletC
MIT License
app/src/main/java/town/robin/toadua/ui/EntryComposition.kt
toaq
437,669,257
false
null
package town.robin.toadua.ui data class EntryComposition( val term: String, val definition: String, val busy: Boolean, val initialTerm: String = term, val initialDefinition: String = definition, ) val blankEntryComposition = EntryComposition("", "", false)
0
Kotlin
1
8
b469900edd315e4c1db5faeda6fc537af679d31d
278
toadua-android
MIT License
app/src/main/java/com/azamovhudstc/tashkentmetro/viewmodel/profile/ProfileViewModel.kt
professorDeveloper
852,378,882
false
{"Kotlin": 85366}
package com.azamovhudstc.tashkentmetro.viewmodel.profile import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.azamovhudstc.tashkentmetro.data.local.shp.AppReference import com.azamovhudstc.tashkentmetro.data.local.shp.Language import com.azamovhudstc.tashkentmetro.data.local.shp.ThemeStyle import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class ProfileViewModel @Inject constructor( private val appReference: AppReference ) : ViewModel() { private val _language = MutableLiveData<Language>() val language: LiveData<Language> = _language fun setLanguage(language: Language) { appReference.language = language _language.value = language } fun setTheme(style: ThemeStyle){ appReference.theme = style appReference.applyTheme(style) } fun loadCurrentLanguage() { _language.value = appReference.language } }
0
Kotlin
0
0
c2269dccac0955cdebffcfb0f540b24ad25823b1
999
Tashkent-Metro
MIT License
shared/src/commonMain/kotlin/co/touchlab/kampkit/openweather/repo/WeatherReportRepositoryInputHandler.kt
whether-jacket
444,513,496
false
{"Kotlin": 46655, "Swift": 13426, "Ruby": 1920}
package co.touchlab.kampkit.openweather.repo import co.touchlab.kampkit.openweather.model.Response import com.copperleaf.ballast.InputHandler import com.copperleaf.ballast.InputHandlerScope import com.copperleaf.ballast.observeFlows import com.copperleaf.ballast.postInput import com.copperleaf.ballast.repository.bus.EventBus import com.copperleaf.ballast.repository.bus.observeInputsFromBus import com.copperleaf.ballast.repository.cache.fetchWithCache import kotlinx.coroutines.flow.MutableStateFlow class WeatherReportRepositoryInputHandler( private val weatherUseCase: WeatherUseCase, private val eventBus: EventBus ) : InputHandler< WeatherRepositoryContract.Inputs, Any, WeatherRepositoryContract.State> { override suspend fun InputHandlerScope<WeatherRepositoryContract.Inputs, Any, WeatherRepositoryContract.State>.handleInput( input: WeatherRepositoryContract.Inputs ) = when (input) { is WeatherRepositoryContract.Inputs.Initialize -> { val previousState = getCurrentState() if(!previousState.initialized){ updateState { it.copy(initialized = true) } observeFlows( key = "Observe inputs from EventBus", eventBus .observeInputsFromBus<WeatherRepositoryContract.Inputs>(), ) }else{ logger.debug("already initialized") noOp() } } is WeatherRepositoryContract.Inputs.ClearCaches -> {} is WeatherRepositoryContract.Inputs.RefreshAllCaches -> { val currentState = getCurrentState() if (currentState.weatherReportInitialized) { postInput(WeatherRepositoryContract.Inputs.RefreshWeatherReport(true)) } Unit } is WeatherRepositoryContract.Inputs.RefreshWeatherReport -> { updateState { it.copy(weatherReportInitialized = true) } val weatherReport : MutableStateFlow<WeatherReport> = MutableStateFlow(WeatherReport()) fetchWithCache( input = input, forceRefresh = input.forceRefresh, getValue = { it.weatherReport }, updateState = { WeatherRepositoryContract.Inputs.WeatherReportUpdated(it) }, doFetch = { when(val weatherReportResponse = weatherUseCase.getWeatherReport()){ is Response.Success -> { logger.info("WeatherReport API network result: $weatherReportResponse") weatherReport.value = weatherReportResponse.data } else -> { logger.info("WeatherReport API network result: $weatherReportResponse") } } }, observe = weatherReport, ) } is WeatherRepositoryContract.Inputs.WeatherReportUpdated -> { updateState { it.copy(weatherReport = input.value) } } } }
11
Kotlin
2
31
7c03d45ff28f86d9671f0a4e892cdc435370833e
3,073
weather-app-2022-kmm
MIT License
movies/src/test/java/com/caueferreira/movies/data/MovieRawTransformerTest.kt
caueferreira
162,075,948
false
{"Gradle": 11, "Markdown": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "Proguard": 4, "Kotlin": 27, "Java": 6, "XML": 20, "YAML": 1}
package com.caueferreira.movies.data import com.caueferreira.movies.domain.Genre import com.caueferreira.movies.domain.Movie import com.caueferreira.movies.domain.ProductionCompany import com.caueferreira.movies.domain.Status import io.reactivex.Observable import org.junit.Test import java.util.* class MovieRawTransformerTest { @Test fun `should transform raw to movie`() { val raw = MovieRaw( 550, false, "/fCayJrkfRaCRCTh8GqN30f8oyQF.jpg", 63000000, "", "en", "Fight Club", "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.", 0.5, null, Date(939693600000), 100853753, 139, 7.8, 3439, arrayListOf(GenreRaw(18, "Drama")), StatusRaw.RELEASED, arrayListOf( ProductionCompanyRaw(508, "Regency Enterprises", "/7PzJdsLGlR7oW4J0J5Xcd0pHGRg.png", "US"), ProductionCompanyRaw(711, "Fox 2000 Pictures", null, ""), ProductionCompanyRaw(20555, "Taurus Film", null, ""), ProductionCompanyRaw(54050, "Linson Film", null, ""), ProductionCompanyRaw(54051, "Atman Entertainment", null, ""), ProductionCompanyRaw(54052, "Knickerbocker Films", null, ""), ProductionCompanyRaw(25, "20th Century Fox", "/qZCc1lty5FzX30aOCVRBLzaVmcp.png", "US") ), arrayListOf(ProductionCountryRaw("US", "United States of America")), arrayListOf(SpokenLanguageRaw("en", "English")), "" ) val movie = Movie( 550, false, "https://image.tmdb.org/t/p/w300/fCayJrkfRaCRCTh8GqN30f8oyQF.jpg", 63000000, "en", "Fight Club", "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.", 5, null, Date(939693600000), 100853753, 139, 78, 3439, arrayListOf(Genre(18, "Drama")), Status.RELEASED, arrayListOf( ProductionCompany( 508, "Regency Enterprises", "https://image.tmdb.org/t/p/w300/7PzJdsLGlR7oW4J0J5Xcd0pHGRg.png", "US" ), ProductionCompany(711, "Fox 2000 Pictures", null, ""), ProductionCompany(20555, "Taurus Film", null, ""), ProductionCompany(54050, "Linson Film", null, ""), ProductionCompany(54051, "Atman Entertainment", null, ""), ProductionCompany(54052, "Knickerbocker Films", null, ""), ProductionCompany( 25, "20th Century Fox", "https://image.tmdb.org/t/p/w300/qZCc1lty5FzX30aOCVRBLzaVmcp.png", "US" ) ), arrayListOf("United States of America"), arrayListOf("English") ) Observable.just(raw).map(MovieRawTransformer()).test().assertValue(movie) } }
9
Kotlin
0
1
e5fa24fe24952d343499508713ae85ec4cc8d56b
3,687
OpenMovieDB
MIT License
app/src/main/java/com/ant/app/ui/main/login/LoginViewModel.kt
toaderandrei
786,415,615
false
{"Kotlin": 272237, "Java": 376}
package com.ant.app.ui.main.login import androidx.lifecycle.viewModelScope import com.ant.analytics.AnalyticsEvent import com.ant.analytics.AnalyticsHelper import com.ant.analytics.CrashlyticsHelper import com.ant.app.ui.base.BaseViewModel import com.ant.app.ui.extensions.parseResponse import com.ant.common.logger.TmdbLogger import com.ant.domain.usecases.login.LoginUserAndSaveSessionUseCase import com.ant.domain.usecases.login.LogoutUserAndClearSessionUseCase import com.ant.models.model.MoviesState import com.ant.models.model.UserData import com.ant.models.request.RequestType import com.ant.models.session.SessionManager import com.ant.models.source.repositories.Repository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor( private val loginUserUseCase: LoginUserAndSaveSessionUseCase, private val logoutUserUseCase: LogoutUserAndClearSessionUseCase, private val sessionManager: SessionManager, private val analyticsHelper: AnalyticsHelper, private val crashlyticsHelper: CrashlyticsHelper, private val logger: TmdbLogger, ) : BaseViewModel<MoviesState<UserData>>(MoviesState()) { init { logger.d("LoginViewModel created.") viewModelScope.launch { sessionManager.getUsername()?.let { username -> logger.d("Username: $username") loginUserUseCase.invoke( Repository.Params( RequestType.LoginSessionRequest.WithCredentials( username, null ) ) ).collectAndSetState { response -> parseResponse(response) } } } } fun login( username: String, password: String, ) { job?.cancel() job = viewModelScope.launch { if (sessionManager.isUserLoggedInToTmdbApi()) { logger.d("User is already logged in.") return@launch } loginUserUseCase.invoke( Repository.Params( RequestType.LoginSessionRequest.WithCredentials( username = username, password = <PASSWORD> ) ) ).collectAndSetState { parseResponse( response = it, onSuccess = { success -> analyticsHelper.logEvent( AnalyticsEvent( type = AnalyticsEvent.Types.LOGIN_SCREEN, mutableListOf( AnalyticsEvent.Param( AnalyticsEvent.ParamKeys.LOGIN_NAME.name, success?.username ) ) ) ) }, onError = { error -> logger.e(error, "Logging to crashlytics: $error") crashlyticsHelper.logError(throwable = error) } ) } } } fun logout() { job?.cancel() job = viewModelScope.launch { logger.d("Logout user.") if (!sessionManager.isUserLoggedInToTmdbApi()) { logger.d("User is already logged out.") return@launch } logoutUserUseCase.invoke( Repository.Params( RequestType.LoginSessionRequest.Logout( username = sessionManager.getUsername(), ) ) ).collectAndSetState { parseResponse( response = it, ) } } } fun signUp() { // signup user. logger.d("Sign up user.") } }
2
Kotlin
0
0
0cf503f37b998652136040e75d1531cc93583eaa
4,103
popular-movies-kt
MIT License
app/src/main/java/com/capstone/crashsnap/ui/welcome/WelcomeActivity.kt
CrashSnap
817,768,477
false
{"Kotlin": 89219}
package com.capstone.crashsnap.ui.welcome import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.capstone.crashsnap.databinding.ActivityWelcomeBinding import com.capstone.crashsnap.ui.auth.LoginActivity class WelcomeActivity : AppCompatActivity() { private lateinit var binding: ActivityWelcomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityWelcomeBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnNext.setOnClickListener { startActivity(Intent(this, LoginActivity::class.java)) finish() } } }
0
Kotlin
0
0
5c4355910ec164fce3745e4603037e98d5f49f58
720
mobile-development
MIT License
undertow/src/test/kotlin/org/springframework/samples/petclinic/rest/webmvc/jdbc/UndertowWebMvcJdbcVisitControllerTest.kt
kotoant
612,221,740
false
{"Kotlin": 230920, "JavaScript": 102019, "Mustache": 10054, "PLpgSQL": 2929, "Shell": 1403, "Dockerfile": 709}
package org.springframework.samples.petclinic.rest.webmvc.jdbc class UndertowWebMvcJdbcVisitControllerTest : WebMvcJdbcVisitControllerTest()
0
Kotlin
0
2
365b0ce4d9eaacee8c888511915c404f414cbd8c
142
spring-petclinic-rest
Apache License 2.0
core/src/main/java/org/albaspazio/core/updater/UpdateManager.kt
albaspazio
506,573,511
false
{"Kotlin": 135663}
/* ================================================================================================= Part of android-core module https://github.com/albaspazio/android-core Author: <NAME> Copyright (©) 2019-2023 ==================================================================================================*/ package org.albaspazio.core.updater import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.content.pm.PackageManager import android.os.Bundle import android.os.Handler import android.os.Message import android.util.Log import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.albaspazio.core.R import org.albaspazio.core.accessory.isOnline import org.albaspazio.core.ui.CustomProgressAlertDialog import org.albaspazio.core.ui.show2ChoisesDialog import org.json.JSONObject class UpdateManager(private var activity: Activity, private var updateXmlUrl: String, private val onSuccess:(Int)-> Unit, private val onError:(String)-> Unit, private var timeOutMs:Int = 10000, private var options:JSONObject? = null) { /* * <update> * <version>2222</version> * <sver>0.2.25</version> * <description>%s</description> * <name>name</name> * <url>http://192.168.3.102/android.apk</url> * </update> */ var appCurrentCode:Int = getVersionCodeLocal(activity).first var appRemoteCode:Int = -1 private val TAG = "UpdateManager" private var packageName: String = activity.packageName private var isDownloading = false private var checkUpdateThread: CheckUpdateThread? = null private var downloadApkThread: DownloadApkThread? = null private lateinit var alertDialog:AlertDialog private val progressDialog = CustomProgressAlertDialog(activity) private val errors:HashMap<Int, String> = hashMapOf( Constants.NETWORK_ERROR to activity.resources.getString(R.string.network_error), Constants.CONNECTION_ERROR to activity.resources.getString(R.string.connection_error), Constants.VERSION_PARSE_FAIL to activity.resources.getString(R.string.parse_error), Constants.REMOTE_FILE_NOT_FOUND to activity.resources.getString(R.string.remotefile_notfound_error), Constants.TIMEOUT_ERROR to activity.resources.getString(R.string.timeout_error), Constants.UNKNOWN_ERROR to activity.resources.getString(R.string.unknown_error), Constants.NETWORK_ABSENT to activity.resources.getString(R.string.network_absent)) private val mHandler: Handler = object : Handler() { override fun handleMessage(msg: Message) { super.handleMessage(msg) when (msg.what) { Constants.VERSION_COMPARE_END -> onCompareEnd(msg.data) Constants.DOWNLOAD_CLICK_START -> downloadApk() Constants.DOWNLOAD_FINISH -> isDownloading = false Constants.VERSION_UP_TO_UPDATE, Constants.UPDATE_CANCELLED, Constants.NETWORK_ABSENT -> onSuccess(msg.what) Constants.NETWORK_ERROR -> onError(errors.get(Constants.NETWORK_ERROR)!!) Constants.CONNECTION_ERROR -> onError(errors.get(Constants.CONNECTION_ERROR)!!) Constants.VERSION_PARSE_FAIL -> onError(errors.get(Constants.VERSION_PARSE_FAIL)!!) Constants.REMOTE_FILE_NOT_FOUND -> onError(errors.get(Constants.REMOTE_FILE_NOT_FOUND)!!) Constants.TIMEOUT_ERROR -> onError(errors.get(Constants.TIMEOUT_ERROR)!!) else -> onError(errors.get(Constants.UNKNOWN_ERROR)!!) } } } companion object{ fun getVersionCodeLocal(context: Context): Pair<Int, String> { return try { Pair(context.packageManager.getPackageInfo(context.packageName, 0).versionCode, context.packageManager.getPackageInfo(context.packageName, 0).versionName) } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() Pair(0, "") } } } // called by activity => VERSION_COMPARE_END => onCompareEnd : upgrade or skip => downloadApk() fun checkUpdate() { if(!isOnline(activity)){ mHandler.sendEmptyMessage(Constants.NETWORK_ABSENT) return } Log.d(TAG, "checkUpdate..") checkUpdateThread = CheckUpdateThread(activity, mHandler, updateXmlUrl, timeOutMs, options) GlobalScope.launch { (checkUpdateThread as CheckUpdateThread).run() } } // ===================================================================================================================================== // ===================================================================================================================================== // from handleMessage private fun onCompareEnd(ver:Bundle) { appRemoteCode = ver.getInt("remotecode") if (appCurrentCode < appRemoteCode) { Log.d(TAG, activity.resources.getString(R.string.update_title)) alertDialog = show2ChoisesDialog(activity, activity.resources.getString(R.string.update_title), activity.resources.getString(R.string.update_message, ver.getString("localver"),ver.getString("remotever"), ver.getString("description")), activity.resources.getString(R.string.update_update_btn), activity.resources.getString(R.string.no), { // ok alertDialog.dismiss() mHandler.sendEmptyMessage(Constants.DOWNLOAD_CLICK_START) }, { // cancel alertDialog.dismiss() mHandler.sendEmptyMessage(Constants.UPDATE_CANCELLED) }) } else mHandler.sendEmptyMessage(Constants.VERSION_UP_TO_UPDATE) } // onCompareEnd -> USER CLICK private fun downloadApk() { Log.d(TAG, "downloadApk") progressDialog.show(activity.resources.getString(R.string.downloading), activity.resources.getString(R.string.download_complete_neu_btn), activity.resources.getString(R.string.update_cancel), null, downloadCancelOnClick) downloadApkThread = DownloadApkThread(activity, mHandler, progressDialog, checkUpdateThread!!.update) GlobalScope.launch { (downloadApkThread as DownloadApkThread).run() } } // USER CLICK => handleMessage => cancel new version's download private val downloadCancelOnClick = DialogInterface.OnClickListener { _: DialogInterface, _: Int -> downloadApkThread?.cancelBuildUpdate() progressDialog.dismiss() mHandler.sendEmptyMessage(Constants.UPDATE_CANCELLED) } }
0
Kotlin
0
0
b8c5e795dd5eba63b43ff370cfc75c9247e4683a
7,398
android-core
MIT License
src/main/kotlin/de/l/oklab/klimawatch/catalog/to/Organization.kt
CodeforLeipzig
560,069,196
false
{"Kotlin": 50118, "Shell": 362, "Dockerfile": 247}
package de.l.oklab.klimawatch.catalog.to import com.fasterxml.jackson.annotation.JsonIgnoreProperties import de.l.oklab.klimawatch.catalog.to.ValueHandler.singleValue import jakarta.json.JsonValue @JsonIgnoreProperties(ignoreUnknown = true) data class Organization( var id: String? = null, var type: String? = null, var email: String? = null, var fax: String? = null, var label: String? = null, var locality: String? = null, var tel: String? = null, var url: String? = null ): CatalogElement() { fun setter(key: String, value: JsonValue?) { when (key) { "@id" -> this.id = singleValue(value) "@type" -> this.type = singleValue(value) "http://www.w3.org/2006/vcard/ns#email" -> this.email = singleValue(value) "http://statistik.leipzig.de/ontology/fax" -> this.fax = singleValue(value) "http://www.w3.org/2000/01/rdf-schema#label" -> this.label = singleValue(value) "http://www.w3.org/2006/vcard/ns#locality" -> this.locality = singleValue(value) "http://www.w3.org/2006/vcard/ns#tel" -> this.tel = singleValue(value) "http://www.w3.org/2006/vcard/ns#url" -> this.url = singleValue(value) else -> println("missed $key in Organization") } } override fun getResolvedType() = Types.Organization }
0
Kotlin
0
2
3f3f61fdb79b47d55b4c41badfbe9252e2895438
1,364
klimawatch-leipzig
MIT License
src/main/kotlin/MainWindow.kt
kolod
432,822,401
false
{"Kotlin": 31465}
package io.github.kolod import com.formdev.flatlaf.FlatLightLaf import com.jcabi.manifests.Manifests import net.sourceforge.tess4j.Tesseract import net.sourceforge.tess4j.util.LoadLibs import java.awt.* import java.io.File import java.io.FileNotFoundException import java.util.* import java.util.prefs.Preferences import javax.swing.* import javax.swing.JFileChooser.* class MainWindow : JFrame() { private val bundle = ResourceBundle.getBundle("i18n/GroundTruthEditor") private val prefs = Preferences.userNodeForPackage(MainWindow::class.java) private var tesseract = Tesseract() private val list = mutableListOf<File>() private var current : Int = -1 private var directory :File? = null private val mainMenuBar = JMenuBar() private val menuFile = JMenu() private val menuEdit = JMenu() private val openFolder = JMenuItem() private val reload = JMenuItem() private val renumber = JMenuItem() private val removeDuplicates = JMenuItem() private val markAllUnfinished = JMenuItem() private val next = JMenuItem() private val nextUnfinished = JMenuItem() private val previous = JMenuItem() private val previousUnfinished = JMenuItem() private val first = JMenuItem() private val last = JMenuItem() private val markAsFinished = JMenuItem() private val markAsFinishedAndNext = JMenuItem() private val markAsUnfinished = JMenuItem() private val delete = JMenuItem() private val spellCheck = JMenuItem() private val imageView = JLabel() private val imageViewScroll = JScrollPane(imageView) private val textView = JEditorPane() private val textViewScroll = JScrollPane(textView) private val rawTextView = JTextArea() private val rawTextViewScroll = JScrollPane(rawTextView) private fun initTesseract() { logger.trace("Tesseract initialization started.") tesseract.setDatapath(LoadLibs.extractTessResources("tessdata").path) tesseract.setLanguage("rus+lat") tesseract.setVariable("user_defined_dpi", "96") tesseract.setVariable("tessedit_create_hocr", "0") } private fun loadIcons(name :String, extension :String = "png") :List<Image> { val toolkit = Toolkit.getDefaultToolkit() return listOf(16, 24, 32, 48, 64, 72, 96, 128, 256).map{ size -> "$name$size.$extension" }.mapNotNull{ path -> javaClass.classLoader.getResource(path) }.mapNotNull{ url -> try { toolkit.createImage(url) } catch (ex: Exception) { logger.warn(ex.message, ex) null } } } private fun updateTitle() { title = bundle.getString("title") + " " + Manifests.read("Build-Date") + (list.getOrNull(current)?.fileName?.let { " [$it]" } ?: "") } private fun translateUI() { updateTitle() with(bundle) { menuFile.text = getString("file_menu") menuEdit.text = getString("file_edit") openFolder.text = getString("menu_open") reload.text = getString("menu_reload") renumber.text = getString("menu_renumber") removeDuplicates.text = getString("menu_remove_duplicates") markAllUnfinished.text = getString("menu_mark_all_unfinished") spellCheck.text = getString("menu_spell_check") next.text = getString("menu_next") nextUnfinished.text = getString("menu_next_unfinished") previous.text = getString("menu_previous") previousUnfinished.text = getString("menu_previous_unfinished") first.text = getString("menu_first") last.text = getString("menu_last") markAsFinished.text = getString("menu_mark_as_finished") markAsFinishedAndNext.text = getString("menu_mark_as_finished_and_next") markAsUnfinished.text = getString("menu_mark_as_unfinished") delete.text = getString("menu_delete") } } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The * content of this method is always regenerated by the Form Editor. */ private fun initComponents() { preferredSize = Dimension(1200, 600) defaultCloseOperation = EXIT_ON_CLOSE iconImages = loadIcons("icon/") rawTextView.isEditable = false translateUI() with(menuFile) { add(openFolder) addSeparator() add(renumber) add(removeDuplicates) add(spellCheck) add(markAllUnfinished) } with (menuEdit) { add(previous) add(next) addSeparator() add(previousUnfinished) add(nextUnfinished) addSeparator() add(first) add(last) addSeparator() add(markAsUnfinished) add(markAsFinished) add(markAsFinishedAndNext) addSeparator() add(delete) } with (mainMenuBar) { add(menuFile) add(menuEdit) } jMenuBar = mainMenuBar val splitter1 = JSplitPane(JSplitPane.VERTICAL_SPLIT, rawTextViewScroll, textViewScroll) val splitter2 = JSplitPane(JSplitPane.VERTICAL_SPLIT, imageViewScroll, splitter1) contentPane.add(splitter2, BorderLayout.CENTER) pack() setLocationRelativeTo(null) splitter2.dividerLocation = splitter2.height / 2 splitter1.dividerLocation = splitter1.height / 2 } private fun save() = try { list.getOrNull(current)?.let { file -> File(directory, file.fileName + ".gt.txt").let { finished -> finished.writeText(textView.plainText) logger.debug("Save: ${finished.absolutePath}") } } } catch (ex :Exception) { logger.error(ex.message, ex) } private fun loadText(image : File) = try { File(directory, image.nameWithoutExtension + ".gt.txt").readText().ifBlank { null } } catch (ex : FileNotFoundException) { null } catch (ex : Exception) { logger.error(ex.message, ex) null } private fun load(id : Int) { current = id list.getOrNull(current)?.let { imageFile -> val image = preProcessImage(imageFile) val text = loadText(imageFile) imageView.icon = ImageIcon(image) rawTextView.text = tesseract.doOCR(image) textView.setPlainText( text ?: rawTextView.text ) } ?: run { imageView.icon = null rawTextView.text = "" textView.setPlainText("") } updateTitle() } private fun next() = if (current + 1 < list.size) { current += 1; load(current) } else logger.info("Last file.") private fun previous() = if (current > 0) { current -= 1; load(current) } else logger.info("First file.") private fun loadFolder() { list.clear() directory?.walk()?.filter { it.isFile && it.path.endsWith(".png") }?.let { list.addAll( it ) } load(if (list.size > 0) 0 else -1) } /** * Creates new form TestTrainer */ init { logger.info("Application started") initComponents() initTesseract() prefs.get("directory", null)?.let { it -> directory = File(it) loadFolder() } removeDuplicates.addActionListener { directory?.deleteDuplicatesWithCompanions(".*\\.png".toRegex())?.forEach { file -> logger.debug("Removed: ${file.absolutePath}") } } renumber.addActionListener { directory?.renumberWithCompanions(""".*\.png""") } markAllUnfinished.addActionListener { directory?.list { _, filename -> filename.endsWith(".gt.txt") }?.mapNotNull { name -> File(directory, name).renameTo( File(directory, name.split(".").first() + ".txt")) } } delete.addActionListener { list.getOrNull(current)?.let { file -> file.getCompanions().forEach { it.delete() } list.remove(file) load(maxOf(current, list.size - 1)) } } openFolder.addActionListener { val dialog = JFileChooser() dialog.fileSelectionMode = DIRECTORIES_ONLY dialog.isMultiSelectionEnabled = false dialog.selectedFile = directory if (dialog.showOpenDialog(this) == APPROVE_OPTION) { directory = dialog.selectedFile directory?.absolutePath?.let { path -> prefs.put("directory", path) logger.info("Directory: $path") loadFolder() } } } reload.addActionListener { loadFolder() } spellCheck.addActionListener { logger.info( directory?.getAllSpellCheckErrors()?.toSet()?.joinToString() ?: "none") } markAsFinished.addActionListener { save() } next.addActionListener { next() } previous.addActionListener { previous() } first.addActionListener { load(if (list.size > 0) 0 else -1) } last.addActionListener { load(if (list.size > 0) list.size - 1 else -1) } markAsFinishedAndNext.addActionListener { save(); next() } } companion object { /** * @param args the command line arguments */ @JvmStatic fun main(args: Array<String>) { FlatLightLaf.setup() UIManager.put("defaultFont", UIManager.getFont("defaultFont")/*.deriveFont(14f)*/) SwingUtilities.invokeLater { MainWindow().isVisible = true } } } }
0
Kotlin
0
0
dfa51f12cfd78b6f78ac85c05adfe652e11e62ff
9,018
GroundTruthEditor
MIT License
androidext/src/main/java/com/david/hackro/androidext/ImageView.kt
David-Hackro
260,338,201
false
null
package com.david.hackro.androidext import android.widget.ImageView import androidx.core.content.ContextCompat import com.bumptech.glide.Glide fun ImageView.setImageVector(resId: Int) { setImageDrawable(ContextCompat.getDrawable(this.context, resId)) } fun ImageView.setUrl(url: String) { Glide.with(this.context) .load(url) .into(this) } fun ImageView.setUrlCircle(url: String) { Glide.with(this.context) .load(url) .circleCrop() .into(this) }
0
Kotlin
4
24
fab77132389c46e9773982f5a31e33b694091530
502
Covid
MIT License
kgl-vulkan/src/nativeMain/kotlin/com/kgl/vulkan/enums/ExternalFenceFeature.kt
BrunoSilvaFreire
223,607,080
true
{"Kotlin": 1880529, "C": 10037}
/** * Copyright [2019] [<NAME>] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kgl.vulkan.enums import com.kgl.vulkan.utils.VkFlag import cvulkan.VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT import cvulkan.VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT import cvulkan.VkExternalFenceFeatureFlagBits actual enum class ExternalFenceFeature(override val value: VkExternalFenceFeatureFlagBits) : VkFlag<ExternalFenceFeature> { EXPORTABLE(VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT), IMPORTABLE(VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT); companion object { private val enumLookUpMap: Map<UInt, ExternalFenceFeature> = enumValues<ExternalFenceFeature>().associateBy({ it.value }) fun fromMultiple(value: VkExternalFenceFeatureFlagBits): VkFlag<ExternalFenceFeature> = VkFlag(value) fun from(value: VkExternalFenceFeatureFlagBits): ExternalFenceFeature = enumLookUpMap[value]!! } }
0
null
0
0
74de23862c29404e7751490331cbafbef310bd63
1,416
kgl
Apache License 2.0
EvoMaster/core/src/test/kotlin/org/evomaster/core/search/modellearning/BuildingBlockModelTest.kt
BrotherKim
397,139,860
false
{"Markdown": 32, "Shell": 14, "Maven POM": 66, "Text": 16, "Ignore List": 13, "Java": 1366, "SQL": 44, "YAML": 13, "JSON": 37, "JavaScript": 183, "XML": 14, "Mermaid": 1, "Java Properties": 36, "INI": 15, "HTML": 52, "Dockerfile": 2, "CSS": 8, "JSON with Comments": 3, "Less": 8, "SVG": 16, "Kotlin": 541, "OASv2-yaml": 1, "XSLT": 3, "Python": 3, "Graphviz (DOT)": 1, "OASv2-json": 18, "BibTeX": 1, "R": 5, "OASv3-json": 12, "ANTLR": 4}
package org.evomaster.core.search.modellearning import com.google.inject.Injector import com.google.inject.Key import com.google.inject.Module import com.google.inject.TypeLiteral import com.netflix.governator.guice.LifecycleInjector import org.evomaster.core.BaseModule import org.evomaster.core.EMConfig import org.evomaster.core.search.algorithms.MioAlgorithm import org.evomaster.core.search.algorithms.onemax.OneMaxIndividual import org.evomaster.core.search.algorithms.onemax.OneMaxModule import org.evomaster.core.search.algorithms.onemax.OneMaxSampler import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.tracer.ArchiveMutationTrackService import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach internal class BuildingBlockModelTest { private lateinit var buildingBlockModel: BuildingBlockModel @Test fun parentMatrixConstructorContainsAll() { val parentMatrix = arrayOf( intArrayOf(0, 2, 0), intArrayOf(1, 0, 0), intArrayOf(0, 0, 0) ) buildingBlockModel = BuildingBlockModel(parentMatrix) assert(buildingBlockModel.toString().contains("0")) assert(buildingBlockModel.toString().contains("1")) assert(buildingBlockModel.toString().contains("2")) } @Test fun parentMatrixConstructorContainsBlock() { val parentMatrix = arrayOf( intArrayOf(0, 2, 0), intArrayOf(1, 0, 0), intArrayOf(0, 0, 0) ) buildingBlockModel = BuildingBlockModel(parentMatrix) assert(buildingBlockModel.toString().contains("0, 1")) } @Test fun largeParentMatrixConstructorContainsBlock() { val parentMatrix = arrayOf( intArrayOf(0, 2, 0, 1), intArrayOf(1, 0, 2, 0), intArrayOf(0, 1, 0, 0), intArrayOf(2, 0, 0, 0) ) buildingBlockModel = BuildingBlockModel(parentMatrix) println(buildingBlockModel.toString()) assert(buildingBlockModel.toString().contains("0, 1, 2, 3")) } @Test fun fosConstructorContainsRelevant() { val fos = mutableListOf( mutableListOf(1, 2, 3), mutableListOf(2, 3), mutableListOf(1) ) buildingBlockModel = BuildingBlockModel(fos) assert(buildingBlockModel.toString().contains("2")) assert(buildingBlockModel.toString().contains("3")) } @Test fun fosConstructorContainsBlock() { val fos = mutableListOf( mutableListOf(1, 2, 3), mutableListOf(2, 3), mutableListOf(1) ) buildingBlockModel = BuildingBlockModel(fos) assert(buildingBlockModel.toString().contains("2, 3")) } @Test fun getRandomBuildingBlockExistingBlock() { val fos = mutableListOf( mutableListOf(1, 2, 3), mutableListOf(2, 3), mutableListOf(1) ) buildingBlockModel = BuildingBlockModel(fos) val injector: Injector = LifecycleInjector.builder() .withModules(* arrayOf<Module>(OneMaxModule(), BaseModule())) .build().createInjector() val randomness = injector.getInstance(Randomness::class.java) val block = buildingBlockModel.getRandomBuildingBlock(randomness) assert(block.contains(2)) assert(block.contains(3)) } }
1
null
1
1
a7a120fe7c3b63ae370e8a114f3cb71ef79c287e
3,560
ASE-Technical-2021-api-linkage-replication
MIT License
asm-logging-level-plugin/src/main/java/it/sephiroth/android/library/asm/plugin/logginglevel/LoggingLevelPluginExtension.kt
sephiroth74
429,513,067
false
null
package it.sephiroth.android.library.asm.plugin.logginglevel import it.sephiroth.android.library.asm.plugin.core.AndroidLogLevel import it.sephiroth.android.library.asm.plugin.core.AsmCorePluginExtension @Suppress("LeakingThis") abstract class LoggingLevelPluginExtension : AsmCorePluginExtension() { /** * Minimum log level allowed per project * All logs with smaller priority will be removed from the bytecodes */ var minLogLevel: AndroidLogLevel = AndroidLogLevel.VERBOSE /** * Process or ignore external included libraries */ var includeLibs: Boolean = false override fun toString(): String { return "${BuildConfig.EXTENSION_NAME}(enabled=${enabled}, minLogLevel=${minLogLevel}, includeLibs=${includeLibs}, runVariant=${runVariant})" } }
0
Kotlin
0
0
e8ec660baec7d813a42581c1974b5c1c33ba3bbc
804
AndroidDebugLog
MIT License
app/src/main/java/com/lucianbc/receiptscan/presentation/components/Transformers.kt
lucianbc
183,749,890
false
{"Kotlin": 288397, "JavaScript": 4190, "Java": 2530}
package com.lucianbc.receiptscan.presentation.components import android.animation.ArgbEvaluator import android.content.Context import android.graphics.Color import android.view.View import android.widget.TextView import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import com.lucianbc.receiptscan.R private fun resolveColor(@ColorRes resId: Int, context: Context) = ContextCompat.getColor(context, resId) fun washedToBlackTextTransform( textView: TextView, factor: Float, context: Context ) { val color = ArgbEvaluator().evaluate( factor, resolveColor(R.color.washed, context), resolveColor(R.color.black, context) ) as Int textView.setTextColor(color) } fun washedToActiveTransform ( view: View, factor: Float, context: Context ) { val color = ArgbEvaluator().evaluate( factor, resolveColor(R.color.washed, context), Color.parseColor("#c8d4eb") ) as Int view.setBackgroundColor(color) }
13
Kotlin
1
2
05950c87f2eda6f53f886e340459aa13cdbdd621
1,015
ReceiptScan
Apache License 2.0
app/src/main/java/com/kotlin/android_kotlin/data/savingTips/SavingTipsDao.kt
jabandersnatch
668,274,988
false
null
package com.kotlin.android_kotlin.data.savingTips import com.google.firebase.firestore.FirebaseFirestore import kotlinx.coroutines.tasks.await class SavingTipsDao { private val db = FirebaseFirestore.getInstance() private val savingtipsref = db.collection("saving_tips") suspend fun addSavingTip(savingTip: SavingTips) { savingtipsref.document().set(savingTip).await() } suspend fun getSavingTipById(savingTipId: String): SavingTips { val snapshot = savingtipsref.document(savingTipId).get().await() return snapshot.toObject(SavingTips::class.java)!! } // retrieve all savingtip documents suspend fun getAllSavingTips(): List<SavingTips> { val snapshot = savingtipsref.get().await() return snapshot.toObjects(SavingTips::class.java) } // update the likes count of a savingtip document suspend fun updateLikes(savingTipId: String, likes: Int) { val docref = savingtipsref.document(savingTipId) docref.update("likes", likes).await() } // delete a savingtip document suspend fun deleteSavingTip(savingTipId: String) { savingtipsref.document(savingTipId).delete().await() } }
0
Kotlin
0
0
dd492c6c54b03fa795255bb27a04e384a3a145cd
1,205
android_kotlin
MIT License
shared-stats/src/main/java/com/dragote/shared/stats/data/StatsDao.kt
Dragote
718,160,762
false
{"Kotlin": 147679}
package com.dragote.shared.stats.data import androidx.room.ColumnInfo import androidx.room.Dao import androidx.room.Database import androidx.room.Entity import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.PrimaryKey import androidx.room.Query import androidx.room.RoomDatabase @Entity data class Stats( @PrimaryKey val id: String, @ColumnInfo(name = "percentage") val percentage: Float, ) @Dao interface StatsDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertStats(vararg stats: Stats) @Query("SELECT * FROM stats WHERE id=:id ") suspend fun loadSingle(id: String): Stats @Query("DELETE FROM stats") suspend fun clear() } @Database(entities = [Stats::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun statsDao(): StatsDao }
0
Kotlin
0
2
59d44860a9a74bd8824e6e617f834102a3a1f7b1
855
Flapp
MIT License
mmHealthcare/app/src/main/java/com/padcmyanmar/mmhealthcare/activities/BaseActivity.kt
ayemyatminn
140,542,669
false
{"Kotlin": 18324}
package com.padcmyanmar.mmhealthcare.activities import android.support.v7.app.AppCompatActivity open class BaseActivity : AppCompatActivity(){ }
0
Kotlin
0
0
761c7b3169904fa4a6b3fef1cdceefe5bcbdff74
147
PADC-5-P-MM-HealthCare
Apache License 2.0
main/src/main/java/org/mechdancer/ftclib/core/opmode/async/BaseOpModeAsync.kt
MechDancer
146,752,676
false
null
package org.mechdancer.ftclib.core.opmode.async import com.qualcomm.robotcore.eventloop.opmode.Disabled import com.qualcomm.robotcore.util.RobotLog import org.mechdancer.ftclib.algorithm.* import org.mechdancer.ftclib.core.opmode.OpModeWithRobot import org.mechdancer.ftclib.core.opmode.RobotFactory.createRobot import org.mechdancer.ftclib.core.structure.composite.Robot import org.mechdancer.ftclib.core.structure.takeAll import org.mechdancer.ftclib.internal.impl.sensor.VoltageSensorImpl import org.mechdancer.ftclib.internal.impl.takeAllDevices import org.mechdancer.ftclib.util.OpModeLifecycle import org.mechdancer.ftclib.util.info import java.io.PrintWriter import java.io.StringWriter import java.util.* @Disabled abstract class BaseOpModeAsync<T : Robot> : OpModeWithRobot<T>() { private val jumpQueue: Queue<State> = LinkedList() protected val robot = createRobot() private val initializations = robot.takeAll<OpModeLifecycle.Initialize<T>>() private val initializationLoops = robot.takeAll<OpModeLifecycle.InitializeLoop>() private val starts = robot.takeAll<OpModeLifecycle.Start>() private val actions = robot.takeAll<OpModeLifecycle.Run>() private val stops = robot.takeAll<OpModeLifecycle.Stop>() private val devices = robot.takeAllDevices().map { it.first.dropWhile { name -> name != '.' }.removePrefix(".") to it.second } private val voltageSensor = robot.takeAll<VoltageSensorImpl>()[0] private var lastAsyncPeriod = -1L private var lastSyncPeriod = -1L var asyncPeriod = -1 private set var syncPeriod = -1 private set protected var exceptionHandler: (String, Throwable) -> Unit = { lifecycle: String, t: Throwable -> RobotLog.setGlobalErrorMsg("User code throw an Exception in <$lifecycle> :\n" + StringWriter().also { t.printStackTrace(PrintWriter(it)) }.toString()) } private inline fun catchException(lifecycle: String, block: () -> Unit) = try { block() } catch (t: Throwable) { exceptionHandler(lifecycle, t) } private fun runDevices() { devices.forEach { (_, device) -> device.run() } voltageSensor.run() } internal val core = StellateStateMachine { jumpQueue.poll()?.also { state = it } ?: state } .add(State.Initializing) { devices.forEach { (name, device) -> info("Binding device: $name") device.bind(hardwareMap, name) } info("Binding voltage sensor") voltageSensor.bind(hardwareMap) robot.reset() info("Calling init task") catchException("init") { initializations.forEach { it.init(this) } initTask.runToFinish() } info("Initialized") jumpQueue.offer(State.InitLoop) } .add(State.InitLoop) { catchException("init_loop") { actions.forEach { it.run() } initializationLoops.forEach { it.initLoop() } initLoopMachine.run() } asyncPeriod = (System.currentTimeMillis() - lastAsyncPeriod).toInt() lastAsyncPeriod = System.currentTimeMillis() } .add(State.Starting) { catchException("start") { devices.forEach { (name, device) -> info("Calling reset of device: $name") device.reset() } info("Calling reset of robot") robot.reset() starts.forEach { info("Calling start of ${it.name}") it.start() } info("Calling start task") startTask.runToFinish() } jumpQueue.offer(State.Loop) } .add(State.Loop) { catchException("loop") { actions.forEach { it.run() } if (loopMachine.run() == FINISH) requestOpModeStop() } asyncPeriod = (System.currentTimeMillis() - lastAsyncPeriod).toInt() lastAsyncPeriod = System.currentTimeMillis() } .add(State.Stopping) { stopTask.runToFinish() jumpQueue.offer(State.AfterStopLoop) } .add(State.AfterStopLoop) { catchException("after_stop_loop") { actions.forEach { it.run() } runDevices() if (afterStopMachine.run() == FINISH) requestOpModeTerminate() } } .add(State.Terminating) { catchException("terminate") { info("Calling terminate task") terminateTask.runToFinish() stops.forEach { info("Calling stop of ${it.name}") it.stop() } } devices.forEach { (name, device) -> info("Unbinding device: $name") device.unbind() } info("Unbinding voltage sensor") voltageSensor.unbind() info("Terminated") jumpQueue.offer(State.Terminated) } internal var state = State.Initializing private set protected val displayTask = RepeatingLinearStateMachine() protected val initTask = LinearStateMachine() protected abstract val initLoopMachine: StateMachine protected val startTask = LinearStateMachine() protected abstract val loopMachine: StateMachine protected val stopTask = LinearStateMachine() protected abstract val afterStopMachine: StateMachine protected val terminateTask = LinearStateMachine() enum class State { Initializing, InitLoop, Starting, Loop, Stopping, AfterStopLoop, Terminating, Terminated } fun requestOpModeTerminate() { jumpQueue.offer(State.Terminating) } final override fun init() { AsyncOpModeController.setup(this) displayTask.add { telemetry.addLine().addData("State", state) } } final override fun init_loop() { if (state == State.InitLoop) { runDevices() displayTask.runToFinish() } syncPeriod = (System.currentTimeMillis() - lastSyncPeriod).toInt() lastSyncPeriod = System.currentTimeMillis() } final override fun start() { jumpQueue.offer(State.Starting) } final override fun loop() { if (state == State.Loop) { runDevices() displayTask.runToFinish() } syncPeriod = (System.currentTimeMillis() - lastSyncPeriod).toInt() lastSyncPeriod = System.currentTimeMillis() } final override fun stop() { jumpQueue.offer(State.Stopping) } }
0
Kotlin
0
3
6b9bbc0f90f83b45b9a2873c7617cd372bbbd57e
7,416
mechdancerlib
Do What The F*ck You Want To Public License
testing_app/android/app/src/main/kotlin/dev/flutter/testing_app/MainActivity.kt
flutter
136,667,574
false
{"Dart": 5741915, "C": 997312, "C++": 584360, "CMake": 470856, "Swift": 91789, "Kotlin": 78509, "Ruby": 68405, "HTML": 42620, "Shell": 16694, "Objective-C": 13067, "SCSS": 9955, "TypeScript": 9633, "Java": 8802, "CSS": 6965, "GLSL": 6630, "JavaScript": 5903, "Nix": 5260, "Dockerfile": 566, "Makefile": 425}
package dev.flutter.testing_app import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
53
Dart
7520
17,216
9a01200cf85b77e78f0d098dd5157e10f8a03247
128
samples
Apache License 2.0
http/src/main/java/me/chunyu/http/core/builder/GetRequestBuilder.kt
hpsoar
110,518,415
false
null
package me.chunyu.http.core.builder import me.chunyu.http.core.common.Method /** * Created by huangpeng on 12/11/2017. */ open class GetRequestBuilder(url: String): RequestBuilder(url, Method.GET) { }
0
Kotlin
0
0
d1b42c78f2800b54ff64efc3b2bfa1a353cad11d
205
kotlin-http
Apache License 2.0
app/src/main/java/com/vengateshm/android/composecalculators/ui/theme/Color.kt
vengateshm
404,667,162
false
{"Kotlin": 12303}
package com.vengateshm.android.composecalculators.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
0
Kotlin
0
1
04fee3175a2c37733bc8fa699acc54c9e53796b4
236
jetpack_compose_calculators
Apache License 2.0
analytics/src/main/java/io/appmetrica/analytics/impl/NetworkAppContextProvider.kt
appmetrica
650,662,094
false
{"Java": 5984877, "C++": 5729793, "Kotlin": 2117747, "Python": 229161, "Objective-C++": 152166, "C": 127185, "Assembly": 59003, "Emacs Lisp": 14657, "Objective-C": 10302, "Starlark": 7767, "Shell": 5746, "Go": 4930, "CMake": 3562, "CSS": 1454, "AppleScript": 1429, "AIDL": 504}
package io.appmetrica.analytics.impl import io.appmetrica.analytics.BuildConfig import io.appmetrica.analytics.coreapi.internal.identifiers.AppSetIdProvider import io.appmetrica.analytics.coreapi.internal.identifiers.SimpleAdvertisingIdGetter import io.appmetrica.analytics.coreapi.internal.system.LocaleProvider import io.appmetrica.analytics.coreutils.internal.services.FrameworkDetector import io.appmetrica.analytics.networktasks.internal.AppInfo import io.appmetrica.analytics.networktasks.internal.NetworkAppContext import io.appmetrica.analytics.networktasks.internal.ScreenInfoProvider import io.appmetrica.analytics.networktasks.internal.SdkInfo class NetworkAppContextProvider { fun getNetworkAppContext(): NetworkAppContext { return object : NetworkAppContext { override val sdkInfo: SdkInfo = object : SdkInfo { override val sdkVersionName: String = BuildConfig.VERSION_NAME override val sdkBuildNumber: String = BuildConfig.BUILD_NUMBER override val sdkBuildType: String = "${BuildConfig.SDK_BUILD_FLAVOR}_${BuildConfig.SDK_DEPENDENCY}_${BuildConfig.SDK_BUILD_TYPE}" } override val appInfo: AppInfo = object : AppInfo { override val appFramework: String = FrameworkDetector.framework() } override val screenInfoProvider: ScreenInfoProvider get() = GlobalServiceLocator.getInstance().screenInfoHolder override val localeProvider: LocaleProvider get() = LocaleHolder.getInstance(GlobalServiceLocator.getInstance().context) override val advertisingIdGetter: SimpleAdvertisingIdGetter get() = GlobalServiceLocator.getInstance().serviceInternalAdvertisingIdGetter override val appSetIdProvider: AppSetIdProvider get() = GlobalServiceLocator.getInstance().appSetIdGetter } } }
0
Java
3
49
fcd58866d88b4bea09eb34a9bb8078cc8b79e338
1,963
appmetrica-sdk-android
MIT License
app/src/main/java/com/fitken/lanchat/base/BAdapter.kt
nmhung
115,481,934
false
null
package com.fitken.lanchat.base import android.databinding.ViewDataBinding import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import java.lang.reflect.InvocationTargetException import java.util.ArrayList import android.support.v7.widget.RecyclerView.NO_POSITION /** * Created by vophamtuananh on 4/8/17. */ abstract class BAdapter<VH : BAdapter.BHolder<*, *>, T> protected constructor(onItemClickListener: OnItemClickListener?) : RecyclerView.Adapter<VH>() { var dataSource: MutableList<T>? = null private var onItemClickListener: OnItemClickListener? = onItemClickListener protected abstract fun getViewHolder(parent: ViewGroup, viewType: Int): VH? override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH? { val viewHolder = getViewHolder(parent, viewType) viewHolder?.boundView?.root?.setOnClickListener { view -> val pos = viewHolder.adapterPosition if (pos != NO_POSITION) { onItemClicked(view, pos) if (onItemClickListener != null) onItemClickListener!!.onItemClick(view, pos) } } return viewHolder } override fun onBindViewHolder(holder: VH, position: Int) { holder.bindData(dataSource!![position]) } override fun getItemCount(): Int { return if (dataSource != null) dataSource!!.size else 0 } protected fun onItemClicked(v: View, position: Int) {} fun setOnItemClickListener(onItemClickListener: OnItemClickListener) { this.onItemClickListener = onItemClickListener } fun updateItem(position: Int, item: T) { dataSource!![position] = item notifyItemChanged(position) } fun appendItem(item: T?) { if (dataSource == null) dataSource = ArrayList() if (item != null) { dataSource!!.add(item) notifyItemInserted(dataSource!!.size) } } fun appenItems(items: List<T>?) { if (dataSource == null) { dataSource = items as MutableList<T>? } else { if (items != null && items.isNotEmpty()) { val positionStart = dataSource!!.size - 1 dataSource!!.addAll(items) if (positionStart < 0) notifyDataSetChanged() else notifyItemRangeInserted(positionStart, items.size) } } } fun release() { onItemClickListener = null } open class BHolder<V : ViewDataBinding, T>(var boundView: V) : RecyclerView.ViewHolder(boundView.root) { fun bindData(model: Any?) { if (model != null) { val bindingMethods = boundView.javaClass.declaredMethods if (bindingMethods != null && bindingMethods.isNotEmpty()) { for (method in bindingMethods) { val parameterTypes = method.parameterTypes if (parameterTypes != null && parameterTypes.size == 1) { val clazz = parameterTypes[0] try { if (clazz.isInstance(model)) { method.isAccessible = true method.invoke(boundView, model) } else if (clazz.isAssignableFrom(this.javaClass)) { method.isAccessible = true method.invoke(boundView, this) } } catch (e1: InvocationTargetException) { e1.printStackTrace() } catch (e2: IllegalAccessException) { e2.printStackTrace() } } } } } } } }
1
Kotlin
1
3
97df05546b9e0b2b454ffb039762ff5a705284e2
4,003
chat-in-LAN-android-ios
MIT License
encoding/src/commonTest/kotlin/diglol/encoding/VerifyBase64Test.kt
diglol
398,510,655
false
{"Kotlin": 50480}
@file:OptIn(InternalApi::class) package diglol.encoding import diglol.encoding.internal.commonDecodeBase64 import diglol.encoding.internal.commonEncodeBase64 import kotlin.random.Random import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals class VerifyBase64Test { private val sample1 = Random.nextBytes(1024) @Test fun verifyBase64() { ignoreNpe { assertContentEquals( sample1.commonEncodeBase64(), sample1.encodeBase64(), ) assertEquals( sample1.commonEncodeBase64().decodeToString(), sample1.encodeBase64ToString() ) assertContentEquals( sample1.commonEncodeBase64(), sample1.encodeBase64ToString().encodeToByteArray() ) assertContentEquals(sample1.commonEncodeBase64(), sample1.encodeBase64()) assertContentEquals(sample1.commonEncodeBase64(), sample1.encodeBase64()) assertContentEquals(sample1, sample1.commonEncodeBase64().decodeBase64()) assertContentEquals(sample1, sample1.encodeBase64().commonDecodeBase64()) } } }
3
Kotlin
1
9
6f16529086116fcfea849759d12d2c634a1c47b4
1,098
encoding
Apache License 2.0
base-kotlin-compiler/src/main/java/com/izikode/izilib/basekotlincompiler/source/AbstractSource.kt
iFanie
149,670,426
false
null
package com.izikode.izilib.basekotlincompiler.source import com.izikode.izilib.basekotlincompiler.CompilationUtilities import javax.lang.model.element.Element abstract class AbstractSource( protected val element: Element, protected val compilationUtilities: CompilationUtilities )
0
Kotlin
0
0
524a42ba3d339bf75fc5a33e61bb7758451eb0f4
300
BaseKotlinCompiler
Apache License 2.0
promise-ktx/src/main/kotlin/com/voxeet/promise/Promise.kt
voxeet
226,332,046
true
{"Gradle": 5, "XML": 13, "Shell": 3, "Markdown": 4, "Java Properties": 2, "Ignore List": 3, "Batchfile": 1, "YAML": 6, "Proguard": 2, "INI": 3, "Kotlin": 33, "Java": 22, "Text": 1, "Handlebars": 4, "JavaScript": 1}
package com.voxeet.promise import com.voxeet.promise.solve.ThenVoid import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException @SuppressWarnings("TooGenericExceptionCaught", "PrintStackTrace") @Deprecated("This method will exist until the Configuration lets developers use resolve/reject multiple") fun <T> CancellableContinuation<T>.safeResumeWithException(e: Throwable) { try { this.resumeWithException(e) } catch (e: Throwable) { println("Warning, in future versions, this will lead to unexpected crash.") e.printStackTrace() } } suspend fun <T> Promise<T>.await(): T = suspendCancellableCoroutine { continuation -> this.then(ThenVoid { continuation.resume(it) }) .error { continuation.safeResumeWithException(it) } } suspend fun <T> Promise<T>.awaitNullable(): T? = suspendCancellableCoroutine { continuation -> this.then(ThenVoid { continuation.resume(it) }) .error { continuation.safeResumeWithException(it) } } suspend fun <T : Any> Promise<T>.awaitNonNull(): T = suspendCancellableCoroutine { continuation -> this.then { if (null == it) throw NullPointerException("Promise result : value was null") continuation.resume(it) }.error { continuation.safeResumeWithException(it) } } suspend fun <I, O> PromiseInOut<I, O>.await(): O = suspendCancellableCoroutine { continuation -> this.then { continuation.resume(it) } .error { continuation.safeResumeWithException(it) } } suspend fun <I, O> PromiseInOut<I, O>.awaitNullable(): O? = suspendCancellableCoroutine { continuation -> this.then { continuation.resume(it) } .error { continuation.safeResumeWithException(it) } } suspend fun <I, O : Any> PromiseInOut<I, O>.awaitNonNull(): O = suspendCancellableCoroutine { continuation -> this.then { if (null == it) throw NullPointerException("Promise result : value was null") continuation.resume(it) }.error { continuation.safeResumeWithException(it) } }
0
Kotlin
0
0
cb43a9c25635064723066f126cd6a1ec8d7d3971
2,194
sdk-android-lib-promise
Apache License 2.0
app/src/main/java/com/niqr/magicbutton/data/repository/MagickColorPaginationSource.kt
Niqrs
556,910,414
false
{"Kotlin": 53946}
package com.niqr.magicbutton.data.repository import androidx.paging.PagingSource import androidx.paging.PagingState import com.niqr.magicbutton.data.model.MagickColor class MagickColorPaginationSource( private val repo: MagickColorRepository ): PagingSource<Int, MagickColor>() { override val jumpingSupported: Boolean get() = true override fun getRefreshKey(state: PagingState<Int, MagickColor>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1) } } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MagickColor> { return try { //Loading from high to low val lastId = repo.lastId() val pageId = params.key ?: lastId val response = repo.magickColor(pageId) val prevKey = pageId + 1 val nextKey = if (pageId > 1) pageId - 1 else null LoadResult.Page( data = response, prevKey = prevKey, nextKey = nextKey ) } catch (e: Exception) { LoadResult.Error(e) } } }
0
Kotlin
0
3
d9e0661b315ebd970a48dfb7f955372c75a8cce8
1,255
Magic-Button
MIT License
app/src/main/java/com/oceanbrasil/ocean_a6_22_06_20/MainActivity.kt
paulosalvatore
274,265,210
false
null
package com.oceanbrasil.ocean_a6_22_06_20 import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btPesquisar.setOnClickListener { pesquisarLinguagem() } } private fun pesquisarLinguagem() { val language = etLinguagem.text.toString() if (language.isBlank()) { etLinguagem.error = "Digite uma linguagem..." return } textView.text = "Carregando os repositórios..." // Implementação do Retrofit val retrofit = Retrofit.Builder() .baseUrl("https://api.github.com/") .addConverterFactory(GsonConverterFactory.create()) .build() val service = retrofit.create(GitHubService::class.java) val call = service.searchRepositories("language:$language") call.enqueue(object : Callback<GitHubRepositoriesResult> { override fun onFailure(call: Call<GitHubRepositoriesResult>, t: Throwable) { textView.text = "Erro ao carregar os repositórios." Log.e("MAIN_ACTIVITY", "Erro ao executar API", t) } override fun onResponse( call: Call<GitHubRepositoriesResult>, response: Response<GitHubRepositoriesResult> ) { if (response.isSuccessful) { val body = response.body() body?.items?.let { repositories -> textView.text = "" repositories.forEach { textView.append(it.full_name) } } } } }) } }
0
Kotlin
1
2
00f4c2d45b3895a99e1c8845ea21a4a2aafb7d19
2,117
Ocean_A6_22_06_20
MIT License
app/src/main/java/io/hasegawa/stonesafio/StonesafioApp.kt
AllanHasegawa
103,752,410
true
{"Gradle": 7, "Java Properties": 2, "JSON": 1, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 1, "Kotlin": 84, "Proguard": 3, "Java": 6, "XML": 43}
package io.hasegawa.stonesafio import android.support.multidex.MultiDexApplication import io.hasegawa.stonesafio.di.AppDIComponent class StonesafioApp : MultiDexApplication() { override fun onCreate() { super.onCreate() AppDIComponent.initialize(this) } }
0
Kotlin
0
2
e3ec1735ae78e303765a60497ae088510d923089
284
desafio-mobile
MIT License
Teacher-App/app/src/main/java/com/example/seeds/repository/CallStatusRepository.kt
microsoft
657,158,700
false
{"Java": 594936, "JavaScript": 461778, "Kotlin": 196564, "HTML": 2134, "CSS": 1829, "Dockerfile": 534, "Batchfile": 373}
package com.example.seeds.repository class CallStatusRepository { }
2
Java
0
13
4e013636615321ab105cc239b3fa59533d1ac270
68
SEEDS
MIT License
app/src/main/java/com/kuss/krude/AppDetailActivity.kt
KusStar
294,712,671
false
null
package com.kuss.krude import android.annotation.SuppressLint import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.Settings import androidx.appcompat.app.AppCompatActivity import com.kuss.krude.databinding.ActivityAppDetailBinding import com.kuss.krude.utils.ActivityHelper import me.zhanghai.android.appiconloader.AppIconLoader class AppDetailActivity : AppCompatActivity() { private lateinit var binding: ActivityAppDetailBinding @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAppDetailBinding.inflate(layoutInflater) val view = binding.root setContentView(view) intent?.let { val label = it.getStringExtra("label") val packageName = it.getStringExtra("packageName") val info = packageManager.getPackageInfo(packageName!!, 0) val iconSize = resources.getDimensionPixelSize(R.dimen.detail_icon_size) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) { binding.versionInfo.text = "${info.versionName}(${info.longVersionCode})" } else { binding.versionInfo.text = "${info.versionName}(${info.versionCode})" } binding.iconView.setImageBitmap( AppIconLoader(iconSize, true, this) .loadIcon(info.applicationInfo) ) binding.labelView.text = label binding.packageNameView.text = packageName binding.detailBtn.setOnClickListener { toDetail(packageName) } binding.uninstallBtn.setOnClickListener { toUninstall(packageName) } } } private fun toDetail(packageName: String) { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK data = Uri.parse("package:$packageName") } ActivityHelper.startWithRevealAnimation( this, binding.iconView, intent ) finish() } private fun toUninstall(packageName: String) { val intent = Intent(Intent.ACTION_UNINSTALL_PACKAGE).apply { data = Uri.parse("package:$packageName") } ActivityHelper.startWithRevealAnimation( this, binding.iconView, intent ) finish() } }
0
Kotlin
0
2
b9973ddfda3b046c01d4bda524f0379793aac8f9
2,566
krude
MIT License