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
WishFetcher.kt
jabree937
560,236,368
false
null
package com.example.whishlist class WishFetcher { companion object { private val nameList = mutableListOf<String>() private val urlList = mutableListOf<String>() private val priceList = mutableListOf<String>() fun addWishes(name: String, url: String, price: String) { nameList.add(name) urlList.add(url) priceList.add(price) } fun getWishes(): MutableList<Wish> { val wishes : MutableList<Wish> = ArrayList() for (i in nameList.indices) { val wish = Wish(nameList[i], urlList[i], priceList[i]) wishes.add(wish) } return wishes } } }
0
Kotlin
0
0
aff7370b5f12982b3935b33c68bff8d3b9dba299
727
project2WishList
Apache License 2.0
collections/src/main/kotlin/moe/kanon/kommons/collections/Maps.kt
Olivki
219,809,070
false
null
/* * Copyright 2019-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("KMaps") package moe.kanon.kommons.collections import java.util.Collections import java.util.EnumMap import java.util.TreeMap // -- FACTORY FUNCTIONS -- \\ /** * Returns a new [Map] that only contains the given [value] mapped to the given [key]. */ @Deprecated( message = "Use 'mapOf(key, value)' instead.", replaceWith = ReplaceWith("mapOf(key, value)", "moe.kanon.kommons.collections") ) fun <K, V> singletonMapOf(key: K, value: V): Map<K, V> = mapOf(key, value) /** * Returns a new [Map] that only contains the given [value] mapped to the given [key]. */ @JvmName("singletonOf") fun <K, V> mapOf(key: K, value: V): Map<K, V> = Collections.singletonMap(key, value) /** * Returns a new [Map] that only contains the given [value][Pair.second] mapped to the given [key][Pair.first]. */ @JvmName("singletonOf") @Deprecated( message = "Use 'mapOf(pair)' instead.", replaceWith = ReplaceWith("mapOf(pair)", "kotlin.collections") ) fun <K, V> singletonMapOf(pair: Pair<K, V>): Map<K, V> = mapOf(pair) /** * Returns an [unmodifiable view][Collections.unmodifiableMap] of `this` map. */ fun <K, V> Map<K, V>.asUnmodifiableMap(): Map<K, V> = Collections.unmodifiableMap(this) /** * Returns a new [TreeMap] that contains the specified [pairs]. */ fun <K : Comparable<K>, V> treeMapOf(vararg pairs: Pair<K, V>): TreeMap<K, V> = TreeMap(pairs.toMap()) // enum-map /** * Returns a new [EnumMap] that contains the specified [entries]. */ // we're using the enum class constructor rather than the one that accepts a map so that the function won't fail if // the supplied 'entries' is empty. inline fun <reified K : Enum<K>, V> enumMapOf(vararg entries: Pair<K, V>): EnumMap<K, V> = EnumMap<K, V>(K::class.java).fillWith(entries) /** * Returns a new and empty [EnumMap] based on the specified [enum][K]. */ inline fun <reified K : Enum<K>, V> emptyEnumMap(): EnumMap<K, V> = EnumMap(K::class.java) /** * Returns a new [EnumMap] which is populated by the specified [init] function. */ @JvmName("enumMap") inline fun <reified K : Enum<K>, V> enumMap(init: (K) -> V): EnumMap<K, V> = emptyEnumMap<K, V>().fillWith(enumValues<K>().associate { it to init(it) }) /** * Returns a new [enum-map][EnumMap] containing the entries of `this` map. */ inline fun <reified K : Enum<K>, V> Map<K, V>.toEnumMap(): EnumMap<K, V> = convertToEnumMap(this, K::class.java) @PublishedApi internal fun <K : Enum<K>, V> convertToEnumMap(origin: Map<K, V>, clz: Class<K>): EnumMap<K, V> = when (origin) { is EnumMap -> origin else -> EnumMap<K, V>(clz).apply { putAll(origin) } } // -- UTIL FUNCTIONS -- \\ /** * Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if * supplied. * * If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first * [limit] elements will be appended, followed by the [truncated] string (which defaults to "..."). */ fun <K, V> Map<K, V>.joinToString( separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((Map.Entry<K, V>) -> CharSequence)? = null ): String = entries.joinToString(separator, prefix, postfix, limit, truncated, transform) /** * Returns the value stored under the given [key], or throws a [NoSuchElementException] where the `message` is set to * the result of invoking [toString] on the given [lazyMessage] function. */ @Deprecated( message = "The name does not follow naming convention", replaceWith = ReplaceWith("this.getOrThrow(key, lazyMessage)", "moe.kanon.kommons.collections"), level = DeprecationLevel.ERROR ) inline fun <K, V> Map<K, V>.getValueOrThrow(key: K, lazyMessage: () -> Any): V = this[key] ?: throw NoSuchElementException(lazyMessage().toString()) /** * Returns the value stored under the given [key], or throws a [NoSuchElementException] where the `message` is set to * the result of invoking [toString] on the given [lazyMessage] function if no value is stored under `key`. */ @Suppress("UNCHECKED_CAST") inline fun <K, V> Map<K, V>.getOrThrow(key: K, lazyMessage: () -> Any): V { if (key !in this) throw NoSuchElementException(lazyMessage().toString()) return this[key] as V } /** * Executes the specified [action] every time an `entry` matches the specified [predicate]. */ inline fun <K, V> Map<K, V>.onMatch(predicate: (Map.Entry<K, V>) -> Boolean, action: (Map.Entry<K, V>) -> Unit) { for (entry in this) if (predicate(entry)) action(entry) } /** * Throws the specified [exception] every time an `entry` matches the specified [predicate]. */ inline fun <K, V, X : Throwable> Map<K, V>.throwOnMatch( predicate: (Map.Entry<K, V>) -> Boolean, exception: (Map.Entry<K, V>) -> X ) = this.onMatch(predicate) { throw exception(it) } /** * Adds the specified [pairs] to `this` map and returns `this`. */ @JvmName("populate") fun <K, V, M : MutableMap<K, V>> M.fillWith(vararg pairs: Pair<K, V>): M = this.apply { putAll(pairs) } /** * Adds the specified [pairs] to `this` map and returns `this`. */ fun <K, V, M : MutableMap<K, V>> M.fillWith(pairs: Iterable<Pair<K, V>>): M = this.apply { putAll(pairs) } /** * Adds the specified [pairs] to `this` map and returns `this`. */ fun <K, V, M : MutableMap<K, V>> M.fillWith(pairs: Array<out Pair<K, V>>): M = this.apply { putAll(pairs) } /** * Adds the contents of the specified [map] to `this` map, and returns `this`. */ fun <K, V, M : MutableMap<K, V>> M.fillWith(map: Map<K, V>): M = this.apply { putAll(map) } /** * Returns a map containing all entries that have a key that are instances of the specified type parameter [R]. */ inline fun <reified R, V> Map<*, V>.filterKeysIsInstance(): Map<R, V> = this.filterKeys { it is R } as Map<R, V> /** * Returns a map containing all entries that have a value that are instances of the specified type parameter [R]. */ inline fun <K, reified R> Map<K, *>.filterValuesIsInstance(): Map<K, R> = this.filterValues { it is R } as Map<K, R>
0
Kotlin
0
0
d667161238bc5d891fa6669ffd2d6cfa558c5e32
6,729
kanon.kommons
Apache License 2.0
kotlin-typescript/src/main/generated/typescript/TransientIdentifier.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! package typescript sealed external interface TransientIdentifier : Identifier { var resolvedSymbol: Symbol }
10
Kotlin
145
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
159
kotlin-wrappers
Apache License 2.0
presentation/src/main/java/com/cheesecake/presentation/screens/match/events/MatchEventAdapter.kt
CheeseCake-Team
645,082,831
false
{"Kotlin": 443813}
package com.cheesecake.presentation.screens.match.events import android.view.View import androidx.core.view.isVisible import com.cheesecake.domain.entity.EventType import com.cheesecake.presentation.R import com.cheesecake.presentation.base.BaseAdapter import com.cheesecake.presentation.databinding.ItemMatchEventBinding class MatchEventAdapter(private val homeTeamId: Int, private val awayTeamId: Int) : BaseAdapter<EventItemUiState>(null) { override val layoutId = R.layout.item_match_event override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { val currentItem = itemList[position] if (holder is ItemViewHolder) { with(holder.binding) { setVariable(androidx.databinding.library.baseAdapters.BR.item, currentItem) this as ItemMatchEventBinding when (currentItem.eventType) { EventType.OWN_GOAL -> { imageViewEventType.setImageResource(R.drawable.ic_own_goal) textViewHomeTeamSubstituentPlayerName.visibility = View.GONE textViewAwayTeamSubstituentPlayerName.visibility = View.GONE } EventType.PENALTY -> { imageViewEventType.setImageResource(R.drawable.ic_penalty) textViewHomeTeamSubstituentPlayerName.visibility = View.GONE textViewAwayTeamSubstituentPlayerName.visibility = View.GONE } EventType.MISSED_PENALTY -> { imageViewEventType.setImageResource(R.drawable.ic_missed_penalty) textViewHomeTeamSubstituentPlayerName.visibility = View.GONE textViewAwayTeamSubstituentPlayerName.visibility = View.GONE } EventType.YELLOW_CARD -> { imageViewEventType.setImageResource(R.drawable.ic_yellow_card) textViewHomeTeamSubstituentPlayerName.visibility = View.GONE textViewAwayTeamSubstituentPlayerName.visibility = View.GONE } EventType.RED_CARD -> { imageViewEventType.setImageResource(R.drawable.ic_red_card) textViewHomeTeamSubstituentPlayerName.visibility = View.GONE textViewAwayTeamSubstituentPlayerName.visibility = View.GONE } EventType.SUBST -> { imageViewEventType.setImageResource(R.drawable.ic_substitution) textViewHomeTeamSubstituentPlayerName.isVisible = true textViewAwayTeamSubstituentPlayerName.isVisible = true } EventType.GOAL_CANCELLED -> { imageViewEventType.setImageResource(R.drawable.ic_goal_cancelled) textViewHomeTeamSubstituentPlayerName.visibility = View.GONE textViewAwayTeamSubstituentPlayerName.visibility = View.GONE } EventType.GOAL_CONFIRMED -> { imageViewEventType.setImageResource(R.drawable.ic_goal_confirmed) textViewHomeTeamSubstituentPlayerName.visibility = View.GONE textViewAwayTeamSubstituentPlayerName.visibility = View.GONE } EventType.PENALTY_CONFIRMED -> { imageViewEventType.setImageResource(R.drawable.ic_penalty_confirmed) textViewHomeTeamSubstituentPlayerName.visibility = View.GONE textViewAwayTeamSubstituentPlayerName.visibility = View.GONE } EventType.PENALTY_CANCELLED -> { imageViewEventType.setImageResource(R.drawable.ic_penalty_cancelled) textViewHomeTeamSubstituentPlayerName.visibility = View.GONE textViewAwayTeamSubstituentPlayerName.visibility = View.GONE } else -> { imageViewEventType.setImageResource(R.drawable.ic_football) textViewHomeTeamSubstituentPlayerName.visibility = View.GONE textViewAwayTeamSubstituentPlayerName.visibility = View.GONE } } when (currentItem.teamId) { homeTeamId -> { cardViewHomeTeamEvent.isVisible = true cardViewAwayTeamEvent.visibility = View.GONE } awayTeamId -> { cardViewHomeTeamEvent.visibility = View.GONE cardViewAwayTeamEvent.isVisible = true } } } } } }
0
Kotlin
2
4
cb032f91ae1fb7f35fc5242de6f6eb076ce51330
4,957
kickoff
Apache License 2.0
bindings/core/gobject/src/nativeMain/kotlin/org/gtkkn/bindings/gobject/TypeFundamentalInfo.kt
gtk-kn
609,191,895
false
{"Kotlin": 10448515, "Shell": 2740}
// This is a generated file. Do not modify. package org.gtkkn.bindings.gobject import kotlinx.cinterop.CPointed import kotlinx.cinterop.CPointer import kotlinx.cinterop.pointed import kotlinx.cinterop.reinterpret import org.gtkkn.extensions.glib.Record import org.gtkkn.extensions.glib.RecordCompanion import org.gtkkn.native.gobject.GTypeFundamentalInfo /** * A structure that provides information to the type system which is * used specifically for managing fundamental types. */ public class TypeFundamentalInfo( pointer: CPointer<GTypeFundamentalInfo>, ) : Record { public val gobjectTypeFundamentalInfoPointer: CPointer<GTypeFundamentalInfo> = pointer /** * #GTypeFundamentalFlags describing the characteristics of the fundamental type */ public var typeFlags: TypeFundamentalFlags get() = gobjectTypeFundamentalInfoPointer.pointed.type_flags.run { TypeFundamentalFlags(this) } set(`value`) { gobjectTypeFundamentalInfoPointer.pointed.type_flags = value.mask } public companion object : RecordCompanion<TypeFundamentalInfo, GTypeFundamentalInfo> { override fun wrapRecordPointer(pointer: CPointer<out CPointed>): TypeFundamentalInfo = TypeFundamentalInfo(pointer.reinterpret()) } }
0
Kotlin
0
13
c033c245f1501134c5b9b46212cd153c61f7efea
1,324
gtk-kn
Creative Commons Attribution 4.0 International
src/main/kotlin/com/tuk/oriddle/quiz/application/port/out/GetQuizPort.kt
Team-Oriddle
731,663,342
false
{"Kotlin": 119817}
package com.tuk.oriddle.quiz.application.port.out import com.tuk.oriddle.quiz.domain.Quiz import com.tuk.oriddle.quiz.domain.QuizInfo import java.util.* interface GetQuizPort { fun getQuizInfo(quizId: UUID): QuizInfo fun getQuiz(quizId: UUID): Quiz }
1
Kotlin
1
0
541b98644d44a2b10223fbb470d37bd0c5ec771d
260
oriddle-backend
MIT License
src/main/kotlin/br/com/ot6/shared/clients/bcb/dtos/SavePixKeyClientReturn.kt
Joao-Nunes-Zup
398,877,471
true
{"Kotlin": 75606}
package br.com.ot6.shared.clients.bcb.dtos data class SavePixKeyReturn( val keyType: String, val key: String, val bankAccount: BankAccountReturn, val owner: OwnerReturn ) data class BankAccountReturn( val participant: String, val branch: String, val accountNumber: String, val accountType: String ) data class OwnerReturn( val type: String, val name: String, val taxIdNumber: String )
0
Kotlin
0
0
d4d3a24430bf2c54670521543a529c9e3c4304f6
432
orange-talents-06-template-pix-keymanager-grpc
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/visitscheduler/model/entity/session/SessionTemplate.kt
ministryofjustice
409,259,375
false
null
package uk.gov.justice.digital.hmpps.visitscheduler.model.entity.session import uk.gov.justice.digital.hmpps.visitscheduler.model.VisitType import uk.gov.justice.digital.hmpps.visitscheduler.model.entity.Prison import uk.gov.justice.digital.hmpps.visitscheduler.model.entity.base.AbstractReferenceEntity import java.time.DayOfWeek import java.time.LocalDate import java.time.LocalTime import javax.persistence.CascadeType import javax.persistence.Column import javax.persistence.Entity import javax.persistence.EnumType import javax.persistence.Enumerated import javax.persistence.FetchType import javax.persistence.JoinColumn import javax.persistence.JoinTable import javax.persistence.ManyToMany import javax.persistence.ManyToOne import javax.persistence.Table @Entity @Table(name = "SESSION_TEMPLATE") class SessionTemplate( @Column(name = "PRISON_ID", nullable = false) val prisonId: Long, @ManyToOne(cascade = [CascadeType.DETACH]) @JoinColumn(name = "PRISON_ID", updatable = false, insertable = false) val prison: Prison, @Column(nullable = false) var name: String, @Column(nullable = false) val visitRoom: String, @Column(nullable = false) val enhanced: Boolean = false, @ManyToMany(fetch = FetchType.LAZY, cascade = [CascadeType.REFRESH]) @JoinTable( name = "SESSION_TO_LOCATION_GROUP", joinColumns = [JoinColumn(name = "session_template_id",)], inverseJoinColumns = [JoinColumn(name = "group_id")], ) val permittedSessionGroups: MutableList<SessionLocationGroup> = mutableListOf(), @Column @Enumerated(EnumType.STRING) val visitType: VisitType, @Column(nullable = false) val startTime: LocalTime, @Column(nullable = false) val endTime: LocalTime, @Column(nullable = false) val validFromDate: LocalDate, @Column val validToDate: LocalDate?, @Column(nullable = false) val closedCapacity: Int, @Column(nullable = false) val openCapacity: Int, @Column(name = "bi_weekly", nullable = false) val biWeekly: Boolean = false, @Column(nullable = false) @Enumerated(EnumType.STRING) val dayOfWeek: DayOfWeek ) : AbstractReferenceEntity(delimiter = ".", chunkSize = 3)
3
Kotlin
2
6
01dcad3b0defb675a12da8d0f14cc130766410ff
2,166
visit-scheduler
MIT License
app/src/main/java/io/github/joaogouveia89/retedex/pokemon/presentation/PokemonViewModel.kt
joaogouveia89
776,063,726
false
{"Kotlin": 98924}
package io.github.joaogouveia89.retedex.pokemon.presentation import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.cachedIn import dagger.hilt.android.lifecycle.HiltViewModel import io.github.joaogouveia89.retedex.pokemon.domain.usecase.GetPokemonsUseCase import io.github.joaogouveia89.retedex.pokemon.presentation.state.PokemonsState import javax.inject.Inject @HiltViewModel class PokemonViewModel @Inject constructor( getPokemonsUseCase: GetPokemonsUseCase ) : ViewModel() { var uiState by mutableStateOf(PokemonsState()) private set init { val pokemons = getPokemonsUseCase.invoke() .cachedIn(viewModelScope) uiState = uiState.copy(pokemons = pokemons) } }
0
Kotlin
0
0
4129136266aeb81418c691853b4473fbf03c5440
893
Retedex
MIT License
app/src/main/java/com/anangkur/mediku/feature/view/mens/menstrual/MenstrualViewModel.kt
anangkur
236,449,731
false
null
package com.anangkur.mediku.feature.view.mens.menstrual import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.anangkur.mediku.base.BaseFirebaseListener import com.anangkur.mediku.data.Repository import com.anangkur.mediku.data.model.menstrual.MenstrualPeriodResume import com.anangkur.mediku.feature.mapper.MenstrualPeriodResumeMapper import com.anangkur.mediku.feature.model.menstrual.MenstrualPeriodMonthlyIntent import com.anangkur.mediku.feature.model.menstrual.MenstrualPeriodResumeIntent import com.anangkur.mediku.util.Const import com.google.firebase.firestore.ktx.toObject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.* class MenstrualViewModel(private val repository: Repository): ViewModel() { private val menstrualPeriodResumeMapper = MenstrualPeriodResumeMapper.getInstance() var activeYear = "" var activeYearData: MenstrualPeriodMonthlyIntent? = null var maxCycleLong = 0 var minCycleLong = 0 var periodLong = 0 var activeMonth = 0 val progressGetMenstrualRecord = MutableLiveData<Boolean>() val successGetMenstrualRecord = MutableLiveData<MenstrualPeriodMonthlyIntent>() val errorGetMenstrualRecord = MutableLiveData<String>() fun getMenstrualPeriod(year: String){ CoroutineScope(Dispatchers.IO).launch { try { progressGetMenstrualRecord.postValue(true) val user = repository.remoteRepository.firebaseAuth.currentUser activeYear = year periodLong = 0 activeMonth = 0 repository.remoteRepository.firestore .collection(Const.COLLECTION_MENSTRUAL_PERIOD) .document(user?.uid?:"") .collection(activeYear) .get() .addOnSuccessListener {result -> val menstrualPeriodMonthly = MenstrualPeriodMonthlyIntent() if (!result.isEmpty){ for (querySnapshot in result){ val data = querySnapshot?.toObject<MenstrualPeriodResumeIntent>() if (data != null){ if (maxCycleLong == 0 && minCycleLong == 0){ maxCycleLong = data.longCycle minCycleLong = data.longCycle } if (data.longCycle > maxCycleLong){ maxCycleLong = data.longCycle } if (data.longCycle < minCycleLong){ minCycleLong = data.longCycle } periodLong += data.longPeriod activeMonth++ } when (querySnapshot.id){ Const.KEY_JAN -> { menstrualPeriodMonthly.jan = data } Const.KEY_FEB -> { menstrualPeriodMonthly.feb = data } Const.KEY_MAR -> { menstrualPeriodMonthly.mar = data } Const.KEY_APR -> { menstrualPeriodMonthly.apr = data } Const.KEY_MAY -> { menstrualPeriodMonthly.may = data } Const.KEY_JUN -> { menstrualPeriodMonthly.jun = data } Const.KEY_JUL -> { menstrualPeriodMonthly.jul = data } Const.KEY_AUG -> { menstrualPeriodMonthly.aug = data } Const.KEY_SEP -> { menstrualPeriodMonthly.sep = data } Const.KEY_OCT -> { menstrualPeriodMonthly.oct = data } Const.KEY_NOV -> { menstrualPeriodMonthly.nov = data } Const.KEY_DEC -> { menstrualPeriodMonthly.dec = data } } } periodLong /= activeMonth } progressGetMenstrualRecord.postValue(false) successGetMenstrualRecord.postValue(menstrualPeriodMonthly) } .addOnFailureListener {exception -> progressGetMenstrualRecord.postValue(false) errorGetMenstrualRecord.postValue(exception.message) } }catch (e: Exception){ progressGetMenstrualRecord.postValue(false) errorGetMenstrualRecord.postValue(e.message) } } } val progressAddMenstrualRecord = MutableLiveData<Boolean>() val successAddMenstrualRecord = MutableLiveData<MenstrualPeriodResumeIntent>() val errorAddMenstrualRecord = MutableLiveData<String>() fun addMenstrualPeriod(menstrualPeriodResume: MenstrualPeriodResumeIntent, date: Date){ val month = SimpleDateFormat("MMMM", Locale.US).format(date) addMenstrualResumeDataMonth(month, menstrualPeriodResume) CoroutineScope(Dispatchers.IO).launch { repository.addMenstrualPeriod(menstrualPeriodResumeMapper.mapFromIntent(menstrualPeriodResume)!!, object: BaseFirebaseListener<MenstrualPeriodResume>{ override fun onLoading(isLoading: Boolean) { progressAddMenstrualRecord.postValue(isLoading) } override fun onSuccess(data: MenstrualPeriodResume) { successAddMenstrualRecord.postValue(menstrualPeriodResumeMapper.mapToIntent(data)) } override fun onFailed(errorMessage: String) { errorAddMenstrualRecord.postValue(errorMessage) } }) } } fun getMenstrualResumeDataCurrentMonth(month: String): MenstrualPeriodResumeIntent? { return when (month){ Const.KEY_JAN -> activeYearData?.jan Const.KEY_FEB -> activeYearData?.feb Const.KEY_MAR -> activeYearData?.mar Const.KEY_APR -> activeYearData?.apr Const.KEY_MAY -> activeYearData?.may Const.KEY_JUN -> activeYearData?.jun Const.KEY_JUL -> activeYearData?.jul Const.KEY_AUG -> activeYearData?.aug Const.KEY_SEP -> activeYearData?.sep Const.KEY_OCT -> activeYearData?.oct Const.KEY_NOV -> activeYearData?.nov Const.KEY_DEC -> activeYearData?.dec else -> null } } private fun addMenstrualResumeDataMonth(month: String, data: MenstrualPeriodResumeIntent) { when (month){ Const.KEY_JAN -> activeYearData?.jan = data Const.KEY_FEB -> activeYearData?.feb = data Const.KEY_MAR -> activeYearData?.mar = data Const.KEY_APR -> activeYearData?.apr = data Const.KEY_MAY -> activeYearData?.may = data Const.KEY_JUN -> activeYearData?.jun = data Const.KEY_JUL -> activeYearData?.jul = data Const.KEY_AUG -> activeYearData?.aug = data Const.KEY_SEP -> activeYearData?.sep = data Const.KEY_OCT -> activeYearData?.oct = data Const.KEY_NOV -> activeYearData?.nov = data Const.KEY_DEC -> activeYearData?.dec = data } } }
2
Kotlin
1
4
4b4e184a5ea9368c0901262ce9899bad6c56fb87
7,683
Medi-Ku
MIT License
codekit/src/main/java/com/ctrlbytes/codekit/utils/AppsInDevice.kt
ctrlbytes
282,138,397
false
null
/* * MIT License * * Copyright (c) 2020 CtrlBytes Technologies * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.ctrlbytes.codekit.utils import android.content.Context import android.content.Intent @Suppress("unused") object AppsInDevice { @JvmStatic fun isInstalled(context: Context, packageName: String): Boolean { val appIntent = Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER) val resolveInfoList = context.packageManager.queryIntentActivities(appIntent, 0) for (resolveInfo in resolveInfoList) { if (resolveInfo.activityInfo.packageName == packageName) { return true } } return false } object Packages { const val FACEBOOK = "com.facebook.katana" const val FACEBOOK_MESSENGER = "com.facebook.orca" const val FACEBOOK_LITE = "com.facebook.lite" const val FACEBOOK_MENTIONS = "com.facebook.Mentions" const val FACEBOOK_GROUPS = "com.facebook.groups" const val FACEBOOK_PAGES_MANAGER = "com.facebook.pages.app" const val WHATSAPP = "com.whatsapp" const val VIBER = "com.viber.voip" const val TELEGRAM = "org.telegram.messenger" const val GOOGLE = "com.google.android.googlequicksearchbox" const val GOOGLE_DRIVE = "com.google.android.apps.docs" const val GOOGLE_TRANSLATE = "com.google.android.apps.translate" const val GOOGLE_CALENDAR = "com.google.android.calendar" const val GOOGLE_MAPS = "com.google.android.apps.maps" const val GOOGLE_DOCS = "com.google.android.apps.docs.editors.docs" const val GOOGLE_ALLO = "com.google.android.apps.fireball" const val GOOGLE_SHEETS = "com.google.android.apps.docs.editors.sheets" const val CHROME = "com.android.chrome" const val GMAIL = "com.google.android.gm" const val YOUTUBE = "com.google.android.youtube" const val HANGOUTS = "com.google.android.talk" const val UBER = "com.ubercab" const val LYFT = "me.lyft.android" const val CLEAN_MASTER = "com.cleanmaster.mguard" const val DUBSMASH = "com.mobilemotion.dubsmash" const val SNAPCHAT = "com.snapchat.android" const val NETFLIX = "com.netflix.mediaclient" const val MSQRD = "me.msqrd.android" const val QUORA = "com.quora.android" const val LINKEDIN = "com.linkedin.android" const val PINTEREST = "com.pinterest" const val TUMBLR = "com.tumblr" } }
5
Kotlin
0
9
304a52e7d0c98e31ebe6ed50a99b40b1228a28ff
3,579
CodeKit
MIT License
src/main/kotlin/de/sambalmueslie/games/hll/tool/features/mapvote/process/MapVoteEventProcess.kt
sambalmueslie
439,963,166
false
null
package de.sambalmueslie.games.hll.tool.features.mapvote.process import de.sambalmueslie.games.hll.tool.features.mapvote.MapVoteService import de.sambalmueslie.games.hll.tool.features.mapvote.discord.MapVoteBotEventHandler import discord4j.core.event.domain.message.ReactionAddEvent import discord4j.core.event.domain.message.ReactionRemoveEvent import jakarta.inject.Singleton import org.slf4j.Logger import org.slf4j.LoggerFactory import reactor.core.publisher.Mono @Singleton class MapVoteEventProcess( private val service: MapVoteService ) : MapVoteBotEventHandler { companion object { val logger: Logger = LoggerFactory.getLogger(MapVoteEventProcess::class.java) } @Suppress("BlockingMethodInNonBlockingContext") override fun handleReactionEvent(event: ReactionAddEvent): Mono<Void> { val messageId = event.messageId.asLong() val voting = service.getByMessageId(messageId) ?: return Mono.empty() val user = event.user.block() ?: return Mono.empty() voting.addVote(user, event.emoji) val message = event.message.block() ?: return Mono.empty() // TODO filter out duplicates return Mono.empty() } override fun handleReactionEvent(event: ReactionRemoveEvent): Mono<Void> { val messageId = event.messageId.asLong() val voting = service.getByMessageId(messageId) ?: return Mono.empty() val user = event.user.block() ?: return Mono.empty() voting.removeVote(user, event.emoji) return Mono.empty() } }
0
Kotlin
0
0
a67a6acefeb38b341bc87d24c5e44157349a62a5
1,545
hll-tool
Apache License 2.0
PracticaRecyclerViewKotlin/app/src/main/java/edu/unicauca/aplimovil/practicarecyclerviewapp/UserAdapter.kt
cfigmart
491,656,397
false
null
package edu.unicauca.aplimovil.practicarecyclerviewapp import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import edu.unicauca.aplimovil.practicarecyclerviewapp.model.User class UserAdapter: RecyclerView.Adapter<UserAdapter.UserViewHolder> () { var users = listOf<User>() set (value){ field = value notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder { val view = LayoutInflater .from(parent.context) .inflate(R.layout.layout_user_item, parent, false) return UserViewHolder(view) } override fun onBindViewHolder(holder: UserViewHolder, position: Int) { val user = users[position] holder.bind(user) } override fun getItemCount() = users.size class UserViewHolder(view: View):RecyclerView.ViewHolder(view) { val tvName: TextView = view.findViewById(R.id.tvName) val tvDescription: TextView = view.findViewById(R.id.tvDescription) val userImage: ImageView = view.findViewById(R.id.userImage) fun bind (user : User){ tvName.text = user.name tvDescription.text = user.description userImage.setImageResource(user.imageId) } } }
0
Kotlin
0
0
6647b2dd12e0098a62f024e42b5adf900de218af
1,436
aplimovil2022
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/transfer/S3InputFileLocationPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.transfer import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.transfer.CfnWorkflow @Generated public fun buildS3InputFileLocationProperty(initializer: @AwsCdkDsl CfnWorkflow.S3InputFileLocationProperty.Builder.() -> Unit): CfnWorkflow.S3InputFileLocationProperty = CfnWorkflow.S3InputFileLocationProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
483
aws-cdk-kt
Apache License 2.0
src/main/kotlin/br/com/keymanagergrpc/pix/remove/RemoveChaveEndPoint.kt
rodrigodeoliveira19
387,889,045
true
{"Kotlin": 34499}
package br.com.keymanagergrpc.pix.remove import br.com.keymanagergrpc.KeyManagerRemoveGrpcServiceGrpc import br.com.keymanagergrpc.RemoveChavePixRequest import br.com.keymanagergrpc.RemoveChavePixResponse import br.com.keymanagergrpc.shared.grpc.ErrorHandler import io.grpc.stub.StreamObserver import javax.inject.Inject import javax.inject.Singleton @ErrorHandler @Singleton class RemoveChaveEndPoint (@Inject private val service: RemoveChavePixService): KeyManagerRemoveGrpcServiceGrpc.KeyManagerRemoveGrpcServiceImplBase(){ override fun remove(request: RemoveChavePixRequest, responseObserver: StreamObserver<RemoveChavePixResponse> ) { service.remove(clienteId = request.clienteId, pixId = request.pixId) responseObserver.onNext(RemoveChavePixResponse.newBuilder() .setClienteId(request.clienteId) .setPixId(request.pixId) .build()) responseObserver.onCompleted() } }
0
Kotlin
0
0
351ec51a6280c95d478e0b8e5868a7aa2f4eb0fb
977
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
test-automation-core/src/main/kotlin/com/nortal/test/core/report/util/CurlBuilder.kt
nortal
504,492,420
false
{"Kotlin": 332735, "Java": 39099, "CSS": 6064, "JavaScript": 2198, "Gherkin": 2044, "HTML": 377}
/** * Copyright (c) 2022 Nortal AS * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.nortal.test.core.report.util import com.nortal.test.core.report.JsonFormattingUtils import com.nortal.test.core.report.model.HttpHeader import com.nortal.test.core.report.model.HttpRequest import org.springframework.stereotype.Component import java.util.function.Consumer @Component class CurlBuilder { fun getRequestCurl(request: HttpRequest): String { val curl = StringBuilder("curl -X ") .append(request.method.uppercase()) .append(" \\\n'") .append(request.url) .append("' \\\n") request.headers.asMap() .forEach { (headerKey: String, header: HttpHeader) -> header.values.forEach( Consumer { headerValue: String -> appendHeader(curl, headerKey, headerValue) }) } if (request.body != null) { val json = JsonFormattingUtils.prettyPrintJson(request.body) curl.append("-d '").append(json).append('\'') } curl.append('\n') //TODO verify query params return curl.toString() } private fun appendHeader(curl: StringBuilder, headerKey: String, headerValue: String) { curl.append("-H '").append(headerKey).append(": ").append(headerValue).append("' \\\n") } }
0
Kotlin
2
2
6deaf66c37d6a9cc78c49a81ea59779ad95e5c7f
2,400
test-automation
MIT License
src/main/kotlin/org/rust/cargo/toolchain/WasmPack.kt
jhinch
290,145,903
true
{"Kotlin": 6467845, "Rust": 113429, "Python": 64032, "Lex": 20296, "HTML": 15783, "Java": 1274, "Shell": 760, "RenderScript": 129}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.toolchain import com.intellij.execution.configurations.GeneralCommandLine import org.rust.cargo.util.splitOnDoubleDash import org.rust.openapiext.GeneralCommandLine import java.io.File import java.nio.file.Path class WasmPack(private val wasmPackExecutable: Path) { fun createCommandLine(workingDirectory: File, command: String, args: List<String>): GeneralCommandLine { val (pre, post) = splitOnDoubleDash(args) .let { (pre, post) -> pre.toMutableList() to post.toMutableList() } val buildableCommands = setOf("build", "test") val forceColorsOption = "--color=always" if (command in buildableCommands && forceColorsOption !in post) { post.add(forceColorsOption) } val allArgs = if (post.isEmpty()) pre else pre + "--" + post return GeneralCommandLine(wasmPackExecutable) .withWorkDirectory(workingDirectory) .withParameters(command, *allArgs.toTypedArray()) .withRedirectErrorStream(true) } }
0
null
0
0
c59483dcc538b3e3f4e40296305ab6ce36ffb400
1,154
intellij-rust
MIT License
base/media/medialib/src/main/kotlin/com/flammky/common/media/audio/meta_tag/audio/asf/io/ChunkReader.kt
flammky
462,795,948
false
{"Kotlin": 5222947}
package com.flammky.musicplayer.common.media.audio.meta_tag.audio.asf.io import com.flammky.musicplayer.common.media.audio.meta_tag.audio.asf.data.Chunk import com.flammky.musicplayer.common.media.audio.meta_tag.audio.asf.data.GUID import java.io.IOException import java.io.InputStream /** * A ChunkReader provides methods for reading an ASF chunk.<br></br> * * @author <NAME> */ interface ChunkReader { /** * Tells whether the reader can fail to return a valid chunk.<br></br> * The current Use would be a modified version of [StreamChunkReader], * which is configured to only manage audio streams. However, the primary * GUID for audio and video streams is the same. So if a stream shows itself * to be a video stream, the reader would return `null`.<br></br> * * @return `true`, if further analysis of the chunk can show, * that the reader is not applicable, despite the header GUID * [identification][.getApplyingIds] told it can handle * the chunk. */ fun canFail(): Boolean /** * Returns the GUIDs identifying the types of chunk, this reader will parse.<br></br> * * @return the GUIDs identifying the types of chunk, this reader will parse.<br></br> */ val applyingIds: Array<GUID> /** * Parses the chunk. * * @param guid the GUID of the chunks header, which is about to be read. * @param stream source to read chunk from.<br></br> * No [GUID] is expected at the currents stream position. * The length of the chunk is about to follow. * @param streamPosition the position in stream, the chunk starts.<br></br> * @return the read chunk. (Mostly a subclass of [Chunk]).<br></br> * @throws IOException On I/O Errors. */ @Throws(IOException::class) fun read(guid: GUID?, stream: InputStream, streamPosition: Long): Chunk? }
0
Kotlin
6
56
a452c453815851257462623be704559d306fb383
1,809
Music-Player
Apache License 2.0
app/src/test/java/com/fave/breezil/fave/util/ApiAbstract.kt
breel93
255,382,688
false
null
package com.fave.breezil.fave.util import androidx.arch.core.executor.testing.InstantTaskExecutorRule import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okio.BufferedSource import okio.Source import okio.buffer import okio.source import org.hamcrest.CoreMatchers import org.hamcrest.MatcherAssert import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.runner.RunWith import org.junit.runners.JUnit4 import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.IOException import java.nio.charset.StandardCharsets import kotlin.jvm.Throws @RunWith(JUnit4::class) open class ApiAbstract<T> { @Rule @JvmField val instantExecutorRule: InstantTaskExecutorRule = InstantTaskExecutorRule() lateinit var mockWebServer: MockWebServer @Before @Throws(IOException::class) fun mockServer() { mockWebServer = MockWebServer() mockWebServer.start() } @After @Throws(IOException::class) fun stopServer() { mockWebServer.shutdown() } @Throws(IOException::class) fun enqueueResponse(fileName: String) { enqueueResponse(fileName, emptyMap()) } @Throws(IOException::class) private fun enqueueResponse(fileName: String, headers: Map<String, String>) { val inputStream = javaClass.classLoader!!.getResourceAsStream("api-response/$fileName") val source = inputStream.source().buffer() val mockResponse = MockResponse() for ((key, value) in headers) { mockResponse.addHeader(key, value) } mockWebServer.enqueue(mockResponse.setBody(source.readString(StandardCharsets.UTF_8))) } fun createService(clazz: Class<T>): T { return Retrofit.Builder() .baseUrl(mockWebServer.url("/")) .addConverterFactory(GsonConverterFactory.create()) .build() .create(clazz) } @Throws(InterruptedException::class) fun assertRequestPath(path: String?) { val request = mockWebServer.takeRequest() MatcherAssert.assertThat(request.path, CoreMatchers.`is`(path)) } }
0
Kotlin
0
0
a5b774548bb1c747bbb4a0263031f6935eca3c75
2,061
Fave
Apache License 2.0
project/src/main/kotlin/cga/exercise/components/geometry/Renderable.kt
nthometzki
280,411,694
true
{"Kotlin": 147371, "GLSL": 20259}
package cga.exercise.components.geometry import cga.exercise.components.shader.ShaderProgram class Renderable(val meshes : MutableList<Mesh>) : Transformable(), IRenderable{ fun x() = this.getWorldPosition().x fun y() = this.getWorldPosition().y fun z() = this.getWorldPosition().z override fun render(shaderProgram: ShaderProgram) { meshes.forEach {mesh -> shaderProgram.setUniform("model_matrix", getWorldModelMatrix()) mesh.render(shaderProgram) } } }
0
Kotlin
0
0
09f966e074ad728daf9b9b704087afe41b9e5e4a
522
CGAProject
MIT License
recipes/src/main/java/com/uber/lintchecks/recipes/guardrails/JavaOnlyDetector.kt
uber
183,370,095
false
null
/* * Copyright (C) 2020. Uber Technologies * * 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.uber.lintchecks.recipes.guardrails import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.LintFix import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import com.android.tools.lint.detector.api.UastLintUtils import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.uber.lintchecks.android.createImplementation import org.jetbrains.uast.UAnnotation import org.jetbrains.uast.UAnonymousClass import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UCallableReferenceExpression import org.jetbrains.uast.UClass import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.ULambdaExpression import org.jetbrains.uast.UMethod import org.jetbrains.uast.UReturnExpression import org.jetbrains.uast.getContainingUClass import org.jetbrains.uast.getContainingUMethod import org.jetbrains.uast.toUElementOfType /** * Logic adapted from the analogous KotlinOnlyChecker in Error-Prone. */ class JavaOnlyDetector : Detector(), SourceCodeScanner { companion object { private const val KOTLIN_ONLY = "com.uber.lintchecks.recipes.guardrails.KotlinOnly" private const val JAVA_ONLY = "com.uber.lintchecks.recipes.guardrails.JavaOnly" private const val ISSUE_ID = "JavaOnlyDetector" private const val MESSAGE_LINT_ERROR_TITLE = "Using @JavaOnly elements in Kotlin code." private const val MESSAGE_LINT_ERROR_EXPLANATION = "This should not be called from Kotlin code" @JvmField val ISSUE = Issue.create( ISSUE_ID, MESSAGE_LINT_ERROR_TITLE, MESSAGE_LINT_ERROR_EXPLANATION, Category.INTEROPERABILITY_KOTLIN, 6, Severity.ERROR, createImplementation<JavaOnlyDetector>()) private fun anonymousTypeString(psiClass: PsiClass, type: String): String { return "Cannot create $type instances of @JavaOnly-annotated type ${UastLintUtils.getClassName(psiClass)} (in ${psiClass.containingFile.name}) " + "in Kotlin. Make a concrete class instead." } } override fun createUastHandler(context: JavaContext): UElementHandler? { if (context.file.extension != "kt") { // We only run this on Kotlin files, the ErrorProne analogue handles Java files. Can revisit if we get lint in the IDE or otherwise unify return UElementHandler.NONE } return object : UElementHandler() { override fun visitClass(node: UClass) { val hasJavaOnly = context.evaluator.findAnnotation(node, JAVA_ONLY) != null val hasKotlinOnly = context.evaluator.findAnnotation(node, KOTLIN_ONLY) != null if (hasJavaOnly && hasKotlinOnly) { context.report(ISSUE, context.getLocation(node.sourcePsi!!), "Cannot annotate types with both @KotlinOnly and @JavaOnly") return } if (hasJavaOnly || hasKotlinOnly) { return } if (node is UAnonymousClass) { if (node.uastParent.isReturnExpression() && node.isEnclosedInJavaOnlyMethod()) { return } node.baseClassType.resolve()?.let { psiClass -> context.evaluator.findAnnotation(psiClass, JAVA_ONLY)?.run { val message = anonymousTypeString(psiClass, "anonymous") context.report(ISSUE, context.getLocation(node.sourcePsi!!), message) } } return } val reportData = checkMissingSubclass(node, KOTLIN_ONLY, "KotlinOnly") ?: checkMissingSubclass(node, JAVA_ONLY, "JavaOnly") ?: return context.report(ISSUE, context.getLocation(node.sourcePsi!!), reportData.first, reportData.second) } private fun checkMissingSubclass( node: UClass, targetAnnotation: String, targetAnnotationSimpleName: String ): Pair<String, LintFix>? { return listOfNotNull(node.superClass, *node.interfaces) .mapNotNull { psiClass -> context.evaluator.findAnnotation(psiClass, targetAnnotation)?.run { val message = "Type subclasses/implements ${UastLintUtils.getClassName(psiClass)} in ${psiClass.containingFile.name} which is annotated @$targetAnnotationSimpleName, it should also be annotated." val source = node.text return@mapNotNull message to fix() .replace() .name("Add @$targetAnnotationSimpleName") .range(context.getLocation(node.sourcePsi!!)) .shortenNames() .text(source) .with("@$targetAnnotation $source") .autoFix() .build() } } .firstOrNull() } override fun visitLambdaExpression(node: ULambdaExpression) { if (node.isReturnExpression() && node.isEnclosedInJavaOnlyMethod()) { return } node.functionalInterfaceType?.let { type -> if (type is PsiClassType) { type.resolve()?.let { psiClass -> context.evaluator.findAnnotation(psiClass, JAVA_ONLY)?.let { val message = anonymousTypeString(psiClass, "lambda") context.report(ISSUE, context.getLocation(node.sourcePsi!!), message) return } val functionalMethod = psiClass.methods.first() functionalMethod.toUElementOfType<UMethod>()?.isAnnotationPresent()?.let { node.report(it, "expressed as a lambda in Kotlin") } } } } } override fun visitMethod(node: UMethod) { val hasJavaOnly = context.evaluator.findAnnotation(node, JAVA_ONLY) != null val hasKotlinOnly = context.evaluator.findAnnotation(node, KOTLIN_ONLY) != null if (hasJavaOnly && hasKotlinOnly) { context.report(ISSUE, context.getLocation(node.sourcePsi!!), "Cannot annotate functions with both @KotlinOnly and @JavaOnly") return } if (hasJavaOnly || hasKotlinOnly) { return } val reportData = checkMissingOverride(node, KOTLIN_ONLY, "KotlinOnly") ?: checkMissingOverride(node, JAVA_ONLY, "JavaOnly") ?: return context.report(ISSUE, context.getLocation(node), reportData.first, reportData.second) } private fun checkMissingOverride( node: UMethod, targetAnnotation: String, targetAnnotationSimpleName: String ): Pair<String, LintFix>? { return context.evaluator.getSuperMethod(node)?.let { method -> context.evaluator.findAnnotation(method, targetAnnotation)?.run { val message = "Function overrides ${method.name} in ${UastLintUtils.getClassName( method.containingClass)} which is annotated @$targetAnnotationSimpleName, it should also be annotated." val modifier = node.modifierList.children.joinToString(separator = " ") { it.text } return@let message to fix() .replace() .name("Add @$targetAnnotationSimpleName") .range(context.getLocation(node)) .shortenNames() .text(modifier) .with("@$targetAnnotation $modifier") .autoFix() .build() } } } override fun visitCallExpression(node: UCallExpression) { node.resolve().toUElementOfType<UMethod>()?.isAnnotationPresent()?.let { node.report(it) } } override fun visitCallableReferenceExpression(node: UCallableReferenceExpression) { node.resolve().toUElementOfType<UMethod>()?.isAnnotationPresent()?.let { node.report(it) } } private fun UExpression.report(javaOnlyMessage: String?, callString: String = "called from Kotlin") { val message = StringBuilder("This method should not be $callString") if (javaOnlyMessage.isNullOrBlank()) { message.append(", see its documentation for details.") } else { message.append(": $javaOnlyMessage") } context.report(ISSUE, context.getLocation(this), message.toString()) } private fun UElement?.isReturnExpression(): Boolean = this != null && uastParent is UReturnExpression private fun UElement.isEnclosedInJavaOnlyMethod(): Boolean { return getContainingUMethod()?.isAnnotationPresent() != null } private fun UMethod.isAnnotationPresent(): String? { findAnnotation(JAVA_ONLY)?.let { return it.extractValue() } getContainingUClass()?.findAnnotation(JAVA_ONLY)?.let { return it.extractValue() } context.evaluator.getPackage(this)?.let { pkg -> context.evaluator.findAnnotation(pkg, KOTLIN_ONLY)?.toUElementOfType<UAnnotation>()?.let { return it.extractValue() } } return null } private fun UAnnotation.extractValue(): String { return UastLintUtils.getAnnotationStringValue(this, "value").orEmpty() } } } override fun getApplicableUastTypes(): List<Class<out UElement>> { return listOf( UMethod::class.java, UCallExpression::class.java, UCallableReferenceExpression::class.java, ULambdaExpression::class.java, UClass::class.java ) } }
2
null
8
62
1cc2d30171896525c8a1974f99e3f090037ba453
10,282
lint-checks
Apache License 2.0
service/src/main/kotlin/com/jongmin/upbit/quotation/UpbitQuotationService.kt
jongmin92
397,954,845
false
null
package com.jongmin.upbit.quotation import com.jongmin.upbit.quotation.candles.UpbitCandleService import com.jongmin.upbit.quotation.market.UpbitMarketService import com.jongmin.upbit.quotation.orderbook.UpbitOrderbookService import com.jongmin.upbit.quotation.ticker.UpbitTickerService import com.jongmin.upbit.quotation.trades.UpbitTradeService interface UpbitQuotationService : UpbitCandleService, UpbitMarketService, UpbitOrderbookService, UpbitTickerService, UpbitTradeService
0
Kotlin
4
5
ce31d9b32fe4baa44807f5194f43b38a7b3d252d
488
spring-boot-starter-upbit
MIT License
fabric/src/main/kotlin/com/plasmoverse/rpshare/gui/DownloadScreen.kt
plasmoapp
655,924,413
false
null
package com.plasmoverse.rpshare.gui import com.plasmoverse.rpshare.DownloadTask import com.plasmoverse.rpshare.model.DownloadData import io.wispforest.owo.ui.base.BaseOwoScreen import io.wispforest.owo.ui.component.Components import io.wispforest.owo.ui.component.LabelComponent import io.wispforest.owo.ui.container.Containers import io.wispforest.owo.ui.container.FlowLayout import io.wispforest.owo.ui.core.* import net.minecraft.text.Text class DownloadScreen( private val data: DownloadData, private val task: DownloadTask, ): BaseOwoScreen<FlowLayout>() { override fun createAdapter(): OwoUIAdapter<FlowLayout> { return OwoUIAdapter.create(this, Containers::verticalFlow) } override fun tick() { val inMegaBytes = String.format("%.2f", task.fileSize.toDouble() / 1000000) val component = Text.translatable("resourcepack.progress", inMegaBytes).append( Text.literal(" ${task.percent}%") ) component(LabelComponent::class.java, "progress")?.text(component) } override fun close() { task.cancel() super.close() } override fun build(rootComponent: FlowLayout) { StyleSheet.applyRoot(rootComponent) val container = StyleSheet.container val title = Components.label(Text.translatable("resourcepack.downloading")) .maxWidth(StyleSheet.width) .horizontalTextAlignment(HorizontalAlignment.CENTER) .margins(Insets.bottom(StyleSheet.margin)) container.child(title) val progress = Components.label(Text.literal(task.percent.toString())).apply { maxWidth(StyleSheet.width) horizontalTextAlignment(HorizontalAlignment.CENTER) id("progress") } container.child(progress) val cancel = Components.button(Text.translatable("gui.cancel")) { close() }.also { it.horizontalSizing(Sizing.fill(100)) }.margins(Insets.top(StyleSheet.buttonPadding)) container.child(cancel) rootComponent.child(container) } companion object { fun andStartTask(data: DownloadData) = DownloadScreen(data, DownloadTask(data).also { it.start() }) } }
0
Kotlin
0
1
b9a55364d5acd7a6a8471fd5972a1af62eb4040f
2,261
RPShare
MIT License
data/RF02599/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF02599" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 3 to 16 21 to 34 } value = "#24feda" } color { location { 40 to 47 114 to 121 } value = "#b00b5d" } color { location { 50 to 52 78 to 80 } value = "#7807b2" } color { location { 55 to 58 72 to 75 } value = "#e2b27a" } color { location { 59 to 61 68 to 70 } value = "#52bbe2" } color { location { 83 to 88 104 to 109 } value = "#ccc00b" } color { location { 89 to 93 98 to 102 } value = "#8ea6bf" } color { location { 125 to 128 306 to 309 } value = "#be9aa1" } color { location { 130 to 135 300 to 305 } value = "#ed1ea8" } color { location { 137 to 138 297 to 298 } value = "#ce457e" } color { location { 139 to 144 290 to 295 } value = "#1e190f" } color { location { 145 to 146 153 to 154 } value = "#907bf8" } color { location { 158 to 160 165 to 167 } value = "#815277" } color { location { 179 to 184 208 to 213 } value = "#6074f7" } color { location { 190 to 192 200 to 202 } value = "#8f9c56" } color { location { 232 to 239 280 to 287 } value = "#53eff2" } color { location { 243 to 245 276 to 278 } value = "#b101d7" } color { location { 247 to 249 263 to 265 } value = "#53a9a7" } color { location { 251 to 254 258 to 261 } value = "#03053a" } color { location { 312 to 314 331 to 333 } value = "#09bf05" } color { location { 317 to 320 325 to 328 } value = "#ce3ef7" } color { location { 335 to 339 420 to 424 } value = "#9891ca" } color { location { 340 to 346 412 to 418 } value = "#dc9125" } color { location { 354 to 356 403 to 405 } value = "#b427a2" } color { location { 359 to 365 395 to 401 } value = "#188362" } color { location { 366 to 372 384 to 390 } value = "#2bbcd7" } color { location { 374 to 376 380 to 382 } value = "#2fae14" } color { location { 17 to 20 } value = "#a11166" } color { location { 48 to 49 81 to 82 110 to 113 } value = "#e16adf" } color { location { 53 to 54 76 to 77 } value = "#e99099" } color { location { 59 to 58 71 to 71 } value = "#fa70f6" } color { location { 62 to 67 } value = "#10dbeb" } color { location { 89 to 88 103 to 103 } value = "#72ce32" } color { location { 94 to 97 } value = "#3293de" } color { location { 129 to 129 306 to 305 } value = "#76fe45" } color { location { 136 to 136 299 to 299 } value = "#7b80a5" } color { location { 139 to 138 296 to 296 } value = "#ca2eaf" } color { location { 145 to 144 155 to 157 168 to 178 214 to 231 288 to 289 } value = "#f648e4" } color { location { 147 to 152 } value = "#b48ce2" } color { location { 161 to 164 } value = "#583b9b" } color { location { 185 to 189 203 to 207 } value = "#d0206c" } color { location { 193 to 199 } value = "#55c2c8" } color { location { 240 to 242 279 to 279 } value = "#e05c6e" } color { location { 246 to 246 266 to 275 } value = "#091f33" } color { location { 250 to 250 262 to 262 } value = "#cd9a3a" } color { location { 255 to 257 } value = "#a5abab" } color { location { 315 to 316 329 to 330 } value = "#2a84d6" } color { location { 321 to 324 } value = "#663eea" } color { location { 340 to 339 419 to 419 } value = "#b7d0ec" } color { location { 347 to 353 406 to 411 } value = "#45539f" } color { location { 357 to 358 402 to 402 } value = "#e9529a" } color { location { 366 to 365 391 to 394 } value = "#a4ca88" } color { location { 373 to 373 383 to 383 } value = "#026660" } color { location { 377 to 379 } value = "#be49fb" } color { location { 1 to 2 } value = "#fa7b39" } color { location { 35 to 39 } value = "#2bc982" } color { location { 122 to 124 } value = "#cdd9a4" } color { location { 310 to 311 } value = "#5f5ce9" } color { location { 334 to 334 } value = "#d66d5e" } color { location { 425 to 436 } value = "#48ec71" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
8,872
Rfam-for-RNArtist
MIT License
app/src/main/java/dev/techpolis/studservice/di/module/ActivityModule.kt
StudServices
353,117,513
false
null
package dev.techpolis.studservice.di.module import android.view.LayoutInflater import androidx.fragment.app.FragmentManager import dagger.Module import dagger.Provides import dev.techpolis.studservice.di.qual.ActivityFragmentManager import dev.techpolis.studservice.di.scope.ActivityScope import dev.techpolis.studservice.screens.common.base.BaseActivity import dev.techpolis.studservice.screens.common.nav.BackPressDispatcher import dev.techpolis.studservice.screens.common.nav.app.AppScreenRouter import dev.techpolis.studservice.screens.common.nav.app.AppScreenRouterImpl @Module object ActivityModule { @Provides @ActivityScope fun layoutInflater(baseActivity: BaseActivity): LayoutInflater = LayoutInflater.from(baseActivity)!! @Provides @ActivityFragmentManager @ActivityScope fun fragmentManager(baseActivity: BaseActivity): FragmentManager = baseActivity.supportFragmentManager @Module interface Binds { @dagger.Binds fun backPressDispatcher(baseActivity: BaseActivity): BackPressDispatcher @dagger.Binds fun appScreenRouter(appScreenRouterImpl: AppScreenRouterImpl): AppScreenRouter } }
0
Kotlin
0
0
a844a9ac31fa02245237a7af68a66b2451dac7cd
1,190
StudServices-Android
MIT License
src/main/kotlin/com/github/beaver010/beechat/config/SpyConfig.kt
beaver010
755,248,524
false
{"Kotlin": 18103}
package com.github.beaver010.beechat.config import org.spongepowered.configurate.objectmapping.ConfigSerializable @ConfigSerializable data class SpyConfig( val format: String = "<aqua>Spy</aqua> <channel_message>", val disableOnLeave: Boolean = true, )
0
Kotlin
0
0
65b9bf8f65391fabc28dae922aa88283a4d08a77
263
bee-chat
MIT License
app/src/main/java/br/com/dev/applogin/model/dto/IdProfile.kt
brunoHsantos
635,525,968
false
null
package br.com.dev.applogin.model.dto data class IdProfile ( val idPessoa: String )
0
Kotlin
0
0
301a51447c6fe80a969c702d0d47ce58be407320
92
AppLogin
MIT License
sdk/src/main/java/ch/opentransportdata/ojp/domain/usecase/RequestMockTrips.kt
openTdataCH
783,593,283
false
{"Kotlin": 283777}
package ch.opentransportdata.ojp.domain.usecase import ch.opentransportdata.ojp.data.dto.response.delivery.TripDeliveryDto import ch.opentransportdata.ojp.domain.model.Result import ch.opentransportdata.ojp.domain.repository.OjpRepository import java.io.InputStream /** * Created by Michael Ruppen on 19.09.2024 */ internal class RequestMockTrips( private val ojpRepository: OjpRepository ) { suspend operator fun invoke(stream: InputStream): Result<TripDeliveryDto> { return when (val response = ojpRepository.requestMockTrips(stream)) { is Result.Success -> Result.Success(response.data) is Result.Error -> Result.Error(response.error) } } }
0
Kotlin
0
1
3c796dea2ab3aa83a8e9c494c1a9660187ef9d54
701
ojp-android
MIT License
spring-boot-test-dbunit/src/main/kotlin/io/camassia/spring/dbunit/api/customization/ConnectionModifier.kt
camassia-io
397,872,845
false
null
package io.camassia.spring.dbunit.api.customization import org.dbunit.database.IDatabaseConnection fun interface ConnectionModifier { fun modify(connection: IDatabaseConnection) }
0
Kotlin
0
0
732588e72773304618ad2ce7e5ff8c00a947896d
187
spring-boot-test-dbunit
Apache License 2.0
entities/src/main/java/com/redvelvet/entities/movie/details/MovieFullDetails.kt
RedVelvet-Team
670,763,637
false
null
package com.redvelvet.entities.movie.details data class MovieFullDetails( val details:MovieDetails, val images: MovieImages, val keyWords: MovieKeyWords, val recommendations: MovieRecommendations, val reviews: MovieReviews, val similar: MovieSimilar, val topCast: MovieTopCast )
1
Kotlin
1
4
b9b17caa25439823ae354d3262921fb5f88c73d7
308
IMovie
Apache License 2.0
core/src/main/java/com/cube/fusion/android/core/utils/extensions/IntentExtensions.kt
3sidedcube
465,729,737
false
{"Kotlin": 105599}
package com.cube.fusion.android.core.utils.extensions import android.content.Intent import android.view.View /** * Set of extensions relevant to intents and intent handling * * Created by <NAME> on 05/May/2022. * Copyright ® 3SidedCube. All rights reserved. */ /** * Convenience method to handle a nullable intent created during action handling by starting an activity if not-null * * @param view the view to handle the nullable intent with * @return true if the intent is non-null, and therefore startActivity has been called; false otherwise */ fun Intent?.handledByView(view: View) = this?.let { view.context.startActivity(it) true } ?: false
0
Kotlin
0
2
1c1db817504533c97383c26d788a252e489227e5
660
Android-Fusion-AndroidUi
MIT License
app/src/main/java/com/github/polyKa/gtKawasaki/GTKawasakiApp.kt
PolyKA
304,835,575
false
null
package com.github.polyKa.gtKawasaki import android.app.Application class GTKawasakiApp: Application() { }
0
Kotlin
0
0
d49af80e8842b6a5a0df1229e6f5e1b8a4d39bc7
108
GTKawasaki
Apache License 2.0
4_poo/3_enum_classes/exemplo2.kt
Ciro-TI-System
695,667,220
false
{"Kotlin": 29254}
/** * Enum podem ter propriedades e métodos. * * @see [Enum Classes](https://play.kotlinlang.org/byExample/03_special_classes/02_Enum) */ enum class Color(val rgb: Int) { // 1 RED(0xFF0000), // 2 GREEN(0x00FF00), BLUE(0x0000FF), YELLOW(0xFFFF00); fun containsRed() = (this.rgb and 0xFF0000 != 0) // 3 } fun main() { val red = Color.RED println(red) // 4 println(red.containsRed()) // 5 println(Color.BLUE.containsRed()) // 6 println(Color.YELLOW.containsRed()) // 7 }
0
Kotlin
0
0
71ed5edd9756b819634379f4e8df36392ff311c4
661
aprenda-kotlin-com-exemplos
MIT License
src/main/java/ru/hollowhorizon/hc/common/events/entity/EntityTrackingEvent.kt
HollowHorizon
450,852,365
false
{"Kotlin": 1120056, "Java": 247984, "GLSL": 44525}
package ru.hollowhorizon.hc.common.events.entity import net.minecraft.world.entity.Entity import net.minecraft.world.entity.player.Player import ru.hollowhorizon.hc.common.events.Event class EntityTrackingEvent(val player: Player, val entity: Entity) : Event
0
Kotlin
4
20
7e0c4510a0e5d2d3540aff428871b7ecc642c898
260
HollowCore
MIT License
src/main/kotlin/org/ivangrod/domainevents/domain/events/BookChangedInfo.kt
ivangrod
507,595,158
false
null
package org.ivangrod.domainevents.domain.events import org.ivangrod.domainevents.domain.Book class BookChangedInfo(book: Book) { val authorEmail by lazy { book.author?.email } }
0
Kotlin
0
0
931cb816b37942020d71044c261aa36ac4834375
184
se-journey-spring
MIT License
app/src/main/java/com/github/yohannestz/fastcall/ui/fragments/InputDialogFragment.kt
YohannesTz
637,138,771
false
null
package com.github.yohannestz.fastcall.ui.fragments import android.app.Dialog import android.content.Context import android.os.Bundle import android.view.View import android.widget.EditText import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatDialogFragment import com.github.yohannestz.fastcall.R class InputDialogFragment: AppCompatDialogFragment() { private var listener: InputDialogFragmentListener? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val inflater = requireActivity().layoutInflater val view: View = inflater.inflate(R.layout.input_dialog_layout, null) val contactNameEditText: EditText = view.findViewById(R.id.contact_name_input) val phoneNumberEditText: EditText = view.findViewById(R.id.phone_number) return AlertDialog.Builder(requireActivity()) .setView(view) .setTitle("Add Contact") .setNegativeButton("Cancel") {_, _, ->} .setPositiveButton("Ok") {_, _, -> val contactName = contactNameEditText.text.toString() val phoneNumber = phoneNumberEditText.text.toString() listener!!.applyTexts(contactName, phoneNumber) } .create() } override fun onAttach(context: Context) { super.onAttach(context) listener = try { context as InputDialogFragmentListener } catch (e: ClassCastException) { throw ClassCastException( context.toString() + "must implement ExampleDialogListener" ) } } interface InputDialogFragmentListener { fun applyTexts(name: String, phoneNum: String) } }
0
Kotlin
0
0
14ea0ae05a4d2be2399067ea044e3873e0c8e2ff
1,755
FastCall
MIT License
LoggingManager.kt
Couchbase-Ecosystem
849,511,380
false
{"Kotlin": 18915}
package cbl.js.kotiln import com.couchbase.lite.* import java.util.EnumSet object LoggingManager { fun setFileLoggingConfig( directory: String, logLevel: Int, maxSize: Long, maxRotateCount: Int, shouldUsePlainText: Boolean, ) { val loggingValue = getLogLevel(logLevel) val config = LogFileConfiguration(directory) config.setMaxSize(maxSize) config.setMaxRotateCount(maxRotateCount) config.setUsePlaintext(shouldUsePlainText) Database.log.file.config = config Database.log.file.level = loggingValue } fun setLogLevel(logDomain: String, logLevel: Int) { when (logDomain) { "ALL" -> Database.log.console.domains = LogDomain.ALL_DOMAINS "DATABASE" -> Database.log.console.domains = EnumSet.of(LogDomain.DATABASE) "NETWORK" -> Database.log.console.domains = EnumSet.of(LogDomain.NETWORK) "QUERY" -> Database.log.console.domains = EnumSet.of(LogDomain.QUERY) "REPLICATOR" -> Database.log.console.domains = EnumSet.of(LogDomain.REPLICATOR) } val loggingValue = getLogLevel(logLevel) Database.log.console.level = loggingValue } private fun getLogLevel(logLevelValue: Int): LogLevel { when (logLevelValue) { 0 -> return LogLevel.DEBUG 1 -> return LogLevel.VERBOSE 2 -> return LogLevel.INFO 3 -> return LogLevel.WARNING 4 -> return LogLevel.ERROR 5 -> return LogLevel.NONE } return LogLevel.DEBUG } }
0
Kotlin
0
0
e59bbce226d6942a7150f60ecc732b1603ff7d3d
1,591
cbl-js-kotlin
Apache License 2.0
winmdj-core/src/main/kotlin/com/github/danielchemko/winmdj/core/autoobject/stubs/StubSecurityAttributeImpl.kt
danielchemko
774,741,943
false
{"Kotlin": 284901}
package com.github.danielchemko.winmdj.core.autoobject.stubs import com.github.danielchemko.winmdj.core.MdObjectMapper import com.github.danielchemko.winmdj.core.autoobject.BaseWinMdStub import com.github.danielchemko.winmdj.core.mdspec.CLRMetadataType import com.github.danielchemko.winmdj.core.mdspec.SecurityAttribute import com.github.danielchemko.winmdj.core.mdspec.WinMdStub import com.github.danielchemko.winmdj.parser.WinMdNavigator import javax.annotation.processing.Generated /** * THIS FILE IS AUTOMATICALLY GENERATED BY RegenerateSubs.kt. DO NOT EDIT IT BY HAND */ @Generated class StubSecurityAttributeImpl( objectMapper: MdObjectMapper, navigator: WinMdNavigator, index: Int ) : SecurityAttribute { val stub = BaseWinMdStub(objectMapper, navigator, index) override fun toString(): String { return "SecurityAttribute/${getToken()}" } override fun getStub(): WinMdStub { return stub } override fun getRowNumber(): Int { return getStub().getRowNumber() } override fun getToken(): UInt { return stub.getToken(CLRMetadataType.DECL_SECURITY) } override fun getOffset(): UInt { return stub.getObjectTableOffset(CLRMetadataType.DECL_SECURITY, 0).toUInt() } override fun copy(rowNum: Int): StubSecurityAttributeImpl { return StubSecurityAttributeImpl::class.constructors.first() .call(stub.getObjectMapper(), stub.getNavigator(), rowNum) } override fun getAction(): kotlin.UShort { return stub.lookupTableValue(CLRMetadataType.DECL_SECURITY, 0, kotlin.UShort::class)!! } override fun getParent(): com.github.danielchemko.winmdj.core.mdspec.HasDeclSecurity? { return stub.lookupInterfaceReferent( CLRMetadataType.DECL_SECURITY, 1, com.github.danielchemko.winmdj.core.mdspec.HasDeclSecurity::class ) } override fun getPermissionSet(): kotlin.ByteArray { return stub.lookupBlob(CLRMetadataType.DECL_SECURITY, 2) } }
0
Kotlin
0
0
0d2a72ee7ea6f0dc05803b06039a8ac8bfc0dbd0
2,049
winmdj
MIT License
winmdj-core/src/main/kotlin/com/github/danielchemko/winmdj/core/autoobject/stubs/StubSecurityAttributeImpl.kt
danielchemko
774,741,943
false
{"Kotlin": 284901}
package com.github.danielchemko.winmdj.core.autoobject.stubs import com.github.danielchemko.winmdj.core.MdObjectMapper import com.github.danielchemko.winmdj.core.autoobject.BaseWinMdStub import com.github.danielchemko.winmdj.core.mdspec.CLRMetadataType import com.github.danielchemko.winmdj.core.mdspec.SecurityAttribute import com.github.danielchemko.winmdj.core.mdspec.WinMdStub import com.github.danielchemko.winmdj.parser.WinMdNavigator import javax.annotation.processing.Generated /** * THIS FILE IS AUTOMATICALLY GENERATED BY RegenerateSubs.kt. DO NOT EDIT IT BY HAND */ @Generated class StubSecurityAttributeImpl( objectMapper: MdObjectMapper, navigator: WinMdNavigator, index: Int ) : SecurityAttribute { val stub = BaseWinMdStub(objectMapper, navigator, index) override fun toString(): String { return "SecurityAttribute/${getToken()}" } override fun getStub(): WinMdStub { return stub } override fun getRowNumber(): Int { return getStub().getRowNumber() } override fun getToken(): UInt { return stub.getToken(CLRMetadataType.DECL_SECURITY) } override fun getOffset(): UInt { return stub.getObjectTableOffset(CLRMetadataType.DECL_SECURITY, 0).toUInt() } override fun copy(rowNum: Int): StubSecurityAttributeImpl { return StubSecurityAttributeImpl::class.constructors.first() .call(stub.getObjectMapper(), stub.getNavigator(), rowNum) } override fun getAction(): kotlin.UShort { return stub.lookupTableValue(CLRMetadataType.DECL_SECURITY, 0, kotlin.UShort::class)!! } override fun getParent(): com.github.danielchemko.winmdj.core.mdspec.HasDeclSecurity? { return stub.lookupInterfaceReferent( CLRMetadataType.DECL_SECURITY, 1, com.github.danielchemko.winmdj.core.mdspec.HasDeclSecurity::class ) } override fun getPermissionSet(): kotlin.ByteArray { return stub.lookupBlob(CLRMetadataType.DECL_SECURITY, 2) } }
0
Kotlin
0
0
0d2a72ee7ea6f0dc05803b06039a8ac8bfc0dbd0
2,049
winmdj
MIT License
confluence-plugin/src/main/java/com/networkedassets/git4c/core/ViewMacroUseCase.kt
rpaasche
321,741,515
true
{"Kotlin": 798728, "JavaScript": 351426, "Java": 109291, "Groovy": 55451, "CSS": 37375, "ANTLR": 19544, "Gherkin": 15007, "HTML": 14268, "Shell": 4490, "Ruby": 1378, "Batchfile": 1337, "PowerShell": 716}
package com.networkedassets.git4c.core import com.github.kittinunf.result.Result import com.networkedassets.git4c.application.BussinesPluginComponents import com.networkedassets.git4c.boundary.ViewMacroCommand import com.networkedassets.git4c.boundary.outbound.MacroView import com.networkedassets.git4c.core.datastore.repositories.MacroLocationDatabase import com.networkedassets.git4c.core.datastore.repositories.MacroSettingsDatabase import com.networkedassets.git4c.core.process.MacroViewProcess import com.networkedassets.git4c.data.MacroLocation import com.networkedassets.git4c.data.MacroType import com.networkedassets.git4c.delivery.executor.execution.UseCase class ViewMacroUseCase( components: BussinesPluginComponents, val macroLocationDatabase: MacroLocationDatabase = components.database.macroLocationDatabase, val macroViewProcess: MacroViewProcess = components.processing.macroViewProcess, val macroSettingsDatabase: MacroSettingsDatabase = components.providers.macroSettingsProvider ) : UseCase<ViewMacroCommand, MacroView> (components) { override fun execute(request: ViewMacroCommand): Result<MacroView, Exception> { updateMacroLocation(request) updateMacroType(request) macroViewProcess.prepareMacroToBeViewed(request.macro.uuid); return Result.of { MacroView(request.macro.uuid, request.page.id, request.space.uuid) } } private fun updateMacroType(request: ViewMacroCommand) { macroSettingsDatabase.get(request.macro.uuid)?.apply { this.type = MacroType.valueOf(request.macro.type.name) macroSettingsDatabase.put(request.macro.uuid, this) } } private fun updateMacroLocation(request: ViewMacroCommand) { macroLocationDatabase.put(request.macro.uuid, MacroLocation( request.macro.uuid, request.page.id, request.space.uuid )) } }
0
Kotlin
0
0
e55391b33cb70d66bbf5f36ba570fb8822f10953
1,997
git4c
Apache License 2.0
app/src/main/kotlin/org/jw/warehousecontrol/presentation/fragments/VolunteerRegisterFragment.kt
anandacamara
739,857,108
false
{"Kotlin": 83107}
package org.jw.warehousecontrol.presentation.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import org.jw.warehousecontrol.databinding.FragmentVolunteerRegisterBinding /** * @author <NAME> */ internal class VolunteerRegisterFragment : Fragment() { private lateinit var view: FragmentVolunteerRegisterBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { view = FragmentVolunteerRegisterBinding.inflate(layoutInflater, container, false) return view.root } }
0
Kotlin
0
0
f4f704cedb41cb4cc536fb7678fbb3371e44a05c
693
warehouse_control
MIT License
addendum/src/main/java/com/commit451/addendum/ViewPager.kt
Commit451
91,985,179
false
null
@file:Suppress("NOTHING_TO_INLINE", "unused") package com.commit451.addendum import androidx.viewpager.widget.ViewPager inline fun ViewPager.back(animate: Boolean = true) { setCurrentItem(currentItem - 1, animate) } inline fun ViewPager.forward(animate: Boolean = true) { setCurrentItem(currentItem + 1, animate) } inline fun ViewPager.isOnLastPage(): Boolean { return currentItem == (adapter?.count ?: 0) - 1 } inline fun ViewPager.isOnFirstPage(): Boolean { return currentItem == 0 }
0
Kotlin
0
17
d42395934bfd9df352bf85eda894e1de14775678
507
Addendum
Apache License 2.0
src/shmp/lang/language/syntax/sequence/FoldedWordSequence.kt
ShMPMat
240,860,070
false
null
package shmp.lang.language.syntax.sequence import shmp.lang.language.lexis.Word data class FoldedWordSequence(val words: List<Pair<Word, LatchType>> = listOf()) { constructor(wordToType: Pair<Word, LatchType>): this(listOf(wordToType)) val size = words.size operator fun get(position: Int) = words[position] operator fun plus(that: FoldedWordSequence) = FoldedWordSequence(this.words + that.words) fun mapIndexed(transform: (Int, Word) -> Word) = words .mapIndexed { i, (w, l) -> transform(i, w) to l } .toFoldedWordSequence() fun swapWord(i: Int, transform: (Word) -> Word) = mapIndexed { j, w -> if (i == j) transform(w) else w } }
0
Kotlin
0
1
4d26b0d50a1c3c6318eede8dd9678d3765902d4b
702
LanguageGenerator
MIT License
sources/app/src/main/java/com/mikyegresl/valostat/features/player/exoplayer/ExoVideoPlayer.kt
sergey-lvovich-kim
629,918,357
false
null
package com.mikyegresl.valostat.features.player.exoplayer import android.content.Context import android.media.session.PlaybackState import android.os.Looper import android.util.Log import android.widget.ImageView import androidx.appcompat.content.res.AppCompatResources import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.material.CircularProgressIndicator import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.core.view.isVisible import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.media3.common.MediaItem import androidx.media3.common.Player import androidx.media3.datasource.DataSource import androidx.media3.datasource.DefaultDataSource import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.trackselection.DefaultTrackSelector import androidx.media3.exoplayer.trackselection.TrackSelector import androidx.media3.extractor.DefaultExtractorsFactory import androidx.media3.extractor.ExtractorsFactory import androidx.media3.ui.PlayerView import com.mikyegresl.valostat.features.player.exoplayer.VideoPlayerContentState.VideoPlayerLoadingContentState import com.mikyegresl.valostat.features.player.exoplayer.VideoPlayerContentState.VideoPlayerReadyContentState import com.mikyegresl.valostat.features.player.exoplayer.VideoPlayerIntent.* import com.mikyegresl.valostat.features.player.exoplayer.VideoPlayerIntent.VideoReadyPlayerIntent.* import com.mikyegresl.valostat.ui.theme.mainTextDark import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch private const val TAG = "PlayerVideoPlayer" private const val PEARSON_JS_PLAYER_SIGNATURE = "mediaplayer.pearsoncmg.com" private const val PEARSON_JS_PLAYER_URL = "https://mediaplayer.pearsoncmg.com/assets/_pmd.true/" private val VIDEO_EXTENSIONS = listOf( "avi", "mp4" ) private const val USER_AGENT = "Exoplayer" class ExoPlayerPearsonVideoPlayer( private val mediaUrl: String, private val lifecycleOwner: LifecycleOwner, val uiCoroutineScope: CoroutineScope, private val fullScreenListener: ExoPlayerFullScreenListener? ) { companion object { private const val DOWNLOAD_CONTENT_DIRECTORY = "downloads" } private var dataSourceFactory: DataSource.Factory? = null private var extractorsFactory: ExtractorsFactory? = null // player-related variables private var exoPlayer: ExoPlayer? = null private var trackSelector: TrackSelector? = null private var playerView: PlayerView? = null // data-related and player configuration-related variables private var config: PearsonVideoPlayerConfig = PearsonVideoPlayerConfig.DEFAULT_PLAYER_CONFIG private var dispatchedPlayOnInit = false private var isFullScreen: Boolean = fullScreenListener?.let { config.areInFullscreenFromStart } ?: false private val _playerStateFlow = lazy { MutableStateFlow<VideoPlayerContentState>(VideoPlayerLoadingContentState) } val state get() = _playerStateFlow.value.asStateFlow() private val playerState: VideoPlayerContentState get() = state.value private fun initializeWithParams(mediaUrl: String, onPlayerReady: (ExoPlayer) -> Unit): Boolean { return exoPlayer?.let { loadVideoAndPreparePlayer(mediaUrl, onPlayerReady) true } ?: false } @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) private fun loadVideoAndPreparePlayer(uri: String, onPlayerReady: (ExoPlayer) -> Unit) { val mediaItem = MediaItem.fromUri(uri) // val mediaSource = DefaultDataSource.Factory(dataSourceFactory!!).createMediaSource(mediaItem) exoPlayer?.let { onPlayerReady(it) it.setMediaItem(mediaItem) it.prepare() } } private fun withConfig(config: PearsonVideoPlayerConfig) = this.also { it.config = config isFullScreen = fullScreenListener?.let { config.areInFullscreenFromStart } ?: false } @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) private fun initVideoPlaybackObjects(context: Context) { // val downloadContentDirectory = File(context.getExternalFilesDir(null), DOWNLOAD_CONTENT_DIRECTORY) // val downloadCache = SimpleCache(downloadContentDirectory, NoOpCacheEvictor()) // val upstreamFactory = DefaultDataSourceFactory(context, Util.getUserAgent(context, USER_AGENT)) dataSourceFactory = dataSourceFactory ?: DefaultDataSource.Factory(context) // .setCache(downloadCache).setUpstreamDataSourceFactory(upstreamFactory) extractorsFactory = extractorsFactory ?: DefaultExtractorsFactory() } @Composable fun InflatePlayer(modifier: Modifier) = RenderPlayerView( modifier = modifier, playbackPosition = 0 ) @Composable fun ContinuePlayback( modifier: Modifier, playbackPosition: Long ) = RenderPlayerView( modifier = modifier, playbackPosition = playbackPosition ) @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) @Composable private fun RenderPlayerView( modifier: Modifier, playbackPosition: Long ) { initVideoPlaybackObjects(LocalContext.current) trackSelector = trackSelector ?: DefaultTrackSelector(LocalContext.current) val state = _playerStateFlow.value.collectAsState() val dispatchedState = remember { mutableStateOf<VideoPlayerContentState?>(null) } key(state) { (state.value as? VideoPlayerReadyContentState)?.let { // Dispatch if present state are in state of ready if (dispatchedState.value != it) { reactOnVideoReadyStateOnPlayer(it) dispatchedState.value = it } } } Box(modifier = modifier) { DisposableEffect( key1 = lifecycleOwner, AndroidView( modifier = Modifier .fillMaxWidth() .wrapContentHeight(), factory = { context -> PlayerView(context).let { setPlayerUi(context, it) initialize(playbackPosition) it.keepScreenOn = config.keepScreenOnWhenPlayerInitialized playerView = it it } } ) ) { val lifecycleObserver = LifecycleEventObserver { _, event -> onStateChanged(event, playbackPosition) } lifecycleOwner.lifecycle.addObserver(lifecycleObserver) onDispose { lifecycleOwner.lifecycle.removeObserver(lifecycleObserver) releaseResources() } } val isBuffering = (state.value as? VideoPlayerReadyContentState)?.isLoadingVideo ?: false AnimatedVisibility( visible = state.value is VideoPlayerLoadingContentState || isBuffering, modifier = Modifier.align(Alignment.Center), enter = fadeIn(), exit = fadeOut() ) { CircularProgressIndicator( modifier = Modifier.size(36.dp), color = mainTextDark ) } } } private fun setPlayerUi( context: Context, playerView: PlayerView ) { // val fullScreenBtn = playerView.findViewById<ImageView>(com.mikyegresl.valostat.R.id.exo_fullscreen_icon) // fullScreenBtn.isVisible = fullScreenListener != null // fullScreenBtn.takeIf { it.isVisible }?.setOnClickListener { // val params = playerView.layoutParams // val playOnInit = (playerState as? VideoPlayerReadyContentState)?.isPlaying ?: false // // isFullScreen = if (fullScreenListener == null) false // else if (isFullScreen) { // fullScreenListener.onExitFullScreen( // exoPlayer?.currentPosition ?: 0, // playOnInit // ) // params.height = ViewGroup.LayoutParams.WRAP_CONTENT // false // } else { // fullScreenListener.onEnterFullScreen( // exoPlayer?.currentPosition ?: 0, // playOnInit // ) // params.height = ViewGroup.LayoutParams.MATCH_PARENT // true // } // params.width = ViewGroup.LayoutParams.MATCH_PARENT // playerView.layoutParams = params // setFullscreenImageByFullscreenState(context, playerView) // } // setFullscreenImageByFullscreenState(context, playerView) } private fun setFullscreenImageByFullscreenState(context: Context, playerView: PlayerView) { val fullScreenBtn = playerView.findViewById<ImageView>(com.mikyegresl.valostat.R.id.exo_fullscreen_icon) ?: return fullScreenBtn.takeIf { it.isVisible }?.let { if (fullScreenListener == null) return val res = if (isFullScreen) com.mikyegresl.valostat.R.drawable.ic_disable_fullscreen else com.mikyegresl.valostat.R.drawable.ic_enable_fullscreen fullScreenBtn.setImageDrawable( AppCompatResources.getDrawable(context, res) ) } } private fun reactOnVideoReadyStateOnPlayer( state: VideoPlayerReadyContentState, ) { exoPlayer ?: return val needToStartPlay = (state.isPlaying && exoPlayer?.playbackState != PlaybackState.STATE_PLAYING) || config.playOnInit && !dispatchedPlayOnInit if (needToStartPlay) { exoPlayer?.playWhenReady = true dispatchedPlayOnInit = true } } private fun dispatchIntent(intent: VideoPlayerIntent) { when (intent) { is VideoViewGotClickedIntent -> processOnReadyVideoViewClickIntent(state.value as? VideoPlayerReadyContentState) is VideoReadyPlayerIntent -> processVideoReadyPlayerIntent(intent) is CleanupVideoPlayerIntent -> { releaseResources() } is ReinitializeVideoPlayerIntent.StartFromBeginningVideoPlayerIntent -> { initialize() } is ReinitializeVideoPlayerIntent.ContinuePlaybackVideoPlayerIntent -> { initialize(intent.playbackPosition) } } } /** * Lifecycle observer method that behaves according to state of lifecycle owner */ private fun onStateChanged(event: Lifecycle.Event, playbackPosition: Long?) { when (event) { Lifecycle.Event.ON_STOP -> { dispatchIntent(CleanupVideoPlayerIntent) } Lifecycle.Event.ON_START -> { dispatchIntent( ReinitializeVideoPlayerIntent.ContinuePlaybackVideoPlayerIntent( playbackPosition = (playerState as? VideoPlayerReadyContentState)?.currentMillis ?: playbackPosition ?: 0 ) ) } else -> {} } } protected fun changeContentState(contentState: VideoPlayerContentState) { uiCoroutineScope.launch { _playerStateFlow.value.emit(contentState) } } @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) private fun setUpPlayer(player: ExoPlayer) { player.addListener(object : Player.Listener { override fun onPlaybackStateChanged(playbackState: Int) { } override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) { changeContentState( VideoPlayerReadyContentState( isEnded = reason == PlaybackState.STATE_STOPPED, isPlaying = reason == PlaybackState.STATE_PLAYING && playWhenReady, isLoadingVideo = reason == PlaybackState.STATE_PAUSED && playWhenReady, ), ) } }) } private fun releaseResources() { changeContentState( VideoPlayerReadyContentState( isEnded = false, currentMillis = exoPlayer?.currentPosition ?: 0, isPlaying = false ) ) exoPlayer?.release() exoPlayer = null } private fun initialize(playbackPosition: Long = 0) { if (exoPlayer != null) { return } val context = playerView?.context if (context == null) { android.os.Handler(Looper.myLooper()!!).post { initialize(playbackPosition) } Log.d(TAG, "ExoPlayer init scheduled") return } exoPlayer = ExoPlayer.Builder(context).build() playerView?.player = exoPlayer setUpPlayer(exoPlayer!!) val isInitialized = initializeWithParams(mediaUrl) { with(playbackPosition) { if (this > 0) it.seekTo(this) } } if (isInitialized) { changeContentState( VideoPlayerReadyContentState( isEnded = false, isPlaying = false, currentMillis = config.millisOnInit ) ) } else { Log.e(ExoPlayerPearsonVideoPlayer::class.java.name, "Player has not been initialized") // TODO based on flag show error on view if smth went wrong } } private fun processOnReadyVideoViewClickIntent(state: VideoPlayerReadyContentState?) { if (state == null) return if (state.isPlaying) { dispatchIntent(PauseCurrentVideo) } else { if (state.isEnded) { dispatchIntent(RewindCurrentVideo()) } else { dispatchIntent(PlayCurrentVideo) } } } private fun processVideoReadyPlayerIntent(intent: VideoReadyPlayerIntent) { val playing: Boolean var currentMillis = exoPlayer?.currentPosition ?: 0 when (intent) { PauseCurrentVideo -> { playing = false exoPlayer?.playWhenReady = false } PlayCurrentVideo -> { playing = true exoPlayer?.playWhenReady = true } is RewindCurrentVideo -> { exoPlayer?.seekTo(intent.millisecond) currentMillis = intent.millisecond playing = true } } // Uncomment when would do it with custom controls (playerState as? VideoPlayerReadyContentState)?.let { contentStateAsPlaying -> changeContentState( contentStateAsPlaying.copy( isPlaying = playing, currentMillis = currentMillis ) ) } } } enum class OnResumePlayerStrategy { VIDEO_RESUMED, VIDEO_PAUSED } class PearsonVideoPlayerConfig( val onResumePlayerStrategy: OnResumePlayerStrategy = OnResumePlayerStrategy.VIDEO_PAUSED, val playOnInit: Boolean = false, val millisOnInit: Long = VideoPlayerIntent.VIDEO_START_MILLISECOND_DEFAULT, val areInFullscreenFromStart: Boolean = false, val keepScreenOnWhenPlayerInitialized: Boolean = true ) { companion object { val DEFAULT_PLAYER_CONFIG = PearsonVideoPlayerConfig() } }
0
Kotlin
1
8
22bda996b0defdf67b201d5768ff27a6d6cfb561
16,429
ValoStat
Apache License 2.0
core/src/main/java/com/tapptitude/template/core/model/extension/ImageExt.kt
tapptitude
462,275,098
false
{"Kotlin": 55298}
package com.tapptitude.template.core.model.extension import com.tapptitude.template.core.model.Image import com.tapptitude.template.network.dto.ImageDto import com.tapptitude.template.persistence.images.ImageEntity internal fun ImageDto.toEntity() = ImageEntity(url = imageUrl.orEmpty()) internal fun ImageEntity.toImage() = Image(imageUrl = url) internal fun Image.toImageDto() = ImageDto(imageUrl = imageUrl)
3
Kotlin
0
5
b5d29a8cf4d07775c6039072a852e7f38f53eea2
415
AndroidKotlinMVVMTemplate
MIT License
app/src/main/java/com/example/valorantwiki/ui/viewPager/ViewPagerAdapter.kt
LucasMelll0
530,731,178
false
null
package com.example.valorantwiki.ui.viewPager import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter class ViewPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) { var fragmentList: MutableList<Fragment> = ArrayList() var titleList: MutableList<String> = ArrayList() fun getTitle(position: Int): String = titleList.get(position) fun addFragment(fragment: Fragment, title: String){ fragmentList.add(fragment) titleList.add(title) } override fun createFragment(position: Int): Fragment = fragmentList[position] override fun getItemCount(): Int = fragmentList.size }
0
Kotlin
0
2
8cc66c87d5c3830b1df451189f486d4e472bcd19
741
Valorant_Wiki
Apache License 2.0
app/src/main/java/tech/edroomdevs/edroom/activity/doubtcorner/AddDoubtActivity.kt
arwazkhan189
483,951,570
false
null
package tech.edroomdevs.edroom.activity.doubtcorner import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import android.os.Environment import android.provider.Settings import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.net.toUri import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.firebase.auth.FirebaseAuth import com.google.firebase.ktx.Firebase import com.google.firebase.storage.ktx.storage import com.google.firebase.storage.ktx.storageMetadata import tech.edroomdevs.edroom.R import tech.edroomdevs.edroom.daos.DoubtDao import tech.edroomdevs.edroom.databinding.ActivityAddDoubtBinding import tech.edroomdevs.edroom.util.ConnectionManager import tech.edroomdevs.edroom.util.ImageCompression import java.io.File import java.text.SimpleDateFormat import java.util.* class AddDoubtActivity : AppCompatActivity() { private lateinit var binding: ActivityAddDoubtBinding private lateinit var sharedPreferences: SharedPreferences private val pickImageCode = 1 private var imageUri: Uri? = null private val storage = Firebase.storage("gs://edroom-146bd.appspot.com/") private val storageRef = storage.reference private var metadata = storageMetadata { contentType = "image/jpg" } private var storageImageUrl: String = "" private var doubtImageTitle: String = "Please select an Image…" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAddDoubtBinding.inflate(layoutInflater) setContentView(binding.root) sharedPreferences = getSharedPreferences(getString(R.string.preference_file_name), Context.MODE_PRIVATE) //select image button binding.tvDoubtImagePickup.setOnClickListener { selectDoubtImage() } //image upload button binding.btnUploadImage.setOnClickListener { if (binding.tvDoubtImagePickup.text == resources.getString(R.string.please_select_an_image)) Toast.makeText( this@AddDoubtActivity, "Please select an image first...", Toast.LENGTH_SHORT ).show() else uploadDoubtImage() } binding.btnDoubtSubmit.setOnClickListener { checkInputFunction() } } //on resume function override fun onResume() { if (!(ConnectionManager().checkConnectivity(this))) { checkInternet() } super.onResume() } // internet check function private fun checkInternet() { val dialog = MaterialAlertDialogBuilder(this) dialog.setTitle("Error") dialog.setMessage("Internet Connection is not Found") dialog.setPositiveButton("Open Settings") { _, _ -> val settingsIntent = Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS) startActivity(settingsIntent) } dialog.setNegativeButton("Exit") { _, _ -> ActivityCompat.finishAffinity(this) } dialog.create() dialog.show() } //check input function private fun checkInputFunction() { if (binding.etDoubtTitle.text.toString() == "") { Toast.makeText( this@AddDoubtActivity, "Please enter Doubt Title.", Toast.LENGTH_SHORT ).show() } else if (binding.etDoubtSubject.text.toString() == "") { Toast.makeText( this@AddDoubtActivity, "Please enter Subject.", Toast.LENGTH_SHORT ).show() } else if (binding.etDoubtChapter.text.toString() == "") { Toast.makeText( this@AddDoubtActivity, "Please enter Chapter.", Toast.LENGTH_SHORT ).show() } else if (binding.etDoubtDesc.text.toString() == "") { Toast.makeText( this@AddDoubtActivity, "Please enter Doubt description.", Toast.LENGTH_SHORT ).show() } else if (binding.tvPressUploadButton.visibility == View.VISIBLE) { Toast.makeText( this@AddDoubtActivity, "Please upload the image first...", Toast.LENGTH_SHORT ).show() } else { uploadDoubtDetails() } } //select image function private fun selectDoubtImage() { val selectImageIntent = Intent() selectImageIntent.type = "image/*" selectImageIntent.action = Intent.ACTION_PICK startActivityForResult( Intent.createChooser(selectImageIntent, "Select an image :"), pickImageCode ) } //get image uri function @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == RESULT_OK && requestCode == pickImageCode) { val file = File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "EdRoom" ) imageUri = ImageCompression(applicationContext).compress( (data?.data).toString(), file ).toUri() binding.tvDoubtImagePickup.text = (imageUri.toString().split("%2F", "/").last()) binding.tvPressUploadButton.visibility = View.VISIBLE } } //upload doubt image function and return url private fun uploadDoubtImage() { //showing progress bar when uploading started binding.plUploadImage.visibility = View.VISIBLE binding.tvPressUploadButton.visibility = View.INVISIBLE binding.btnDoubtSubmit.visibility = View.INVISIBLE //taking doubt title and date to rename image as doubtTitle_Date val doubtTitle = binding.etDoubtTitle.editableText.toString() val currentDate = SimpleDateFormat("ddMMyyyy", Locale.getDefault()).format(Date()) doubtImageTitle = "${doubtTitle}_${currentDate}".replace(" ", "") //firebase storage reference and upload task val storageReference = storageRef.child("Doubts/$doubtImageTitle") val uploadTask = storageReference.putFile(imageUri!!, metadata) //this is used to return the url after uploading uploadTask.continueWithTask { task -> if (!task.isSuccessful) { Toast.makeText(this@AddDoubtActivity, "Uploading Failed...", Toast.LENGTH_SHORT) .show() } storageReference.downloadUrl }.addOnCompleteListener { task -> if (task.isSuccessful) { val downloadUri = task.result storageImageUrl = downloadUri.toString() binding.plUploadImage.visibility = View.INVISIBLE binding.btnDoubtSubmit.visibility = View.VISIBLE Toast.makeText( this@AddDoubtActivity, "Image Uploaded Successfully...", Toast.LENGTH_SHORT ).show() } else { Toast.makeText(this@AddDoubtActivity, "Uploading Failed...", Toast.LENGTH_SHORT) .show() } } } //upload doubt data to firestore private fun uploadDoubtDetails() { val doubtTime = System.currentTimeMillis() val doubtCreatedBy = sharedPreferences.getString("fullName", "Name")!! val doubtId = "${doubtCreatedBy}${doubtTime}".replace(" ", "") val userId = FirebaseAuth.getInstance().currentUser?.uid.toString() val answersArray: ArrayList<String>? = null DoubtDao().addDoubtByUser( doubtId, binding.etDoubtTitle.editableText.toString(), doubtCreatedBy, doubtTime, binding.etDoubtSubject.editableText.toString(), binding.etDoubtChapter.editableText.toString(), binding.etDoubtDesc.editableText.toString(), storageImageUrl, userId, doubtImageTitle, answersArray ) finish() Toast.makeText( this@AddDoubtActivity, "Your Doubt will be solved soon 🙂", Toast.LENGTH_SHORT ).show() } }
0
Kotlin
2
1
de0fda2187e15fb538184425027b65f22f066bfc
8,700
EdRoom
MIT License
androidutils/src/main/java/eu/espeo/androidutils/extensions/EditTextExtensions.kt
espeo
184,033,917
false
null
package eu.espeo.androidutils.extensions import android.text.Editable import android.text.TextWatcher import android.widget.EditText /** * Created by Maciej Kozłowski on 2019-08-14. */ fun EditText.addOnTextChangeListener(action: (String) -> Unit) { addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { // Do nothing } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { // Do nothing } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { action(s.toString()) } }) }
0
Kotlin
0
0
0e624e9885e009851276b44f8f4be720adf15282
671
AndroidUtils
MIT License
yandex-mapkit-kmp/src/commonMain/kotlin/ru/sulgik/mapkit/PointF.kt
SuLG-ik
813,953,018
false
{"Kotlin": 321441}
package ru.sulgik.mapkit public data class PointF( val x: Float, val y: Float, )
0
Kotlin
1
17
2d292b701adb2c538f8cd3ddf614250f9d6a444d
89
yandex-mapkit-kmp
Apache License 2.0
korge-core/test/korlibs/io/net/ws/RawSocketWebSocketClientTest.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.net.ws import korlibs.io.async.suspendTestNoJs import korlibs.io.lang.toByteArray import korlibs.io.net.FakeAsyncClient import korlibs.io.net.URL import korlibs.io.net.http.Http import korlibs.io.stream.MemorySyncStreamToByteArray import korlibs.io.stream.openSync import korlibs.io.stream.readString import korlibs.io.stream.readU16BE import korlibs.io.stream.toAsync import korlibs.io.stream.write16BE import korlibs.io.stream.writeBytes import korlibs.io.stream.writeString import korlibs.encoding.hex import kotlin.test.* class RawRawSocketWebSocketClient { @Test fun test() = suspendTestNoJs { assertEquals( "GET / HTTP/1.1", (RawSocketWebSocketClient( "ws://127.0.0.1:8081/", connect = false ) as RawSocketWebSocketClient).buildHeader().split("\r\n").first() ) } @Test fun test2() = suspendTestNoJs { val ws = RawSocketWebSocketClient("ws://127.0.0.1:8081/path?id=someId", connect = false) as RawSocketWebSocketClient assertEquals( "GET /path?id=someId HTTP/1.1\r\n" + "Host: 127.0.0.1:8081\r\n" + "Pragma: no-cache\r\n" + "Cache-Control: no-cache\r\n" + "Upgrade: websocket\r\n" + "Sec-WebSocket-Version: 13\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Key: <KEY>" + "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36\r\n" + "\r\n", ws.buildHeader() ) } @Test fun test3() = suspendTestNoJs { val ws = RawSocketWebSocketClient("ws://127.0.0.1:8081/path?id=someId", connect = false, headers = Http.Headers.build { put("user-agent", "myagent!") }) as RawSocketWebSocketClient assertEquals( "GET /path?id=someId HTTP/1.1\r\n" + "Host: 127.0.0.1:8081\r\n" + "Pragma: no-cache\r\n" + "Cache-Control: no-cache\r\n" + "Upgrade: websocket\r\n" + "Sec-WebSocket-Version: 13\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Key: <KEY>" + "user-agent: myagent!\r\n" + "\r\n", ws.buildHeader() ) } @Test fun testClose() = suspendTestNoJs { val log = arrayListOf<String>() val client = FakeAsyncClient() client.serverToClient.writeBytes(WsFrame("hello".toByteArray(), WsOpcode.Text, masked = false).toByteArray()) val ws = RawSocketWebSocketClient(coroutineContext, client, URL("ws://127.0.0.1:8081/")) ws.onOpen { log += "open" } ws.onClose { log += "close" } ws.onError { it.printStackTrace(); log += "error" } ws.onStringMessage { log += "'$it'" } ws.internalReadPackets() ws.close() val frame = RawSocketWebSocketClient.readWsFrameOrNull(client.clientToServer.toAsync()) val message = frame!!.data.openSync() assertEquals("open,'hello',close", log.joinToString(",")) assertEquals(1000, message.readU16BE()) assertEquals("OK", message.readString(2)) } @Test fun testContinuation() = suspendTestNoJs { val log = arrayListOf<String>() val client = FakeAsyncClient() val a = "あ" val aData = a.toByteArray() client.serverToClient.writeBytes(WsFrame(aData.sliceArray(0..0), WsOpcode.Text, isFinal = false, masked = false).toByteArray()) client.serverToClient.writeBytes(WsFrame(aData.sliceArray(1 until aData.size), WsOpcode.Continuation, isFinal = true, masked = false).toByteArray()) val ws = RawSocketWebSocketClient(coroutineContext, client, URL("ws://127.0.0.1:8081/")) ws.onOpen { log += "open" } ws.onClose { log += "close" } ws.onError { it.printStackTrace(); log += "error" } ws.onBinaryMessage { log += "#${it.hex}#" } ws.onStringMessage { log += "'$it'" } ws.onAnyMessage.add { log += "[$it]" } ws.internalReadPackets() ws.close() assertEquals("open,'あ',[あ],close", log.joinToString(",")) } @Test fun testServerCloseResponse() = suspendTestNoJs { val log = arrayListOf<String>() val client = FakeAsyncClient() client.serverToClient.writeBytes(WsFrame(MemorySyncStreamToByteArray { write16BE(WebSocketClient.CloseReasons.PROTOCOL_ERROR) writeString("testing!") }, WsOpcode.Close, isFinal = true, masked = false).toByteArray()) val ws = RawSocketWebSocketClient(coroutineContext, client, URL("ws://127.0.0.1:8081/")) ws.onOpen { log += "open" } ws.onClose { log += "close[${it.code},${it.message}]" } ws.onError { it.printStackTrace(); log += "error" } ws.onBinaryMessage { log += "#${it.hex}#" } ws.onStringMessage { log += "'$it'" } ws.onAnyMessage.add { log += "[$it]" } ws.internalReadPackets() ws.close() assertEquals("open,close[1002,testing!]", log.joinToString(",")) } @Test fun testWrongSizeWSKey() = suspendTestNoJs { assertFailsWith<IllegalStateException> { RawSocketWebSocketClient("ws://127.0.0.1/test", wskey = "...", connect = false) } } }
444
WebAssembly
121
2,207
dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a
5,481
korge
Apache License 2.0
app/src/main/java/de/boscall/dbTasks/RemoveAllAlarmsTask.kt
dorianweidler
127,475,477
false
null
package de.boscall.dbTasks import android.app.Activity import android.os.AsyncTask import de.boscall.dto.Alarm import de.boscall.services.AlarmDatabase import java.lang.ref.WeakReference class RemoveAllAlarmsTask(activity: Activity) : AsyncTask<Unit, Unit, Unit>() { val activity: WeakReference<Activity> = WeakReference(activity) override fun doInBackground(vararg params: Unit) { val activity = this.activity.get() if (activity != null) { val db = AlarmDatabase.getInstance(activity) db.alarmDao().deleteAll() } } }
0
Kotlin
0
1
28598c73745d8f99a713211652797f27f7da4b12
582
BOSCall
Creative Commons Attribution 3.0 Unported
src/main/kotlin/me/sd_master92/customvoting/database/PlayerDatabase.kt
sanderderks
306,723,396
false
null
package me.sd_master92.customvoting.database import me.sd_master92.core.database.CustomColumn import me.sd_master92.core.database.CustomDatabase import me.sd_master92.core.database.CustomTable import me.sd_master92.core.errorLog import me.sd_master92.core.infoLog import me.sd_master92.customvoting.CV import me.sd_master92.customvoting.constants.models.UniqueVote import me.sd_master92.customvoting.dayDifferenceToday import java.util.* class PlayerDatabase(private val plugin: CV, database: CustomDatabase) { private val queueTable: CustomTable val playersTable: CustomTable private fun addPlayer(uuid: String): Boolean { val defaultData = mutableMapOf<String, Any>() for (column in PlayerTableColumn.columns(uuid)) { defaultData[column.columnName] = column.defaultValue!! } return playersTable.insertData(defaultData.keys.toTypedArray(), defaultData.values.toTypedArray()) } fun getName(uuid: String): String { val result = playersTable.getData(PlayerTableColumn.UUID.columnName, uuid) try { if (result.next()) { return result.getString(PlayerTableColumn.NAME.columnName) } } catch (e: Exception) { plugin.errorLog("Could not retrieve name of $uuid from database", e) } return "Unknown" } fun setName(uuid: String, name: String): Boolean { return playersTable.updateData(PlayerTableColumn.UUID.columnName, uuid, PlayerTableColumn.NAME.columnName, name) } fun getVotes(uuid: String): Int { val result = playersTable.getData(PlayerTableColumn.UUID.columnName, uuid) try { if (result.next()) { return result.getInt(PlayerTableColumn.VOTES.columnName) } else { addPlayer(uuid) } } catch (e: Exception) { plugin.errorLog("Could not retrieve votes of $uuid from database", e) } return 0 } fun setVotes(uuid: String, votes: Int): Boolean { return playersTable.updateData( PlayerTableColumn.UUID.columnName, uuid, PlayerTableColumn.VOTES.columnName, votes ) } fun getMonthlyVotes(uuid: String): Int { val result = playersTable.getData(PlayerTableColumn.UUID.columnName, uuid) try { if (result.next()) { return result.getInt(PlayerTableColumn.MONTHLY_VOTES.columnName) } else { addPlayer(uuid) } } catch (e: Exception) { plugin.errorLog("Could not retrieve period votes of $uuid from database", e) } return 0 } fun setMonthlyVotes(uuid: String, votes: Int): Boolean { return playersTable.updateData( PlayerTableColumn.UUID.columnName, uuid, PlayerTableColumn.MONTHLY_VOTES.columnName, votes ) } fun getWeeklyVotes(uuid: String): Int { val result = playersTable.getData(PlayerTableColumn.UUID.columnName, uuid) try { if (result.next()) { return result.getInt(PlayerTableColumn.WEEKLY_VOTES.columnName) } } catch (e: Exception) { plugin.errorLog("Could not retrieve weekly votes of $uuid from database", e) } return 0 } fun setWeeklyVotes(uuid: String, votes: Int): Boolean { return playersTable.updateData( PlayerTableColumn.UUID.columnName, uuid, PlayerTableColumn.WEEKLY_VOTES.columnName, votes ) } fun getDailyVotes(uuid: String): Int { val result = playersTable.getData(PlayerTableColumn.UUID.columnName, uuid) try { if (result.next()) { return result.getInt(PlayerTableColumn.DAILY_VOTES.columnName) } } catch (e: Exception) { plugin.errorLog("Could not retrieve daily votes of $uuid from database", e) } return 0 } fun setDailyVotes(uuid: String, votes: Int): Boolean { return playersTable.updateData( PlayerTableColumn.UUID.columnName, uuid, PlayerTableColumn.DAILY_VOTES.columnName, votes ) } fun getLast(uuid: String): Long { val result = playersTable.getData(PlayerTableColumn.UUID.columnName, uuid) try { if (result.next()) { return result.getLong(PlayerTableColumn.LAST_VOTE.columnName) } else { addPlayer(uuid) } } catch (e: Exception) { plugin.errorLog("Could not retrieve last timestamp of $uuid from database", e) } return 0 } fun getLastSite(uuid: String): String? { val result = playersTable.getData(PlayerTableColumn.UUID.columnName, uuid) try { if (result.next()) { return result.getString(PlayerTableColumn.LAST_SITE.columnName) } else { addPlayer(uuid) } } catch (e: Exception) { plugin.errorLog("Could not retrieve last site of $uuid from database", e) } return null } fun setLast(uuid: String, site: String? = null): Boolean { return playersTable.updateData( PlayerTableColumn.UUID.columnName, uuid, PlayerTableColumn.LAST_VOTE.columnName, System.currentTimeMillis() ) && playersTable.updateData( PlayerTableColumn.UUID.columnName, uuid, PlayerTableColumn.LAST_SITE.columnName, site ) } fun getQueue(uuid: String): List<String> { val result = queueTable.getData(QueueTableColumn.UUID.columnName, uuid) val uniqueVotes = mutableSetOf<UniqueVote>() val queue = mutableListOf<String>() try { while (result.next()) { val site = result.getString(QueueTableColumn.SITE.columnName) if (getLastSite(uuid) == site && getLast(uuid).dayDifferenceToday() == 0) { continue } val calendar = Calendar.getInstance() calendar.time = Date(result.getLong(QueueTableColumn.TIME.columnName)) val vote = UniqueVote(calendar[Calendar.DAY_OF_YEAR], site) if (uniqueVotes.add(vote)) { queue.add(site) } } } catch (e: Exception) { plugin.errorLog("Could not retrieve queue of $uuid from database", e) } return queue } fun addQueue(uuid: String, site: String): Boolean { return queueTable.insertData( arrayOf( QueueTableColumn.UUID.columnName, QueueTableColumn.SITE.columnName, QueueTableColumn.TIME.columnName ), arrayOf(uuid, site, Date().time) ) } fun clearQueue(uuid: String): Boolean { return queueTable.deleteData(QueueTableColumn.UUID.columnName, uuid) } fun getPower(uuid: String): Boolean { val result = playersTable.getData(PlayerTableColumn.UUID.columnName, uuid) try { if (result.next()) { return result.getBoolean(PlayerTableColumn.POWER.columnName) } } catch (e: Exception) { plugin.errorLog("Could not retrieve op status of $uuid from database", e) } return false } fun setPower(uuid: String, power: Boolean): Boolean { return playersTable.updateData( PlayerTableColumn.UUID.columnName, uuid, PlayerTableColumn.POWER.columnName, if (power) 1 else 0 ) } fun getStreak(uuid: String): Int { val result = playersTable.getData(PlayerTableColumn.UUID.columnName, uuid) try { if (result.next()) { return result.getInt(PlayerTableColumn.DAILY_VOTE_STREAK.columnName) } } catch (e: Exception) { plugin.errorLog("Could not retrieve streak of $uuid from database", e) } return 0 } fun setStreak(uuid: String, streak: Int): Boolean { return playersTable.updateData( PlayerTableColumn.UUID.columnName, uuid, PlayerTableColumn.DAILY_VOTE_STREAK.columnName, streak ) } private fun migratePlayers() { rename(playersTable, "period", PlayerTableColumn.MONTHLY_VOTES.columnName, CustomColumn.DataType.INT) rename(playersTable, "monthly_votes", PlayerTableColumn.MONTHLY_VOTES.columnName, CustomColumn.DataType.INT) rename(playersTable, "is_op", PlayerTableColumn.POWER.columnName, CustomColumn.DataType.BOOLEAN) for (column in PlayerTableColumn.columns()) { create(playersTable, column.columnName, column.dataType) } delete(playersTable, "queue") } private fun migrateQueue() { rename(queueTable, "votes", QueueTableColumn.SITE.columnName, QueueTableColumn.SITE.dataType) for (column in QueueTableColumn.columns()) { create(queueTable, column.columnName, column.dataType) } } private fun create(table: CustomTable, name: String, dataType: CustomColumn.DataType) { val column = table.getColumn(name) if (!column.exists()) { if (column.create(dataType)) { plugin.infoLog("| successfully created column '$name'!") } else { plugin.errorLog("| could not create column '$name'!") } } } private fun rename(table: CustomTable, oldName: String, newName: String, dataType: CustomColumn.DataType) { if (!table.getColumn(newName).exists()) { val column = table.getColumn(oldName) if (column.exists()) { if (column.renameOrCreate(newName, dataType)) { plugin.infoLog("| successfully created column '$newName'!") } else { plugin.errorLog("| could not create column '$newName'!") } } } } private fun delete(table: CustomTable, name: String) { val column = table.getColumn(name) if (column.exists()) { if (table.getColumn(name).delete()) { plugin.infoLog("| successfully deleted column '$name'!") } else { plugin.errorLog("| could not delete column '$name'!") } } } companion object { const val PLAYERS_TABLE = "players" const val QUEUE_TABLE = "queue" } init { playersTable = database.getTable(PLAYERS_TABLE) if (!playersTable.exists()) { PlayerTableColumn.create(plugin, playersTable) } else { plugin.infoLog("| successfully located table '$PLAYERS_TABLE'") plugin.infoLog("|") migratePlayers() } queueTable = database.getTable(QUEUE_TABLE) if (!queueTable.exists()) { QueueTableColumn.create(plugin, queueTable) } else { plugin.infoLog("| successfully located table '$QUEUE_TABLE'") plugin.infoLog("|") migrateQueue() } if (playersTable.exists() && queueTable.exists()) { plugin.infoLog("|___successfully connected to database") } else { plugin.errorLog("|___database disabled") } } }
0
Kotlin
1
0
7e1e23d09862390d05fe9aac92e46c9e5bf48a0d
12,362
CustomVoting
MIT License
app/src/main/java/com/example/friendzone/presentation/screens/user/OtherUsers.kt
mohitdamke
839,901,877
false
{"Kotlin": 310975}
package com.example.friendzone.presentation.screens.user import android.content.Context import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import coil.compose.rememberAsyncImagePainter import com.example.friendzone.common.PostItem import com.example.friendzone.dimension.FontDim import com.example.friendzone.dimension.TextDim import com.example.friendzone.ui.theme.DarkBlack import com.example.friendzone.ui.theme.White import com.example.friendzone.viewmodel.auth.AuthViewModel import com.example.friendzone.viewmodel.home.HomeViewModel import com.example.friendzone.viewmodel.user.UserViewModel import com.google.firebase.auth.FirebaseAuth import java.util.Locale @OptIn(ExperimentalMaterial3Api::class) @Composable fun OtherUsers( modifier: Modifier = Modifier, navController: NavHostController, uid: String, context: Context = LocalContext.current ) { var currentUserId = "" if (FirebaseAuth.getInstance().currentUser != null) { currentUserId = FirebaseAuth.getInstance().currentUser!!.uid } val authViewModel: AuthViewModel = viewModel() val firebaseUser by authViewModel.firebaseUser.observeAsState(null) val userViewModel: UserViewModel = viewModel() val homeViewModel: HomeViewModel = viewModel() val posts by userViewModel.posts.observeAsState(null) val story by userViewModel.story.observeAsState(null) val users by userViewModel.users.observeAsState(null) val followerList by userViewModel.followerList.observeAsState(null) val followingList by userViewModel.followingList.observeAsState(null) val isFollowing = followerList?.contains(currentUserId) == true val postsToDisplay = posts!!.filter { it.userId == uid } .sortedByDescending { it.timeStamp.toLong() } LaunchedEffect(key1 = uid) { userViewModel.fetchPosts(uid) userViewModel.fetchStory(uid) userViewModel.fetchUsers(uid) userViewModel.getFollowers(uid) userViewModel.getFollowing(uid) } Scaffold( topBar = { CenterAlignedTopAppBar( colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = DarkBlack, titleContentColor = White, actionIconContentColor = White, navigationIconContentColor = White, scrolledContainerColor = DarkBlack, ), title = { Text( text = users?.name?.toUpperCase(Locale.ROOT) ?: "Loading", maxLines = 1, letterSpacing = 1.sp, fontSize = TextDim.titleTextSize, overflow = TextOverflow.Visible, fontFamily = FontDim.Bold, ) }, navigationIcon = { Icon(imageVector = Icons.Default.ArrowBack, contentDescription = null, modifier = modifier .size(30.dp) .clickable { navController.navigateUp() }) } ) }, ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .background(DarkBlack) .padding(paddingValues), horizontalAlignment = Alignment.CenterHorizontally ) { LazyColumn { item { Column( modifier = modifier .fillMaxSize() .padding(10.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = modifier.padding(top = 20.dp)) Image( painter = rememberAsyncImagePainter( model = users?.imageUrl ?: "https://picsum.photos/200/300" ), contentDescription = null, modifier = modifier .size(120.dp) .padding(2.dp) .border(width = 4.dp, color = Color.White, shape = CircleShape) .padding(2.dp) .border(width = 4.dp, color = Color.Black, shape = CircleShape) .clip(CircleShape), contentScale = ContentScale.Crop ) Text( text = users?.name ?: "Loading", fontSize = TextDim.titleTextSize, fontFamily = FontDim.Bold, color = White ) Spacer(modifier = modifier.padding(top = 4.dp)) Text( text = "@${users?.userName ?: "Loading Username"}", fontSize = TextDim.secondaryTextSize, fontFamily = FontDim.Normal, color = Color.LightGray ) Spacer(modifier = modifier.padding(top = 4.dp)) Text( text = "@${users?.bio ?: "Loading Bio"}", fontSize = TextDim.bodyTextSize, fontFamily = FontDim.Normal, color = Color.LightGray, textAlign = TextAlign.Center ) } Row( modifier = modifier .fillMaxWidth() .padding(10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly ) { Column( modifier = modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = postsToDisplay.size.toString(), fontSize = TextDim.titleTextSize, fontFamily = FontDim.Bold, color = White ) Text( text = "posts", fontSize = TextDim.secondaryTextSize, fontFamily = FontDim.Normal, color = White ) } Column( modifier = modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = followerList?.size.toString(), fontSize = TextDim.titleTextSize, fontFamily = FontDim.Bold, color = White ) Text( text = "followers", fontSize = TextDim.secondaryTextSize, fontFamily = FontDim.Normal, color = White ) } Column( modifier = modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = followingList?.size.toString(), fontSize = TextDim.titleTextSize, fontFamily = FontDim.Bold, color = White ) Text( text = "following", fontSize = TextDim.secondaryTextSize, fontFamily = FontDim.Normal, color = White ) } } Button( onClick = { if (currentUserId != "") { userViewModel.followOrUnfollowUser( uid, currentUserId, isFollowing ) } }, elevation = ButtonDefaults.buttonElevation(10.dp), border = ButtonDefaults.outlinedButtonBorder, modifier = modifier .fillMaxWidth() .padding(10.dp) .clip(RoundedCornerShape(40.dp)), colors = ButtonDefaults.buttonColors( containerColor = DarkBlack, contentColor = Color.White ) ) { Text( text = if (isFollowing) { "Following" } else { "Follow" }, fontSize = 16.sp, modifier = modifier.padding(10.dp) ) } } if (users != null) { this@LazyColumn.items( posts ?: emptyList() ) { post -> PostItem( post = post, users = users!!, rootNavController = navController, homeViewModel = homeViewModel ) } } } } } }
0
Kotlin
0
2
6d016f16d12b5a037c30ced93ade4d1c72c36295
12,129
FriendZone-App
MIT License
kotlin-node/src/jsMain/generated/node/fs/FileHandleWriteFileOptionsAsync.kt
JetBrains
93,250,841
false
{"Kotlin": 12127852, "JavaScript": 330528}
// Generated by Karakum - do not modify it manually! package node.fs import web.abort.Abortable sealed external interface FileHandleWriteFileAsyncOptions : ObjectEncodingOptions, FlagAndOpenMode, Abortable { var flush: Boolean? }
40
Kotlin
165
1,307
5dcda74b62898966c8d9a73623d9791e2ebb931f
238
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/edoubletech/moviemania/data/MovieDb.kt
etonotieno
137,695,371
false
{"Kotlin": 22205}
/* * Copyright (C) 2018 Eton Otieno Oboch * * 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.edoubletech.moviemania.data import com.edoubletech.moviemania.data.dao.MovieDao /** * This is a Room database with access to the DAOs */ abstract class MovieDb { abstract fun movieDao(): MovieDao }
0
Kotlin
0
1
197eb7d360be46417c6fecaee6e49388940e5a9b
855
MovieMania
Apache License 2.0
app/src/main/java/com/example/composezoomanimation/MainActivity.kt
tusharhow
597,453,051
false
null
package com.example.composezoomanimation import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.ui.Modifier import com.example.composezoomanimation.ui.theme.ComposeZoomAnimationTheme import com.example.composezoomanimation.views.HomePage class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ComposeZoomAnimationTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { HomePage() } } } } }
0
Kotlin
0
2
bfedc98acbea188cbf98b94f08783f7ce6db647e
932
compose-coffee-animation
The Unlicense
contentdetails/src/main/kotlin/com/socros/android/app/gitez/contentdetails/data/ContentDetailsRepository.kt
wrozwad
147,568,743
false
null
package com.socros.android.app.gitez.contentdetails.data import com.socros.android.app.gitez.contentdetails.di.ContentDetailsScope import com.socros.android.lib.repository.Resource import dagger.Lazy import io.reactivex.Observable import javax.inject.Inject @ContentDetailsScope class ContentDetailsRepository @Inject constructor() { @Inject internal lateinit var userDetailsResourceFactoryProvider: Lazy<UserDetailsResource.Factory> fun getUser(username: String): Observable<Resource<UserDetails?>> { return userDetailsResourceFactoryProvider.get().createResource(username).run { initialize() result } } }
0
Kotlin
0
0
afec0824ac2bd4c4ebadac0be5282f7c7eb7147e
626
gitez
MIT License
core/src/test/kotlin/org/ufoss/dino/internal/heap/HeapOptionsTest.kt
ufoss-org
264,428,446
false
{"Java": 573879, "Kotlin": 288125}
/* * Copyright 2023 UFOSS, Org. Use of this source code is governed by the Apache 2.0 license. */ package org.ufoss.dino.internal.heap import org.ufoss.dino.Dino import org.ufoss.dino.internal.OptionsTest class HeapOptionsTest : OptionsTest { override val dino: Dino = Dino.Builder().forJavaIO().build() }
1
null
1
1
f0bc77842605320a4dda2a78dacab54cf6f9e8f2
315
dino
Apache License 2.0
vertx-examples/src/main/kotlin/echo/EchoSslClient.kt
alextkachman
5,105,781
true
{"Java": 1387474, "Python": 1313735, "Groovy": 255623, "Ruby": 185134, "JavaScript": 172452, "Kotlin": 35631, "Shell": 17719, "CoffeeScript": 2008}
/* * Copyright 2011-2012 the original author or authors. * * 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.vertx.kotlin.examples.echo import org.vertx.java.deploy.Verticle import org.vertx.java.core.streams.Pump import org.vertx.kotlin.core.* import org.vertx.java.core.buffer.Buffer public class EchoSslClient() : Verticle() { public override fun start() { createNetClient { setSSL(true) setTrustAll(true) connect(1234){ socket -> socket.dataHandler{ buffer -> System.out.println("Net client receiving:\n-------\n$buffer\n-------") } //Now send some data for (var i in 0..9) { val str = "hello$i\n" System.out.print("Net client sending: $str") socket.write(str) } } } } }
0
Java
3
7
22eaa44ec212524efb59a6e219291ea6186352a0
1,435
vert.x
Apache License 2.0
src/test/kotlin/net/leanix/vsm/githubbroker/health/HealthEndpointTest.kt
leanix
563,788,890
false
{"Kotlin": 96728, "Dockerfile": 244}
package net.leanix.vsm.githubbroker.health import com.github.tomakehurst.wiremock.client.WireMock import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultMatchers import org.springframework.test.web.servlet.setup.MockMvcBuilders import org.springframework.web.context.WebApplicationContext @SpringBootTest @AutoConfigureWireMock(port = 6666) class HealthEndpointTest { @Autowired private lateinit var context: WebApplicationContext internal lateinit var mockMvc: MockMvc @BeforeEach fun setup() { mockMvc = MockMvcBuilders .webAppContextSetup(context) .build() WireMock.resetAllRequests() } @Test fun `it responds with http status ok`() { mockMvc.perform( MockMvcRequestBuilders.get("/actuator/health") ) .andExpect(MockMvcResultMatchers.status().isOk) } }
1
Kotlin
1
4
abb0fae7a95d7532431fdc95ef1f50edbe972885
1,283
vsm-github-broker
Apache License 2.0
idea/testData/quickfix/createFromUsage/createFunction/get/createGetFromUsage2.kt
staltz
38,581,975
true
{"Markdown": 33, "XML": 666, "Ant Build System": 45, "Ignore List": 7, "Git Attributes": 1, "Kotlin": 21040, "Java": 4546, "Protocol Buffer": 7, "Text": 4675, "JavaScript": 63, "JAR Manifest": 3, "Roff": 46, "Roff Manpage": 11, "INI": 17, "HTML": 154, "Groovy": 23, "Java Properties": 14, "Maven POM": 49, "Gradle": 74, "CSS": 2, "Proguard": 1, "JFlex": 2, "Shell": 11, "Batchfile": 10, "ANTLR": 1}
// "Create extension function 'get'" "true" fun x (y: Any) { val z: Any = y<caret>[""] }
0
Java
0
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
93
kotlin
Apache License 2.0
browser/src/main/java/laurenyew/imagebrowser/browser/adapters/ImageBrowserRecyclerViewAdapter.kt
laurenyew
130,925,684
false
{"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 7, "Batchfile": 1, "Markdown": 1, "Kotlin": 48, "XML": 31, "Proguard": 3, "Java": 1}
package laurenyew.imagebrowser.browser.adapters import android.os.Handler import android.support.annotation.VisibleForTesting import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.squareup.picasso.Picasso import laurenyew.imagebrowser.browser.R import laurenyew.imagebrowser.browser.adapters.data.ImageDiffCallback import laurenyew.imagebrowser.browser.adapters.data.ImagePreviewDataWrapper import laurenyew.imagebrowser.browser.adapters.viewHolder.ImagePreviewViewHolder import laurenyew.imagebrowser.browser.contracts.ImageBrowserContract import java.util.* import kotlin.collections.ArrayList /** * @author <NAME> on 04/29/2018. * * ImageBrowser Preview RecyclerView Adapter * Uses DiffUtil for better performance on adapter updates */ open class ImageBrowserRecyclerViewAdapter(private val presenter: ImageBrowserContract.Presenter?) : RecyclerView.Adapter<ImagePreviewViewHolder>() { private var data: MutableList<ImagePreviewDataWrapper> = ArrayList() @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) var pendingDataUpdates = ArrayDeque<List<ImagePreviewDataWrapper>>() //RecyclerView Diff.Util (List Updates) open fun updateData(newData: List<ImagePreviewDataWrapper>?) { val data = newData ?: ArrayList() pendingDataUpdates.add(data) if (pendingDataUpdates.size <= 1) { updateDataInternal(data) } } /** * Handle the diff util update on a background thread * (this can take O(n) time so we don't want it on the main thread) */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) open fun updateDataInternal(newData: List<ImagePreviewDataWrapper>?) { val oldData = ArrayList(data) val handler = Handler() Thread(Runnable { val diffCallback = createDataDiffCallback(oldData, newData) val diffResult = DiffUtil.calculateDiff(diffCallback) handler.post { applyDataDiffResult(newData, diffResult) } }).start() } /** * UI thread callback to apply the diff result to the adapter * and take in the latest update */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) open fun applyDataDiffResult(newData: List<ImagePreviewDataWrapper>?, diffResult: DiffUtil.DiffResult) { if (pendingDataUpdates.isNotEmpty()) { pendingDataUpdates.remove() } //Apply the data to the view data.clear() if (newData != null) { data.addAll(newData) } diffResult.dispatchUpdatesTo(this) //Take in the next latest update if (pendingDataUpdates.isNotEmpty()) { val latestDataUpdate = pendingDataUpdates.pop() pendingDataUpdates.clear() updateDataInternal(latestDataUpdate) } } open fun createDataDiffCallback(oldData: List<ImagePreviewDataWrapper>?, newData: List<ImagePreviewDataWrapper>?): DiffUtil.Callback = ImageDiffCallback(oldData, newData) //endregion //region RecyclerView.Adapter override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImagePreviewViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.image_browser_preview_view, parent, false) return ImagePreviewViewHolder(view) } override fun onBindViewHolder(holder: ImagePreviewViewHolder, position: Int) { val item = data[position] val itemImageUrl = item.imageUrl if (holder.imageView != null) { Picasso.get() .load(itemImageUrl) .placeholder(laurenyew.imagebrowser.base.R.drawable.image_placeholder) .error(laurenyew.imagebrowser.base.R.drawable.image_placeholder) .into(holder.imageView) } holder.view.setOnClickListener { presenter?.onSelectPreview(item.id, item.imageUrl, item.imageTitle) } } override fun getItemCount(): Int = data.size //endregion }
1
null
1
1
66dde9a063ef71fc11f3a40eae61537db7af445b
4,159
InstantAppImageBrowser
Apache License 2.0
browser/src/main/java/laurenyew/imagebrowser/browser/adapters/ImageBrowserRecyclerViewAdapter.kt
laurenyew
130,925,684
false
{"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 7, "Batchfile": 1, "Markdown": 1, "Kotlin": 48, "XML": 31, "Proguard": 3, "Java": 1}
package laurenyew.imagebrowser.browser.adapters import android.os.Handler import android.support.annotation.VisibleForTesting import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.squareup.picasso.Picasso import laurenyew.imagebrowser.browser.R import laurenyew.imagebrowser.browser.adapters.data.ImageDiffCallback import laurenyew.imagebrowser.browser.adapters.data.ImagePreviewDataWrapper import laurenyew.imagebrowser.browser.adapters.viewHolder.ImagePreviewViewHolder import laurenyew.imagebrowser.browser.contracts.ImageBrowserContract import java.util.* import kotlin.collections.ArrayList /** * @author <NAME> on 04/29/2018. * * ImageBrowser Preview RecyclerView Adapter * Uses DiffUtil for better performance on adapter updates */ open class ImageBrowserRecyclerViewAdapter(private val presenter: ImageBrowserContract.Presenter?) : RecyclerView.Adapter<ImagePreviewViewHolder>() { private var data: MutableList<ImagePreviewDataWrapper> = ArrayList() @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) var pendingDataUpdates = ArrayDeque<List<ImagePreviewDataWrapper>>() //RecyclerView Diff.Util (List Updates) open fun updateData(newData: List<ImagePreviewDataWrapper>?) { val data = newData ?: ArrayList() pendingDataUpdates.add(data) if (pendingDataUpdates.size <= 1) { updateDataInternal(data) } } /** * Handle the diff util update on a background thread * (this can take O(n) time so we don't want it on the main thread) */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) open fun updateDataInternal(newData: List<ImagePreviewDataWrapper>?) { val oldData = ArrayList(data) val handler = Handler() Thread(Runnable { val diffCallback = createDataDiffCallback(oldData, newData) val diffResult = DiffUtil.calculateDiff(diffCallback) handler.post { applyDataDiffResult(newData, diffResult) } }).start() } /** * UI thread callback to apply the diff result to the adapter * and take in the latest update */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) open fun applyDataDiffResult(newData: List<ImagePreviewDataWrapper>?, diffResult: DiffUtil.DiffResult) { if (pendingDataUpdates.isNotEmpty()) { pendingDataUpdates.remove() } //Apply the data to the view data.clear() if (newData != null) { data.addAll(newData) } diffResult.dispatchUpdatesTo(this) //Take in the next latest update if (pendingDataUpdates.isNotEmpty()) { val latestDataUpdate = pendingDataUpdates.pop() pendingDataUpdates.clear() updateDataInternal(latestDataUpdate) } } open fun createDataDiffCallback(oldData: List<ImagePreviewDataWrapper>?, newData: List<ImagePreviewDataWrapper>?): DiffUtil.Callback = ImageDiffCallback(oldData, newData) //endregion //region RecyclerView.Adapter override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImagePreviewViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.image_browser_preview_view, parent, false) return ImagePreviewViewHolder(view) } override fun onBindViewHolder(holder: ImagePreviewViewHolder, position: Int) { val item = data[position] val itemImageUrl = item.imageUrl if (holder.imageView != null) { Picasso.get() .load(itemImageUrl) .placeholder(laurenyew.imagebrowser.base.R.drawable.image_placeholder) .error(laurenyew.imagebrowser.base.R.drawable.image_placeholder) .into(holder.imageView) } holder.view.setOnClickListener { presenter?.onSelectPreview(item.id, item.imageUrl, item.imageTitle) } } override fun getItemCount(): Int = data.size //endregion }
1
null
1
1
66dde9a063ef71fc11f3a40eae61537db7af445b
4,159
InstantAppImageBrowser
Apache License 2.0
src/main/kotlin/no/nav/arbeidsgiver/iatjenester/metrikker/config/DBConfig.kt
navikt
338,342,215
false
null
package no.nav.arbeidsgiver.iatjenester.metrikker.config import com.zaxxer.hikari.HikariDataSource import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import javax.sql.DataSource @Configuration class DBConfig(private val dbConfigProperties: DBConfigProperties) { @Bean fun dataSource(): DataSource { return HikariDataSource(dbConfigProperties.hikari) } }
1
Kotlin
0
0
bc52398f394e996bf635fb773c4b0b938408cdc5
437
ia-tjenester-metrikker
MIT License
year2019/day13/game/src/main/kotlin/com/curtislb/adventofcode/year2019/day13/game/strategy/GreedyStrategy.kt
curtislb
226,797,689
false
{"Kotlin": 2014224}
package com.curtislb.adventofcode.year2019.day13.game.strategy import com.curtislb.adventofcode.year2019.day13.game.Board import com.curtislb.adventofcode.year2019.day13.game.Tile import java.math.BigInteger import kotlin.math.abs /** * A strategy that selects the move which moves the closest paddle and ball closer together. */ object GreedyStrategy : Strategy { override fun nextMove(board: Board): BigInteger { var ballX: Int? = null var paddleX: Int? = null var minDistance = Int.MAX_VALUE // Find the closest ball and paddle on the board. val balls = board.findAll(Tile.BALL) val paddles = board.findAll(Tile.PADDLE) for (ball in balls) { for (paddle in paddles) { val distance = abs(ball.x - paddle.x) if (distance < minDistance) { ballX = ball.x paddleX = paddle.x minDistance = distance } } } // Move the closest paddle towards the closest ball. return when { ballX == null || paddleX == null -> BigInteger.ZERO ballX < paddleX -> BigInteger("-1") ballX > paddleX -> BigInteger.ONE else -> BigInteger.ZERO } } }
0
Kotlin
1
1
a55341d18b4a44f05efbc9b0b9583e11d9528285
1,303
AdventOfCode
MIT License
sample/shared/src/androidMain/kotlin/com/huynn109/kmp/internetconnection/sample/InternetStatus.android.kt
huynn109
849,268,328
false
{"Kotlin": 4323}
package com.huynn109.kmp.internetconnection.sample import android.content.Context import com.huynn109.kmp.internetconnection.InternetConnection import kotlinx.coroutines.flow.MutableStateFlow actual class InternetStatus( context: Context ) { val internetConnection = InternetConnection(context) actual val current: MutableStateFlow<Boolean> = internetConnection.isNetworkConnected actual fun start() { internetConnection.start() } actual fun stop() { internetConnection.stop() } }
0
Kotlin
0
0
def735fc2633d7d347e3a25a1d48641f1eeb0883
530
kmp-internet-connection
MIT License
content/report/src/main/kotlin/br/com/mrocigno/bigbrother/report/coverter/LocalDateTimeConverter.kt
mrocigno
574,215,368
false
{"Kotlin": 296135}
package br.com.mrocigno.bigbrother.report.coverter import androidx.room.TypeConverter import org.threeten.bp.LocalDateTime internal class LocalDateTimeConverter { @TypeConverter fun toDate(date: String): LocalDateTime = LocalDateTime.parse(date) @TypeConverter fun toDateString(date: LocalDateTime): String = date.toString() }
1
Kotlin
0
3
947ba5d49dda39800a57b3979419ae502e2fe210
346
big-brother
Apache License 2.0
src/main/kotlin/com/team2898/robot/FieldMap.kt
TheFlyingHedgehogs
587,113,427
false
null
package com.team2898.robot import com.bpsrobotics.engine.utils.geometry.* import edu.wpi.first.wpilibj.DriverStation import edu.wpi.first.wpilibj2.command.SubsystemBase import com.bpsrobotics.engine.utils.ft import com.bpsrobotics.engine.utils.toMeters /** * Used to store Alliance-specific locations * @property community The community zone on the field, stored as a Polygon * @property chargingDock The alliance's charging dock, stored as a Rectangle * @property loadingBay The alliance's loading bay, stored as a Polygon * @property gridWall The line separating the scoring grid from the community zone. * */ class Map(val community : Polygon, val chargingDock : Rectangle, val loadingBay : Polygon, val gridWall : Line ) { } private val redLoadingBay = Polygon( Coordinate(0.0.ft, 18.0.ft), Coordinate(11.0.ft, 18.0.ft), Coordinate(11.0.ft, 22.048.ft), Coordinate(22.0.ft, 22.048.ft), Coordinate(22.0.ft, 26.25.ft), Coordinate(0.0.ft, 26.25.ft), ) private val blueLoadingBay = Polygon( Coordinate(4.5.ft,0.0.ft), Coordinate(4.5.ft,18.0.ft), Coordinate(11.0.ft,18.0.ft), Coordinate(11.0.ft,13.22.ft), Coordinate(16.07.ft,13.22.ft), Coordinate(16.07.ft, 0.0.ft) ) private val blueChargeStation = Rectangle( Coordinate(9.56.ft,13.05.ft), Coordinate(15.9.ft,4.95.ft) ) private val blueGridWall = Line( Coordinate(4.5.ft,0.0.ft), Coordinate(4.5.ft,18.0.ft), ) /** Map of the blue alliance side * @see Field * */ val blueTeam = Map( community = blueLoadingBay, chargingDock = blueChargeStation, loadingBay = redLoadingBay.reflectHorizontally(27.ft), gridWall = blueGridWall ) /** Map of the red alliance side * @see Field * */ val redTeam = Map( community = blueLoadingBay.reflectHorizontally(27.ft), chargingDock = blueChargeStation.reflectHorizontally(27.ft), loadingBay = redLoadingBay, gridWall = blueGridWall.reflectHorizontally(27.ft) ) /** Map of the feild based off of the Driverstation alliance * @author <NAME> * @property map Includes alliance-specific zones * */ object Field : SubsystemBase() { private var teamColor: DriverStation.Alliance = DriverStation.getAlliance() lateinit var map : Map fun initialize() { map = if (teamColor == DriverStation.Alliance.Blue) { blueTeam } else { redTeam } } }
0
Kotlin
0
1
6c4b280c449d88c93e10926a015ae4be5ecdb2c9
2,460
2898-2023-charged-up
Apache License 2.0
year2019/src/main/kotlin/net/olegg/aoc/year2019/day18/Day18.kt
0legg
110,665,187
false
null
package net.olegg.aoc.year2019.day18 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions.Companion.Neighbors4 import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.find import net.olegg.aoc.utils.get import net.olegg.aoc.utils.set import net.olegg.aoc.year2019.DayOf2019 import java.util.BitSet import java.util.PriorityQueue /** * See [Year 2019, Day 18](https://adventofcode.com/2019/day/18) */ object Day18 : DayOf2019(18) { override fun first(): Any? { val map = matrix val keys = (('a'..'z') + '@') .associateWith { checkNotNull(map.find(it)) } val routes = mutableMapOf<Char, MutableMap<Char, Pair<Int, BitSet>>>() keys.entries.forEach { (key, position) -> val queue = ArrayDeque(listOf(Triple(position, 0, BitSet(26)))) val visited = mutableSetOf(position) while (queue.isNotEmpty()) { val (curr, steps, doors) = queue.removeFirst() Neighbors4.map { it.step + curr } .filter { map[it] != '#' } .filter { it !in visited } .forEach { next -> visited += next when (val char = map[next]!!) { '.', '#' -> { queue += Triple(next, steps + 1, doors) } in 'a'..'z' -> { routes.getOrPut(key) { mutableMapOf() }[char] = steps + 1 to doors queue += Triple(next, steps + 1, doors) } in 'A'..'Z' -> { val newDoors = doors.get(0, 26).apply { set(char - 'A') } queue += Triple(next, steps + 1, newDoors) } } } } } val queue = PriorityQueue<Config>(1000, compareBy({ -it.keys.cardinality() }, { it.steps })) queue.add(Config()) val visited = mutableMapOf<Pair<Char, BitSet>, Int>() var best = Int.MAX_VALUE while (queue.isNotEmpty()) { val config = queue.poll() if (config.steps >= best) { continue } routes[config.char] .orEmpty() .asSequence() .filterNot { config.keys[it.key - 'a'] } .filter { (_, route) -> val doors = route.second return@filter (0..<26).none { doors[it] && !config.keys[it] } } .map { (next, route) -> return@map Config( char = next, steps = config.steps + route.first, keys = config.keys.get(0, 26).apply { set(next - 'a') } ) } .filter { it.steps < best } .filter { it.steps < visited.getOrDefault(it.char to it.keys, Int.MAX_VALUE) } .forEach { visited[it.char to it.keys] = it.steps if (it.keys.cardinality() == 26) { best = minOf(best, it.steps) queue.removeIf { config -> config.steps >= best } } else { queue.offer(it) } } } return best } override fun second(): Any? { val map = matrix.map { it.toMutableList() } val start = checkNotNull(map.find('@')) (-1..1).forEach { y -> (-1..1).forEach { x -> map[start + Vector2D(x, y)] = '#' } } map[start + Vector2D(-1, -1)] = '@' map[start + Vector2D(-1, 1)] = '$' map[start + Vector2D(1, -1)] = '%' map[start + Vector2D(1, 1)] = '&' val bots = "@$%&".toList() val keys = (('a'..'z') + bots) .associateWith { checkNotNull(map.find(it)) } val routes = mutableMapOf<Char, MutableMap<Char, Pair<Int, BitSet>>>() keys.entries.forEach { (key, position) -> val queue = ArrayDeque(listOf(Triple(position, 0, BitSet(26)))) val visited = mutableSetOf(position) while (queue.isNotEmpty()) { val (curr, steps, doors) = queue.removeFirst() Neighbors4.map { it.step + curr } .filter { map[it] != '#' } .filter { it !in visited } .forEach { next -> visited += next when (val char = map[next]!!) { '.', in bots -> { queue += Triple(next, steps + 1, doors) } in 'a'..'z' -> { routes.getOrPut(key) { mutableMapOf() }[char] = steps + 1 to doors queue += Triple(next, steps + 1, doors) } in 'A'..'Z' -> { val newDoors = doors.get(0, 26).apply { set(char - 'A') } queue += Triple(next, steps + 1, newDoors) } } } } } val queue = PriorityQueue<MultiConfig>(1000, compareBy({ -it.keys.cardinality() }, { it.steps })) val visited = mutableMapOf<Pair<String, BitSet>, Int>() queue.add(MultiConfig()) var best = Int.MAX_VALUE while (queue.isNotEmpty()) { val config = queue.poll() if (config.steps >= best) { continue } config.bots .toList() .flatMap { key -> routes[key].orEmpty().map { Triple(key, it.key, it.value) } } .asSequence() .filterNot { config.keys[it.second - 'a'] } .filter { (_, _, route) -> val doors = route.second return@filter (0..<26).none { doors[it] && !config.keys[it] } } .map { (curr, next, route) -> return@map MultiConfig( bots = config.bots.replace(curr, next), steps = config.steps + route.first, keys = config.keys.get(0, 26).apply { set(next - 'a') } ) } .filter { it.steps < best } .filter { it.steps < visited.getOrDefault(it.bots to it.keys, Int.MAX_VALUE) } .forEach { visited[it.bots to it.keys] = it.steps if (it.keys.cardinality() == 26) { best = minOf(best, it.steps) queue.removeIf { config -> config.steps >= best } } else { queue.offer(it) } } } return best } data class Config( val char: Char = '@', val steps: Int = 0, val keys: BitSet = BitSet(26) ) data class MultiConfig( val bots: String = "@$%&", val steps: Int = 0, val keys: BitSet = BitSet(26) ) } fun main() = SomeDay.mainify(Day18)
0
Kotlin
1
8
3006775fc2d1da3b12303029b9f35d2793c912df
6,140
adventofcode
MIT License
src/main/kotlin/me/mintdev/routing/LoginRoute.kt
marco-introini
805,907,048
false
{"Kotlin": 9780}
package me.mintdev.routing import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import me.mintdev.routing.request.LoginRequest import me.mintdev.service.JwtService fun Route.loginRoute(jwtService: JwtService) { post { val loginRequest = call.receive<LoginRequest>() val token = jwtService.createJwtToken(loginRequest) if (token != null) { call.respond(HttpStatusCode.OK, token) } else { call.respond(HttpStatusCode.Unauthorized, "Invalid credentials") } /* Versione del video token?.let { call.respond(hashMapOf("token" to it)) } ?: call.respond (HttpStatusCode.Unauthorized) */ } }
0
Kotlin
0
0
e4513331cc117c17b72bd37e0e3e8a111ef6b167
803
ktor-jwt
MIT License
src/main/kotlin/me/mintdev/routing/LoginRoute.kt
marco-introini
805,907,048
false
{"Kotlin": 9780}
package me.mintdev.routing import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import me.mintdev.routing.request.LoginRequest import me.mintdev.service.JwtService fun Route.loginRoute(jwtService: JwtService) { post { val loginRequest = call.receive<LoginRequest>() val token = jwtService.createJwtToken(loginRequest) if (token != null) { call.respond(HttpStatusCode.OK, token) } else { call.respond(HttpStatusCode.Unauthorized, "Invalid credentials") } /* Versione del video token?.let { call.respond(hashMapOf("token" to it)) } ?: call.respond (HttpStatusCode.Unauthorized) */ } }
0
Kotlin
0
0
e4513331cc117c17b72bd37e0e3e8a111ef6b167
803
ktor-jwt
MIT License
app/src/main/java/tech/salroid/filmy/data/local/model/WatchlistData.kt
salRoid
64,316,425
false
null
package tech.salroid.filmy.data.local.model data class WatchlistData @JvmOverloads constructor( var id: String, var title: String? = null, var poster: String? = null )
1
Kotlin
180
733
c6ac0c3b47964e552b8d44a0b586e1ce3b418a9a
180
Filmy
Apache License 2.0
src/main/kotlin/no/nav/pensjon/innsyn/popp/domain/support/Person.kt
navikt
191,574,968
false
{"Kotlin": 59984, "Shell": 408, "Dockerfile": 196}
package no.nav.pensjon.innsyn.popp.domain.support import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Table @Entity @Table(name = "T_PERSON") data class Person( @Id @Column(name = "PERSON_ID") val personId: Int, @Column(name = "FNR_FK") val fnr: String )
0
Kotlin
0
0
0c65a89fc4ff6583d9e0e9c4aad2adf617ad082e
362
pensjon-pol-innsyn
MIT License
app/src/main/java/com/flaxstudio/drawon/utils/ProjectRoomDatabase.kt
nitesh-dev
596,201,028
false
null
package com.flaxstudio.drawon.utils import android.content.Context import androidx.annotation.WorkerThread import androidx.room.* import kotlinx.coroutines.flow.Flow @Entity(tableName = "projects") data class Project( @PrimaryKey(autoGenerate = true) var id: Int, @ColumnInfo(name = "project_id") var projectId: String, @ColumnInfo(name = "project_bitmap_id") var projectBitmapId: String, @ColumnInfo(name = "project_name") var projectName: String, @ColumnInfo(name = "is_fav") var isFavourite: Boolean, @ColumnInfo(name = "project_created") var projectCreated: String, @ColumnInfo(name = "last_modified") var lastModified: String, @ColumnInfo(name = "whiteboard_width") var whiteboardWidth: Int, @ColumnInfo(name = "whiteboard_height") var whiteboardHeight: Int, ) { } @Dao interface ProjectDao { @Query("SELECT * FROM projects ORDER BY last_modified DESC") fun getAllProjects(): List<Project> @Query("SELECT * FROM projects WHERE is_fav = 1 ORDER BY last_modified DESC") fun getAllFavouriteProjects(): List<Project> @Query("SELECT * FROM projects WHERE project_id = :id LIMIT 1") fun getProjectById(id: String): Project @Query("UPDATE projects SET project_bitmap_id = :projectBitmapId, project_name = :projectName, is_fav = :isFavourite, last_modified = :lastModified WHERE project_id = :projectId") fun updateProject( projectId: String, projectBitmapId: String, projectName: String, isFavourite: Boolean, lastModified: String ) @Insert fun addProject(project: Project) @Delete fun deleteProject(project: Project) } class ProjectRepository(private val projectDao: ProjectDao) { @Suppress("RedundantSuspendModifier") @WorkerThread suspend fun insert(project: Project) { projectDao.addProject(project) } @WorkerThread suspend fun getAllProjects(): List<Project> { return projectDao.getAllProjects() } @WorkerThread suspend fun getAllFavouriteProjects(): List<Project>{ return projectDao.getAllFavouriteProjects() } @WorkerThread suspend fun update(project: Project) { projectDao.updateProject( project.projectId, project.projectBitmapId, project.projectName, project.isFavourite, project.lastModified ) } @WorkerThread suspend fun delete(project: Project) { projectDao.deleteProject(project) } @WorkerThread suspend fun getProjectById(projectId: String): Project { return projectDao.getProjectById(projectId) } } @Database(entities = [Project::class], version = 1, exportSchema = false) abstract class AppProjectDatabase : RoomDatabase() { abstract fun projectDao(): ProjectDao companion object { // Singleton prevents multiple instances of database opening at the // same time. @Volatile private var INSTANCE: AppProjectDatabase? = null fun getDatabase(context: Context): AppProjectDatabase { // if the INSTANCE is not null, then return it, // if it is, then create the database return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, AppProjectDatabase::class.java, "database-project" ).build() INSTANCE = instance // return instance instance } } } }
1
Kotlin
4
6
88bcb3f9f1d6913571d81d8f21009f0e7372f439
3,596
DrawOn
Apache License 2.0
src/main/kotlin/de/sambalmueslie/eventorg/event/api/EventAPI.kt
sambalmueslie
363,757,768
false
{"Kotlin": 73386, "PLpgSQL": 5480}
package de.sambalmueslie.eventorg.event.api import de.sambalmueslie.eventorg.common.CrudAPI interface EventAPI : CrudAPI<Event, EventChangeRequest> { }
0
Kotlin
0
1
f7442ed15a42dfd37f94fc87ac83e2eea6704b52
154
event-organizer-server
Apache License 2.0
projects/forge/src/main/kotlin/site/siredvin/peripheralworks/integrations/integrateddynamics/Configuration.kt
SirEdvin
489,471,520
false
{"Kotlin": 617308, "Java": 4072}
package site.siredvin.peripheralworks.integrations.integrateddynamics import net.minecraftforge.common.ForgeConfigSpec import site.siredvin.peripheralium.api.config.IConfigHandler object Configuration : IConfigHandler { private var ENABLE_VARIABLE_STORE: ForgeConfigSpec.BooleanValue? = null private var ENABLE_COMPUTER_ASPECT: ForgeConfigSpec.BooleanValue? = null val enableVariableStore: Boolean get() = ENABLE_VARIABLE_STORE?.get() ?: true val enableComputerAspect: Boolean get() = ENABLE_COMPUTER_ASPECT?.get() ?: true override val name: String get() = "integrateddynamics" override fun addToConfig(builder: ForgeConfigSpec.Builder) { ENABLE_VARIABLE_STORE = builder.comment("Enables variable store integration").define("enableVariableStore", true) ENABLE_COMPUTER_ASPECT = builder.comment("Enables computer aspect for block reader").define("enableComputerAspect", true) } }
4
Kotlin
2
7
7aafe795d2d4b852c537a7b4bcc89b26dc284231
954
UnlimitedPeripheralWorks
MIT License
unittestshared/src/main/java/io/melih/android/currencyconverter/unittestshared/TestCoroutineDispatcherProvider.kt
melomg
282,532,575
false
null
/* * Copyright 2020 CurrencyConverter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.melih.android.currencyconverter.unittestshared import io.melih.android.currencyconverter.core.CoroutineDispatcherProvider import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineDispatcher @ExperimentalCoroutinesApi class TestCoroutineDispatcherProvider : CoroutineDispatcherProvider() { val testDispatcher = TestCoroutineDispatcher() override val main: CoroutineDispatcher = testDispatcher override val io: CoroutineDispatcher = testDispatcher override val default: CoroutineDispatcher = testDispatcher }
1
Kotlin
0
0
5d94b9ce0a141403082a9157b4df19787f455bf2
1,225
currency-converter-android
Apache License 2.0
src/main/kotlin/jp/nephy/penicillin/endpoints/parameters/UserStreamFilterLevel.kt
7u4
162,947,832
true
{"Kotlin": 259979}
package jp.nephy.penicillin.endpoints.parameters enum class UserStreamFilterLevel(val value: String) { None("none"), Low("low"), Medium("medium") }
0
Kotlin
0
0
747aa281b512072d99e9b03cfe68b6c54d98b6f0
153
Penicillin
MIT License
app/src/main/java/com/rgbstudios/todomobile/data/local/CategoryDao.kt
cooncudee
673,320,875
false
{"Kotlin": 337116}
package com.rgbstudios.todomobile.data.local import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import com.rgbstudios.todomobile.data.entity.CategoryEntity import kotlinx.coroutines.flow.Flow @Dao interface CategoryDao { @Query("SELECT * FROM categories") fun getCategories(): Flow<List<CategoryEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertCategory(category: CategoryEntity) @Update suspend fun updateCategory(category: CategoryEntity): Int @Query("DELETE FROM categories WHERE categoryId = :categoryId") suspend fun deleteCategory(categoryId: String): Int @Query("DELETE FROM categories") suspend fun deleteAllCategories(): Int @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAllCategories(categories: List<CategoryEntity>): List<Long> }
0
Kotlin
0
2
2fee10f774058bab2f6be4eff2707b953a339c40
941
TODO_Mobile
MIT License
plugins/full-line/src/org/jetbrains/completion/full/line/platform/diagnostics/DiagnosticsLogConsole.kt
xGreat
182,651,778
false
{"Text": 7190, "INI": 570, "YAML": 416, "Ant Build System": 10, "Batchfile": 28, "Shell": 616, "Markdown": 680, "Ignore List": 125, "Git Revision List": 1, "Git Attributes": 10, "EditorConfig": 244, "XML": 7188, "SVG": 3739, "Kotlin": 48905, "Java": 80666, "HTML": 3312, "Java Properties": 214, "Gradle": 419, "Maven POM": 82, "JavaScript": 212, "CSS": 69, "JFlex": 32, "JSON": 1374, "Groovy": 3308, "XSLT": 113, "desktop": 1, "Python": 15070, "JAR Manifest": 18, "PHP": 47, "Gradle Kotlin DSL": 477, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Diff": 135, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 1, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 27, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 67, "GraphQL": 60, "OpenStep Property List": 47, "Tcl": 1, "Dockerfile": 5, "fish": 1, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 5, "XML Property List": 81, "Starlark": 2, "E-mail": 18, "Roff": 38, "Roff Manpage": 2, "Swift": 3, "C": 84, "TOML": 153, "Proguard": 2, "PlantUML": 6, "Checksums": 72, "Java Server Pages": 8, "reStructuredText": 68, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 17, "C++": 32, "Handlebars": 1, "Rust": 9, "Makefile": 1, "Go": 34, "Go Checksums": 1, "Go Module": 1, "VBScript": 1, "NSIS": 5, "Thrift": 3, "Cython": 12, "Regular Expression": 3, "JSON5": 4}
package org.jetbrains.completion.full.line.platform.diagnostics import com.intellij.diagnostic.logging.DefaultLogFilterModel import com.intellij.diagnostic.logging.LogConsoleBase import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.ToolWindowManager import com.intellij.util.text.DateFormatUtil import org.jetbrains.completion.full.line.settings.MLServerCompletionBundle.Companion.message import java.io.File class DiagnosticsLogConsole(private val project: Project) : LogConsoleBase(project, null, message("full.line.diagnostics.tab.title"), true, DefaultLogFilterModel(project)), BaseLogConsole { override fun isActive(): Boolean { return ToolWindowManager.getInstance(project).getToolWindow(FULL_LINE_TOOL_WINDOW_ID)?.isVisible ?: false } override fun addMessage(message: DiagnosticsListener.Message) { val msg = prepareMessage(message) super.addMessage(msg) } override fun dispose() { storeLog(originalDocument?.toString()) super.dispose() } } class InMemoryLogConsole : BaseLogConsole { val content = StringBuilder() override fun addMessage(message: DiagnosticsListener.Message) { val msg = prepareMessage(message) content.append(msg).append("\n") } override fun dispose() { storeLog(content.toString()) } } interface BaseLogConsole : Disposable { fun addMessage(message: DiagnosticsListener.Message) fun prepareMessage(message: DiagnosticsListener.Message): String { val time = DateFormatUtil.formatTime(message.time) val part = message.part.toString().padStart(PAD_COUNT) return "[ $time | $part ] ${message.text}" } fun storeLog(content: String?) { Registry.get("full.line.diagnostics.file").asString().takeIf { it.isNotEmpty() }?.let { val logFile = File(it) if (!logFile.exists()) logFile.createNewFile() content?.let(logFile::appendText) } } private companion object { val PAD_COUNT = FullLinePart.values().maxOf { it.name.length } } }
1
null
1
1
fb5f23167ce9cc53bfa3ee054b445cf4d8f1ce98
2,083
intellij-community
Apache License 2.0
src/main/kotlin/com/dude/dms/backend/repositories/DocFilterRepository.kt
axelvondreden
208,427,538
false
null
package com.dude.dms.backend.repositories import com.dude.dms.backend.data.filter.DocFilter import org.springframework.data.jpa.repository.JpaRepository interface DocFilterRepository : JpaRepository<DocFilter, Long> { fun findByName(name: String): DocFilter? }
46
Kotlin
1
3
418c7df3589b85c934f0da13642f14aa4c66a851
267
dms
Apache License 2.0
app/src/main/java/com/igomezal/calculoaristachimenea/repository/AppDatabase.kt
igomezal
148,942,985
false
{"Kotlin": 19495}
package com.igomezal.calculoaristachimenea.repository import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.igomezal.calculoaristachimenea.util.SingletonHolder import com.igomezal.calculoaristachimenea.repository.entities.Chimenea import com.igomezal.calculoaristachimenea.repository.entities.ChimeneaDAO @Database(entities = [Chimenea::class], version = 1) abstract class AppDatabase: RoomDatabase() { abstract fun chimeneaDao(): ChimeneaDAO companion object: SingletonHolder<AppDatabase, Context>({ Room.databaseBuilder(it.applicationContext, AppDatabase::class.java, "calc-arista-chimenea") .build() }) }
0
Kotlin
0
0
781eb2ed97ddaa2be16169d787464d22b4d6f3c5
724
CalculoAristaChimenea
MIT License
app/src/main/java/com/stocksexchange/android/ui/dashboard/DashboardPresenter.kt
nscoincommunity
277,168,471
true
{"Kotlin": 2814235}
package com.stocksexchange.android.ui.dashboard import com.stocksexchange.android.BuildConfig import com.stocksexchange.android.events.SettingsEvent import com.stocksexchange.android.events.UserEvent import com.stocksexchange.android.model.DashboardArgs import com.stocksexchange.android.model.DashboardBottomMenuItem import com.stocksexchange.android.model.Settings import com.stocksexchange.android.model.VerificationPromptDescriptionType import com.stocksexchange.android.ui.base.mvp.model.StubModel import com.stocksexchange.android.ui.base.mvp.presenters.BasePresenter import com.stocksexchange.android.utils.SavedState import com.stocksexchange.android.utils.extensions.extract import com.stocksexchange.android.utils.managers.SessionManager import com.stocksexchange.core.utils.interfaces.Selectable import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode class DashboardPresenter( view: DashboardContract.View, model: StubModel, private val sessionManager: SessionManager ) : BasePresenter<DashboardContract.View, StubModel>(view, model), DashboardContract.ActionListener { lateinit var dashboardArgs: DashboardArgs var isBottomNavigationVisible: Boolean = true override fun start() { super.start() if(shouldLaunchVerificationPromptActivity()) { launchVerificationPromptActivity() } } private fun shouldLaunchVerificationPromptActivity(): Boolean { val isRelease = !BuildConfig.DEBUG val isUserSignedIn = sessionManager.isUserSignedIn() val isUserNotVerified = (sessionManager.getProfileInfo()?.isVerified() == false) val wasVerificationPromptNotDisplayed = !sessionManager.wasVerificationPromptDisplayed() return (isUserSignedIn && isUserNotVerified && wasVerificationPromptNotDisplayed) } private fun launchVerificationPromptActivity() { sessionManager.setVerificationPromptDisplayed(true) val profileInfo = sessionManager.getProfileInfo() val areWithdrawalsAllowed = (profileInfo?.areWithdrawalsAllowed == true) val descriptionType = if(areWithdrawalsAllowed) { VerificationPromptDescriptionType.LONG } else { VerificationPromptDescriptionType.SHORT } mView.launchVerificationPromptActivity(descriptionType) } override fun onNavigationItemSelected(id: Int): Boolean { val userRequiredPages = DashboardBottomMenuItem.values().filter { it.requiresUser } for(userRequiredPage in userRequiredPages) { if((id == userRequiredPage.id) && !sessionManager.isUserSignedIn()) { mView.launchLoginActivity(DashboardArgs(selectedBottomMenuItem = userRequiredPage)) return false } } val newSelectedBottomMenuItem = DashboardBottomMenuItem.values().firstOrNull { it.id == id } if(newSelectedBottomMenuItem != null) { dashboardArgs = dashboardArgs.copy(selectedBottomMenuItem = newSelectedBottomMenuItem) } val viewPagerNewItemPosition = convertBottomNavItemIdToViewPagerItemPosition(id) val viewPagerCurrentItemPosition = mView.getViewPagerCurrentItemPosition() if(viewPagerNewItemPosition != viewPagerCurrentItemPosition) { mView.setPageSelected(viewPagerCurrentItemPosition, false, Selectable.Source.MENU) mView.setViewPagerCurrentItemPosition(viewPagerNewItemPosition, false) mView.setPageSelected(viewPagerNewItemPosition, true, Selectable.Source.MENU) } return true } override fun onNavigationItemReselected(id: Int) { val viewPagerItemPosition = convertBottomNavItemIdToViewPagerItemPosition(id) if(!mView.isViewPagerAdapterEmpty()) { mView.setPageSelected(viewPagerItemPosition, true, Selectable.Source.MENU) mView.scrollPageToTop(viewPagerItemPosition) } } private fun convertBottomNavItemIdToViewPagerItemPosition(id: Int): Int { return DashboardBottomMenuItem.values() .firstOrNull { it.id == id }?.ordinal ?: DashboardBottomMenuItem.BALANCE.ordinal } private fun restartActivity(dashboardArgs: DashboardArgs) { mView.restartActivity(dashboardArgs) } private fun restartActivityAnew() { restartActivity(DashboardArgs()) } override fun onShowBottomNavigation() { if(!isBottomNavigationVisible) { isBottomNavigationVisible = true mView.showBottomNavigation() } } override fun onHideBottomNavigation() { if(isBottomNavigationVisible) { isBottomNavigationVisible = false mView.hideBottomNavigation() } } @Suppress("NON_EXHAUSTIVE_WHEN") @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(event: SettingsEvent) { if(event.isOriginatedFrom(this)) { return } val newSettings = event.attachment when(event.action) { SettingsEvent.Action.LANGUAGE_CHANGED -> onLanguageChanged() SettingsEvent.Action.FIAT_CURRENCY_CHANGED -> onFiatCurrencyChanged(newSettings) SettingsEvent.Action.THEME_CHANGED -> onThemeChanged(newSettings) SettingsEvent.Action.DEFAULTS_RESTORED -> onDefaultsRestored() SettingsEvent.Action.GROUPING_STATE_CHANGED -> onGroupingStateChanged(newSettings) SettingsEvent.Action.GROUPING_SEPARATOR_CHANGED -> onGroupingSeparatorChanged(newSettings) SettingsEvent.Action.DECIMAL_SEPARATOR_CHANGED -> onDecimalSeparatorChanged(newSettings) } } private fun onLanguageChanged() { restartActivityAnew() } private fun onFiatCurrencyChanged(newSettings: Settings) { notifyPagesAboutSettingsChange(newSettings) } private fun onThemeChanged(newSettings: Settings) { mView.applyNewTheme(newSettings.theme) notifyPagesAboutSettingsChange(newSettings) } private fun onDefaultsRestored() { restartActivityAnew() } private fun onGroupingStateChanged(newSettings: Settings) { notifyPagesAboutSettingsChange(newSettings) } private fun onGroupingSeparatorChanged(newSettings: Settings) { notifyPagesAboutSettingsChange(newSettings) } private fun onDecimalSeparatorChanged(newSettings: Settings) { notifyPagesAboutSettingsChange(newSettings) } private fun notifyPagesAboutSettingsChange(newSettings: Settings) { val pagePositions = DashboardBottomMenuItem.values() .filter { it != DashboardBottomMenuItem.PROFILE } .map { it.ordinal } for(pagePosition in pagePositions) { mView.notifyPageAboutSettingsChange(pagePosition, newSettings) } } @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(event: UserEvent) { if(event.isOriginatedFrom(this)) { return } when(event.action) { UserEvent.Action.SIGNED_OUT -> onUserSignedOut() } } private fun onUserSignedOut() { restartActivity(DashboardArgs(dashboardArgs.selectedBottomMenuItem)) } override fun canReceiveEvents(): Boolean = true override fun onRestoreState(savedState: SavedState) { super.onRestoreState(savedState) savedState.extract(presenterStateExtractor).also { isBottomNavigationVisible = it.isBottomNavigationVisible dashboardArgs = it.dashboardArgs } } override fun onSaveState(savedState: SavedState) { super.onSaveState(savedState) savedState.saveState(PresenterState( isBottomNavigationVisible = isBottomNavigationVisible, dashboardArgs = dashboardArgs )) } }
0
null
0
0
52766afab4f96506a2d9ed34bf3564b6de7af8c3
7,887
Android-app
MIT License
app/src/main/java/com/kylecorry/trail_sense/tools/weather/infrastructure/commands/CurrentWeatherAlertCommand.kt
kylecorry31
215,154,276
false
{"Kotlin": 2589968, "Python": 22919, "HTML": 18863, "Shell": 5290, "CSS": 5120, "JavaScript": 3814, "Batchfile": 2553}
package com.kylecorry.trail_sense.tools.weather.infrastructure.commands import android.content.Context import com.kylecorry.trail_sense.shared.FormatService import com.kylecorry.trail_sense.shared.UserPreferences import com.kylecorry.trail_sense.shared.alerts.IValueAlerter import com.kylecorry.trail_sense.shared.commands.generic.Command import com.kylecorry.trail_sense.tools.weather.domain.CurrentWeather import com.kylecorry.trail_sense.tools.weather.infrastructure.IWeatherPreferences import com.kylecorry.trail_sense.tools.weather.infrastructure.alerts.CurrentWeatherAlerter internal class CurrentWeatherAlertCommand( private val prefs: IWeatherPreferences, private val alerter: IValueAlerter<CurrentWeather> ) : Command<CurrentWeather> { override fun execute(weather: CurrentWeather) { if (prefs.shouldMonitorWeather) { alerter.alert(weather) } } companion object { fun create(context: Context): CurrentWeatherAlertCommand { val prefs = UserPreferences(context) return CurrentWeatherAlertCommand( prefs.weather, CurrentWeatherAlerter( context, FormatService.getInstance(context), prefs.pressureUnits, prefs.temperatureUnits, prefs.weather ) ) } } }
456
Kotlin
66
989
41176d17b498b2dcecbbe808fbe2ac638e90d104
1,411
Trail-Sense
MIT License
app/src/main/java/com/example/scrambletogether/presentation/ui/common/NoBorderButton.kt
ArkhamDm
731,165,119
false
{"Kotlin": 125327}
package com.example.scrambletogether.presentation.ui.common import androidx.compose.foundation.layout.RowScope import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Shape @Composable fun NoBorderButton( modifier: Modifier = Modifier, onClick: () -> Unit, shape: Shape = ButtonDefaults.shape, content: @Composable (RowScope.() -> Unit) ) { Button( onClick = onClick, modifier = modifier, border = null, shape = shape, content = content ) }
0
Kotlin
0
0
2da5eaeb51dc80f153877bc196085dbd4bf87cdc
655
WordleTogether
MIT License
identity/ui/src/main/java/com/thechance/identity/ui/screen/activation/AccountActivationRoute.kt
Salmon-family
569,890,321
false
{"Kotlin": 837143}
package com.thechance.identity.ui.screen.activation import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.compose.composable fun NavController.navigateToAccountActivation() { navigate(route = ACCOUNT_ACTIVATION_Route) { launchSingleTop = true } } const val ACCOUNT_ACTIVATION_Route = "accountActivationScreen" fun NavGraphBuilder.accountActivationRoute(navHostController: NavHostController) { composable(ACCOUNT_ACTIVATION_Route) { AccountActivationScreen( navHostController ) } }
11
Kotlin
19
24
7589d73a400c78ecfa94b24d87189b4f5e01de9b
638
Clubs
Apache License 2.0
app/src/main/java/com/frogobox/movie/mvvm/movie/SearchMovieViewModel.kt
frogobox
221,978,119
false
{"Kotlin": 246872}
package com.frogobox.movie.mvvm.movie import android.app.Application import com.frogobox.base.BaseViewModel import com.frogobox.base.source.model.Movie import com.frogobox.base.source.DataSource import com.frogobox.base.source.Repository import com.frogobox.base.util.SingleLiveEvent /** * Created by <NAME> * FrogoBox Inc License * ========================================= * movie * Copyright (C) 16/11/2019. * All rights reserved * ----------------------------------------- * Name : <NAME> * E-mail : <EMAIL> * Github : github.com/amirisback * LinkedIn : linkedin.com/in/faisalamircs * ----------------------------------------- * FrogoBox Software Industries * com.frogobox.movie.viewmodel * */ class SearchMovieViewModel(private val context: Application, private val repository: Repository) : BaseViewModel(context) { var movieListLive = SingleLiveEvent<List<Movie>>() fun searchMovies(query: String) { repository.searchMovies(query, object : DataSource.GetRemoteCallback<List<Movie>> { override fun onEmpty() { } override fun onShowProgressDialog() { eventShowProgress.postValue(true) } override fun onHideProgressDialog() { eventShowProgress.postValue(false) } override fun onSuccess(data: List<Movie>) { movieListLive.postValue(data) } override fun onFinish() { } override fun onFailed(statusCode: Int, errorMessage: String?) { } }) } }
0
Kotlin
2
16
8cb6e3c49650be2dfe586570d44dd76c207a4598
1,604
kick-start-android-modular
Apache License 2.0
src/test/kotlin/net/jp/vss/sample/usecase/tasks/UpdateTaskUseCaseParameterTest.kt
nemuzuka
184,200,566
false
null
package net.jp.vss.sample.usecase.tasks import net.jp.vss.sample.DatetimeUtils import net.jp.vss.sample.domain.Attributes import net.jp.vss.sample.domain.tasks.TaskFixtures import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test /** * UpdateTaskUseCaseParameter のテスト. */ class UpdateTaskUseCaseParameterTest { companion object { const val NOW = 1545368400001L } @BeforeEach fun setUp() { DatetimeUtils.setDummyDatetimeResource(NOW) } @AfterEach fun tearDown() { DatetimeUtils.clearDummyDatetimeResource() } @Test fun buildUpdateTaskTest() { // setup val task = TaskFixtures.create() val sut = UpdateTaskUseCaseParameterFixture.create() // execution val actual = sut.buildUpdateTask(task) // verify val baseTaskDetail = task.taskDetail val updateDeadline = sut.deadline val taskDetail = baseTaskDetail.copy( title = sut.title!!, content = sut.content!!, deadline = updateDeadline, attributes = Attributes(sut.attributes!!) ) val expected = task.copy( taskDetail = taskDetail, resourceAttributes = task.resourceAttributes.buildForUpdate(sut.updateUserCode)) assertThat(actual).isEqualTo(expected) } @Test fun buildUpdateTaskTest_NullValue() { // setup val task = TaskFixtures.create() val sut = UpdateTaskUseCaseParameterFixture.createNullValue(false) // execution val actual = sut.buildUpdateTask(task) // verify val baseTaskDetail = task.taskDetail val taskDetail = baseTaskDetail.copy( title = baseTaskDetail.title, content = baseTaskDetail.content, deadline = baseTaskDetail.deadline, attributes = baseTaskDetail.attributes ) val expected = task.copy( taskDetail = taskDetail, resourceAttributes = task.resourceAttributes.buildForUpdate(sut.updateUserCode)) assertThat(actual).isEqualTo(expected) } @Test fun buildUpdateTaskTest_SetDeadlineToNull() { // setup val task = TaskFixtures.create() val sut = UpdateTaskUseCaseParameterFixture.createNullValue(true) // execution val actual = sut.buildUpdateTask(task) // verify val baseTaskDetail = task.taskDetail val taskDetail = baseTaskDetail.copy( title = baseTaskDetail.title, content = baseTaskDetail.content, deadline = null, // null を設定する事 attributes = baseTaskDetail.attributes ) val expected = task.copy( taskDetail = taskDetail, resourceAttributes = task.resourceAttributes.buildForUpdate(sut.updateUserCode)) assertThat(actual).isEqualTo(expected) } }
18
Kotlin
0
0
ef8ed4626d2cd1dbbd3455534fedf67940a32361
3,013
spring-kotlin-sample
Apache License 2.0
andreact/src/main/java/chx/studio/andreact/Element.kt
chx-studio
134,814,866
false
{"Kotlin": 19726, "Java": 1107}
package chx.studio.andreact import android.content.Context import android.util.Log import android.view.View abstract class Element(open var widget: Widget) { var depth = 1 var dirty = true abstract fun createView(context: Context): View fun rebuild() { if (!dirty) return performRebuild() dirty = false } abstract fun performRebuild() fun markNeedsBuild(buildContext: BuildContext) { dirty = true buildContext.scheduleBuildFor(this) } companion object { val comparator = Comparator<Element> { a, b -> when (true) { a.depth > b.depth -> 1 a.depth < b.depth -> -1 a.dirty && !b.dirty -> 1 !a.dirty && b.dirty -> -1 else -> 0 } } } }
0
Kotlin
0
2
99f629f1653b3e83289720e60b8b376559701239
837
andreact
Apache License 2.0
src/commonMain/kotlin/kr/jadekim/logger/context/LogContext.kt
jdekim43
222,454,147
false
{"Gradle Kotlin DSL": 10, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java": 4, "Kotlin": 30}
package kr.jadekim.logger.context import co.touchlab.stately.collections.SharedHashMap import co.touchlab.stately.concurrency.ThreadLocalRef interface LogContext : Map<String, Any?> { operator fun plus(other: LogContext?): LogContext fun clone(): LogContext = LogContext(toMap()) fun toImmutable(): LogContext = LogContext(toMap()) fun toMutable(): MutableLogContext = MutableLogContext(toMutableMap()) } internal class LogContextImpl(data: Map<String, Any?>) : LogContext, Map<String, Any?> by data { override fun plus(other: LogContext?): LogContext = if (other == null) this else { LogContext((this as Map<String, Any?>).plus(other)) } } fun LogContext(data: Map<String, Any?>): LogContext = LogContextImpl(data) object EmptyLogContext : LogContext by LogContext(emptyMap()) interface MutableLogContext : LogContext, MutableMap<String, Any?> { override operator fun plus(other: LogContext?): MutableLogContext = if (other == null) clone() else { val data = mutableMapOf<String, Any?>() data.putAll(this) data.putAll(other) MutableLogContext(data) } operator fun plusAssign(other: LogContext?) { if (other != null) { putAll(other) } } fun snap() = LogContext(toMap()) override fun clone(): MutableLogContext = MutableLogContext(toMutableMap()) } internal class MutableLogContextImpl( data: MutableMap<String, Any?>, ) : MutableLogContext, MutableMap<String, Any?> by SharedHashMap() { init { putAll(data) } } fun MutableLogContext(data: MutableMap<String, Any?> = mutableMapOf()): MutableLogContext = MutableLogContextImpl(data) object GlobalLogContext : MutableLogContext by MutableLogContext() object ThreadLogContext : MutableLogContext { private val threadLocal = ThreadLocalRef<MutableLogContext>() private val data: MutableLogContext get() { var data: MutableLogContext? = threadLocal.get() if (data == null) { data = MutableLogContext() threadLocal.set(data) } return data } override val entries: MutableSet<MutableMap.MutableEntry<String, Any?>> get() = data.entries override val keys: MutableSet<String> get() = data.keys override val size: Int get() = data.size override val values: MutableCollection<Any?> get() = data.values override fun containsKey(key: String): Boolean = data.containsKey(key) override fun containsValue(value: Any?): Boolean = data.containsValue(value) override fun get(key: String): Any? = data[key] override fun isEmpty(): Boolean = data.isEmpty() override fun clear() = data.clear() override fun put(key: String, value: Any?): Any? = data.put(key, value) override fun putAll(from: Map<out String, Any?>) = data.putAll(from) override fun remove(key: String): Any? = data.remove(key) }
1
null
1
1
93ed846e0712322f5d16993470875467e33dc823
2,982
j-logger
Apache License 2.0
shared/src/commonMain/kotlin/com/renting/app/core/auth/repository/external/RegistrationRequest.kt
vitalir2
603,790,041
false
null
package com.renting.app.core.auth.repository.external import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal class RegistrationRequest( @SerialName("username") val login: String, @SerialName("password") val password: String, @SerialName("email") val email: String, @SerialName("phoneNumber") val phoneNumber: String, @SerialName("firstName") val firstName: String, @SerialName("lastName") val lastName: String, )
1
Kotlin
0
0
415330e3bf70581a612ab9bda32ccc2094376d53
513
renting-mobile
Apache License 2.0
src/main/kotlin/io/framed/model/bpmn/model/BpmnTask.kt
pixix4
180,147,298
false
null
package io.framed.model.bpmn.model import io.framed.model.bpmn.xml.XmlElement class BpmnTask( override val id: String, override val name: String, override var parent: BpmnElement? ) : BpmnFlowObject { companion object { fun parse(xml: XmlElement, parent: BpmnElement?) = BpmnTask(xml["id"], xml["name"], parent) } }
0
Kotlin
0
0
99095e08c0377c5647da4b546e2c0ed61a099604
358
bpmn-bros-verifier
MIT License
tiltak/src/test/kotlin/no/nav/amt/tiltak/tiltak/services/GjennomforingServiceImplTest.kt
navikt
393,356,849
false
null
package no.nav.amt.tiltak.tiltak.services import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.mockk.every import io.mockk.mockk import no.nav.amt.tiltak.core.domain.tiltak.Deltaker import no.nav.amt.tiltak.core.domain.tiltak.DeltakerStatus import no.nav.amt.tiltak.core.domain.tiltak.Gjennomforing import no.nav.amt.tiltak.core.kafka.KafkaProducerService import no.nav.amt.tiltak.core.port.ArrangorService import no.nav.amt.tiltak.core.port.DeltakerService import no.nav.amt.tiltak.core.port.NavEnhetService import no.nav.amt.tiltak.core.port.TiltakService import no.nav.amt.tiltak.deltaker.repositories.DeltakerRepository import no.nav.amt.tiltak.deltaker.repositories.DeltakerStatusRepository import no.nav.amt.tiltak.deltaker.service.BrukerService import no.nav.amt.tiltak.deltaker.service.DeltakerServiceImpl import no.nav.amt.tiltak.test.database.DbTestDataUtils import no.nav.amt.tiltak.test.database.SingletonPostgresContainer import no.nav.amt.tiltak.test.database.data.TestData.ARRANGOR_1 import no.nav.amt.tiltak.test.database.data.TestData.BRUKER_1 import no.nav.amt.tiltak.test.database.data.TestData.DELTAKER_1 import no.nav.amt.tiltak.test.database.data.TestData.DELTAKER_1_STATUS_1 import no.nav.amt.tiltak.test.database.data.TestData.GJENNOMFORING_1 import no.nav.amt.tiltak.test.database.data.TestData.NAV_ANSATT_1 import no.nav.amt.tiltak.test.database.data.TestData.NAV_ENHET_1 import no.nav.amt.tiltak.test.database.data.TestData.TILTAK_1 import no.nav.amt.tiltak.test.database.data.TestDataRepository import no.nav.amt.tiltak.tiltak.repositories.GjennomforingRepository import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.jdbc.datasource.DataSourceTransactionManager import org.springframework.transaction.support.TransactionTemplate import java.time.LocalDateTime import java.util.* class GjennomforingServiceImplTest : FunSpec({ val dataSource = SingletonPostgresContainer.getDataSource() lateinit var gjennomforingRepository: GjennomforingRepository lateinit var testDataRepository: TestDataRepository lateinit var deltakerService: DeltakerService lateinit var arrangorService: ArrangorService lateinit var tiltakService: TiltakService lateinit var brukerService: BrukerService lateinit var navEnhetService: NavEnhetService lateinit var kafkaProducerService: KafkaProducerService lateinit var service: GjennomforingServiceImpl beforeEach { val parameterTemplate = NamedParameterJdbcTemplate(dataSource) val transactionTemplate = TransactionTemplate(DataSourceTransactionManager(dataSource)) gjennomforingRepository = GjennomforingRepository(parameterTemplate) testDataRepository = TestDataRepository(parameterTemplate) deltakerService = mockk() arrangorService = mockk() tiltakService = mockk() brukerService = mockk() navEnhetService = mockk() kafkaProducerService = mockk(relaxUnitFun = true) service = GjennomforingServiceImpl( gjennomforingRepository = gjennomforingRepository, tiltakService = tiltakService, deltakerService = DeltakerServiceImpl( DeltakerRepository(parameterTemplate), DeltakerStatusRepository(parameterTemplate), brukerService, mockk(), mockk(), transactionTemplate, kafkaProducerService ), arrangorService = arrangorService, transactionTemplate = transactionTemplate, ) DbTestDataUtils.cleanDatabase(dataSource) } test("slettGjennomforing - skal slette gjennomføring") { testDataRepository.insertNavEnhet(NAV_ENHET_1) testDataRepository.insertTiltak(TILTAK_1) testDataRepository.insertArrangor(ARRANGOR_1) testDataRepository.insertGjennomforing(GJENNOMFORING_1) testDataRepository.insertNavAnsatt(NAV_ANSATT_1) testDataRepository.insertBruker(BRUKER_1) testDataRepository.insertDeltaker(DELTAKER_1) testDataRepository.insertDeltakerStatus(DELTAKER_1_STATUS_1) every { deltakerService.slettDeltaker(any()) } returns Unit every { navEnhetService.getNavEnhet(any<UUID>()) } returns NAV_ENHET_1.toNavEnhet() every { deltakerService.hentDeltakerePaaGjennomforing(GJENNOMFORING_1.id) } returns listOf( Deltaker( id = DELTAKER_1.id, fornavn = "Fornavn2", mellomnavn = null, etternavn = "Etternavn", personIdent = "12121231123", navEnhetId = null, navVeilederId = null, epost = "<EMAIL>", telefonnummer = "1234", startDato = null, sluttDato = null, status = DeltakerStatus( UUID.randomUUID(), DeltakerStatus.Type.VENTER_PA_OPPSTART, null, LocalDateTime.now(), LocalDateTime.now(), true ), registrertDato = LocalDateTime.now(), dagerPerUke = null, prosentStilling = null, gjennomforingId = UUID.randomUUID(), erSkjermet = false )) gjennomforingRepository.get(GJENNOMFORING_1.id) shouldNotBe null service.slettGjennomforing(GJENNOMFORING_1.id) gjennomforingRepository.get(GJENNOMFORING_1.id) shouldBe null } test("getGjennomforing - gjennomføring finnes - returnerer gjennomføring") { testDataRepository.insertNavEnhet(NAV_ENHET_1) testDataRepository.insertTiltak(TILTAK_1) testDataRepository.insertArrangor(ARRANGOR_1) testDataRepository.insertGjennomforing(GJENNOMFORING_1) val tiltakInserted = TILTAK_1.toTiltak() val arrangorInserted = ARRANGOR_1.toArrangor() every { arrangorService.getArrangorById(ARRANGOR_1.id) } returns arrangorInserted every { tiltakService.getTiltakById(TILTAK_1.id) } returns tiltakInserted val gjennomforing = service.getGjennomforing(GJENNOMFORING_1.id) GJENNOMFORING_1.toGjennomforing(tiltakInserted, arrangorInserted) shouldBe gjennomforing } test("getByLopenummer - returnerer alle gjennomføringer, uansett status") { testDataRepository.insertNavEnhet(NAV_ENHET_1) testDataRepository.insertTiltak(TILTAK_1) testDataRepository.insertArrangor(ARRANGOR_1) testDataRepository.insertGjennomforing(GJENNOMFORING_1) val avsluttetGjennomforing = GJENNOMFORING_1.copy(id = UUID.randomUUID(), status = Gjennomforing.Status.AVSLUTTET.name) testDataRepository.insertGjennomforing(avsluttetGjennomforing) val tiltakInserted = TILTAK_1.toTiltak() val arrangorInserted = ARRANGOR_1.toArrangor() val lopenr = GJENNOMFORING_1.lopenr every { arrangorService.getArrangorById(ARRANGOR_1.id) } returns arrangorInserted every { tiltakService.getTiltakById(TILTAK_1.id) } returns tiltakInserted val expectedIds = listOf(GJENNOMFORING_1.id, avsluttetGjennomforing.id) service.getByLopenr(lopenr).map { it.id } shouldContainAll expectedIds } })
4
Kotlin
3
3
59ebfd42eb4b8bcea2350e501058584fb80287b9
6,714
amt-tiltak
MIT License
tiltak/src/test/kotlin/no/nav/amt/tiltak/tiltak/services/GjennomforingServiceImplTest.kt
navikt
393,356,849
false
null
package no.nav.amt.tiltak.tiltak.services import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.mockk.every import io.mockk.mockk import no.nav.amt.tiltak.core.domain.tiltak.Deltaker import no.nav.amt.tiltak.core.domain.tiltak.DeltakerStatus import no.nav.amt.tiltak.core.domain.tiltak.Gjennomforing import no.nav.amt.tiltak.core.kafka.KafkaProducerService import no.nav.amt.tiltak.core.port.ArrangorService import no.nav.amt.tiltak.core.port.DeltakerService import no.nav.amt.tiltak.core.port.NavEnhetService import no.nav.amt.tiltak.core.port.TiltakService import no.nav.amt.tiltak.deltaker.repositories.DeltakerRepository import no.nav.amt.tiltak.deltaker.repositories.DeltakerStatusRepository import no.nav.amt.tiltak.deltaker.service.BrukerService import no.nav.amt.tiltak.deltaker.service.DeltakerServiceImpl import no.nav.amt.tiltak.test.database.DbTestDataUtils import no.nav.amt.tiltak.test.database.SingletonPostgresContainer import no.nav.amt.tiltak.test.database.data.TestData.ARRANGOR_1 import no.nav.amt.tiltak.test.database.data.TestData.BRUKER_1 import no.nav.amt.tiltak.test.database.data.TestData.DELTAKER_1 import no.nav.amt.tiltak.test.database.data.TestData.DELTAKER_1_STATUS_1 import no.nav.amt.tiltak.test.database.data.TestData.GJENNOMFORING_1 import no.nav.amt.tiltak.test.database.data.TestData.NAV_ANSATT_1 import no.nav.amt.tiltak.test.database.data.TestData.NAV_ENHET_1 import no.nav.amt.tiltak.test.database.data.TestData.TILTAK_1 import no.nav.amt.tiltak.test.database.data.TestDataRepository import no.nav.amt.tiltak.tiltak.repositories.GjennomforingRepository import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.jdbc.datasource.DataSourceTransactionManager import org.springframework.transaction.support.TransactionTemplate import java.time.LocalDateTime import java.util.* class GjennomforingServiceImplTest : FunSpec({ val dataSource = SingletonPostgresContainer.getDataSource() lateinit var gjennomforingRepository: GjennomforingRepository lateinit var testDataRepository: TestDataRepository lateinit var deltakerService: DeltakerService lateinit var arrangorService: ArrangorService lateinit var tiltakService: TiltakService lateinit var brukerService: BrukerService lateinit var navEnhetService: NavEnhetService lateinit var kafkaProducerService: KafkaProducerService lateinit var service: GjennomforingServiceImpl beforeEach { val parameterTemplate = NamedParameterJdbcTemplate(dataSource) val transactionTemplate = TransactionTemplate(DataSourceTransactionManager(dataSource)) gjennomforingRepository = GjennomforingRepository(parameterTemplate) testDataRepository = TestDataRepository(parameterTemplate) deltakerService = mockk() arrangorService = mockk() tiltakService = mockk() brukerService = mockk() navEnhetService = mockk() kafkaProducerService = mockk(relaxUnitFun = true) service = GjennomforingServiceImpl( gjennomforingRepository = gjennomforingRepository, tiltakService = tiltakService, deltakerService = DeltakerServiceImpl( DeltakerRepository(parameterTemplate), DeltakerStatusRepository(parameterTemplate), brukerService, mockk(), mockk(), transactionTemplate, kafkaProducerService ), arrangorService = arrangorService, transactionTemplate = transactionTemplate, ) DbTestDataUtils.cleanDatabase(dataSource) } test("slettGjennomforing - skal slette gjennomføring") { testDataRepository.insertNavEnhet(NAV_ENHET_1) testDataRepository.insertTiltak(TILTAK_1) testDataRepository.insertArrangor(ARRANGOR_1) testDataRepository.insertGjennomforing(GJENNOMFORING_1) testDataRepository.insertNavAnsatt(NAV_ANSATT_1) testDataRepository.insertBruker(BRUKER_1) testDataRepository.insertDeltaker(DELTAKER_1) testDataRepository.insertDeltakerStatus(DELTAKER_1_STATUS_1) every { deltakerService.slettDeltaker(any()) } returns Unit every { navEnhetService.getNavEnhet(any<UUID>()) } returns NAV_ENHET_1.toNavEnhet() every { deltakerService.hentDeltakerePaaGjennomforing(GJENNOMFORING_1.id) } returns listOf( Deltaker( id = DELTAKER_1.id, fornavn = "Fornavn2", mellomnavn = null, etternavn = "Etternavn", personIdent = "12121231123", navEnhetId = null, navVeilederId = null, epost = "foo@bar.baz", telefonnummer = "1234", startDato = null, sluttDato = null, status = DeltakerStatus( UUID.randomUUID(), DeltakerStatus.Type.VENTER_PA_OPPSTART, null, LocalDateTime.now(), LocalDateTime.now(), true ), registrertDato = LocalDateTime.now(), dagerPerUke = null, prosentStilling = null, gjennomforingId = UUID.randomUUID(), erSkjermet = false )) gjennomforingRepository.get(GJENNOMFORING_1.id) shouldNotBe null service.slettGjennomforing(GJENNOMFORING_1.id) gjennomforingRepository.get(GJENNOMFORING_1.id) shouldBe null } test("getGjennomforing - gjennomføring finnes - returnerer gjennomføring") { testDataRepository.insertNavEnhet(NAV_ENHET_1) testDataRepository.insertTiltak(TILTAK_1) testDataRepository.insertArrangor(ARRANGOR_1) testDataRepository.insertGjennomforing(GJENNOMFORING_1) val tiltakInserted = TILTAK_1.toTiltak() val arrangorInserted = ARRANGOR_1.toArrangor() every { arrangorService.getArrangorById(ARRANGOR_1.id) } returns arrangorInserted every { tiltakService.getTiltakById(TILTAK_1.id) } returns tiltakInserted val gjennomforing = service.getGjennomforing(GJENNOMFORING_1.id) GJENNOMFORING_1.toGjennomforing(tiltakInserted, arrangorInserted) shouldBe gjennomforing } test("getByLopenummer - returnerer alle gjennomføringer, uansett status") { testDataRepository.insertNavEnhet(NAV_ENHET_1) testDataRepository.insertTiltak(TILTAK_1) testDataRepository.insertArrangor(ARRANGOR_1) testDataRepository.insertGjennomforing(GJENNOMFORING_1) val avsluttetGjennomforing = GJENNOMFORING_1.copy(id = UUID.randomUUID(), status = Gjennomforing.Status.AVSLUTTET.name) testDataRepository.insertGjennomforing(avsluttetGjennomforing) val tiltakInserted = TILTAK_1.toTiltak() val arrangorInserted = ARRANGOR_1.toArrangor() val lopenr = GJENNOMFORING_1.lopenr every { arrangorService.getArrangorById(ARRANGOR_1.id) } returns arrangorInserted every { tiltakService.getTiltakById(TILTAK_1.id) } returns tiltakInserted val expectedIds = listOf(GJENNOMFORING_1.id, avsluttetGjennomforing.id) service.getByLopenr(lopenr).map { it.id } shouldContainAll expectedIds } })
4
Kotlin
3
3
59ebfd42eb4b8bcea2350e501058584fb80287b9
6,718
amt-tiltak
MIT License
core/domain/src/main/kotlin/com/lolo/io/onelist/core/domain/use_cases/LoadAllLists.kt
lolo-io
198,519,184
false
{"Kotlin": 363415, "Roff": 549}
package com.lolo.io.onelist.core.domain.use_cases import com.google.gson.JsonIOException import com.google.gson.JsonSyntaxException import com.lolo.io.onelist.core.data.datamodel.ListsWithErrors import kotlinx.coroutines.flow.Flow import java.io.FileNotFoundException import com.lolo.io.onelist.core.data.repository.OneListRepository class LoadAllLists(private val repository: OneListRepository) { @Throws(FileNotFoundException::class, JsonSyntaxException::class, JsonIOException::class) suspend operator fun invoke(): Flow<ListsWithErrors> { return repository.getAllLists() } }
14
Kotlin
26
92
ca7df6ec46344bde7c5e357d0784ecdfdecbb78e
601
OneList
MIT License
src/main/kotlin/no/nav/familie/ef/mottak/featuretoggle/FeatureToggleService.kt
navikt
204,919,927
false
{"Kotlin": 442141, "Dockerfile": 185}
package no.nav.familie.ef.mottak.featuretoggle import no.nav.familie.unleash.UnleashService import org.springframework.stereotype.Service @Service class FeatureToggleService( val unleashService: UnleashService, ) { fun isEnabled(toggleId: String): Boolean = unleashService.isEnabled(toggleId, false) }
0
Kotlin
3
0
c244546c62bfbeae4c031bda0b52cc05c51525c2
312
familie-ef-mottak
MIT License
src/main/kotlin/com/odim/simulator/tree/templates/bmc/embedded/AttributesBmcTemplate.kt
ODIM-Project
355,910,204
false
null
/* * Copyright (c) Intel Corporation * * 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.odim.simulator.tree.templates.bmc.embedded import com.odim.simulator.tree.EmbeddedObjectTemplate import com.odim.simulator.tree.RedfishVersion.V1_0_0 import com.odim.simulator.tree.ResourceTemplate import com.odim.simulator.tree.structure.EmbeddedObjectType.ATTRIBUTES import com.odim.simulator.tree.structure.Resource.Companion.embeddedObject import com.odim.simulator.tree.templates.bmc.BmcVersion.BMC_1_0 @EmbeddedObjectTemplate(ATTRIBUTES) open class AttributesBmcTemplate : ResourceTemplate() { init { version(BMC_1_0, V1_0_0, embeddedObject( "QuietBoot" to 1, "OnboardNICEnable_0" to 1, "OnboardNICPortEnable_0" to 1, "OnboardNICPortEnable_1" to 1, "OnboardNICPortEnable_2" to 1, "OnboardNICPortEnable_3" to 1, "OnboardNICEnable_1" to 1, "OnboardNICPortEnable_4" to 1, "OnboardNICPortEnable_5" to 1, "OnboardNICPortEnable_6" to 1, "OnboardNICPortEnable_7" to 1, "IB1_PXE" to 0, "OnboardNICIOMPortPXEEnable_8" to 1, "OnboardNICIOMPortPXEEnable_9" to 1, "OnboardNICIOMPortPXEEnable_10" to 1, "OnboardNICIOMPortPXEEnable_11" to 1, "IB2_PXE" to 0, "OnboardNICIOMPortPXEEnable_12" to 1, "OnboardNICIOMPortPXEEnable_13" to 1, "OnboardNICIOMPortPXEEnable_14" to 1, "OnboardNICIOMPortPXEEnable_15" to 1, "Pci64BitResourceAllocation" to 1, "MmiohBase" to 0, "MmiohSize" to 4, "AddinVideoAdapter" to 2, "OnboardVideo" to 1, "FastVideo" to 1, "LegacyVgaSocket" to 1, "ARIEnable" to 1, "SRIOVEnable" to 1, "UEFINetworkStack" to 0, "IPv4PXESupport" to 1, "IPv6PXESupport" to 1, "PcieOpROMCtrl_1" to 1, "PcieOpROMCtrl_2" to 1, "PcieOpROMCtrl_3" to 1, "PcieOpROMCtrl_4" to 1, "PcieOpROMCtrl_5" to 1, "PcieOpROMCtrl_6" to 1, "PcieOpROMCtrl_7" to 1, "PcieOpROMCtrl_8" to 1, "PcieOpROMCtrl_9" to 1, "PcieOpROMCtrl_10" to 1, "PcieOpROMCtrl_11" to 1, "PcieOpROMCtrl_12" to 1, "PcieOpROMCtrl_14" to 1, "PcieOpROMCtrl_15" to 1, "PcieOpROMCtrl_16" to 1, "PcieOpROMCtrl_17" to 1, "PcieOpROMCtrl_18" to 1, "PcieOpROMCtrl_19" to 1, "PcieOpROMCtrl_20" to 1, "PcieOpROMCtrl_21" to 1, "PcieOpROMCtrl_22" to 1, "PcieOpROMCtrl_23" to 1, "PcieOpROMCtrl_24" to 1, "PcieOpROMCtrl_25" to 1, "PcieOpROMCtrl_13" to 1, "VmdEnable_0" to 0, "VmdPortEnable_0" to 0, "VmdPortEnable_1" to 0, "VmdPortEnable_2" to 0, "VmdPortEnable_3" to 0, "ReduntantVmdEnableStack_3" to 0, "VmdPortEnable_14" to 0, "VmdPortEnable_15" to 0, "ReduntantVmdEnableStack_0" to 0, "ReduntantVmdEnableStack_2" to 0, "VmdPortEnable_10" to 0, "VmdPortEnable_11" to 0, "VmdEnable_4" to 0, "VmdPortEnable_16" to 0, "VmdPortEnable_17" to 0, "VmdPortEnable_18" to 0, "VmdPortEnable_19" to 0, "VmdEnable_3" to 0, "VmdPortEnable_12" to 0, "VmdPortEnable_13" to 0, "ReduntantVmdEnableStack_4" to 0, "VmdEnable_5" to 0, "VmdPortEnable_20" to 0, "VmdPortEnable_21" to 0, "ReduntantVmdEnableStack_5" to 0, "VmdPortEnable_22" to 0, "VmdPortEnable_23" to 0, "VmdEnable_1" to 0, "VmdPortEnable_4" to 0, "VmdPortEnable_5" to 0, "VmdPortEnable_6" to 0, "VmdPortEnable_7" to 0, "VmdPortEnable_8" to 0, "VmdPortEnable_9" to 0, "VmdEnable_2" to 0, "ConfigIOU0_0" to 255, "ConfigIOU1_1" to 255, "ConfigIOU1_0" to 255, "ConfigIOU2_0" to 255, "ConfigIOU0_1" to 255, "ConfigIOU2_1" to 255, "PcieRiser1ErrEn" to 0, "PcieRiser2ErrEn" to 0, "PcieRiser3ErrEn" to 0, "PcieRiser4ErrEn" to 0, "PciePortLinkSpeed_S_0" to 3, "PciePortLinkSpeed_S_1" to 3, "PciePortLinkSpeed_S_2" to 3, "PciePortLinkSpeed_S_3" to 3, "PciePortLinkSpeed_S_4" to 3, "PciePortLinkSpeed_S_5" to 3, "PciePortLinkSpeed_S_6" to 3, "PciePortLinkSpeed_S_7" to 3, "PciePortLinkSpeed_S_8" to 3, "PciePortLinkSpeed_S_9" to 3, "PciePortLinkSpeed_S_10" to 3, "PciePortLinkSpeed_S_11" to 3, "PciePortLinkSpeed_S_12" to 3, "PciePortLinkSpeed_S_21" to 3, "PciePortLinkSpeed_S_22" to 3, "PciePortLinkSpeed_S_23" to 3, "PciePortLinkSpeed_S_24" to 3, "PciePortLinkSpeed_S_25" to 3, "PciePortLinkSpeed_S_26" to 3, "PciePortLinkSpeed_S_27" to 3, "PciePortLinkSpeed_S_28" to 3, "PciePortLinkSpeed_S_29" to 3, "PciePortLinkSpeed_S_30" to 3, "PciePortLinkSpeed_S_31" to 3, "PciePortLinkSpeed_S_32" to 3, "PciePortLinkSpeed_S_33" to 3, "PciePortLinkSpeed_S_42" to 3, "PciePortLinkSpeed_S_43" to 3, "PciePortLinkSpeed_S_44" to 3, "PciePortLinkSpeed_S_45" to 3, "PciePortLinkSpeed_S_46" to 3, "PciePortLinkSpeed_S_47" to 3, "PciePortLinkSpeed_S_48" to 3, "PciePortLinkSpeed_S_49" to 3, "PciePortLinkSpeed_S_50" to 3, "PciePortLinkSpeed_S_51" to 3, "PciePortLinkSpeed_S_52" to 3, "PciePortLinkSpeed_S_53" to 3, "PciePortLinkSpeed_S_54" to 3, "PciePortLinkSpeed_S_63" to 3, "PciePortLinkSpeed_S_64" to 3, "PciePortLinkSpeed_S_65" to 3, "PciePortLinkSpeed_S_66" to 3, "PciePortLinkSpeed_S_67" to 3, "PciePortLinkSpeed_S_68" to 3, "PciePortLinkSpeed_S_69" to 3, "PciePortLinkSpeed_S_70" to 3, "PciePortLinkSpeed_S_71" to 3, "PciePortLinkSpeed_S_72" to 3, "PciePortLinkSpeed_S_73" to 3, "PciePortLinkSpeed_S_74" to 3, "PciePortLinkSpeed_S_75" to 3, "SerialA" to 1, "SerialAIo" to 0, "SerialB" to 1, "SerialBIo" to 1, "QpiLinkSpeed" to 2, "KtiPrefetchEn" to 1, "StaleAtoSOptEn" to 0, "LLCDeadLineAlloc" to 1, "DfxD2cEn" to 0, "DfxD2kEn" to 0, "NtbPpd_0" to 0, "NtbBarSizeOverride_0" to 0, "NtbSplitBar_0" to 0, "NtbBarSizePBar23_0" to 20, "NtbBarSizePBar4_0" to 20, "NtbBarSizePBar5_0" to 20, "NtbBarSizePBar45_0" to 20, "NtbBarSizeSBar23_0" to 20, "NtbBarSizeSBar4_0" to 20, "NtbBarSizeSBar5_0" to 20, "NtbBarSizeSBar45_0" to 20, "NtbSBar01Prefetch_0" to 0, "NtbXlinkCtlOverride_0" to 3, "NtbPpd_1" to 0, "NtbBarSizeOverride_1" to 0, "NtbSplitBar_1" to 0, "NtbBarSizePBar23_1" to 20, "NtbBarSizePBar4_1" to 20, "NtbBarSizePBar5_1" to 20, "NtbBarSizePBar45_1" to 20, "NtbBarSizeSBar23_1" to 20, "NtbBarSizeSBar4_1" to 20, "NtbBarSizeSBar5_1" to 20, "NtbBarSizeSBar45_1" to 20, "NtbSBar01Prefetch_1" to 0, "NtbXlinkCtlOverride_1" to 3, "NtbPpd_2" to 0, "NtbBarSizeOverride_2" to 0, "NtbSplitBar_2" to 0, "NtbBarSizePBar23_2" to 20, "NtbBarSizePBar4_2" to 20, "NtbBarSizePBar5_2" to 20, "NtbBarSizePBar45_2" to 20, "NtbBarSizeSBar23_2" to 20, "NtbBarSizeSBar4_2" to 20, "NtbBarSizeSBar5_2" to 20, "NtbBarSizeSBar45_2" to 20, "NtbSBar01Prefetch_2" to 0, "NtbXlinkCtlOverride_2" to 3, "NtbPpd_3" to 0, "NtbBarSizeOverride_3" to 0, "NtbSplitBar_3" to 0, "NtbBarSizePBar23_3" to 20, "NtbBarSizePBar4_3" to 20, "NtbBarSizePBar5_3" to 20, "NtbBarSizePBar45_3" to 20, "NtbBarSizeSBar23_3" to 20, "NtbBarSizeSBar4_3" to 20, "NtbBarSizeSBar5_3" to 20, "NtbBarSizeSBar45_3" to 20, "NtbSBar01Prefetch_3" to 0, "NtbXlinkCtlOverride_3" to 3, "NtbPpd_4" to 0, "NtbBarSizeOverride_4" to 0, "NtbSplitBar_4" to 0, "NtbBarSizePBar23_4" to 20, "NtbBarSizePBar4_4" to 20, "NtbBarSizePBar5_4" to 20, "NtbBarSizePBar45_4" to 20, "NtbBarSizeSBar23_4" to 20, "NtbBarSizeSBar4_4" to 20, "NtbBarSizeSBar5_4" to 20, "NtbBarSizeSBar45_4" to 20, "NtbSBar01Prefetch_4" to 0, "NtbXlinkCtlOverride_4" to 3, "NtbPpd_5" to 0, "NtbBarSizeOverride_5" to 0, "NtbSplitBar_5" to 0, "NtbBarSizePBar23_5" to 20, "NtbBarSizePBar4_5" to 20, "NtbBarSizePBar5_5" to 20, "NtbBarSizePBar45_5" to 20, "NtbBarSizeSBar23_5" to 20, "NtbBarSizeSBar4_5" to 20, "NtbBarSizeSBar5_5" to 20, "NtbBarSizeSBar45_5" to 20, "NtbSBar01Prefetch_5" to 0, "NtbXlinkCtlOverride_5" to 3, "VTdSupport" to 1, "AcsControl" to 1, "CoherencySupport" to 0, "PciePllSsc" to 20, "CbRelaxedOrdering" to 0, "Cb3NoSnoopEn_0" to 0, "Cb3NoSnoopEn_1" to 0, "Cb3NoSnoopEn_2" to 0, "Cb3NoSnoopEn_3" to 0, "Cb3NoSnoopEn_4" to 0, "Cb3NoSnoopEn_5" to 0, "Cb3NoSnoopEn_6" to 0, "Cb3NoSnoopEn_7" to 0, "Cb3NoSnoopEn_8" to 0, "Cb3NoSnoopEn_9" to 0, "Cb3NoSnoopEn_10" to 0, "Cb3NoSnoopEn_11" to 0, "Cb3NoSnoopEn_12" to 0, "Cb3NoSnoopEn_13" to 0, "Cb3NoSnoopEn_14" to 0, "Cb3NoSnoopEn_15" to 0, "DdrFreqLimit" to 0, "ImcInterleaving" to 0, "PagePolicy" to 3, "ADREn" to 1, "eraseArmNVDIMMS" to 1, "restoreNVDIMMS" to 1, "interNVDIMMS" to 0, "MirrorMode" to 0, "ADDDCEn" to 0, "RankSparing" to 0, "Nvar1_multiSparingRanks" to 1, "EPSDRASMode" to 0, "Nvar0_multiSparingRanks" to 1, "NumaEn" to 1, "Nvar1_SncEn" to 0, "PatrolScrub" to 1, "spareErrTh" to 10, "CorrMemErrEn" to 1, "CorrMemErrCmciEn" to 0, "ProcessorPowerPolicy" to 0, "WorkLdConfig" to 0, "UFSDisable" to 0, "PerfPLimitEn" to 1, "ProcessorEistEnable" to 1, "ConfigTDP" to 0, "ConfigTDPLevel" to 0, "TurboMode" to 1, "EETurboDisable" to 0, "ProcessorHWPMEnable" to 1, "ProcessorHWPMInterrupt" to 0, "ProcessorEPPEnable" to 1, "ProcessorAPSrocketing" to 1, "ProcessorScalability" to 1, "ProcessorPPOBudget" to 1, "PackageCState" to 3, "ProcessorC1eEnable" to 1, "C3Enable" to 0, "C6Enable" to 1, "ProcessorHyperThreadingDisable" to 0, "ActiveCoreNum" to 0, "ExecuteDisableBit" to 1, "ProcessorVmxEnable" to 1, "ProcessorSmxEnable" to 0, "PoisonEn" to 0, "MlcStreamerPrefetcherEnable" to 1, "MlcSpatialPrefetcherEnable" to 1, "DCUStreamerPrefetcherEnable" to 1, "DCUIPPrefetcherEnable" to 1, "LlcPrefetchEnable" to 0, "SataInterfaceMode" to 0, "SataInterfaceRAIDMode" to 2, "SataSpinUpOption" to 0, "sSataInterfaceMode" to 0, "sSataSpinUpOption" to 0, "FanSpdCtrlProfile" to 2, "UsbLegacySupport" to 0, "UsbEmul6064" to 1, "UsbNonBoot" to 0, "UsbMassResetDelay" to 1, "UsbEmu1" to 0, "UsbEmu2" to 0, "UsbEmu3" to 0, "UsbEmu4" to 0, "UsbEmu5" to 0, "UsbEmu6" to 0, "UsbEmu7" to 0, "UsbEmu8" to 0, "UsbEmu9" to 0, "UsbEmu10" to 0, "UsbEmu11" to 0, "UsbEmu12" to 0, "UsbEmu13" to 0, "UsbEmu14" to 0, "UsbEmu15" to 0, "UsbEmu16" to 0, "OverclockingSupport" to 0, "SvidEnable" to 1, "SvidVoltageOverride" to 0, "VDimmVddEnable" to 0, "VDimmVdd" to 1200, "EnforcePOR" to 3, "RankMargin" to 0, "rmtPatternLength" to 1000, "MrcSerialDebug" to 0, "bdatEn" to 0, "EnableBiosSsaLoader" to 2, "EnableBiosSsaRMT" to 2, "ScrambleEnDDRT" to 2, "ScrambleEn" to 2, "PcieGlobalAspm" to 0, "ASPML1Check" to 0, "PmaxSign" to 0, "PmaxOffset" to 0, "DirectoryModeEn" to 1, "SataTestMode" to 0, "SataPort_0" to 1, "SataPort_1" to 1, "SataPort_2" to 1, "SataPort_3" to 1, "SataPort_4" to 1, "SataPort_5" to 1, "SataPort_6" to 1, "SataPort_7" to 1, "sSataTestMode" to 0, "sSataPort_0" to 1, "sSataPort_1" to 1, "sSataPort_2" to 1, "sSataPort_3" to 1, "sSataPort_4" to 1, "sSataPort_5" to 1, "PciePortDisable_0" to 2, "PciePortDisable_1" to 2, "PciePortDisable_2" to 2, "PciePortDisable_3" to 2, "PciePortDisable_4" to 2, "PciePortDisable_5" to 2, "PciePortDisable_6" to 2, "PciePortDisable_7" to 2, "PciePortDisable_8" to 2, "PciePortDisable_9" to 2, "PciePortDisable_10" to 2, "PciePortDisable_11" to 2, "PciePortDisable_12" to 2, "PciePortDisable_13" to 2, "PciePortDisable_14" to 2, "PciePortDisable_15" to 2, "PciePortDisable_16" to 2, "PciePortDisable_17" to 2, "PciePortDisable_18" to 2, "PciePortDisable_19" to 2, "PciePortDisable_20" to 2, "PciePortDisable_21" to 2, "PciePortDisable_22" to 2, "PciePortDisable_23" to 2, "PciePortDisable_24" to 2, "PciePortDisable_25" to 2, "PciePortDisable_26" to 2, "PciePortDisable_27" to 2, "PciePortDisable_28" to 2, "PciePortDisable_29" to 2, "PciePortDisable_30" to 2, "PciePortDisable_31" to 2, "PciePortDisable_32" to 2, "PciePortDisable_33" to 2, "PciePortDisable_34" to 2, "PciePortDisable_35" to 2, "PciePortDisable_36" to 2, "PciePortDisable_37" to 2, "PciePortDisable_38" to 2, "PciePortDisable_39" to 2, "PciePortDisable_40" to 2, "PciePortDisable_41" to 2, "PciePortDisable_42" to 2, "PciePortDisable_43" to 2, "PciePortDisable_44" to 2, "PciePortDisable_45" to 2, "PciePortDisable_46" to 2, "PciePortDisable_47" to 2, "PciePortDisable_48" to 2, "PciePortDisable_49" to 2, "PciePortDisable_50" to 2, "PciePortDisable_51" to 2, "PciePortDisable_52" to 2, "PciePortDisable_53" to 2, "PciePortDisable_54" to 2, "PciePortDisable_55" to 2, "PciePortDisable_56" to 2, "PciePortDisable_57" to 2, "PciePortDisable_58" to 2, "PciePortDisable_59" to 2, "PciePortDisable_60" to 2, "PciePortDisable_61" to 2, "PciePortDisable_62" to 2, "PciePortDisable_63" to 2, "PciePortDisable_64" to 2, "PciePortDisable_65" to 2, "PciePortDisable_66" to 2, "PciePortDisable_67" to 2, "PciePortDisable_68" to 2, "PciePortDisable_69" to 2, "PciePortDisable_70" to 2, "PciePortDisable_71" to 2, "PciePortDisable_72" to 2, "PciePortDisable_73" to 2, "PciePortDisable_74" to 2, "PciePortDisable_75" to 2, "PciePortDisable_76" to 2, "PciePortDisable_77" to 2, "PciePortDisable_78" to 2, "PciePortDisable_79" to 2, "PciePortDisable_80" to 2, "PciePortDisable_81" to 2, "PciePortDisable_82" to 2, "PciePortDisable_83" to 2, "Dwr_Enable" to 0, "Dwr_Stall" to 0, "Dwr_BmcRootPort" to 3, "DwrEn_PMCGBL" to 1, "DwrEn_MEWDT" to 0, "DwrEn_IEWDT" to 0, "Dwr_MeResetPrepDone" to 0, "Dwr_IeResetPrepDone" to 0, "IccSscOverride" to 0, "IccSscMode_2" to 4, "USB2Port10Pehalfbit" to 1, "USB2Port10Petxiset" to 7, "USB2Port10Txiset" to 7, "USB2Port10Predeemp" to 2, "USB2Port12Pehalfbit" to 1, "USB2Port12Petxiset" to 7, "USB2Port12Txiset" to 7, "FPGASocketEnable_0" to 0, "FPGABBS_0" to 0, "FPGASocketEnable_1" to 1, "FPGABBS_1" to 0, "IccSscMode_0" to 4, "IccSscMode_1" to 4, "IccSscMode_3" to 4, "IccSscMode_4" to 4, "IccSscMode_5" to 4, "IccSscMode_6" to 4, "IccSscMode_7" to 4, "PowerOnPassword" to 0, "FrontPanelLockOut" to 0, "TpmOperation" to 1, "Tpm2Operation" to 0, "TCG2ActivatePCRBank0" to 1, "TCG2ActivatePCRBank1" to 1, "Tpm2FwUpdateEnable" to 0, "PropagateSerr" to 1, "PropagatePerr" to 1, "PcieAer" to 1, "PCIECorrErrorEn" to 0, "PcieCeErrThreshold" to 0, "WheaSupport" to 1, "ResetCaterr" to 1, "ResetErr2" to 1, "EnforcedPasswd" to 0, "RandomPowerPolicy" to 0, "RandomPowerOnDelayValue" to 60, "SerialOverLanEnable_0" to 0, "SerialOverLanEnable_1" to 0, "SerialOverLanEnable_2" to 0, "ContinueLOSRIntoDOS" to 0, "Nvar3_TerminalResolution" to 0, "SvrMngmntDiagnosticMsgEnable" to 0, "EarlyBootTimeout" to 0, "BootMode" to 1, "UefiWindowsInt10Workaround" to 0, "BootOrder_0" to 5, "BootOrder_1" to 0, "BootOrder_2" to 1, "BootOrder_3" to 2, "BootOrder_4" to 3 )) } }
1
Kotlin
0
7
7e8a3030ca83c040678f8edf76def588b2b01cca
22,616
BMCSimulator
Apache License 2.0
src/test/kotlin/gal/usc/citius/processmining/dfgfiltering/filtering/TwoWaysEdmondsGreedyTests.kt
david-chapela
322,881,845
false
null
package gal.usc.citius.processmining.dfgfiltering.filtering import gal.usc.citius.processmining.dfgfiltering.graph.DirectedGraphBuilder import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object TwoWaysEdmondsGreedyTests : Spek({ describe("A connected directed graph with many edges and no long cycles (only a self-cycle)") { val dg = getDFGManyEdgesNoLongCycles() context("get the minimum equivalent graph with maximum weight using the TWE+G method") { val mwmfdfg = dg.filterEdgesTWEG() it("should be the same as the following MWMF-DFG") { val realMWMFDFG = DirectedGraphBuilder() .vertex("A") .vertex("B") .vertex("C") .vertex("D") .vertex("E") .vertex("F") .vertex("G") .vertex("H") .vertex("I") .vertex("J") .vertex("K") .vertex("L") .vertex("M") .vertex("N") .edge().weight(5.0).from("A").to("B") .edge().weight(3.0).from("A").to("C") .edge().weight(4.0).from("A").to("D") .edge().weight(8.0).from("B").to("E") .edge().weight(3.0).from("C").to("F") .edge().weight(2.0).from("D").to("G") .edge().weight(2.0).from("E").to("H") .edge().weight(5.0).from("F").to("H") .edge().weight(7.0).from("G").to("I") .edge().weight(9.0).from("G").to("L") .edge().weight(3.0).from("H").to("N") .edge().weight(6.0).from("I").to("J") .edge().weight(8.0).from("J").to("K") .edge().weight(4.0).from("K").to("N") .edge().weight(4.0).from("L").to("M") .edge().weight(5.0).from("M").to("N") .build() mwmfdfg shouldBeEqualTo realMWMFDFG } } context("get the minimum equivalent graph with minimum weight using the TWE+G method") { val mwmfdfg = dg.filterEdgesTWEG(true) it("should be the same as the following MWMF-DFG") { val realMWMFDFG = DirectedGraphBuilder() .vertex("A") .vertex("B") .vertex("C") .vertex("D") .vertex("E") .vertex("F") .vertex("G") .vertex("H") .vertex("I") .vertex("J") .vertex("K") .vertex("L") .vertex("M") .vertex("N") .edge().weight(5.0).from("A").to("B") .edge().weight(3.0).from("A").to("C") .edge().weight(4.0).from("A").to("D") .edge().weight(7.0).from("B").to("H") .edge().weight(1.0).from("C").to("E") .edge().weight(3.0).from("C").to("F") .edge().weight(6.0).from("D").to("I") .edge().weight(2.0).from("D").to("G") .edge().weight(2.0).from("E").to("H") .edge().weight(5.0).from("F").to("J") .edge().weight(3.0).from("G").to("K") .edge().weight(1.0).from("H").to("K") .edge().weight(6.0).from("I").to("L") .edge().weight(8.0).from("J").to("K") .edge().weight(2.0).from("K").to("M") .edge().weight(4.0).from("L").to("M") .edge().weight(5.0).from("M").to("N") .build() mwmfdfg shouldBeEqualTo realMWMFDFG } } } })
0
Kotlin
0
0
d73d1f3f3462f9ef3d699d8fafb1435084b472ef
4,065
dfg-edge-filtering
MIT License
src/commonAntlr/kotlin/eopseox/parser/EopseoLexer.kt
eopseo-lang
650,985,844
false
null
// Generated from java-escape by ANTLR 4.7.1 package eopseox.parser import com.strumenta.kotlinmultiplatform.asCharArray import org.antlr.v4.kotlinruntime.CharStream import org.antlr.v4.kotlinruntime.Lexer import org.antlr.v4.kotlinruntime.ThreadLocal import org.antlr.v4.kotlinruntime.Vocabulary import org.antlr.v4.kotlinruntime.VocabularyImpl import org.antlr.v4.kotlinruntime.atn.ATN import org.antlr.v4.kotlinruntime.atn.ATNDeserializer import org.antlr.v4.kotlinruntime.atn.LexerATNSimulator import org.antlr.v4.kotlinruntime.atn.PredictionContextCache import org.antlr.v4.kotlinruntime.dfa.DFA class EopseoLexer(val input: CharStream) : Lexer(input) { // TODO Verify the runtime version is correct override val ruleNames: Array<String>? get() = Rules.values().map { it.name }.toTypedArray() override val grammarFileName: String get() = "Eopseo.g4" override val atn: ATN get() = EopseoLexer.Companion.ATN override val vocabulary: Vocabulary get() = EopseoLexer.Companion.VOCABULARY @ThreadLocal companion object { val decisionToDFA : Array<DFA> val sharedContextCache = PredictionContextCache() private val LITERAL_NAMES: List<String?> = listOf(null, null, null, null, "'package'", "'import'", "'new'", "'rTrue'", "'rFalse'", "'RInt'", "'RDouble'", "'RString'", "'RBoolean'", "'->'", "'<-'", "'#'", "'('", "')'", "'['", "']'", "'{'", "'}'", "'.'") private val SYMBOLIC_NAMES: List<String?> = listOf(null, "WS", "COMMENT", "LINE_COMMENT", "PACKAGE", "IMPORT", "NEW", "RTRUE", "RFALSE", "RINT", "RDOUBLE", "RSTRING", "RBOOLEAN", "RARROW", "LARROW", "SHARP", "LPAREN", "RPAREN", "LSQUARE", "RSQUARE", "LBRACE", "RBRACE", "DOT", "ID", "OPID", "Integer", "Double", "String") val VOCABULARY = VocabularyImpl(LITERAL_NAMES.toTypedArray(), SYMBOLIC_NAMES.toTypedArray()) val tokenNames: Array<String?> = Array<String?>(SYMBOLIC_NAMES.size) { var el = VOCABULARY.getLiteralName(it) if (el == null) { el = VOCABULARY.getSymbolicName(it) } if (el == null) { el = "<INVALID>" } el } private const val serializedATN : String = "\u0003\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\u0002\u001d\u00f0\u0008\u0001\u0004\u0002\u0009\u0002\u0004\u0003\u0009\u0003\u0004\u0004\u0009\u0004\u0004\u0005\u0009\u0005\u0004\u0006\u0009\u0006\u0004\u0007\u0009\u0007\u0004\u0008\u0009\u0008\u0004\u0009\u0009\u0009\u0004\u000a\u0009\u000a\u0004\u000b\u0009\u000b\u0004\u000c\u0009\u000c\u0004\u000d\u0009\u000d\u0004\u000e\u0009\u000e\u0004\u000f\u0009\u000f\u0004\u0010\u0009\u0010\u0004\u0011\u0009\u0011\u0004\u0012\u0009\u0012\u0004\u0013\u0009\u0013\u0004\u0014\u0009\u0014\u0004\u0015\u0009\u0015\u0004\u0016\u0009\u0016\u0004\u0017\u0009\u0017\u0004\u0018\u0009\u0018\u0004\u0019\u0009\u0019\u0004\u001a\u0009\u001a\u0004\u001b\u0009\u001b\u0004\u001c\u0009\u001c\u0004\u001d\u0009\u001d\u0004\u001e\u0009\u001e\u0004\u001f\u0009\u001f\u0004\u0020\u0009\u0020\u0004\u0021\u0009\u0021\u0003\u0002\u0006\u0002\u0045\u000a\u0002\u000d\u0002\u000e\u0002\u0046\u0003\u0002\u0003\u0002\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0007\u0003\u004f\u000a\u0003\u000c\u0003\u000e\u0003\u0052\u000b\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0004\u0003\u0004\u0003\u0004\u0003\u0004\u0007\u0004\u005d\u000a\u0004\u000c\u0004\u000e\u0004\u0060\u000b\u0004\u0003\u0004\u0003\u0004\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0005\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0006\u0003\u0007\u0003\u0007\u0003\u0007\u0003\u0007\u0003\u0008\u0003\u0008\u0003\u0008\u0003\u0008\u0003\u0008\u0003\u0008\u0003\u0009\u0003\u0009\u0003\u0009\u0003\u0009\u0003\u0009\u0003\u0009\u0003\u0009\u0003\u000a\u0003\u000a\u0003\u000a\u0003\u000a\u0003\u000a\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000b\u0003\u000c\u0003\u000c\u0003\u000c\u0003\u000c\u0003\u000c\u0003\u000c\u0003\u000c\u0003\u000c\u0003\u000d\u0003\u000d\u0003\u000d\u0003\u000d\u0003\u000d\u0003\u000d\u0003\u000d\u0003\u000d\u0003\u000d\u0003\u000e\u0003\u000e\u0003\u000e\u0003\u000f\u0003\u000f\u0003\u000f\u0003\u0010\u0003\u0010\u0003\u0011\u0003\u0011\u0003\u0012\u0003\u0012\u0003\u0013\u0003\u0013\u0003\u0014\u0003\u0014\u0003\u0015\u0003\u0015\u0003\u0016\u0003\u0016\u0003\u0017\u0003\u0017\u0003\u0018\u0003\u0018\u0003\u0019\u0003\u0019\u0003\u001a\u0003\u001a\u0003\u001b\u0003\u001b\u0007\u001b\u00c0\u000a\u001b\u000c\u001b\u000e\u001b\u00c3\u000b\u001b\u0003\u001c\u0006\u001c\u00c6\u000a\u001c\u000d\u001c\u000e\u001c\u00c7\u0003\u001d\u0003\u001d\u0003\u001e\u0006\u001e\u00cd\u000a\u001e\u000d\u001e\u000e\u001e\u00ce\u0003\u001e\u0003\u001e\u0003\u001e\u0003\u001e\u0006\u001e\u00d5\u000a\u001e\u000d\u001e\u000e\u001e\u00d6\u0005\u001e\u00d9\u000a\u001e\u0003\u001f\u0006\u001f\u00dc\u000a\u001f\u000d\u001f\u000e\u001f\u00dd\u0003\u001f\u0003\u001f\u0006\u001f\u00e2\u000a\u001f\u000d\u001f\u000e\u001f\u00e3\u0003\u0020\u0003\u0020\u0007\u0020\u00e8\u000a\u0020\u000c\u0020\u000e\u0020\u00eb\u000b\u0020\u0003\u0020\u0003\u0020\u0003\u0021\u0003\u0021\u0003\u0050\u0002\u0022\u0003\u0003\u0005\u0004\u0007\u0005\u0009\u0006\u000b\u0007\u000d\u0008\u000f\u0009\u0011\u000a\u0013\u000b\u0015\u000c\u0017\u000d\u0019\u000e\u001b\u000f\u001d\u0010\u001f\u0011\u0021\u0012\u0023\u0013\u0025\u0014\u0027\u0015\u0029\u0016\u002b\u0017\u002d\u0018\u002f\u0002\u0031\u0002\u0033\u0002\u0035\u0019\u0037\u001a\u0039\u0002\u003b\u001b\u003d\u001c\u003f\u001d\u0041\u0002\u0003\u0002\u000a\u0005\u0002\u000b\u000c\u000e\u000f\u0022\u0022\u0004\u0002\u000c\u000c\u000f\u000f\u0005\u0002\u0043\u005c\u0061\u0061\u0063\u007c\u0007\u0002\u002f\u002f\u0032\u003b\u0043\u005c\u0061\u0061\u0063\u007c\u000a\u0002\u0023\u0023\u0026\u0028\u002c\u0031\u003c\u0042\u005e\u005e\u0060\u0060\u007e\u007e\u0080\u0080\u0003\u0002\u0032\u003b\u0003\u0002\u0024\u0024\u0005\u0002\u0032\u003b\u0043\u0048\u0063\u0068\u0002\u00f5\u0002\u0003\u0003\u0002\u0002\u0002\u0002\u0005\u0003\u0002\u0002\u0002\u0002\u0007\u0003\u0002\u0002\u0002\u0002\u0009\u0003\u0002\u0002\u0002\u0002\u000b\u0003\u0002\u0002\u0002\u0002\u000d\u0003\u0002\u0002\u0002\u0002\u000f\u0003\u0002\u0002\u0002\u0002\u0011\u0003\u0002\u0002\u0002\u0002\u0013\u0003\u0002\u0002\u0002\u0002\u0015\u0003\u0002\u0002\u0002\u0002\u0017\u0003\u0002\u0002\u0002\u0002\u0019\u0003\u0002\u0002\u0002\u0002\u001b\u0003\u0002\u0002\u0002\u0002\u001d\u0003\u0002\u0002\u0002\u0002\u001f\u0003\u0002\u0002\u0002\u0002\u0021\u0003\u0002\u0002\u0002\u0002\u0023\u0003\u0002\u0002\u0002\u0002\u0025\u0003\u0002\u0002\u0002\u0002\u0027\u0003\u0002\u0002\u0002\u0002\u0029\u0003\u0002\u0002\u0002\u0002\u002b\u0003\u0002\u0002\u0002\u0002\u002d\u0003\u0002\u0002\u0002\u0002\u0035\u0003\u0002\u0002\u0002\u0002\u0037\u0003\u0002\u0002\u0002\u0002\u003b\u0003\u0002\u0002\u0002\u0002\u003d\u0003\u0002\u0002\u0002\u0002\u003f\u0003\u0002\u0002\u0002\u0003\u0044\u0003\u0002\u0002\u0002\u0005\u004a\u0003\u0002\u0002\u0002\u0007\u0058\u0003\u0002\u0002\u0002\u0009\u0063\u0003\u0002\u0002\u0002\u000b\u006b\u0003\u0002\u0002\u0002\u000d\u0072\u0003\u0002\u0002\u0002\u000f\u0076\u0003\u0002\u0002\u0002\u0011\u007c\u0003\u0002\u0002\u0002\u0013\u0083\u0003\u0002\u0002\u0002\u0015\u0088\u0003\u0002\u0002\u0002\u0017\u0090\u0003\u0002\u0002\u0002\u0019\u0098\u0003\u0002\u0002\u0002\u001b\u00a1\u0003\u0002\u0002\u0002\u001d\u00a4\u0003\u0002\u0002\u0002\u001f\u00a7\u0003\u0002\u0002\u0002\u0021\u00a9\u0003\u0002\u0002\u0002\u0023\u00ab\u0003\u0002\u0002\u0002\u0025\u00ad\u0003\u0002\u0002\u0002\u0027\u00af\u0003\u0002\u0002\u0002\u0029\u00b1\u0003\u0002\u0002\u0002\u002b\u00b3\u0003\u0002\u0002\u0002\u002d\u00b5\u0003\u0002\u0002\u0002\u002f\u00b7\u0003\u0002\u0002\u0002\u0031\u00b9\u0003\u0002\u0002\u0002\u0033\u00bb\u0003\u0002\u0002\u0002\u0035\u00bd\u0003\u0002\u0002\u0002\u0037\u00c5\u0003\u0002\u0002\u0002\u0039\u00c9\u0003\u0002\u0002\u0002\u003b\u00d8\u0003\u0002\u0002\u0002\u003d\u00db\u0003\u0002\u0002\u0002\u003f\u00e5\u0003\u0002\u0002\u0002\u0041\u00ee\u0003\u0002\u0002\u0002\u0043\u0045\u0009\u0002\u0002\u0002\u0044\u0043\u0003\u0002\u0002\u0002\u0045\u0046\u0003\u0002\u0002\u0002\u0046\u0044\u0003\u0002\u0002\u0002\u0046\u0047\u0003\u0002\u0002\u0002\u0047\u0048\u0003\u0002\u0002\u0002\u0048\u0049\u0008\u0002\u0002\u0002\u0049\u0004\u0003\u0002\u0002\u0002\u004a\u004b\u0007\u0031\u0002\u0002\u004b\u004c\u0007\u002c\u0002\u0002\u004c\u0050\u0003\u0002\u0002\u0002\u004d\u004f\u000b\u0002\u0002\u0002\u004e\u004d\u0003\u0002\u0002\u0002\u004f\u0052\u0003\u0002\u0002\u0002\u0050\u0051\u0003\u0002\u0002\u0002\u0050\u004e\u0003\u0002\u0002\u0002\u0051\u0053\u0003\u0002\u0002\u0002\u0052\u0050\u0003\u0002\u0002\u0002\u0053\u0054\u0007\u002c\u0002\u0002\u0054\u0055\u0007\u0031\u0002\u0002\u0055\u0056\u0003\u0002\u0002\u0002\u0056\u0057\u0008\u0003\u0002\u0002\u0057\u0006\u0003\u0002\u0002\u0002\u0058\u0059\u0007\u0031\u0002\u0002\u0059\u005a\u0007\u0031\u0002\u0002\u005a\u005e\u0003\u0002\u0002\u0002\u005b\u005d\u000a\u0003\u0002\u0002\u005c\u005b\u0003\u0002\u0002\u0002\u005d\u0060\u0003\u0002\u0002\u0002\u005e\u005c\u0003\u0002\u0002\u0002\u005e\u005f\u0003\u0002\u0002\u0002\u005f\u0061\u0003\u0002\u0002\u0002\u0060\u005e\u0003\u0002\u0002\u0002\u0061\u0062\u0008\u0004\u0002\u0002\u0062\u0008\u0003\u0002\u0002\u0002\u0063\u0064\u0007\u0072\u0002\u0002\u0064\u0065\u0007\u0063\u0002\u0002\u0065\u0066\u0007\u0065\u0002\u0002\u0066\u0067\u0007\u006d\u0002\u0002\u0067\u0068\u0007\u0063\u0002\u0002\u0068\u0069\u0007\u0069\u0002\u0002\u0069\u006a\u0007\u0067\u0002\u0002\u006a\u000a\u0003\u0002\u0002\u0002\u006b\u006c\u0007\u006b\u0002\u0002\u006c\u006d\u0007\u006f\u0002\u0002\u006d\u006e\u0007\u0072\u0002\u0002\u006e\u006f\u0007\u0071\u0002\u0002\u006f\u0070\u0007\u0074\u0002\u0002\u0070\u0071\u0007\u0076\u0002\u0002\u0071\u000c\u0003\u0002\u0002\u0002\u0072\u0073\u0007\u0070\u0002\u0002\u0073\u0074\u0007\u0067\u0002\u0002\u0074\u0075\u0007\u0079\u0002\u0002\u0075\u000e\u0003\u0002\u0002\u0002\u0076\u0077\u0007\u0074\u0002\u0002\u0077\u0078\u0007\u0056\u0002\u0002\u0078\u0079\u0007\u0074\u0002\u0002\u0079\u007a\u0007\u0077\u0002\u0002\u007a\u007b\u0007\u0067\u0002\u0002\u007b\u0010\u0003\u0002\u0002\u0002\u007c\u007d\u0007\u0074\u0002\u0002\u007d\u007e\u0007\u0048\u0002\u0002\u007e\u007f\u0007\u0063\u0002\u0002\u007f\u0080\u0007\u006e\u0002\u0002\u0080\u0081\u0007\u0075\u0002\u0002\u0081\u0082\u0007\u0067\u0002\u0002\u0082\u0012\u0003\u0002\u0002\u0002\u0083\u0084\u0007\u0054\u0002\u0002\u0084\u0085\u0007\u004b\u0002\u0002\u0085\u0086\u0007\u0070\u0002\u0002\u0086\u0087\u0007\u0076\u0002\u0002\u0087\u0014\u0003\u0002\u0002\u0002\u0088\u0089\u0007\u0054\u0002\u0002\u0089\u008a\u0007\u0046\u0002\u0002\u008a\u008b\u0007\u0071\u0002\u0002\u008b\u008c\u0007\u0077\u0002\u0002\u008c\u008d\u0007\u0064\u0002\u0002\u008d\u008e\u0007\u006e\u0002\u0002\u008e\u008f\u0007\u0067\u0002\u0002\u008f\u0016\u0003\u0002\u0002\u0002\u0090\u0091\u0007\u0054\u0002\u0002\u0091\u0092\u0007\u0055\u0002\u0002\u0092\u0093\u0007\u0076\u0002\u0002\u0093\u0094\u0007\u0074\u0002\u0002\u0094\u0095\u0007\u006b\u0002\u0002\u0095\u0096\u0007\u0070\u0002\u0002\u0096\u0097\u0007\u0069\u0002\u0002\u0097\u0018\u0003\u0002\u0002\u0002\u0098\u0099\u0007\u0054\u0002\u0002\u0099\u009a\u0007\u0044\u0002\u0002\u009a\u009b\u0007\u0071\u0002\u0002\u009b\u009c\u0007\u0071\u0002\u0002\u009c\u009d\u0007\u006e\u0002\u0002\u009d\u009e\u0007\u0067\u0002\u0002\u009e\u009f\u0007\u0063\u0002\u0002\u009f\u00a0\u0007\u0070\u0002\u0002\u00a0\u001a\u0003\u0002\u0002\u0002\u00a1\u00a2\u0007\u002f\u0002\u0002\u00a2\u00a3\u0007\u0040\u0002\u0002\u00a3\u001c\u0003\u0002\u0002\u0002\u00a4\u00a5\u0007\u003e\u0002\u0002\u00a5\u00a6\u0007\u002f\u0002\u0002\u00a6\u001e\u0003\u0002\u0002\u0002\u00a7\u00a8\u0007\u0025\u0002\u0002\u00a8\u0020\u0003\u0002\u0002\u0002\u00a9\u00aa\u0007\u002a\u0002\u0002\u00aa\u0022\u0003\u0002\u0002\u0002\u00ab\u00ac\u0007\u002b\u0002\u0002\u00ac\u0024\u0003\u0002\u0002\u0002\u00ad\u00ae\u0007\u005d\u0002\u0002\u00ae\u0026\u0003\u0002\u0002\u0002\u00af\u00b0\u0007\u005f\u0002\u0002\u00b0\u0028\u0003\u0002\u0002\u0002\u00b1\u00b2\u0007\u007d\u0002\u0002\u00b2\u002a\u0003\u0002\u0002\u0002\u00b3\u00b4\u0007\u007f\u0002\u0002\u00b4\u002c\u0003\u0002\u0002\u0002\u00b5\u00b6\u0007\u0030\u0002\u0002\u00b6\u002e\u0003\u0002\u0002\u0002\u00b7\u00b8\u0009\u0004\u0002\u0002\u00b8\u0030\u0003\u0002\u0002\u0002\u00b9\u00ba\u0009\u0005\u0002\u0002\u00ba\u0032\u0003\u0002\u0002\u0002\u00bb\u00bc\u0009\u0006\u0002\u0002\u00bc\u0034\u0003\u0002\u0002\u0002\u00bd\u00c1\u0005\u002f\u0018\u0002\u00be\u00c0\u0005\u0031\u0019\u0002\u00bf\u00be\u0003\u0002\u0002\u0002\u00c0\u00c3\u0003\u0002\u0002\u0002\u00c1\u00bf\u0003\u0002\u0002\u0002\u00c1\u00c2\u0003\u0002\u0002\u0002\u00c2\u0036\u0003\u0002\u0002\u0002\u00c3\u00c1\u0003\u0002\u0002\u0002\u00c4\u00c6\u0005\u0033\u001a\u0002\u00c5\u00c4\u0003\u0002\u0002\u0002\u00c6\u00c7\u0003\u0002\u0002\u0002\u00c7\u00c5\u0003\u0002\u0002\u0002\u00c7\u00c8\u0003\u0002\u0002\u0002\u00c8\u0038\u0003\u0002\u0002\u0002\u00c9\u00ca\u0009\u0007\u0002\u0002\u00ca\u003a\u0003\u0002\u0002\u0002\u00cb\u00cd\u0005\u0039\u001d\u0002\u00cc\u00cb\u0003\u0002\u0002\u0002\u00cd\u00ce\u0003\u0002\u0002\u0002\u00ce\u00cc\u0003\u0002\u0002\u0002\u00ce\u00cf\u0003\u0002\u0002\u0002\u00cf\u00d9\u0003\u0002\u0002\u0002\u00d0\u00d1\u0007\u0032\u0002\u0002\u00d1\u00d2\u0007\u007a\u0002\u0002\u00d2\u00d4\u0003\u0002\u0002\u0002\u00d3\u00d5\u0005\u0041\u0021\u0002\u00d4\u00d3\u0003\u0002\u0002\u0002\u00d5\u00d6\u0003\u0002\u0002\u0002\u00d6\u00d4\u0003\u0002\u0002\u0002\u00d6\u00d7\u0003\u0002\u0002\u0002\u00d7\u00d9\u0003\u0002\u0002\u0002\u00d8\u00cc\u0003\u0002\u0002\u0002\u00d8\u00d0\u0003\u0002\u0002\u0002\u00d9\u003c\u0003\u0002\u0002\u0002\u00da\u00dc\u0005\u0039\u001d\u0002\u00db\u00da\u0003\u0002\u0002\u0002\u00dc\u00dd\u0003\u0002\u0002\u0002\u00dd\u00db\u0003\u0002\u0002\u0002\u00dd\u00de\u0003\u0002\u0002\u0002\u00de\u00df\u0003\u0002\u0002\u0002\u00df\u00e1\u0007\u0030\u0002\u0002\u00e0\u00e2\u0005\u0039\u001d\u0002\u00e1\u00e0\u0003\u0002\u0002\u0002\u00e2\u00e3\u0003\u0002\u0002\u0002\u00e3\u00e1\u0003\u0002\u0002\u0002\u00e3\u00e4\u0003\u0002\u0002\u0002\u00e4\u003e\u0003\u0002\u0002\u0002\u00e5\u00e9\u0007\u0024\u0002\u0002\u00e6\u00e8\u000a\u0008\u0002\u0002\u00e7\u00e6\u0003\u0002\u0002\u0002\u00e8\u00eb\u0003\u0002\u0002\u0002\u00e9\u00e7\u0003\u0002\u0002\u0002\u00e9\u00ea\u0003\u0002\u0002\u0002\u00ea\u00ec\u0003\u0002\u0002\u0002\u00eb\u00e9\u0003\u0002\u0002\u0002\u00ec\u00ed\u0007\u0024\u0002\u0002\u00ed\u0040\u0003\u0002\u0002\u0002\u00ee\u00ef\u0009\u0009\u0002\u0002\u00ef\u0042\u0003\u0002\u0002\u0002\u000e\u0002\u0046\u0050\u005e\u00c1\u00c7\u00ce\u00d6\u00d8\u00dd\u00e3\u00e9\u0003\u0008\u0002\u0002" val ATN = ATNDeserializer().deserialize(serializedATN.asCharArray()) init { decisionToDFA = Array<DFA>(ATN.numberOfDecisions, { DFA(ATN.getDecisionState(it)!!, it) }) } } enum class Tokens(val id: Int) { WS(1), COMMENT(2), LINE_COMMENT(3), PACKAGE(4), IMPORT(5), NEW(6), RTRUE(7), RFALSE(8), RINT(9), RDOUBLE(10), RSTRING(11), RBOOLEAN(12), RARROW(13), LARROW(14), SHARP(15), LPAREN(16), RPAREN(17), LSQUARE(18), RSQUARE(19), LBRACE(20), RBRACE(21), DOT(22), ID(23), OPID(24), Integer(25), Double(26), String(27) } enum class Channels(val id: Int) { DEFAULT_TOKEN_CHANNEL(0), HIDDEN(1), } override val channelNames = Channels.values().map(Channels::name).toTypedArray() enum class Modes(val id: Int) { DEFAULT_MODE(0), } enum class Rules { WS, COMMENT, LINE_COMMENT, PACKAGE, IMPORT, NEW, RTRUE, RFALSE, RINT, RDOUBLE, RSTRING, RBOOLEAN, RARROW, LARROW, SHARP, LPAREN, RPAREN, LSQUARE, RSQUARE, LBRACE, RBRACE, DOT, IDLETTERHEAD, IDLETTERTAIL, IDLETTERSPECIAL, ID, OPID, DIGITLETTER, Integer, Double, String, HEX } init { this.interpreter = LexerATNSimulator(this, ATN, decisionToDFA as Array<DFA?>, sharedContextCache) } }
0
Kotlin
0
0
d0118094206b71cb0ed71246dff612569ae96653
17,451
eopseo-parser-kotlin
Apache License 2.0
cassandra-service/src/main/kotlin/fund/cyber/cassandra/migration/configuration/MigrationRepositoryConfiguration.kt
GoodforGod
129,151,733
true
{"Kotlin": 332422, "Shell": 139}
package fund.cyber.cassandra.migration.configuration import fund.cyber.cassandra.common.CassandraRepositoriesConfiguration import fund.cyber.search.configuration.CASSANDRA_HOSTS import fund.cyber.search.configuration.CASSANDRA_HOSTS_DEFAULT import fund.cyber.search.configuration.CASSANDRA_PORT import fund.cyber.search.configuration.CASSANDRA_PORT_DEFAULT import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.cassandra.ReactiveSession import org.springframework.data.cassandra.config.CassandraSessionFactoryBean import org.springframework.data.cassandra.core.ReactiveCassandraOperations import org.springframework.data.cassandra.core.ReactiveCassandraTemplate import org.springframework.data.cassandra.core.cql.session.DefaultBridgedReactiveSession import org.springframework.data.cassandra.core.cql.session.DefaultReactiveSessionFactory import org.springframework.data.cassandra.repository.config.EnableReactiveCassandraRepositories @Configuration @EnableReactiveCassandraRepositories( basePackages = ["fund.cyber.cassandra.migration.repository"], reactiveCassandraTemplateRef = "keyspaceMigrationCassandraTemplate" ) class MigrationRepositoryConfiguration( @Value("\${$CASSANDRA_HOSTS:$CASSANDRA_HOSTS_DEFAULT}") private val cassandraHosts: String, @Value("\${$CASSANDRA_PORT:$CASSANDRA_PORT_DEFAULT}") private val cassandraPort: Int ) : CassandraRepositoriesConfiguration(cassandraHosts, cassandraPort) { override fun getKeyspaceName(): String = "cyber_system" override fun getEntityBasePackages(): Array<String> = arrayOf("fund.cyber.cassandra.migration.model") @Bean("keyspaceMigrationCassandraTemplate") fun reactiveCassandraTemplate( @Qualifier("keyspaceReactiveMigrationSession") session: ReactiveSession ): ReactiveCassandraOperations { return ReactiveCassandraTemplate(DefaultReactiveSessionFactory(session), cassandraConverter()) } @Bean("keyspaceReactiveMigrationSession") fun reactiveSession( @Qualifier("keyspaceMigrationSession") session: CassandraSessionFactoryBean ): ReactiveSession { return DefaultBridgedReactiveSession(session.`object`) } @Bean("keyspaceMigrationSession") override fun session(): CassandraSessionFactoryBean { val session = super.session() session.setKeyspaceName(keyspaceName) return session } }
0
Kotlin
0
1
dcf7f09463cd76674326caf87509e048882b4176
2,620
cyber-search
MIT License