path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/costular/marvelheroes/di/modules/DataModule.kt
jventor
138,651,450
true
{"Kotlin": 42550}
package com.costular.marvelheroes.di.modules import android.arch.persistence.room.Room import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import com.costular.marvelheroes.data.db.HeroDatabase import com.costular.marvelheroes.data.model.mapper.MarvelHeroMapper import com.costular.marvelheroes.data.net.MarvelHeroesService import com.costular.marvelheroes.data.repository.MarvelHeroesRepositoryImpl import com.costular.marvelheroes.data.repository.datasource.LocalMarvelDatasource import com.costular.marvelheroes.data.repository.datasource.RemoteMarvelHeroesDataSource import com.costular.marvelheroes.presentation.util.SettingsManager import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class DataModule { @Provides @Singleton fun provideMarvelHeroMapper(): MarvelHeroMapper = MarvelHeroMapper() @Provides @Singleton fun provideRemoteMarvelHeroesDataSource(marvelHeroesService: MarvelHeroesService, marvelHeroMapper: MarvelHeroMapper) : RemoteMarvelHeroesDataSource = RemoteMarvelHeroesDataSource(marvelHeroesService, marvelHeroMapper) @Provides @Singleton fun provideLocalMarvelHeroesDataSource(heroDatabase: HeroDatabase) : LocalMarvelDatasource = LocalMarvelDatasource(heroDatabase) @Provides @Singleton fun provideMarvelHeroesRepository( marvelRemoteMarvelHeroesDataSource: RemoteMarvelHeroesDataSource, localMarvelDataSource: LocalMarvelDatasource, settingsManager: SettingsManager): MarvelHeroesRepositoryImpl = MarvelHeroesRepositoryImpl(marvelRemoteMarvelHeroesDataSource, localMarvelDataSource, settingsManager) @Provides @Singleton fun provideHeroDatabase(context: Context): HeroDatabase = Room.databaseBuilder(context, HeroDatabase::class.java, "heroe_db").build() @Provides @Singleton fun provideSharedPreferences(context: Context) : SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) @Provides @Singleton fun provideSettingsManager(sharedPreferences: SharedPreferences) : SettingsManager = SettingsManager(sharedPreferences) }
0
Kotlin
0
0
ca9409ca793cbf10fa3bb4c32789057b042ca1b6
2,236
marvel-super-heroes
MIT License
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/regular/CheckSquare.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.fontawesomeicons.regular import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.fontawesomeicons.RegularGroup public val RegularGroup.CheckSquare: ImageVector get() { if (_checkSquare != null) { return _checkSquare!! } _checkSquare = Builder(name = "CheckSquare", defaultWidth = 448.0.dp, defaultHeight = 512.0.dp, viewportWidth = 448.0f, viewportHeight = 512.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(400.0f, 32.0f) lineTo(48.0f, 32.0f) curveTo(21.49f, 32.0f, 0.0f, 53.49f, 0.0f, 80.0f) verticalLineToRelative(352.0f) curveToRelative(0.0f, 26.51f, 21.49f, 48.0f, 48.0f, 48.0f) horizontalLineToRelative(352.0f) curveToRelative(26.51f, 0.0f, 48.0f, -21.49f, 48.0f, -48.0f) lineTo(448.0f, 80.0f) curveToRelative(0.0f, -26.51f, -21.49f, -48.0f, -48.0f, -48.0f) close() moveTo(400.0f, 432.0f) lineTo(48.0f, 432.0f) lineTo(48.0f, 80.0f) horizontalLineToRelative(352.0f) verticalLineToRelative(352.0f) close() moveTo(364.14f, 190.28f) lineTo(191.55f, 361.48f) curveToRelative(-4.7f, 4.67f, -12.3f, 4.64f, -16.97f, -0.07f) lineToRelative(-90.78f, -91.52f) curveToRelative(-4.67f, -4.7f, -4.64f, -12.3f, 0.07f, -16.97f) lineToRelative(22.72f, -22.54f) curveToRelative(4.7f, -4.67f, 12.3f, -4.64f, 16.97f, 0.07f) lineToRelative(59.79f, 60.28f) lineToRelative(141.35f, -140.22f) curveToRelative(4.7f, -4.67f, 12.3f, -4.64f, 16.97f, 0.07f) lineToRelative(22.54f, 22.72f) curveToRelative(4.67f, 4.71f, 4.64f, 12.3f, -0.07f, 16.97f) close() } } .build() return _checkSquare!! } private var _checkSquare: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,750
compose-icons
MIT License
src/commonTest/kotlin/RetriesTest.kt
andstatus
299,049,641
false
null
import korlibs.korge.tests.ViewsForTesting import kotlinx.coroutines.delay import org.andstatus.game2048.model.PlyAndPosition.Companion.allowedRandomPly import kotlin.test.Test import kotlin.test.assertEquals class RetriesTest : ViewsForTesting(log = true) { @Test fun retriesTest() = myViewsTest(this) { val game1 = generateGame(7, 3) assertEquals(1, game1.shortRecord.bookmarks.size, currentGameString()) waitForMainViewShown { presenter.onUndoClick() } waitForMainViewShown { presenter.onUndoClick() } val positionAfterUndos = presenter.model.gamePosition.copy() allowedRandomPly(presenter.model.gamePosition).ply.plyEnum.swipeDirection?.let { waitForMainViewShown { delay(2000) presenter.onSwipe(it) } } assertEquals(1, presenter.model.gamePosition.retries, currentGameString()) waitForMainViewShown { presenter.onUndoClick() } presenter.model.history.currentGame.gamePlies.get(presenter.model.history.redoPlyPointer).let { redoPly -> assertEquals( 1, redoPly.retries, "redoPly: " + "$redoPly, " + currentGameString() ) } assertEquals(0, presenter.model.gamePosition.retries, currentGameString()) waitForMainViewShown { presenter.onRedoClick() } assertEquals(1, presenter.model.gamePosition.retries, currentGameString()) waitForMainViewShown { presenter.onUndoClick() } assertEquals(0, presenter.model.gamePosition.retries, currentGameString()) // TODO: Time is different. //assertEquals(positionAfterUndos.toString(), presenter.model.gamePosition.toString(), currentGameString()) } }
7
null
11
61
7ab38d367cf8070ebc9a11a61a1983679846375f
1,872
game2048
Apache License 2.0
app/src/main/java/com/peruukki/simplecurrencyconverter/db/ConverterContract.kt
peruukki
13,539,498
false
null
package com.peruukki.simplecurrencyconverter.db import android.net.Uri import android.provider.BaseColumns object ConverterContract { private val CONTENT_AUTHORITY = "com.peruukki.simplecurrencyconverter" @JvmField val BASE_CONTENT_URI = Uri.parse("content://$CONTENT_AUTHORITY") class ConversionRateEntry : BaseColumns { companion object { const val TABLE_NAME = "conversionRates" const val COLUMN_FIXED_CURRENCY = "fixed" const val COLUMN_VARIABLE_CURRENCY = "variable" const val COLUMN_CONVERSION_RATE = "rate" } } }
0
Kotlin
0
1
6a0d36d96eb5447bfde5f611ab32393a112b02bf
610
SimpleCurrencyConverter
MIT License
app/src/main/java/com/nedaluof/qurany/util/LocaleManager.kt
nedaluof
279,111,786
false
{"Kotlin": 91881}
package com.nedaluof.qurany.util import android.content.Context import com.nedaluof.qurany.data.repository.SettingsRepository import java.util.Locale import javax.inject.Inject /** * Created by NedaluOf on 12/16/2022. */ class LocaleManager @Inject constructor( private val settingsRepository: SettingsRepository ) { fun configureAppLocale(context: Context): Context { return configureAppResources(context) } private fun configureAppResources(context: Context): Context { val locale = Locale(getLanguage()) Locale.setDefault(locale) return updateResources(context, locale) } private fun updateResources(context: Context, locale: Locale): Context { val configuration = context.resources.configuration.apply { setLocale(locale) setLayoutDirection(locale) } return context.createConfigurationContext(configuration) } private fun getLanguage() = if (settingsRepository.isCurrentLanguageEnglish()) "en" else "ar" }
0
Kotlin
0
2
ecb38606bf1f7dc2f090d51d91d9e3a9aea373b4
973
Qurany
Apache License 2.0
web/src/main/kotlin/controllers/ParadigmController.kt
yole
277,303,975
false
{"Kotlin": 386197, "JavaScript": 108267, "Dockerfile": 4286, "CSS": 1752}
package ru.yole.etymograph.web.controllers import org.springframework.web.bind.annotation.* import ru.yole.etymograph.GraphRepository import ru.yole.etymograph.Paradigm import ru.yole.etymograph.ParadigmCell import ru.yole.etymograph.ParadigmColumn import ru.yole.etymograph.web.resolveLanguage @RestController class ParadigmController { data class ParadigmCellViewModel( val alternativeRuleNames: List<String>, val alternativeRuleSummaries: List<String>, val alternativeRuleIds: List<Int?> ) data class ParadigmColumnViewModel( val title: String, val cells: List<ParadigmCellViewModel> ) data class ParadigmViewModel( val id: Int, val name: String, val language: String, val languageFullName: String, val pos: List<String>, val rowTitles: List<String>, val columns: List<ParadigmColumnViewModel>, val editableText: String ) data class ParadigmListViewModel( val langFullName: String, val paradigms: List<ParadigmViewModel> ) @GetMapping("/{graph}/paradigms") fun allParadigms(repo: GraphRepository): List<ParadigmViewModel> { return repo.allParadigms().map { it.toViewModel() } } @GetMapping("/{graph}/paradigms/{lang}") fun paradigms(repo: GraphRepository, @PathVariable lang: String): ParadigmListViewModel { val language = repo.resolveLanguage(lang) val paradigms = repo.paradigmsForLanguage(language).map { it.toViewModel() } return ParadigmListViewModel(language.name, paradigms) } private fun Paradigm.toViewModel() = ParadigmViewModel(id, name, language.shortName, language.name, pos, rowTitles, columns.map { it.toViewModel(rowTitles.size) }, toEditableText() ) private fun ParadigmColumn.toViewModel(rows: Int) = ParadigmColumnViewModel(title, (0 until rows).map { cells.getOrNull(it)?.toViewModel() ?: ParadigmCellViewModel(emptyList(), emptyList(), emptyList()) }) private fun ParadigmCell.toViewModel() = ParadigmCellViewModel( ruleAlternatives.map { it?.name ?: "." }, ruleAlternatives.map { it?.toSummaryText() ?: "" }, ruleAlternatives.map { it?.id }, ) @GetMapping("/{graph}/paradigm/{id}") fun paradigm(repo: GraphRepository, @PathVariable id: Int): ParadigmViewModel { val paradigmById = repo.resolveParadigm(id) return paradigmById.toViewModel() } private fun GraphRepository.resolveParadigm(id: Int): Paradigm = paradigmById(id) ?: notFound("No paradigm with ID $id") data class UpdateParadigmParameters( val name: String, val pos: String, val text: String ) @PostMapping("/{graph}/paradigms/{lang}", consumes = ["application/json"]) @ResponseBody fun newParadigm(repo: GraphRepository, @PathVariable lang: String, @RequestBody params: UpdateParadigmParameters): ParadigmViewModel { val language = repo.resolveLanguage(lang) val p = repo.addParadigm(params.name, language, parseList(params.pos)) p.parse(params.text, repo::ruleByName) return p.toViewModel() } @PostMapping("/{graph}/paradigm/{id}", consumes = ["application/json"]) @ResponseBody fun updateParadigm(repo: GraphRepository, @PathVariable id: Int, @RequestBody params: UpdateParadigmParameters) { val paradigm = repo.resolveParadigm(id) paradigm.parse(params.text, repo::ruleByName) paradigm.name = params.name paradigm.pos = parseList(params.pos) } @PostMapping("/{graph}/paradigm/{id}/delete") @ResponseBody fun deleteParadigm(repo: GraphRepository, @PathVariable id: Int) { val paradigm = repo.resolveParadigm(id) repo.deleteParadigm(paradigm) } }
0
Kotlin
1
16
c788eb564fb92b1ed5de12ee6cf372bf648d749e
3,925
etymograph
Apache License 2.0
app/src/main/java/com/example/digiit/getAPIResponse/getAPIResponse.kt
cedric190703
595,939,564
false
null
package com.example.digiit.getAPIResponse import android.util.Log import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.* import okhttp3.RequestBody.Companion.asRequestBody import org.json.JSONObject import java.io.File import java.util.concurrent.TimeUnit data class ApiResponse( val status: String, val message: String, val title: String?, val time: String?, val date: String?, val total: String? ) fun getApiResponse(imageFile: File, apiUrl: String): ApiResponse { val client = OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .build() try { val file = File(imageFile.toURI()) val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("image", imageFile.name, imageFile.asRequestBody("image/jpg".toMediaTypeOrNull())) .build() val request = Request.Builder() .url(apiUrl) .method("POST", requestBody) .header("Content-Type", "multipart/form-data") // Add this line .build() Log.d("image", "$file") Log.d("request", "$requestBody") // Get the response from the API val response: Response = client.newCall(request).execute() Log.d("response", "$response") // Check if the response is not valid if (response.code == 400 || !response.isSuccessful) { return ApiResponse( status = "error", message = "Image processing failed", title = "", time = "", date = "", total = "" ) } // Put the API response into string val responseBody = response.body?.string() ?: "" val jsonObject = JSONObject(responseBody) Log.d("JSON Object from the API", "$jsonObject") val title = if (jsonObject.getString("title") == "null") "" else jsonObject.getString("title") val time = if (jsonObject.getString("time") == "null") "" else jsonObject.getString("time") val date = if (jsonObject.getString("date") == "null") "" else jsonObject.getString("date") val total = if (jsonObject.getString("total") == "null") "" else jsonObject.getString("total") val apiResponse = ApiResponse( status = "success", message = "Image processed successfully", title = title, time = time, date = date, total = total ) response.close() return apiResponse } catch (e: Exception) { Log.e("getApiResponse", "Error: ${e.message}") return ApiResponse( status = "error", message = "Image processing failed", title = "", time = "", date = "", total = "" ) } }
0
Kotlin
0
0
7a3554954fe8f94e7b41e2acdf4160b9bb061737
3,053
Digiit
MIT License
app/src/main/java/com/keithsmyth/androidshowcase/service/model/EvolutionChainServiceModel.kt
keithsmyth
756,618,676
false
{"Kotlin": 70798}
package com.keithsmyth.androidshowcase.service.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class EvolutionChainServiceModel( val id: Int, val chain: Chain, ) { @Serializable data class Chain( val species: NamedApiResource, @SerialName("evolves_to") val evolvesTo: List<Chain>, @SerialName("evolution_details") val evolutionDetails: List<EvolutionDetail>, ) @Serializable data class EvolutionDetail( @SerialName("min_level") val minLevel: Int?, val trigger: NamedApiResource, ) }
0
Kotlin
0
0
926aaf793c6efa518caedbdb16ea1abea2d32d2b
617
Android-Showcase
Apache License 2.0
intellij2checkstyle-gradle/src/main/kotlin/de/theodm/intellij2checkstyle/InspectTask.kt
theodm
143,562,099
false
null
package de.theodm.intellij2checkstyle import de.theodm.intellij2checkstyle.convert.domain.Severity import de.theodm.intellij2checkstyle.convert.reporters.checkstyle.CheckstyleReporter import de.theodm.intellij2checkstyle.convert.reporters.plaintext.PlaintextReporter import de.theodm.intellij2checkstyle.convert.reporters.result.Result import de.theodm.intellij2checkstyle.convert.reporters.result.ResultReporter import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.tasks.TaskAction import java.io.File import java.nio.file.FileSystems import java.nio.file.Files import java.nio.file.Paths /** * Task which runs an intellij inspection. */ open class InspectTask : DefaultTask() { private val defaultOutputDir = this .project .rootProject .buildDir .toPath() .resolve("reports") .resolve("i2c") .toFile() /** * Should temporary files be deleted. */ var keepTemp: Boolean = false /** * Path to IntelliJ instance, if not set IDEA_HOME environment variable will be used. */ var intellijPath: String? = null /** * Output folder of the results (default is ${buildDir]/reports/i2c. */ var outputFolder: File = defaultOutputDir /** * Inspection Profile to use. */ var profileName: String? = null /** * Scope of the analysis. */ var scope: String? = null /** * Path to proxy settings file. */ var proxySettingsDir: String? = null /** * Fail the build on defined serverity. */ var failOnSeverity: Severity = Severity.None /** * Main Task action. */ @TaskAction fun inspect() { println( "This task must be run with the --no-daemon parameter. Otherwise the started " + "intellij instance will stop the currently running gradle daemon." ) Files.createDirectories(outputFolder.toPath()) val checkstyleOutputFile = outputFolder.resolve("checkstyle.xml").toPath() val plaintextOutputFile = outputFolder.resolve("plaintext.txt").toPath() val resultReporter = ResultReporter(failOnSeverity) val plaintextReporter = PlaintextReporter(plaintextOutputFile) val checkstyleReporter = CheckstyleReporter(checkstyleOutputFile) Intellij2Checkstyle.inspect( fileSystem = FileSystems.getDefault(), intelliJPathOverride = intellijPath?.let { Paths.get(it) }, profileOverride = profileName, projectFolderPath = Paths.get(this.project.rootDir.absolutePath), scopeOverride = scope, proxySettingsDir = proxySettingsDir?.let { Paths.get(it) }, keepTemp = keepTemp, reporter = listOf( checkstyleReporter, plaintextReporter, resultReporter ) ) plaintextReporter .plaintextResult ?.let { println("\n$it") } val result = resultReporter.result when (result) { is Result.Success -> return is Result.NoResultYet -> throw GradleException( "Inspection task failed because " + "ResultReporter didn't return a result" ) is Result.Error -> throw GradleException(result.message) } } }
1
null
1
1
2607e1f9e4f64e7b4e8140c56918ad5d856a62eb
3,441
intellij2checkstyle
Apache License 2.0
src/jvmMain/kotlin/com/sunnychung/application/multiplatform/hellohttp/ux/AppImage.kt
sunny-chung
711,387,879
false
{"Kotlin": 1426494, "Shell": 3020}
package com.sunnychung.application.multiplatform.hellohttp.ux import androidx.compose.foundation.Image import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.sunnychung.application.multiplatform.hellohttp.ux.local.LocalColor @Composable fun AppImage( modifier: Modifier = Modifier, resource: String, size: Dp = 32.dp, color: Color = LocalColor.current.image, enabled: Boolean = true ) { val colorToUse = if (enabled) { color } else { color.copy(alpha = color.alpha / 2f) } var modifierToUse = modifier.size(size) Image( painter = painterResource("image/$resource"), colorFilter = ColorFilter.tint(colorToUse), contentDescription = null, modifier = modifierToUse ) }
0
Kotlin
0
72
a71b1bab930be2ecbf533c702ee44ef8c549a287
1,048
hello-http
Apache License 2.0
app/src/main/java/com/example/tinypomodoro/PomodoroTimer.kt
kyawakyawa
247,976,757
false
null
package com.example.tinypomodoro class PomodoroTimer(setTimes_: Array<Int>, timerNames_: Array<String>) { private var setTimes: Array<Int> = setTimes_ private var timerNames: Array<String> = timerNames_ private var timers: Array<Timer> = Array(setTimes.size) { i -> Timer(setTimes[i]) } private var activeTimerId: Int = 0 private var status = false fun getSetTimes(): Array<Int> { return setTimes } fun setSetTimes(setTimes_: Array<Int>) { setTimes = setTimes_ timers = Array(setTimes.size) { i -> Timer(setTimes[i]) } } fun getActiveTimerId(): Int { return activeTimerId } fun setActivetimerId(activeTimerId_: Int) { activeTimerId = activeTimerId_ % timers.size } fun getActiveTimerName(): String { return timerNames[activeTimerId] } fun getRemainingTime(): Int { return timers[activeTimerId].getRemainingTime() } fun getStatus(): Boolean { return status } fun setStatus(status_: Boolean) { status = status_ } fun advanceOneSecond(): Boolean { val time_left = timers[activeTimerId].advanceOneSecond() if (!time_left) { timers[activeTimerId].reset() activeTimerId = (activeTimerId + 1) % timers.size } return time_left } fun reset() { for (timer in timers) { timer.reset() } } }
0
Kotlin
0
0
9493a0b70b8f59a2d2b8c4f6c71f26b099350e65
1,447
TinyPomodoro
MIT License
src/main/kotlin/me/steven/indrev/datagen/generators/MaterialRecipeGenerator.kt
GabrielOlvH
265,247,813
false
null
package me.steven.indrev.datagen.generators import com.google.gson.JsonObject import me.steven.indrev.datagen.DataGenerator import me.steven.indrev.datagen.JsonFactory import net.minecraft.util.Identifier import java.io.File class MaterialRecipeGenerator( val root: File, namespace: String, fallback: (String) -> JsonFactory<String> ) : DataGenerator<String, JsonObject?>(File(root, "recipes"), namespace, fallback) { fun register(id: Identifier, factory: JsonFactory<String>) { generators[id.toString()] = factory } override fun generate(): Int { var count = 0 generators.forEach { (tag, _) -> if (generate(Identifier(tag), tag)) count++ } return count } companion object }
51
null
56
192
012a1b83f39ab50a10d03ef3c1a8e2651e517053
779
Industrial-Revolution
Apache License 2.0
app/src/main/java/com/ramzmania/aicammvd/pager/PagerExt.kt
rameshvoltella
775,820,814
false
{"Kotlin": 188167, "Java": 13908}
package com.ramzmania.aicammvd.pager /** * Calculates the current offset for the given page in a PagerState. * This function is experimental and requires opting in to the ExperimentalFoundationApi. * * @param page The page for which to calculate the offset. * @return The current offset for the given page. */ import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.pager.PagerState @OptIn(ExperimentalFoundationApi::class) fun PagerState.calculateCurrentOffsetForPage(page: Int): Float { return (currentPage - page) + currentPageOffsetFraction }
0
Kotlin
0
1
b1ef96dc554d066949b0529d0a76a4503b68fb32
597
KeralaAICameraTracker
MIT License
platform/core-api/src/com/intellij/codeWithMe/ClientIdService.kt
haarlemmer
392,603,002
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeWithMe import com.intellij.diagnostic.LoadingState import com.intellij.openapi.application.ApplicationManager interface ClientIdService { companion object { fun tryGetInstance(): ClientIdService? { if (!LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred || ApplicationManager.getApplication().isDisposed) { return null } return ApplicationManager.getApplication().getService(ClientIdService::class.java) } } var clientIdValue: String? val checkLongActivity: Boolean }
1
null
1
1
de80b70f5507f0110de89a95d72b8f902ca72b3e
685
intellij-community
Apache License 2.0
app/src/main/java/com/example/randompokemongenerator/PokedexListActivity.kt
nohabean
705,996,853
false
{"Kotlin": 42771}
package com.example.randompokemongenerator import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.TextView import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.codepath.asynchttpclient.AsyncHttpClient import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler import okhttp3.Headers import org.json.JSONArray import kotlin.random.Random class PokedexListActivity : AppCompatActivity() { private lateinit var recyclerViewPokedex: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.pokedex_list) recyclerViewPokedex = findViewById<RecyclerView>(R.id.pokedex_recycler_view) val pokedexImageList = mutableListOf<String>() val pokedexNumberList = mutableListOf<String>() val pokedexTypeList = mutableListOf<String>() getPokemonData(1, 1017, pokedexImageList, pokedexNumberList, pokedexTypeList) } private fun getPokemonData(currentPokemonId: Int, lastPokemonId: Int, pokemonImagesList: MutableList<String>, pokemonNumberList: MutableList<String>, pokemonTypeList: MutableList<String>) { if (currentPokemonId <= lastPokemonId) { val client = AsyncHttpClient() val pokemonJSON = "https://pokeapi.co/api/v2/pokemon/$currentPokemonId" client[pokemonJSON, object : JsonHttpResponseHandler() { override fun onFailure(statusCode: Int, headers: Headers?, errorResponse: String, throwable: Throwable?) { Log.d("Error", errorResponse) } override fun onSuccess(statusCode: Int, headers: Headers?, json: JsonHttpResponseHandler.JSON) { Log.d("success", json.jsonObject.toString()) val pokemonObject = json.jsonObject val pokemonNumber = pokemonObject.getString("id") val sprites = json.jsonObject.getJSONObject("sprites") val pokemonImage = sprites.getString("front_default") val types = json.jsonObject.getJSONArray("types") val pokemonType = extractTypeNames(types) pokemonImagesList.add(pokemonImage) pokemonNumberList.add(pokemonNumber) pokemonTypeList.add(pokemonType) // Continue fetching data for the next Pokemon getPokemonData(currentPokemonId + 1, lastPokemonId, pokemonImagesList, pokemonNumberList, pokemonTypeList) } }] } else { Log.d("Images", pokemonImagesList.toString()) Log.d("Numbers", pokemonNumberList.toString()) Log.d("Types", pokemonTypeList.toString()) // All Pokemon data fetched, update RecyclerView val gridLayoutManager = GridLayoutManager(this@PokedexListActivity, 2) recyclerViewPokedex.layoutManager = gridLayoutManager recyclerViewPokedex.adapter = PokedexAdapter(pokemonImagesList, pokemonNumberList, pokemonTypeList) recyclerViewPokedex.addItemDecoration( DividerItemDecoration( this@PokedexListActivity, DividerItemDecoration.VERTICAL ) ) } } private fun extractTypeNames(typesArray: JSONArray): String { val typeNames = mutableListOf<String>() for (i in 0 until typesArray.length()) { val typeObj = typesArray.getJSONObject(i).getJSONObject("type") val typeName = typeObj.getString("name") typeNames.add(typeName) } return typeNames.joinToString(" / ") } }
0
Kotlin
0
0
97b8e68b369c344e21b20468f36f1bf9af098710
4,030
Random-Pokemon-Generator
Apache License 2.0
src/main/kotlin/net/ndrei/teslacorelib/gui/ToggleButtonPiece.kt
MinecraftModDevelopmentMods
75,457,648
false
{"Gradle": 2, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 7, "Ignore List": 1, "Batchfile": 1, "JSON": 54, "Kotlin": 267, "Java": 3}
package net.ndrei.teslacorelib.gui import net.minecraft.client.renderer.GlStateManager import net.minecraft.client.renderer.RenderHelper import net.minecraft.item.ItemStack import net.ndrei.teslacorelib.compatibility.FontRendererUtil import net.ndrei.teslacorelib.inventory.BoundingRectangle /** * Created by CF on 2017-06-28. */ @Suppress("unused") abstract class ToggleButtonPiece(left: Int, top: Int, width: Int, height: Int, private val hoverOffset: Int = 0) : BasicContainerGuiPiece(left, top, width, height) { protected open val currentState: Int = 0 protected open fun getStateToolTip(state: Int): List<String> = listOf() protected abstract fun renderState(container: BasicTeslaGuiContainer<*>, state: Int, box: BoundingRectangle) protected abstract fun clicked() protected open val isEnabled: Boolean = true override fun drawBackgroundLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, partialTicks: Float, mouseX: Int, mouseY: Int) { if (super.isInside(container, mouseX, mouseY) && this.isEnabled) { ButtonPiece.drawHoverArea(container, this, this.hoverOffset) } } override fun drawForegroundLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, mouseX: Int, mouseY: Int) { val state = this.currentState val x = this.left + (this.width - 16) / 2 val y = this.top + (this.height - 16) / 2 this.renderState(container, state, BoundingRectangle(x, y, 16, 16)) } override fun drawForegroundTopLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, mouseX: Int, mouseY: Int) { if (super.isInside(container, mouseX, mouseY)) { val tt = this.getStateToolTip(this.currentState) if (!tt.isEmpty()) { container.drawTooltip(tt, this.left + this.width / 2, this.top + this.height / 2) } } } protected fun renderItemStack(container: BasicTeslaGuiContainer<*>, stack: ItemStack?, box: BoundingRectangle) { if (stack != null) { val item = container.itemRenderer RenderHelper.enableGUIStandardItemLighting() GlStateManager.pushMatrix() GlStateManager.enableDepth() container.itemRenderer.renderItemAndEffectIntoGUI(stack, box.left, box.top) container.itemRenderer.renderItemOverlayIntoGUI(FontRendererUtil.fontRenderer, stack, box.left, box.top, null) GlStateManager.popMatrix() RenderHelper.disableStandardItemLighting() item.renderItemOverlayIntoGUI(container.fontRenderer, stack, box.left, box.top, null) } } override fun mouseClicked(container: BasicTeslaGuiContainer<*>, mouseX: Int, mouseY: Int, mouseButton: Int) { if (super.isInside(container, mouseX, mouseY) && this.isEnabled) { this.clicked() } } }
14
Kotlin
8
6
b418beae0efee11f1bedf60a95c2aa74b0be31ec
2,897
Tesla-Core-Lib
MIT License
src/main/kotlin/de/flapdoodle/tab/observable/ChangeListener.kt
flapdoodle-oss
237,231,857
false
null
package de.flapdoodle.tab.observable fun interface ChangeListener<T : Any> { fun changed(src: AObservable<T>, old: T, new: T) }
0
Kotlin
0
0
d8154544a5ae9e922b31f7a652bcbc5dd5ee9a65
130
tab
Apache License 2.0
src/nl/hannahsten/texifyidea/action/preview/InkscapePreviewer.kt
Hannah-Sten
62,398,769
false
null
package nl.hannahsten.texifyidea.action.preview import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import nl.hannahsten.texifyidea.settings.sdk.LatexSdkUtil import nl.hannahsten.texifyidea.util.SystemEnvironment import nl.hannahsten.texifyidea.util.runCommandWithExitCode import java.io.File import java.io.IOException import java.io.PrintWriter import java.nio.file.Paths import javax.imageio.ImageIO import javax.swing.SwingUtilities /** * Preview based on Inkscape. */ class InkscapePreviewer : Previewer { override fun preview(input: String, previewForm: PreviewForm, project: Project, preamble: String, waitTime: Long) { ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Generating preview...") { override fun run(indicator: ProgressIndicator) { try { // Snap apps are confined to the users home directory if (SystemEnvironment.isInkscapeInstalledAsSnap) { setPreviewCodeInTemp( FileUtil.createTempDirectory(File(System.getProperty("user.home")), "preview", null), input, project, preamble, previewForm, waitTime ) } else { setPreviewCodeInTemp(FileUtil.createTempDirectory("preview", null), input, project, preamble, previewForm, waitTime) } } catch (exception: AccessDeniedException) { previewForm.setLatexErrorMessage("${exception.message}") } catch (exception: IOException) { previewForm.setLatexErrorMessage("${exception.message}") } } }) } /** * First define the function that actually does stuff in a temp folder. The usual temp directory might not be * accessible by inkscape (e.g., when inkscape is a snap), and using function we can specify an alternative * temp directory in case the usual fails. */ private fun setPreviewCodeInTemp( tempDirectory: File, previewCode: String, project: Project, preamble: String, previewForm: PreviewForm, waitTime: Long ) { try { val tempBasename = Paths.get(tempDirectory.path.toString(), "temp").toString() val writer = PrintWriter("$tempBasename.tex", "UTF-8") val tmpContent = """\documentclass{article} $preamble \begin{document} $previewCode \end{document}""" writer.println(tmpContent) writer.close() val latexStdoutText = runPreviewFormCommand( LatexSdkUtil.getExecutableName("pdflatex", project), arrayOf( "-interaction=nonstopmode", "-halt-on-error", "$tempBasename.tex" ), tempDirectory, waitTime, previewForm ) ?: return // Sets error message to the UI if any val success = runInkscape(tempBasename, tempDirectory, waitTime, previewForm) if (success) { val image = ImageIO.read(File("$tempBasename.png")) SwingUtilities.invokeLater { previewForm.setPreview(image, latexStdoutText) } } } finally { // Delete all the created temp files in the default temp directory. tempDirectory.deleteRecursively() } } private fun runPreviewFormCommand( command: String, args: Array<String>, workDirectory: File, waitTime: Long, previewForm: PreviewForm ): String? { val result = runCommandWithExitCode(command, *args, workingDirectory = workDirectory, timeout = waitTime, returnExceptionMessage = true) if (result.second != 0) { previewForm.setLatexErrorMessage("$command exited with ${result.second}\n${result.first ?: ""}") return null } return result.first } /** * Run inkscape command to convert pdf to png, depending on the version of inkscape. * * @return If successful */ private fun runInkscape(tempBasename: String, tempDirectory: File, waitTime: Long, previewForm: PreviewForm): Boolean { // If 1.0 or higher if (SystemEnvironment.inkscapeMajorVersion >= 1 || !SystemEnvironment.isAvailable("inkscape")) { runPreviewFormCommand( inkscapeExecutable(), arrayOf( "$tempBasename.pdf", "--export-area-drawing", "--export-dpi", "1000", "--export-background", "#FFFFFF", "--export-background-opacity", "1.0", "--export-filename", "$tempBasename.png" ), tempDirectory, waitTime, previewForm ) ?: return false } else { runPreviewFormCommand( pdf2svgExecutable(), arrayOf( "$tempBasename.pdf", "$tempBasename.svg" ), tempDirectory, waitTime, previewForm ) ?: return false runPreviewFormCommand( inkscapeExecutable(), arrayOf( "$tempBasename.svg", "--export-area-drawing", "--export-dpi", "1000", "--export-background", "#FFFFFF", "--export-png", "$tempBasename.png" ), tempDirectory, waitTime, previewForm ) ?: return false } return true } private fun inkscapeExecutable(): String { var suffix = "" if (SystemInfo.isWindows) { suffix = ".exe" } return "inkscape$suffix" } private fun pdf2svgExecutable(): String { var suffix = "" if (SystemInfo.isWindows) { suffix = ".exe" } return "pdf2svg$suffix" } }
99
null
87
891
986550410e2fea91d1e93abfc683db1c8527c9d9
6,668
TeXiFy-IDEA
MIT License
src/main/kotlin/dev/benedikt/plutos/models/TagPattern.kt
Bw2801
589,336,596
false
null
package dev.benedikt.plutos.models import dev.benedikt.plutos.api.structure.ResourceObject import dev.benedikt.plutos.api.structure.ResourceObjectBuilder import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import org.jetbrains.exposed.dao.id.IntIdTable import org.jetbrains.exposed.sql.ResultRow import org.jetbrains.exposed.sql.insertAndGetId import org.jetbrains.exposed.sql.transactions.transaction @Serializable class TagPattern : Pattern { companion object { const val type = "tagPatterns" } @Transient var tagId: Int = -1 @Transient var patternId: Int = -1 constructor( name: String, regex: String, matchMode: MatchMode, matchTargets: List<MatchTarget>, accountTargets: List<Int>, squishData: Boolean ) : super(name, regex, matchMode, matchTargets, accountTargets, squishData) } object TagPatterns : IntIdTable() { val patternId = reference("pattern", Patterns).uniqueIndex() val tagId = reference("tag", Tags) } fun ResultRow.toTagPattern() = Model( id = this[TagPatterns.id].value, type = TagPattern.type, attributes = TagPattern( name = this[Patterns.name], regex = this[Patterns.regex], matchMode = this[Patterns.matchMode], matchTargets = this[Patterns.matchTargets]?.split(",")?.map(MatchTarget::valueOf) ?: listOf(), accountTargets = this[Patterns.accountTargets]?.split(",")?.map(String::toInt) ?: listOf(), squishData = this[Patterns.squishData] ).also { it.patternId = this[Patterns.id].value it.tagId = this[TagPatterns.tagId].value } ) fun Model<Pattern>.toTagPattern(patternId: Int, tagId: Int) = Model( id = this.id!!, type = TagPattern.type, attributes = TagPattern( name = this.attributes.name, regex = this.attributes.regex, matchMode = this.attributes.matchMode, matchTargets = this.attributes.matchTargets, accountTargets = this.attributes.accountTargets, squishData = this.attributes.squishData ).also { it.patternId = patternId it.tagId = tagId } ) fun Patterns.insertTagPattern(pattern: Model<TagPattern>, tagId: Int) : Model<TagPattern> { val actualPattern = this.insertPattern(pattern) val id = TagPatterns.insertAndGetId { it[patternId] = actualPattern.id!! it[TagPatterns.tagId] = tagId } val attributes = TagPattern( pattern.attributes.name, pattern.attributes.regex, pattern.attributes.matchMode, pattern.attributes.matchTargets, pattern.attributes.accountTargets, pattern.attributes.squishData ) attributes.tagId = tagId attributes.patternId = actualPattern.id!! return pattern.copy(id = id.value, attributes = attributes) } fun Model<TagPattern>.toResourceObject(): ResourceObject { val entity = this return transaction { return@transaction ResourceObjectBuilder(entity, TagPattern::class) .relationship("tag", Tag.type, entity.attributes.tagId) .build() } }
7
Kotlin
0
4
eeb8965ee3442711803e25553360c9c4193856fe
3,129
plutos
Apache License 2.0
example_mod_1_14_4/src/main/java/sharkbound/forge/firstmod/items/Striker.kt
sharkbound
247,764,906
false
null
package sharkbound.forge.firstmod.items import net.minecraft.client.util.ITooltipFlag import net.minecraft.entity.player.PlayerEntity import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.util.ActionResult import net.minecraft.util.ActionResultType import net.minecraft.util.Hand import net.minecraft.util.text.ITextComponent import net.minecraft.world.World import sharkbound.commonutils.util.randDouble import sharkbound.commonutils.util.randRange import sharkbound.forge.firstmod.creative.FirstModItemGroup import sharkbound.forge.firstmod.events.scheduler.delayTask import sharkbound.forge.shared.extensions.addAll import sharkbound.forge.shared.extensions.doLightningStrike import sharkbound.forge.shared.extensions.isServerPlayer import sharkbound.forge.shared.extensions.isServerWorld import sharkbound.forge.shared.extensions.item import sharkbound.forge.shared.extensions.rayTraceBlocks import sharkbound.forge.shared.extensions.ticks import sharkbound.forge.shared.util.TickUnit import sharkbound.forge.shared.util.asText import kotlin.contracts.ExperimentalContracts class Striker : Item(Properties().maxStackSize(1).group(FirstModItemGroup)) { init { setRegistryName("striker") } override fun getDisplayName(stack: ItemStack): ITextComponent { return asText("&6Striker") } val r get() = randDouble(-4, 4) @ExperimentalContracts fun callStrike(world: World, player: PlayerEntity) { if (world.isServerWorld() && player.isServerPlayer()) { player.rayTraceBlocks(100.0).run { delayTask(5.ticks(TickUnit.SECONDS)) { repeat(randRange(100)) { world.doLightningStrike(hitVec.add(r, 0.0, r)) } } } } } @ExperimentalContracts override fun onItemRightClick(world: World, player: PlayerEntity, handIn: Hand): ActionResult<ItemStack> { callStrike(world, player) return ActionResult(ActionResultType.SUCCESS, player.item.stack) } override fun addInformation(stack: ItemStack, worldIn: World?, tooltip: MutableList<ITextComponent>, flagIn: ITooltipFlag) { tooltip.addAll("&eCalls down a lightning strike upon your enemies!") } }
0
Kotlin
0
0
3302ac118d6ed9da341b74c25e13edcc4e29a040
2,294
forge-projects
MIT License
app/src/main/java/io/sample/smartaccess/data/ble/GattServerManager.kt
CoreWillSoft
668,573,101
false
null
package io.sample.smartaccess.data.ble import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGattCharacteristic.PERMISSION_READ import android.bluetooth.BluetoothGattCharacteristic.PERMISSION_WRITE import android.bluetooth.BluetoothGattCharacteristic.PROPERTY_NOTIFY import android.bluetooth.BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE import android.bluetooth.BluetoothGattService import android.content.Context import android.util.Log import io.sample.smartaccess.data.tunnel.Tunnel import no.nordicsemi.android.ble.BleServerManager import no.nordicsemi.android.ble.observer.ServerObserver import java.util.UUID internal val SERVICE_UUID: UUID = UUID.fromString("49575abc-26e1-11ee-be56-0242ac120002") internal val RECEIVER_CHARACTERISTIC_UUID: UUID = UUID.fromString("49575d8c-26e1-11ee-be56-0242ac120002") internal val BROADCASTER_CHARACTERISTIC_UUID: UUID = UUID.fromString("49575f08-26e1-11ee-be56-0242ac120002") internal class GattServerManager(private val context: Context) : BleServerManager(context), ServerObserver { private val receiverCharacteristic = sharedCharacteristic( RECEIVER_CHARACTERISTIC_UUID, PROPERTY_WRITE_NO_RESPONSE, PERMISSION_WRITE, ) private val broadcasterCharacteristic = sharedCharacteristic( BROADCASTER_CHARACTERISTIC_UUID, PROPERTY_NOTIFY, PERMISSION_READ, ) private val gattService = service(SERVICE_UUID, receiverCharacteristic, broadcasterCharacteristic) private var tunnel: Tunnel? = null override fun initializeServer(): List<BluetoothGattService> = listOf(gattService).also { setServerObserver(this) } override fun onServerReady() { log(Log.INFO, "Gatt server ready") } override fun onDeviceConnectedToServer(device: BluetoothDevice) { if (tunnel != null) return tunnel = Tunnel.make(device, this, context, receiverCharacteristic, broadcasterCharacteristic).apply(Tunnel::connect) } override fun onDeviceDisconnectedFromServer(device: BluetoothDevice) { tunnel?.closeConnection() tunnel = null } }
0
Kotlin
0
0
ebf3259988ccf047ecc9820f4c89c9e5466fcd59
2,123
smart-access-sample-android
MIT License
app/src/main/java/com/scudderapps/moviesup/models/tv/Episode.kt
m-scudder
252,821,750
false
{"Kotlin": 293411}
package com.scudderapps.moviesup.models.tv import com.google.gson.annotations.SerializedName import com.scudderapps.moviesup.models.common.CrewDetail data class Episode( @SerializedName("air_date") val airDate: String, @SerializedName("crew") val crewList: List<CrewDetail>, @SerializedName("episode_number") val episodeNumber: Int, @SerializedName("guest_stars") val guestStars: List<GuestStar>, val id: Int, val name: String, val overview: String, @SerializedName("production_code") val productionCode: String, @SerializedName("season_number") val seasonNumber: Int, @SerializedName("show_id") val showId: Int, @SerializedName("still_path") val stillPath: String, @SerializedName("vote_average") val voteAverage: Double, @SerializedName("vote_count") val voteCount: Int )
0
Kotlin
1
2
000f1539946ad0298f53252464de90bcfe238c83
868
MovieTime
MIT License
src/main/kotlin/com/jetbrains/typofixer/search/index/LocalInnerIndex.kt
bronti
96,321,194
false
null
package com.jetbrains.typofixer.search.index import com.intellij.psi.PsiElement import com.jetbrains.typofixer.lang.LocalDictionaryCollector import com.jetbrains.typofixer.lang.TypoFixerLanguageSupport import com.jetbrains.typofixer.search.signature.Signature import org.jetbrains.annotations.TestOnly import java.util.* class LocalInnerIndex( signature: Signature, private val getWords: (wordsCollector: LocalDictionaryCollector, element: PsiElement) -> Set<String> ) : InnerIndex(signature) { private val index = HashMap<Int, HashSet<String>>() override fun getSize() = index.entries.sumBy { it.value.size } fun clear() = index.clear() override fun getWithDefault(signature: Int) = index[signature]?.asSequence()?.constrainOnce() ?: emptySequence() override fun addAll(signature: Int, strings: Set<String>) { if (index[signature] == null) { index[signature] = hashSetOf() } index[signature]!!.addAll(strings) } fun refresh(element: PsiElement?) { index.clear() element ?: return val collector = TypoFixerLanguageSupport.getSupport(element.language)?.getLocalDictionaryCollector() ?: return addAll(getWords(collector, element)) } fun refreshWithWords(words: Set<String>) { index.clear() addAll(words) } @TestOnly override fun contains(str: String) = index[signature.get(str)]?.contains(str) == true }
1
null
1
1
33e436b815a86cc7980fbbd18ffda543fb895122
1,458
typofixer
Apache License 2.0
dairo-dfs-server/src/main/java/cn/dairo/dfs/controller/app/advanced/AdvancedAppController.kt
DAIRO-HY
850,929,695
false
{"Kotlin": 360103, "HTML": 135261, "JavaScript": 33804, "Java": 27584, "Shell": 4415, "Dockerfile": 3240, "CSS": 2579, "Batchfile": 967, "SCSS": 33}
package cn.dairo.dfs.controller.app.advanced import cn.dairo.dfs.config.Constant import cn.dairo.dfs.controller.base.AppBase import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseBody import java.io.PrintStream /** * 数据同步状态 */ @Controller @RequestMapping("/app/advanced") class AdvancedAppController : AppBase() { /** * 页面初始化 */ @GetMapping fun execute() = "app/advanced" /** * 页面数据初始化 */ @PostMapping("/exec_sql") @ResponseBody fun execSql(sql: String): Any { Constant.dbService.use { if (sql.trim().lowercase().startsWith("select")) {//如果是查询语句 //限制返回条数 return it.selectList(sql).take(10000) } else { return it.exec(sql) } } } }
0
Kotlin
0
0
037e8a4bab1c687820336df0ec368ca82e0e251b
1,018
DairoDfs
Apache License 2.0
presentation/src/commonMain/kotlin/com/chrynan/video/presentation/reducer/SettingsReducer.kt
chRyNaN
174,161,260
false
null
package com.chrynan.video.presentation.reducer import com.chrynan.inject.Inject import com.chrynan.video.presentation.core.Reducer import com.chrynan.video.presentation.state.SettingsChange import com.chrynan.video.presentation.state.SettingsState class SettingsReducer @Inject constructor() : Reducer<SettingsState, SettingsChange> { override suspend fun reduce(previous: SettingsState, change: SettingsChange): SettingsState { TODO("Not yet implemented") } }
0
Kotlin
0
8
63456dcfdd57dbee9ff02b2155b7e1ec5761db81
479
Video
Apache License 2.0
ui/src/main/kotlin/io/github/gmvalentino8/github/sample/ui/features/search/results/pullrequest/SearchPullRequestResultsViewModel.kt
wasabi-muffin
462,369,263
false
{"Kotlin": 2712155, "Mustache": 4796, "Ruby": 1144, "Shell": 812}
package io.github.gmvalentino8.github.sample.ui.features.search.results.pullrequest import android.os.Bundle import androidx.lifecycle.AbstractSavedStateViewModelFactory import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.savedstate.SavedStateRegistryOwner import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import io.github.gmvalentino8.github.sample.domain.entities.PullRequest import io.github.gmvalentino8.github.sample.presentation.core.components.Store import io.github.gmvalentino8.github.sample.presentation.core.contract.State import io.github.gmvalentino8.github.sample.presentation.core.factory.StoreFactory import io.github.gmvalentino8.github.sample.presentation.core.middleware.StateSaverMiddleware import io.github.gmvalentino8.github.sample.presentation.feature.search.results.contract.SearchResultsAction import io.github.gmvalentino8.github.sample.presentation.feature.search.results.contract.SearchResultsEvent import io.github.gmvalentino8.github.sample.presentation.feature.search.results.contract.SearchResultsIntent import io.github.gmvalentino8.github.sample.presentation.feature.search.results.contract.SearchResultsResult import io.github.gmvalentino8.github.sample.presentation.feature.search.results.contract.SearchResultsViewState import io.github.gmvalentino8.github.sample.ui.core.StoreViewModel import io.github.gmvalentino8.github.sample.ui.core.getState import io.github.gmvalentino8.github.sample.ui.core.onInit import io.github.gmvalentino8.github.sample.ui.core.saveState class SearchPullRequestResultsViewModel @AssistedInject constructor( storeFactory: StoreFactory<SearchResultsIntent<PullRequest>, SearchResultsAction<PullRequest>, SearchResultsResult<PullRequest>, SearchResultsViewState<PullRequest>, SearchResultsEvent<PullRequest>>, @Assisted stateHandle: SavedStateHandle, @Assisted val searchText: String, ) : StoreViewModel<SearchResultsIntent<PullRequest>, SearchResultsAction<PullRequest>, SearchResultsResult<PullRequest>, SearchResultsViewState<PullRequest>, SearchResultsEvent<PullRequest>>(storeFactory) { override val store: Store<SearchResultsIntent<PullRequest>, SearchResultsViewState<PullRequest>, SearchResultsEvent<PullRequest>> = storeFactory.create( stateHandle.getState() ?: State(SearchResultsViewState.Initial(searchText)), middlewares = listOf( StateSaverMiddleware<SearchResultsViewState<PullRequest>, SearchResultsEvent<PullRequest>> { stateHandle.saveState(it) } ) ) init { stateHandle.onInit { dispatch(SearchResultsIntent.OnStart()) } } @AssistedFactory interface Factory { fun create( savedStateHandle: SavedStateHandle, searchText: String, ): SearchPullRequestResultsViewModel } companion object { @Suppress("UNCHECKED_CAST") fun provideFactory( assistedFactory: Factory, owner: SavedStateRegistryOwner, arguments: Bundle?, searchText: String, ): AbstractSavedStateViewModelFactory = object : AbstractSavedStateViewModelFactory(owner, arguments) { override fun <T : ViewModel?> create(key: String, modelClass: Class<T>, handle: SavedStateHandle): T = assistedFactory.create(handle, searchText) as T } } }
0
Kotlin
0
1
2194a2504bde08427ad461d92586497c7187fb40
3,493
github-sample-project
Apache License 2.0
src/main/kotlin/com/castlefrog/agl/domains/backgammon/BackgammonMove.kt
paulalewis
8,964,609
false
{"Kotlin": 128948}
package com.castlefrog.agl.domains.backgammon /** * Represents moving a single piece from one location to another. It is a * partial action as an action may be made up of multiple moves. */ data class BackgammonMove(val from: Int, val distance: Int) : Comparable<BackgammonMove> { override fun compareTo(other: BackgammonMove): Int { return when { from < other.from -> -1 from > other.from -> 1 distance < other.distance -> -1 distance > other.distance -> 1 else -> 0 } } override fun toString(): String { return "$from/$distance" } companion object { /** List of all legal moves. */ private val moves = generateMoves() fun valueOf(from: Int, distance: Int): BackgammonMove { return moves[from][distance - 1] } private fun generateMoves(): List<List<BackgammonMove>> { val moves = ArrayList<MutableList<BackgammonMove>>() for (i in 0 until BackgammonState.N_LOCATIONS) { moves.add(ArrayList()) for (j in 0 until BackgammonState.N_DIE_FACES) { moves[i].add(BackgammonMove(i, j + 1)) } } return moves } } }
0
Kotlin
0
1
96c1708e3f9f8859dee300f10103dfb213feae80
1,298
kotlin-age
MIT License
tck/src/main/kotlin/dev/capybaralabs/d4j/store/tck/ChannelTest.kt
CapybaraLabs
378,490,057
false
{"Kotlin": 376455}
package dev.capybaralabs.d4j.store.tck import dev.capybaralabs.d4j.store.common.repository.flag.StoreFlag import discord4j.discordjson.Id import discord4j.discordjson.json.gateway.ChannelCreate import discord4j.discordjson.json.gateway.ChannelDelete import discord4j.discordjson.json.gateway.ChannelUpdate import discord4j.discordjson.json.gateway.GuildCreate import discord4j.discordjson.json.gateway.MessageCreate import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class ChannelTest(storeLayoutProvider: StoreLayoutProvider) { private val storeLayout = storeLayoutProvider.defaultLayout() private val accessor = storeLayout.dataAccessor private val updater = storeLayout.gatewayDataUpdater @Test fun countChannels() { assertThat(accessor.countChannels().blockOptional()).isPresent } @Test fun onChannelCreate_createChannel() { val channelId = generateUniqueSnowflakeId() val channelCreate = ChannelCreate.builder() .channel(channel(channelId).name("Emergency Medical Holographic Channel").build()) updater.onChannelCreate(0, channelCreate.build()).block() val channel = accessor.getChannelById(channelId).block()!! assertThat(channel.id().asLong()).isEqualTo(channelId) assertThat(channel.name().isAbsent).isFalse assertThat(channel.name().get()).isEqualTo("Emergency Medical Holographic Channel") assertThat(channel.guildId().isAbsent).isTrue assertThat(accessor.channels.collectList().block()) .anyMatch { it.id().asLong() == channelId } assertThat(accessor.countChannels().block()!!).isGreaterThan(0) } @Test fun givenChannelInGuild_onChannelCreate_addChannelToGuild() { val channelId = generateUniqueSnowflakeId() val guildId = generateUniqueSnowflakeId() val guildCreate = GuildCreate.builder() .guild(guild(guildId).build()) .build() updater.onGuildCreate(0, guildCreate).block() val channelCreate = ChannelCreate.builder().channel(channel(channelId).guildId(guildId).build()) updater.onChannelCreate(0, channelCreate.build()).block() val channel = accessor.getChannelById(channelId).block()!! assertThat(channel.id().asLong()).isEqualTo(channelId) assertThat(channel.guildId().isAbsent).isFalse assertThat(channel.guildId().get().asLong()).isEqualTo(guildId) assertThat(accessor.getGuildById(guildId).block()!!.channels()) .contains(Id.of(channelId)) assertThat(accessor.countChannelsInGuild(guildId).block()!!) .isEqualTo(1) assertThat(accessor.getChannelsInGuild(guildId).collectList().block()) .anyMatch { it.id().asLong() == channelId } } @Test fun onChannelDelete_deleteChannel() { val channelId = generateUniqueSnowflakeId() val channelCreate = ChannelCreate.builder().channel(channel(channelId).build()) updater.onChannelCreate(0, channelCreate.build()).block() val channel = accessor.getChannelById(channelId).block()!! assertThat(channel.id().asLong()).isEqualTo(channelId) val channelDelete = ChannelDelete.builder().channel(channel(channelId).build()) updater.onChannelDelete(0, channelDelete.build()).block() assertThat(accessor.getChannelById(channelId).block()).isNull() } @Test fun givenChannelInGuild_onChannelDelete_removeChannelFromGuild() { val channelId = generateUniqueSnowflakeId() val guildId = generateUniqueSnowflakeId() val guildCreate = GuildCreate.builder() .guild(guild(guildId).build()) .build() updater.onGuildCreate(0, guildCreate).block() val channelCreate = ChannelCreate.builder().channel(channel(channelId).guildId(guildId).build()) updater.onChannelCreate(0, channelCreate.build()).block() assertThat(accessor.getGuildById(guildId).block()!!.channels()) .contains(Id.of(channelId)) assertThat(accessor.countChannelsInGuild(guildId).block()!!) .isEqualTo(1) assertThat(accessor.getChannelsInGuild(guildId).collectList().block()) .anyMatch { it.id().asLong() == channelId } val channelDelete = ChannelDelete.builder().channel(channel(channelId).guildId(guildId).build()) updater.onChannelDelete(0, channelDelete.build()).block() assertThat(accessor.getGuildById(guildId).block()!!.channels()) .doesNotContain(Id.of(channelId)) assertThat(accessor.countChannelsInGuild(guildId).block()!!).isEqualTo(0) assertThat(accessor.getChannelsInGuild(guildId).collectList().block()) .noneMatch { it.id().asLong() == channelId } } @Test fun onChannelDelete_deleteMessagesInChannel() { val channelId = generateUniqueSnowflakeId() val channelCreate = ChannelCreate.builder().channel(channel(channelId).build()) updater.onChannelCreate(0, channelCreate.build()).block() val messageId = generateUniqueSnowflakeId() val messageCreate = MessageCreate.builder() .message(message(channelId, messageId, generateUniqueSnowflakeId()).build()) .build() updater.onMessageCreate(0, messageCreate).block() assertThat(accessor.getMessagesInChannel(channelId).collectList().block()!!) .anyMatch { it.id().asLong() == messageId } assertThat(accessor.countMessagesInChannel(channelId).block()!!).isEqualTo(1) val channelDelete = ChannelDelete.builder().channel(channel(channelId).build()) updater.onChannelDelete(0, channelDelete.build()).block() assertThat(accessor.getMessagesInChannel(channelId).collectList().block()).isEmpty() assertThat(accessor.countMessagesInChannel(channelId).block()!!).isEqualTo(0) } @Test fun onChannelUpdate_updateChannel() { val channelId = generateUniqueSnowflakeId() val channelCreate = ChannelCreate.builder().channel(channel(channelId).name("Alpha Quadrant").build()) updater.onChannelCreate(0, channelCreate.build()).block() val alphaChannel = accessor.getChannelById(channelId).block()!! assertThat(alphaChannel.name().isAbsent).isFalse assertThat(alphaChannel.name().get()).isEqualTo("Alpha Quadrant") val channelUpdate = ChannelUpdate.builder().channel(channel(channelId).name("Delta Quadrant").build()) updater.onChannelUpdate(0, channelUpdate.build()).block() val deltaChannel = accessor.getChannelById(channelId).block()!! assertThat(deltaChannel.name().isAbsent).isFalse assertThat(deltaChannel.name().get()).isEqualTo("Delta Quadrant") } @Test fun handleNullByte() { val channelId = generateUniqueSnowflakeId() val channelCreate = ChannelCreate.builder() .channel(channel(channelId).name("everybody gangsta until \u0000").build()) updater.onChannelCreate(0, channelCreate.build()).block() val channel = accessor.getChannelById(channelId).block()!! assertThat(channel.id().asLong()).isEqualTo(channelId) assertThat(channel.name().isAbsent).isFalse assertThat(channel.name().get()).isIn( "everybody gangsta until \u0000", // Correct representation "everybody gangsta until \uFFFD", // Unicode replacement character ) assertThat(channel.guildId().isAbsent).isTrue assertThat(accessor.channels.collectList().block()) .anyMatch { it.id().asLong() == channelId } } private val noop = storeLayoutProvider.withFlags(StoreFlag.allBut(StoreFlag.CHANNEL)) private val noopAccessor = noop.dataAccessor private val noopUpdater = noop.gatewayDataUpdater @Test fun givenNoChannelStoreFlag_countIsZero() { // noopAccessor.countChannelsInGuild() TODO with guild // noopAccessor.getChannelsInGuild() TODO with guild // TODO delete guild // TODO delete shard assertThat(noopAccessor.countChannels().block()!!).isZero } @Test fun givenNoChannelStoreFlag_channelsIsEmpty() { assertThat(noopAccessor.channels.collectList().block()).isEmpty() } @Test fun givenNoChannelStoreFlag_onChannelCreate_doNotCreateChannel() { val channelId = generateUniqueSnowflakeId() val channelCreate = ChannelCreate.builder() .channel(channel(channelId).name("Emergency Medical Holographic Channel").build()) noopUpdater.onChannelCreate(0, channelCreate.build()).block() assertThat(accessor.getChannelById(channelId).blockOptional()).isEmpty assertThat(accessor.channels.collectList().block()) .noneMatch { it.id().asLong() == channelId } val channelDelete = ChannelDelete.builder().channel(channel(channelId).build()) assertThat(noopUpdater.onChannelDelete(0, channelDelete.build()).blockOptional()).isEmpty assertThat(updater.onChannelDelete(0, channelDelete.build()).blockOptional()).isEmpty } @Test fun givenNoChannelStoreFlag_onChannelUpdate_doNotCreateChannel() { val channelId = generateUniqueSnowflakeId() val channelUpdate = ChannelUpdate.builder().channel(channel(channelId).name("Alpha Quadrant").build()) assertThat(noopUpdater.onChannelUpdate(0, channelUpdate.build()).blockOptional()).isEmpty assertThat(accessor.getChannelById(channelId).blockOptional()).isEmpty } @Test fun givenNoChannelStoreFlag_onChannelUpdate_doNotUpdateChannel() { val channelId = generateUniqueSnowflakeId() val channelCreate = ChannelCreate.builder().channel(channel(channelId).name("Alpha Quadrant").build()) updater.onChannelCreate(0, channelCreate.build()).block() var alphaChannel = accessor.getChannelById(channelId).block()!! assertThat(alphaChannel.name().isAbsent).isFalse assertThat(alphaChannel.name().get()).isEqualTo("Alpha Quadrant") val channelUpdate = ChannelUpdate.builder().channel(channel(channelId).name("Delta Quadrant").build()) assertThat(noopUpdater.onChannelUpdate(0, channelUpdate.build()).blockOptional()).isEmpty alphaChannel = accessor.getChannelById(channelId).block()!! assertThat(alphaChannel.name().isAbsent).isFalse assertThat(alphaChannel.name().get()).isEqualTo("Alpha Quadrant") } @Test fun givenNoChannelStoreFlag_onChannelDelete_doNoDeleteChannel() { val channelId = generateUniqueSnowflakeId() val channelCreate = ChannelCreate.builder().channel(channel(channelId).name("Alpha Quadrant").build()) updater.onChannelCreate(0, channelCreate.build()).block() var alphaChannel = accessor.getChannelById(channelId).block()!! assertThat(alphaChannel.name().isAbsent).isFalse assertThat(alphaChannel.name().get()).isEqualTo("Alpha Quadrant") val channelDelete = ChannelDelete.builder().channel(channel(channelId).build()) assertThat(noopUpdater.onChannelDelete(0, channelDelete.build()).blockOptional()).isEmpty alphaChannel = accessor.getChannelById(channelId).block()!! assertThat(alphaChannel.name().isAbsent).isFalse assertThat(alphaChannel.name().get()).isEqualTo("Alpha Quadrant") } }
2
Kotlin
0
4
a9ecc4e0ead1f7ec73aa99034df6d25bf1efa10d
10,379
d4j-store
MIT License
Core/src/main/java/com/redelf/commons/search/SearchResult.kt
red-elf
731,934,432
false
{"Kotlin": 156780, "Java": 16328, "Shell": 754}
package com.redelf.commons.search import com.google.gson.annotations.SerializedName data class SearchResult<out T>(@SerializedName("result") val result: T)
0
Kotlin
0
0
07454441aeb6c1cbf80883e349113506bf7f5488
157
Android-Toolkit
Apache License 2.0
app/src/main/java/com/android254/droidconke19/repository/SpeakersRepo.kt
victorvicari
212,577,283
true
{"Kotlin": 177260, "HTML": 54621, "JavaScript": 2282, "Java": 828}
package com.android254.droidconke19.repository import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.ktx.toObjects import com.android254.droidconke19.datastates.Result import com.android254.droidconke19.models.SpeakersModel import com.android254.droidconke19.utils.await class SpeakersRepo(private val firestore: FirebaseFirestore) { suspend fun getSpeakersInfo(speakerId: Int): Result<List<SpeakersModel>> { return try { val snapshot = firestore.collection("speakers") .whereEqualTo("id", speakerId) .get() .await() Result.Success(snapshot.toObjects<SpeakersModel>()) } catch (e: FirebaseFirestoreException) { Result.Error(e.message) } } }
0
Kotlin
0
0
ed249b9cc08427dd2d2f26503c5fe7a043d90472
874
droidconKE2019App
MIT License
codebase/android/core-database/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/database/databasebackupdata/model/DatabaseBackupData.kt
Abhimanyu14
429,663,688
false
null
package com.makeappssimple.abhimanyu.financemanager.android.core.database.databasebackupdata.model import com.makeappssimple.abhimanyu.financemanager.android.core.database.category.model.Category import com.makeappssimple.abhimanyu.financemanager.android.core.database.emoji.model.EmojiLocalEntity import com.makeappssimple.abhimanyu.financemanager.android.core.database.source.model.Source import com.makeappssimple.abhimanyu.financemanager.android.core.database.transaction.model.Transaction import com.makeappssimple.abhimanyu.financemanager.android.core.database.transactionfor.model.TransactionFor import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class DatabaseBackupData( val lastBackupTime: String = "", val lastBackupTimestamp: String = "", val categories: List<Category> = emptyList(), val emojis: List<EmojiLocalEntity> = emptyList(), val sources: List<Source> = emptyList(), val transactions: List<Transaction> = emptyList(), val transactionForValues: List<TransactionFor> = emptyList(), )
0
Kotlin
0
0
29afaec0cf4e95ba4d6c0dcc32cba3fea6a088cb
1,058
finance-manager
Apache License 2.0
features/home/src/main/kotlin/id/rivaldy/feature/home/ui/profile/sections/ProfileCard.kt
im-o
718,908,780
false
{"Kotlin": 156609}
package id.rivaldy.feature.home.ui.profile.sections import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import id.rivaldy.core.R import id.rivaldy.core.util.Dimens /** Created by github.com/im-o on 11/16/2023. */ @Composable fun ProfileCard( modifier: Modifier = Modifier ) { Column( modifier = modifier .fillMaxWidth() .shadow(elevation = Dimens.dp16, shape = RoundedCornerShape(Dimens.dp20)) .background(MaterialTheme.colorScheme.primary, RoundedCornerShape(Dimens.dp20)), ) { Spacer(modifier = modifier.height(Dimens.dp32)) Row( modifier = modifier .fillMaxWidth() .padding(horizontal = Dimens.dp24), ) { Image( modifier = modifier .size(Dimens.dp48) .shadow(elevation = Dimens.dp1, shape = CircleShape) .clip(shape = CircleShape), painter = painterResource(id = R.drawable.rival_profile), contentDescription = stringResource(id = R.string.my_profile), contentScale = ContentScale.Crop, ) Spacer(modifier = modifier.width(Dimens.dp16)) Column(modifier = modifier.align(Alignment.CenterVertically)) { Text( text = stringResource(id = R.string.rivaldy), style = TextStyle( fontWeight = FontWeight.Bold, color = Color.White, fontSize = Dimens.sp20, ), ) Spacer(modifier = modifier.height(Dimens.dp3)) Text( text = stringResource(id = R.string.membership), style = TextStyle( fontWeight = FontWeight.Bold, color = Color.LightGray.copy(alpha = 0.5f), fontSize = Dimens.sp14, ), ) } } Spacer(modifier = modifier.height(Dimens.dp32)) Box( modifier = modifier .fillMaxWidth() .background( color = Color.Gray.copy(alpha = 0.3f), shape = RoundedCornerShape(topStart = Dimens.dp20), ) .padding(Dimens.dp16), ) { Text( text = stringResource(id = R.string.fully_profile), style = TextStyle( color = Color.White, fontSize = Dimens.sp14, ), ) } } }
0
Kotlin
1
0
6cc1658634eb8273d6cf6d02d37b3a9c7f33dd30
3,800
android-compose-haidoc-ui
MIT License
cell/src/commonTest/kotlin/world/phantasmal/cell/list/SimpleListCellTests.kt
DaanVandenBosch
189,066,992
false
null
package world.phantasmal.cell.list import world.phantasmal.cell.test.assertListCellEquals import kotlin.test.Test import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue class SimpleListCellTests : MutableListCellTests<Int> { override fun createProvider() = createListProvider(empty = true) override fun createListProvider(empty: Boolean) = object : MutableListCellTests.Provider<Int> { private var nextElement = 0 override val cell = SimpleListCell(if (empty) mutableListOf() else mutableListOf(-13)) override fun addElement() { cell.add(createElement()) } override fun createValue(): List<Int> = listOf(createElement()) override fun createElement(): Int = nextElement++ } @Test fun instantiates_correctly() = test { val list = SimpleListCell(mutableListOf(1, 2, 3)) assertListCellEquals(listOf(1, 2, 3), list) } @Test fun set() = test { val list = SimpleListCell(mutableListOf("a", "b", "c")) list[1] = "test" list[2] = "test2" assertFailsWith<IndexOutOfBoundsException> { list[-1] = "should not be in list" } assertFailsWith<IndexOutOfBoundsException> { list[3] = "should not be in list" } assertListCellEquals(listOf("a", "test", "test2"), list) } @Test fun add_with_index() = test { val list = SimpleListCell(mutableListOf<String>()) list.add(0, "b") list.add(1, "c") list.add(0, "a") assertListCellEquals(listOf("a", "b", "c"), list) } @Test fun remove() = test { val list = SimpleListCell(mutableListOf("a", "b", "c", "d", "e")) assertTrue(list.remove("c")) assertListCellEquals(listOf("a", "b", "d", "e"), list) assertTrue(list.remove("a")) assertListCellEquals(listOf("b", "d", "e"), list) assertTrue(list.remove("e")) assertListCellEquals(listOf("b", "d"), list) // The following values are not in the list (anymore). assertFalse(list.remove("x")) assertFalse(list.remove("a")) assertFalse(list.remove("c")) // List should remain unchanged after removal attempts of nonexistent elements. assertListCellEquals(listOf("b", "d"), list) } @Test fun removeAt() = test { val list = SimpleListCell(mutableListOf("a", "b", "c", "d", "e")) list.removeAt(2) assertListCellEquals(listOf("a", "b", "d", "e"), list) list.removeAt(0) assertListCellEquals(listOf("b", "d", "e"), list) list.removeAt(2) assertListCellEquals(listOf("b", "d"), list) assertFailsWith<IndexOutOfBoundsException> { list.removeAt(-1) } assertFailsWith<IndexOutOfBoundsException> { list.removeAt(list.size.value) } // List should remain unchanged after invalid calls. assertListCellEquals(listOf("b", "d"), list) } @Test fun splice() = test { val list = SimpleListCell((0..9).toMutableList()) list.splice(fromIndex = 3, removeCount = 5, newElement = 100) assertListCellEquals(listOf(0, 1, 2, 100, 8, 9), list) list.splice(fromIndex = 0, removeCount = 0, newElement = 101) assertListCellEquals(listOf(101, 0, 1, 2, 100, 8, 9), list) list.splice(fromIndex = list.size.value, removeCount = 0, newElement = 102) assertListCellEquals(listOf(101, 0, 1, 2, 100, 8, 9, 102), list) // Negative fromIndex. assertFailsWith<IndexOutOfBoundsException> { list.splice(fromIndex = -1, removeCount = 0, newElement = 200) } // fromIndex too large. assertFailsWith<IndexOutOfBoundsException> { list.splice(fromIndex = list.size.value + 1, removeCount = 0, newElement = 201) } // removeCount too large. assertFailsWith<IndexOutOfBoundsException> { list.splice(fromIndex = 0, removeCount = 50, newElement = 202) } // List should remain unchanged after invalid calls. assertListCellEquals(listOf(101, 0, 1, 2, 100, 8, 9, 102), list) } }
1
Kotlin
5
20
423c3e252b2be6de63a03108915861fced90aaa6
4,267
phantasmal-world
MIT License
IndoorNavAndroid/nav-ui/src/main/java/com/izhxx/navui/domain/usecase/settings/SettingsUseCaseImpl.kt
ZhevlakovII
507,916,442
false
{"Kotlin": 97377}
package com.izhxx.navclient.domain.usecase.settings import com.izhxx.navcore.domain.model.UserSettings import com.izhxx.navcore.domain.repository.SettingsRepository import io.reactivex.Single import javax.inject.Inject internal class SettingsUseCaseImpl @Inject constructor( private val settingsRepository: SettingsRepository ) : SettingsUseCase { override fun insertUserSettings(settings: UserSettings) = settingsRepository.insertUserSettings(settings) override fun getUserSettings(): Single<UserSettings> = settingsRepository.getUserSettings() }
2
Kotlin
0
1
c59bbb793ee28057f49392eab36206a05909265b
571
IndoorNavigation
MIT License
app/src/main/java/com/mahmoud/mohammed/movieapp/dagger/favorites/FavoritesScope.kt
mohammedgmgn
144,587,960
false
null
package com.mahmoud.mohammed.movieapp.dagger.favorites import javax.inject.Scope @Scope @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class FavoritesScope
0
Kotlin
36
189
507bcc8eb24dec94355d3a12f1469a62d76aeecf
179
MovieApp-Clean-Architecture
Apache License 2.0
app/src/main/java/com/example/hbhims/view/activity/bloodpressure/BloodPressureActivity.kt
1962247851
264,593,040
false
null
package com.example.hbhims.view.activity.bloodpressure import android.os.Bundle import android.view.Menu import android.view.View import android.widget.NumberPicker import androidx.appcompat.app.AlertDialog import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.example.hbhims.App import com.example.hbhims.R import com.example.hbhims.model.common.util.MPAChartUtil import com.example.hbhims.model.common.util.http.HttpCallBack import com.example.hbhims.model.common.util.http.RequestCallBack import com.example.hbhims.model.entity.HealthBloodPressure import com.example.hbhims.model.eventbus.HealthDataChange import com.example.hbhims.view.base.ContainerActivity import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.formatter.ValueFormatter import com.google.android.material.textfield.TextInputEditText import com.youth.xframe.utils.XDateUtils import com.youth.xframe.widget.XToast import kotlinx.android.synthetic.main.activity_blood_pressure.* import org.greenrobot.eventbus.EventBus class BloodPressureActivity : ContainerActivity() { private lateinit var viewModel: BloodPressureViewModel override fun preFinish(): Boolean { return true } override fun getOptionsMenuId(menu: Menu?): Int { return 0 } override fun getLayoutId(): Int { return R.layout.activity_blood_pressure } override fun initData(savedInstanceState: Bundle?) { viewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(application) .create(BloodPressureViewModel::class.java) viewModel.mldBloodPressures.observe(this, Observer { updateBloodPressureChart(it) }) smart_refresh_layout.setOnRefreshListener { getUserAllBloodPressureData(false) } getUserAllBloodPressureData(true) } private fun getUserAllBloodPressureData(needShowContent: Boolean) { viewModel.getUserAllBloodPressureData(userId, object : RequestCallBack<List<HealthBloodPressure>>() { override fun onSuccess(result: List<HealthBloodPressure>) { viewModel.mldBloodPressures.value = result showSuccess(needShowContent) } override fun onFailed(errorCode: Int, error: String) { showFailed() } override fun onNoNetWork() { showNoNetWork() } }) } private fun showSuccess(needShowContent: Boolean) { smart_refresh_layout.finishRefresh() if (needShowContent) { loadingView.showContent() } } private fun showFailed() { smart_refresh_layout.finishRefresh(false) loadingView.setOnRetryClickListener { loadingView.showLoading() getUserAllBloodPressureData(true) }.showError() } private fun showNoNetWork() { loadingView.setOnRetryClickListener { loadingView.showLoading() getUserAllBloodPressureData(true) }.showNoNetwork() } private fun updateBloodPressureChart(bloodPressureList: List<HealthBloodPressure>) { val entriesList = ArrayList<List<Entry>>() val lowPressureEntries = ArrayList<Entry>() val highPressureEntries = ArrayList<Entry>() val xValues = ArrayList<String>() bloodPressureList.forEachIndexed { index, healthBloodPressure -> lowPressureEntries.add( Entry( index.toFloat(), healthBloodPressure.lowPressure.toFloat() ) ) highPressureEntries.add( Entry( index.toFloat(), healthBloodPressure.highPressure.toFloat() ) ) xValues.add( XDateUtils.millis2String( healthBloodPressure.measureTime, "yyyy/MM/dd HH:mm:ss" ) ) } entriesList.add(highPressureEntries) entriesList.add(lowPressureEntries) line_chart_blood_pressure.xAxis.labelRotationAngle = -10F MPAChartUtil.updateMultiLineChart(line_chart_blood_pressure, this, entriesList, xValues, listOf(getString(R.string.blood_pressure_high), getString(R.string.blood_pressure_low)), "", object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return value.toInt().toString() + getString(R.string.mmhg) } }, object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return value.toInt().toString() } }) } override fun initView() { if (userId == App.user.id) { image_view_add_pressure.setOnClickListener { var highPressure = 100 var lowPressure = 100 val inflate = layoutInflater.inflate(R.layout.dialog_insert_blood_pressure, null, false) inflate.findViewById<TextInputEditText>(R.id.tiet_blood_pressure_high).apply { setText(highPressure.toString()) setOnClickListener { var selected = highPressure AlertDialog.Builder(this@BloodPressureActivity).setCancelable(false) .setTitle(R.string.blood_pressure_high_mmHg).setView( NumberPicker(this@BloodPressureActivity).apply { minValue = 0 maxValue = 200 value = highPressure setOnValueChangedListener { _, _, newVal -> selected = newVal } } ).setPositiveButton(R.string.confirm) { _, _ -> highPressure = selected setText(selected.toString()) }.setNegativeButton(R.string.cancel, null).show() } } inflate.findViewById<TextInputEditText>(R.id.tiet_blood_pressure_low).apply { setText(lowPressure.toString()) setOnClickListener { var selected = lowPressure AlertDialog.Builder(this@BloodPressureActivity).setCancelable(false) .setTitle(R.string.blood_pressure_low_mmHg).setView( NumberPicker(this@BloodPressureActivity).apply { minValue = 0 maxValue = 200 value = lowPressure setOnValueChangedListener { _, _, newVal -> selected = newVal setText(selected.toString()) } } ).setPositiveButton(R.string.confirm) { _, _ -> lowPressure = selected }.setNegativeButton(R.string.cancel, null).show() } } AlertDialog.Builder(this).setTitle(R.string.insert_blood_pressure) .setView(inflate).setPositiveButton(R.string.confirm) { _, _ -> HealthBloodPressure.insert(HealthBloodPressure().apply { userId = [email protected] this.highPressure = highPressure this.lowPressure = lowPressure this.measureTime = System.currentTimeMillis() }, object : HttpCallBack<HealthBloodPressure>() { override fun onSuccess(result: HealthBloodPressure) { EventBus.getDefault().post(HealthDataChange(result)) XToast.success(getString(R.string.insert_success)) } override fun onFailed(errorCode: Int, error: String) { XToast.error("$errorCode\n$error") } }) }.setNegativeButton(R.string.cancel, null).show() } } else { image_view_add_pressure.visibility = View.GONE } } }
0
Kotlin
1
1
840545aeac2d70bd1311b5b229ba4c37e32267e1
8,855
hbhims_android
MIT License
app/src/main/java/com/example/hbhims/view/activity/bloodpressure/BloodPressureActivity.kt
1962247851
264,593,040
false
null
package com.example.hbhims.view.activity.bloodpressure import android.os.Bundle import android.view.Menu import android.view.View import android.widget.NumberPicker import androidx.appcompat.app.AlertDialog import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.example.hbhims.App import com.example.hbhims.R import com.example.hbhims.model.common.util.MPAChartUtil import com.example.hbhims.model.common.util.http.HttpCallBack import com.example.hbhims.model.common.util.http.RequestCallBack import com.example.hbhims.model.entity.HealthBloodPressure import com.example.hbhims.model.eventbus.HealthDataChange import com.example.hbhims.view.base.ContainerActivity import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.formatter.ValueFormatter import com.google.android.material.textfield.TextInputEditText import com.youth.xframe.utils.XDateUtils import com.youth.xframe.widget.XToast import kotlinx.android.synthetic.main.activity_blood_pressure.* import org.greenrobot.eventbus.EventBus class BloodPressureActivity : ContainerActivity() { private lateinit var viewModel: BloodPressureViewModel override fun preFinish(): Boolean { return true } override fun getOptionsMenuId(menu: Menu?): Int { return 0 } override fun getLayoutId(): Int { return R.layout.activity_blood_pressure } override fun initData(savedInstanceState: Bundle?) { viewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(application) .create(BloodPressureViewModel::class.java) viewModel.mldBloodPressures.observe(this, Observer { updateBloodPressureChart(it) }) smart_refresh_layout.setOnRefreshListener { getUserAllBloodPressureData(false) } getUserAllBloodPressureData(true) } private fun getUserAllBloodPressureData(needShowContent: Boolean) { viewModel.getUserAllBloodPressureData(userId, object : RequestCallBack<List<HealthBloodPressure>>() { override fun onSuccess(result: List<HealthBloodPressure>) { viewModel.mldBloodPressures.value = result showSuccess(needShowContent) } override fun onFailed(errorCode: Int, error: String) { showFailed() } override fun onNoNetWork() { showNoNetWork() } }) } private fun showSuccess(needShowContent: Boolean) { smart_refresh_layout.finishRefresh() if (needShowContent) { loadingView.showContent() } } private fun showFailed() { smart_refresh_layout.finishRefresh(false) loadingView.setOnRetryClickListener { loadingView.showLoading() getUserAllBloodPressureData(true) }.showError() } private fun showNoNetWork() { loadingView.setOnRetryClickListener { loadingView.showLoading() getUserAllBloodPressureData(true) }.showNoNetwork() } private fun updateBloodPressureChart(bloodPressureList: List<HealthBloodPressure>) { val entriesList = ArrayList<List<Entry>>() val lowPressureEntries = ArrayList<Entry>() val highPressureEntries = ArrayList<Entry>() val xValues = ArrayList<String>() bloodPressureList.forEachIndexed { index, healthBloodPressure -> lowPressureEntries.add( Entry( index.toFloat(), healthBloodPressure.lowPressure.toFloat() ) ) highPressureEntries.add( Entry( index.toFloat(), healthBloodPressure.highPressure.toFloat() ) ) xValues.add( XDateUtils.millis2String( healthBloodPressure.measureTime, "yyyy/MM/dd HH:mm:ss" ) ) } entriesList.add(highPressureEntries) entriesList.add(lowPressureEntries) line_chart_blood_pressure.xAxis.labelRotationAngle = -10F MPAChartUtil.updateMultiLineChart(line_chart_blood_pressure, this, entriesList, xValues, listOf(getString(R.string.blood_pressure_high), getString(R.string.blood_pressure_low)), "", object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return value.toInt().toString() + getString(R.string.mmhg) } }, object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return value.toInt().toString() } }) } override fun initView() { if (userId == App.user.id) { image_view_add_pressure.setOnClickListener { var highPressure = 100 var lowPressure = 100 val inflate = layoutInflater.inflate(R.layout.dialog_insert_blood_pressure, null, false) inflate.findViewById<TextInputEditText>(R.id.tiet_blood_pressure_high).apply { setText(highPressure.toString()) setOnClickListener { var selected = highPressure AlertDialog.Builder(this@BloodPressureActivity).setCancelable(false) .setTitle(R.string.blood_pressure_high_mmHg).setView( NumberPicker(this@BloodPressureActivity).apply { minValue = 0 maxValue = 200 value = highPressure setOnValueChangedListener { _, _, newVal -> selected = newVal } } ).setPositiveButton(R.string.confirm) { _, _ -> highPressure = selected setText(selected.toString()) }.setNegativeButton(R.string.cancel, null).show() } } inflate.findViewById<TextInputEditText>(R.id.tiet_blood_pressure_low).apply { setText(lowPressure.toString()) setOnClickListener { var selected = lowPressure AlertDialog.Builder(this@BloodPressureActivity).setCancelable(false) .setTitle(R.string.blood_pressure_low_mmHg).setView( NumberPicker(this@BloodPressureActivity).apply { minValue = 0 maxValue = 200 value = lowPressure setOnValueChangedListener { _, _, newVal -> selected = newVal setText(selected.toString()) } } ).setPositiveButton(R.string.confirm) { _, _ -> lowPressure = selected }.setNegativeButton(R.string.cancel, null).show() } } AlertDialog.Builder(this).setTitle(R.string.insert_blood_pressure) .setView(inflate).setPositiveButton(R.string.confirm) { _, _ -> HealthBloodPressure.insert(HealthBloodPressure().apply { userId = [email protected] this.highPressure = highPressure this.lowPressure = lowPressure this.measureTime = System.currentTimeMillis() }, object : HttpCallBack<HealthBloodPressure>() { override fun onSuccess(result: HealthBloodPressure) { EventBus.getDefault().post(HealthDataChange(result)) XToast.success(getString(R.string.insert_success)) } override fun onFailed(errorCode: Int, error: String) { XToast.error("$errorCode\n$error") } }) }.setNegativeButton(R.string.cancel, null).show() } } else { image_view_add_pressure.visibility = View.GONE } } }
0
Kotlin
1
1
840545aeac2d70bd1311b5b229ba4c37e32267e1
8,855
hbhims_android
MIT License
app/src/main/java/ademar/goodreads/core/initializer/InitializerManager.kt
ademar111190
61,848,305
false
null
package ademar.goodreads.core.initializer import ademar.goodreads.App import mobi.porquenao.gol.Gol import rx.Observable import java.util.* class InitializerManager private constructor(observables: List<Observable<Void>>) { private val mObservable: Observable<Void> init { mObservable = Observable.merge(observables).cache() mObservable.subscribe() } fun onFinish(onFinishListener: OnFinishListener) { mObservable.subscribe({ onFinishListener.finish() }) { throwable -> Gol.getDefault().error(throwable) } } interface OnFinishListener { fun finish() } companion object { var instance: InitializerManager? = null private set @Synchronized fun start(vararg initializers: Initializer) { instance = InitializerManager(object : ArrayList<Observable<Void>>() { init { for (initializer in initializers) { add(initializer.getObservable(App.instance!!)) } } }) } @Synchronized fun stop() { instance = null } } }
0
Kotlin
0
1
b6850cc9ab3e2f93c6fa2470fffe590a8c126082
1,185
goodreads
MIT License
app/src/main/java/ademar/goodreads/core/initializer/InitializerManager.kt
ademar111190
61,848,305
false
null
package ademar.goodreads.core.initializer import ademar.goodreads.App import mobi.porquenao.gol.Gol import rx.Observable import java.util.* class InitializerManager private constructor(observables: List<Observable<Void>>) { private val mObservable: Observable<Void> init { mObservable = Observable.merge(observables).cache() mObservable.subscribe() } fun onFinish(onFinishListener: OnFinishListener) { mObservable.subscribe({ onFinishListener.finish() }) { throwable -> Gol.getDefault().error(throwable) } } interface OnFinishListener { fun finish() } companion object { var instance: InitializerManager? = null private set @Synchronized fun start(vararg initializers: Initializer) { instance = InitializerManager(object : ArrayList<Observable<Void>>() { init { for (initializer in initializers) { add(initializer.getObservable(App.instance!!)) } } }) } @Synchronized fun stop() { instance = null } } }
0
Kotlin
0
1
b6850cc9ab3e2f93c6fa2470fffe590a8c126082
1,185
goodreads
MIT License
app/src/main/java/com/example/myapplication/fragments/CreatePathFragment.kt
tndevelop
584,864,514
false
null
package com.example.myapplication.fragments import android.content.res.Resources import android.os.Bundle import android.util.Log import android.view.View import android.widget.* import androidx.appcompat.widget.SwitchCompat import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.NavController import androidx.navigation.Navigation import com.example.myapplication.R import com.example.myapplication.db.data.FWAppUsage import com.example.myapplication.db.data.Path import com.example.myapplication.db.data.SuggestionOnApp import com.example.myapplication.utils.Functions import com.example.myapplication.viewModels.HomeViewModel class CreatePathFragment : Fragment(R.layout.fragment_create_path) { lateinit var appName: TextView lateinit var appIcon: ImageView lateinit var hourPicker : NumberPicker lateinit var vibrationFlag : SwitchCompat lateinit var brightnessFlag : SwitchCompat lateinit var nextButton : Button lateinit var progressBar : ProgressBar lateinit var selectedAppTv : TextView private lateinit var navController: NavController private lateinit var viewModel: HomeViewModel private lateinit var includeCheckBox: CheckBox private lateinit var path: Path private var existingInt2 = false private lateinit var usage: FWAppUsage private lateinit var pathList: List<Path> private var functions = Functions() val INTERVENTION_FIRST_WEEK = 0 val INTERVENTION_1 = 1 val INTERVENTION_2 = 2 override fun onViewCreated(view: View, savedInstanceState: Bundle?){ appName = view.findViewById(R.id.app_name) appIcon = view.findViewById(R.id.app_icon) hourPicker = view.findViewById(R.id.hour_picker) vibrationFlag = view.findViewById(R.id.vibration_toggle) brightnessFlag = view.findViewById(R.id.brightness_toggle) nextButton = view.findViewById(R.id.next_or_finish_button) progressBar = view.findViewById(R.id.progressBar2) selectedAppTv = view.findViewById(R.id.selected_app_tv) includeCheckBox = view.findViewById(R.id.check) val res: Resources = resources navController = Navigation.findNavController(view) viewModel = ViewModelProvider(requireActivity()).get(HomeViewModel::class.java) val selectedApps = arguments?.get("apps") as MutableList<SuggestionOnApp> val actualAppIdx = arguments?.getInt("actual") val includedApps = arguments?.get("includedApps") as MutableList<Boolean> val app = selectedApps.get(actualAppIdx!!) progressBar.min = 0 progressBar.max = selectedApps.size progressBar.progress = actualAppIdx + 1 val newText = getString(R.string.selected_apps) + " ( ${actualAppIdx + 1} out of ${selectedApps.size} )" selectedAppTv.text = newText appName.text = app.appName val appInfo = requireContext().packageManager?.getApplicationInfo(app.appPackage, 0) appIcon.setImageDrawable(appInfo!!.loadIcon(requireContext().packageManager)) if(selectedApps.size > 1 || requireArguments().get("comesFrom") == "path_edit") { includeCheckBox.visibility = View.VISIBLE updateChecked(includeCheckBox, includedApps, actualAppIdx) includeCheckBox.setOnClickListener { includedApps[actualAppIdx] = !includedApps[actualAppIdx] updateChecked(includeCheckBox, includedApps, actualAppIdx) } }else{ includeCheckBox.visibility = View.INVISIBLE } hourPicker.minValue = res.getInteger(R.integer.min_value_picker) hourPicker.maxValue = res.getInteger(R.integer.max_value_picker) hourPicker.value = app.suggestedTime.toInt() hourPicker.wrapSelectorWheel = true hourPicker.setOnValueChangedListener { _: NumberPicker, _: Int, newVal: Int -> app.suggestedTime = newVal.toLong() } if(vibrationFlag.isChecked != app.vibrationSuggested) { vibrationFlag.toggle() } vibrationFlag.setOnClickListener{ app.vibrationSuggested = vibrationFlag.isChecked } if(brightnessFlag.isChecked() != app.greyOutSuggested) { brightnessFlag.toggle() } brightnessFlag.setOnClickListener{ app.greyOutSuggested = brightnessFlag.isChecked } if(actualAppIdx == selectedApps.size - 1){ //last app nextButton.text = "FINISH" //path is already created and we need to change it if(requireArguments().get("comesFrom") == "path_edit"){ nextButton.setOnClickListener { viewModel.getPath().observe(viewLifecycleOwner) { path -> if (!includedApps[0]) { viewModel.removePath(path, {}, {}) } else{ path.int_duration = selectedApps[0].suggestedTime.toInt() path.hasVibration = selectedApps[0].vibrationSuggested path.hasDisplayModification = selectedApps[0].greyOutSuggested viewModel.updatePath(path, {}, {}) } } navController.navigate(R.id.action_createPathFragment_to_nav_home_paths) } }else { nextButton.setOnClickListener { var originating: String if (requireArguments().get("comesFrom") in listOf("eow", "modify_complete")) { originating = "modify_complete" } else { originating = "save" } val bundle = bundleOf("apps" to selectedApps, "originating" to originating, "includedApps" to includedApps) navController.navigate(R.id.action_createPathFragment_to_nav_chat, bundle) } } }else{ nextButton.setOnClickListener{ val bundle = bundleOf("apps" to selectedApps, "actual" to actualAppIdx + 1, "comesFrom" to requireArguments().get("comesFrom"), "includedApps" to includedApps) navController.navigate(R.id.action_createPathFragment_self, bundle) } } } private fun updateChecked(includeCheckBox: CheckBox, includedApps: MutableList<Boolean>, actualAppIdx: Int) { includeCheckBox.isChecked = includedApps[actualAppIdx] if(includedApps[actualAppIdx]) includeCheckBox.text = getString(R.string.included_app) else includeCheckBox.text = getString(R.string.excluded_app) } /*private fun openP2Dialog(both: Boolean) { AlertDialog.Builder(requireContext()) .setTitle(R.string.path_exist_title) .setMessage(if(both) R.string.path2_exist_message_both else R.string.path2_exist_message) .setPositiveButton(getString(R.string.ok)) { dialog, _ -> dialog.dismiss() if(both) viewModel.upgradePathFWto1(path, usage, { operationSuccess() }, { operationFailure() }) } .show() }*/ }
0
Kotlin
0
2
a7b9a8e4616017cde75d6ed464dfd9867c6f6389
7,428
Android-DigitalWellbeing
Apache License 2.0
shared/src/commonMain/kotlin/com/ghostly/posts/data/PostRepository.kt
roadrage312
822,698,287
false
{"Kotlin": 159064, "Ruby": 2354, "Swift": 342}
package com.ghostly.posts.data import androidx.paging.ExperimentalPagingApi import app.cash.paging.Pager import app.cash.paging.PagingConfig import app.cash.paging.PagingData import com.ghostly.database.dao.PostDao import com.ghostly.database.entities.PostWithAuthorsAndTags import com.ghostly.mappers.toPost import com.ghostly.network.ApiService import com.ghostly.network.models.Result import com.ghostly.posts.models.Post import com.ghostly.posts.models.PostsResponse import com.ghostly.posts.models.UpdateRequestWrapper import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map internal interface PostRepository { suspend fun getOnePost(): Result<PostsResponse> fun getPosts( pageSize: Int, prefetchDistance: Int = pageSize, ): Flow<PagingData<PostWithAuthorsAndTags>> suspend fun publishPost( postId: String, requestWrapper: UpdateRequestWrapper, ): Result<Post> suspend fun getPostById(id: String): Flow<Post> } @OptIn(ExperimentalPagingApi::class) internal class PostRepositoryImpl( private val apiService: ApiService, private val postDao: PostDao, private val postRemoteMediator: PostRemoteMediator, private val postDataSource: PostDataSource, ) : PostRepository { override suspend fun getOnePost(): Result<PostsResponse> { return apiService.getPosts(1, 1) } override suspend fun publishPost( postId: String, requestWrapper: UpdateRequestWrapper, ): Result<Post> { return when (val result = apiService.publishPost(postId, requestWrapper)) { is Result.Success -> { val posts = result.data?.posts?.takeIf { it.isNotEmpty() } ?: return Result.Error( -1, "Something went wrong" ) postDataSource.updatePost(posts.first()) Result.Success(posts.first()) } is Result.Error -> Result.Error(result.errorCode, result.message) } } override fun getPosts( pageSize: Int, prefetchDistance: Int, ): Flow<PagingData<PostWithAuthorsAndTags>> { val pagingDataSource = { postDao.getAllPostsWithAuthorsAndTags() } return Pager( config = PagingConfig( pageSize = pageSize, initialLoadSize = pageSize, prefetchDistance = prefetchDistance ), pagingSourceFactory = pagingDataSource, remoteMediator = postRemoteMediator ).flow } override suspend fun getPostById(id: String): Flow<Post> { return postDao.getPostWithAuthorsAndTags(id).map { it.toPost() } } }
1
Kotlin
1
4
8ed396f4525d1c6b146e503d1f301c55f74cf9b4
2,823
ghostly
MIT License
smash-ranks-android/app/src/test/java/com/garpr/android/data/models/EndpointTest.kt
charlesmadere
41,832,700
true
null
package com.garpr.android.data.models import com.garpr.android.test.BaseTest import org.junit.Assert.assertEquals import org.junit.Test class EndpointTest : BaseTest() { @Test fun testGetBasePath() { assertEquals("https://www.garpr.com", Endpoint.GAR_PR.basePath) assertEquals("https://www.notgarpr.com", Endpoint.NOT_GAR_PR.basePath) } @Test fun testGetPlayerWebPath() { assertEquals("https://www.garpr.com/#/norcal/players/588852e7d2994e3bbfa52d6e", Endpoint.GAR_PR.getPlayerWebPath("norcal", "588852e7d2994e3bbfa52d6e")) assertEquals("https://www.notgarpr.com/#/newjersey/players/545c854e8ab65f127805bd6f", Endpoint.NOT_GAR_PR.getPlayerWebPath("newjersey", "545c854e8ab65f127805bd6f")) } @Test fun testGetRankingsWebPath() { assertEquals("https://www.garpr.com/#/norcal/rankings", Endpoint.GAR_PR.getRankingsWebPath("norcal")) assertEquals("https://www.notgarpr.com/#/newjersey/rankings", Endpoint.NOT_GAR_PR.getRankingsWebPath("newjersey")) } @Test fun testGetTournamentWebPath() { assertEquals("https://www.garpr.com/#/norcal/tournaments/58d8c3e8d2994e057e91f7fd", Endpoint.GAR_PR.getTournamentWebPath("norcal", "58d8c3e8d2994e057e91f7fd")) assertEquals("https://www.notgarpr.com/#/newjersey/tournaments/58bdc6e31d41c867e937fc15", Endpoint.NOT_GAR_PR.getTournamentWebPath("newjersey", "58bdc6e31d41c867e937fc15")) } @Test fun testGetTournamentsWebPath() { assertEquals("https://www.garpr.com/#/googlemtv/tournaments", Endpoint.GAR_PR.getTournamentsWebPath("googlemtv")) assertEquals("https://www.notgarpr.com/#/nyc/tournaments", Endpoint.NOT_GAR_PR.getTournamentsWebPath("nyc")) } @Test fun testGetWebPath() { assertEquals("https://www.garpr.com/#/", Endpoint.GAR_PR.getWebPath()) assertEquals("https://www.notgarpr.com/#/", Endpoint.NOT_GAR_PR.getWebPath()) assertEquals("https://www.garpr.com/#/norcal", Endpoint.GAR_PR.getWebPath("norcal")) assertEquals("https://www.notgarpr.com/#/chicago", Endpoint.NOT_GAR_PR.getWebPath("chicago")) } }
0
Kotlin
0
9
151b2a0f9b4d38be60c3f73344ca444f17810bfd
2,273
smash-ranks-android
The Unlicense
core/collection/src/commonMain/kotlin/app/dreamlightpal/collection/domain/model/Location.kt
rsicarelli
566,965,553
false
{"Kotlin": 406302, "Shell": 8070}
package app.dreamlightpal.collection.domain.model import kotlinx.serialization.Contextual import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @JvmInline value class LocationId(val value: String) @Serializable data class Location( @SerialName("id") @Contextual val id: LocationId, @SerialName("name") val name: String, @SerialName("description") val description: String, )
0
Kotlin
0
1
523f8e7adad2897a18af154f9e9909d1e88fee24
421
KMP-GameCompanion
Apache License 2.0
src/main/kotlin/canon/model/Overlays.kt
leftshiftone
205,671,409
false
null
package canon.model import canon.api.IClassAware import canon.api.IRenderable import com.fasterxml.jackson.annotation.JsonIgnore data class Overlays( @JsonIgnore override val id: String?, @JsonIgnore override val `class`: String?, @JsonIgnore override val ariaLabel: String?, val trigger: String?, @JsonIgnore val renderables: List<IRenderable>? ) : AbstractStackable(renderables), IClassAware { override fun toString() = "Overlays(trigger=$trigger)" }
0
Kotlin
1
0
00030eeabff75a1f87927940d989cb122273a0bf
479
canon
MIT License
app/src/main/java/com/example/unscramble/ui/GameViewModel.kt
samuelbetzler
856,703,545
false
{"Kotlin": 25827}
package com.example.unscramble.ui import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import com.example.unscramble.data.SCORE_INCREASE import com.example.unscramble.data.allWords import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update class GameViewModel : ViewModel() { // Número máximo de palabras y de intentos permitidos private val MAX_NO_OF_WORDS = 5 // Puedes cambiar este valor para ajustar el máximo de palabras private val MAX_NO_OF_ATTEMPTS = 3 // Puedes cambiar este valor para ajustar los intentos // Estado del juego private val _uiState = MutableStateFlow(GameUiState()) val uiState: StateFlow<GameUiState> = _uiState.asStateFlow() var userGuess by mutableStateOf("") private set private var usedWords: MutableSet<String> = mutableSetOf() private var attempts = 0 // Contador de intentos private lateinit var currentWord: String init { resetGame() } fun resetGame() { usedWords.clear() attempts = 0 // Reiniciar intentos _uiState.value = GameUiState(currentScrambledWord = pickRandomWordAndShuffle()) } fun updateUserGuess(guessedWord: String) { userGuess = guessedWord } fun checkUserGuess() { if (userGuess.equals(currentWord, ignoreCase = true)) { val updatedScore = _uiState.value.score.plus(SCORE_INCREASE) updateGameState(updatedScore) } else { attempts++ if (attempts >= MAX_NO_OF_ATTEMPTS) { _uiState.update { currentState -> currentState.copy(isGameOver = true, isGuessedWordWrong = true) } } else { _uiState.update { currentState -> currentState.copy(isGuessedWordWrong = true) } } } updateUserGuess("") } fun skipWord() { updateGameState(_uiState.value.score) updateUserGuess("") } private fun updateGameState(updatedScore: Int) { if (usedWords.size == MAX_NO_OF_WORDS || _uiState.value.isGameOver) { _uiState.update { currentState -> currentState.copy(isGuessedWordWrong = false, score = updatedScore, isGameOver = true) } } else { _uiState.update { currentState -> currentState.copy( isGuessedWordWrong = false, currentScrambledWord = pickRandomWordAndShuffle(), currentWordCount = currentState.currentWordCount.inc(), score = updatedScore ) } } } private fun shuffleCurrentWord(word: String): String { val tempWord = word.toCharArray() tempWord.shuffle() while (String(tempWord) == word) { tempWord.shuffle() } return String(tempWord) } private fun pickRandomWordAndShuffle(): String { currentWord = allWords.random() return if (usedWords.contains(currentWord)) { pickRandomWordAndShuffle() } else { usedWords.add(currentWord) shuffleCurrentWord(currentWord) } } }
0
Kotlin
0
0
b6f1127bb007f709fc5875150e08f7c685d99f17
3,436
UnscrambleAppdemo
Apache License 2.0
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/TriggerTaskerTaskActionType.kt
Waboodoo
34,525,124
false
null
package ch.rmy.android.http_shortcuts.scripting.actions.types import android.content.Context import ch.rmy.android.http_shortcuts.plugin.TaskerIntent import ch.rmy.android.http_shortcuts.scripting.ActionAlias import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO class TriggerTaskerTaskActionType : BaseActionType() { override val type = TYPE override fun fromDTO(actionDTO: ActionDTO) = TriggerTaskerTaskAction( taskName = actionDTO.getString(0) ?: "", variableValuesJson = actionDTO.getString(1) ?: "{}", ) override fun getAlias() = ActionAlias( functionName = FUNCTION_NAME, parameters = 2, ) companion object { private const val TYPE = "trigger_tasker_task" private const val FUNCTION_NAME = "triggerTaskerTask" fun isTaskerAvailable(context: Context): Boolean = TaskerIntent.isTaskerInstalled(context) } }
34
Kotlin
77
502
cc1dfc73f8ea31f24c52dc3de8d70a598f955e35
926
HTTP-Shortcuts
MIT License
module-book-reader/src/main/java/com/timecat/module/read/ReaderCard.kt
LinXueyuanStdio
332,099,365
false
null
package com.timecat.module.read import android.content.Context import android.content.Intent import android.view.View import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import com.timecat.layout.ui.entity.BaseAdapter import com.timecat.layout.ui.entity.BaseItem import com.timecat.layout.ui.layout.setShakelessClickListener import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.viewholders.FlexibleViewHolder import io.legado.app.R import io.legado.app.constant.BookType import io.legado.app.data.entities.Book import io.legado.app.help.IntentDataHelp import io.legado.app.ui.audio.AudioPlayActivity import io.legado.app.ui.book.info.BookInfoActivity import io.legado.app.ui.book.read.ReadBookActivity import io.legado.app.ui.widget.anima.RotateLoading import io.legado.app.ui.widget.image.CoverImageView import io.legado.app.ui.widget.text.BadgeView import org.jetbrains.anko.internals.AnkoInternals /** * @author 林学渊 * @email [email protected] * @date 2021/1/20 * @description null * @usage null */ class ReaderCard( val item: Book, val context: Context ) : BaseItem<ReaderCard.RepoCardVH>(item.bookUrl) { class RepoCardVH(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter) { val cv_content: View = view.findViewById(R.id.cv_content) val tv_name: TextView = view.findViewById(R.id.tv_name) val tv_last: TextView = view.findViewById(R.id.tv_last) val tv_read: TextView = view.findViewById(R.id.tv_read) val tv_author: TextView = view.findViewById(R.id.tv_author) val iv_author: ImageView = view.findViewById(R.id.iv_author) val iv_last: ImageView = view.findViewById(R.id.iv_last) val iv_read: ImageView = view.findViewById(R.id.iv_read) val iv_cover: CoverImageView = view.findViewById(R.id.iv_cover) val fl_has_new: FrameLayout = view.findViewById(R.id.fl_has_new) val bv_unread: BadgeView = view.findViewById(R.id.bv_unread) val rl_loading: RotateLoading = view.findViewById(R.id.rl_loading) val vw_foreground: View = view.findViewById(R.id.vw_foreground) val vw_select: View = view.findViewById(R.id.vw_select) } override fun getLayoutRes(): Int = R.layout.novel_item_bookshelf_list override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<*>>): RepoCardVH { return RepoCardVH(view, adapter) } override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<*>>, holder: RepoCardVH, position: Int, payloads: MutableList<Any>?) { if (adapter is BaseAdapter) { adapter.bindViewHolderAnimation(holder) } holder.apply { tv_name.text = item.name tv_author.text = item.author tv_read.text = item.durChapterTitle tv_last.text = item.latestChapterTitle iv_cover.load(item.getDisplayCover(), item.name, item.author) upRefresh(this, item) cv_content.setShakelessClickListener { open(item) } cv_content.setOnLongClickListener { openBookInfo(item) true } } } fun open(book: Book) { when (book.type) { BookType.audio -> { val intent = AnkoInternals.createIntent(context, AudioPlayActivity::class.java, arrayOf( "bookUrl" to book.bookUrl )) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } else -> { val intent = AnkoInternals.createIntent(context, ReadBookActivity::class.java, arrayOf( "bookUrl" to book.bookUrl, "key" to IntentDataHelp.putData(book) )) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } } } fun openBookInfo(book: Book) { val intent = AnkoInternals.createIntent(context, BookInfoActivity::class.java, arrayOf( "name" to book.name, "author" to book.author )) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } private fun upRefresh(itemView: RepoCardVH, item: Book) = with(itemView) { rl_loading.hide() bv_unread.setHighlight(item.lastCheckCount > 0) bv_unread.setBadgeCount(item.getUnreadChapterNum()) } }
1
null
1
1
1131fe5d2c16c15adfa12111cfac0fda080a50dc
4,603
TimeCatModule-BookReader
Apache License 2.0
library/src/test/java/com/santojon/eventer/event/StringEvent.kt
santojon
237,980,775
false
null
package com.santojon.eventer.event import com.santojon.eventer.core.event.Event /** * Class that represents String event */ class StringEvent(val value: String) : Event, Comparable<StringEvent> { override fun compareTo(other: StringEvent): Int { return this.value.compareTo(other.value) } override fun equals(other: Any?): Boolean { if (other is StringEvent) { return this.value == other.value } return super.equals(other) } override fun hashCode(): Int { return value.hashCode() } override fun toString(): String { return value } }
0
Kotlin
0
0
c6fc2a546fe12b5408d01f9d3bebcc6d97370ee4
631
Eventer
MIT License
app/src/main/kotlin/cn/govast/vmusic/network/BaseServiceCreator.kt
SakurajimaMaii
351,469,044
false
null
/* * Copyright 2022 <NAME> <EMAIL> * * 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 cn.govast.vmusic.network import cn.govast.vmusic.network.interceptor.AddCookiesInterceptor import cn.govast.vasttools.network.RetrofitBuilder import okhttp3.OkHttpClient // Author: <NAME> // Email: <EMAIL> // Date: 2022/9/29 // Description: // Documentation: // Reference: abstract class BaseServiceCreator: RetrofitBuilder() { override fun handleOkHttpClientBuilder(builder: OkHttpClient.Builder) { builder.addInterceptor(AddCookiesInterceptor()) } }
2
Kotlin
0
8
af1cb8e620cb3e65f9ad5a0d05b240142db2608b
1,080
Music-Voice
Apache License 2.0
src/main/kotlin/io/github/hc1839/crul/chemistry/tinker/AtomClassPair.kt
hc1839
724,383,874
false
{"Kotlin": 541316}
package io.github.hc1839.crul.chemistry.tinker import java.nio.ByteBuffer import org.apache.avro.Schema import org.apache.avro.generic.* import io.github.hc1839.crul.serialize.AvroSimple private object AtomClassPairAvsc { /** * Absolute path to the Avro schema file with respect to the JAR. */ val path: String = "/io/github/hc1839/crul/chemistry/tinker/AtomClassPair.avsc" /** * Avro schema for the serialization of [AtomClassPair]. */ val schema: Schema = Schema.Parser().parse( this::class.java.getResourceAsStream(path) ) } /** * Pair of [AtomClass] instances. * * @property first * First atom class. * * @property second * Second atom class. * * @property orderSignificant * Whether the order of the atom classes is significant when calculating * hash code and comparing for equality. * * @constructor */ open class AtomClassPair( val first: AtomClass, val second: AtomClass, val orderSignificant: Boolean ) { override fun hashCode(): Int = if (orderSignificant) { listOf(first, second).hashCode() } else { setOf(first, second).hashCode() } override fun equals(other: Any?): Boolean = other is AtomClassPair && this::class == other::class && if (orderSignificant) { toList() == other.toList() } else { toList().toSet() == other.toList().toSet() } /** * Whether the two atom classes are the same. */ val isLike: Boolean = first == second /** * Returns the atom class if the atom classes are equal, or `null` if they * are not. */ fun singleOrNull(): AtomClass? = if (isLike) { first } else { null } /** * Returns the atom class if the atom classes are equal, or throws an * exception if they are not. */ fun single(): AtomClass = singleOrNull() ?: throw RuntimeException( "Atom classes are not equal." ) /** * Converts this pair to a list. * * Atom classes maintain their order in the returned list regardless of * [orderSignificant]. */ fun toList(): List<AtomClass> = listOf(first, second) companion object { /** * Serializes an [AtomClassPair] in Apache Avro. * * @param obj * [AtomClassPair] to serialize. * * @return * Avro serialization of `obj`. */ @JvmStatic fun serialize(obj: AtomClassPair): ByteBuffer { val avroRecord = GenericData.Record( AtomClassPairAvsc.schema ) avroRecord.put( "atom_class_1", AtomClass.serialize(obj.first) ) avroRecord.put( "atom_class_2", AtomClass.serialize(obj.second) ) avroRecord.put( "order_significant", obj.orderSignificant ) return AvroSimple.serializeData<GenericRecord>( AtomClassPairAvsc.schema, listOf(avroRecord) ) } /** * Deserializes an [AtomClassPair] in Apache Avro. * * @param avroData * Serialized [AtomClassPair] as returned by [serialize]. * * @return * Deserialized [AtomClassPair]. */ @JvmStatic fun deserialize(avroData: ByteBuffer): AtomClassPair { val avroRecord = AvroSimple.deserializeData<GenericRecord>( AtomClassPairAvsc.schema, avroData ).first() val atomClass1 = AtomClass.deserialize( avroRecord.get("atom_class_1") as ByteBuffer ) val atomClass2 = AtomClass.deserialize( avroRecord.get("atom_class_2") as ByteBuffer ) val orderSignificant = avroRecord.get("order_significant") as Boolean return AtomClassPair(atomClass1, atomClass2, orderSignificant) } } }
0
Kotlin
0
0
736b3c8377ca2f2f4a4e86fde6312e50b7ea2505
4,253
crul
Apache License 2.0
market-sim/src/main/kotlin/org/tools4j/fix/RegistryFixDecoder.kt
tools4j
124,669,693
false
{"Gradle": 5, "Text": 1, "Ignore List": 1, "Markdown": 1, "HTML": 4, "Groovy": 64, "XML": 8, "Kotlin": 337, "Java Properties": 2, "Shell": 1, "INI": 7, "JavaScript": 1, "CSS": 1, "Java": 4}
package org.tools4j.fix import org.tools4j.fix.spec.FixSpecDefinition import org.tools4j.model.fix.messages.DecoderRegistry import org.tools4j.model.fix.messages.FixMessage /** * User: ben * Date: 4/9/17 * Time: 6:23 AM */ class RegistryFixDecoder(private val decoderRegistry: DecoderRegistry, private val fixSpec: FixSpecDefinition) : FixDecoder { override fun decode(messageStr: String, delimiter: String): FixMessage { val fields = FieldsFromDelimitedString(messageStr, delimiter).fields val msgTypeCode = fields.getField(FixFieldTypes.MsgType)!!.value.valueRaw val msgName = fixSpec.messagesByMsgType[msgTypeCode]?.name val messageFactory = decoderRegistry.get(msgTypeCode) ?: throw IllegalArgumentException("Cannot find decoder for MsgType") return messageFactory.createMessage(fields) } }
0
Kotlin
1
7
e2cbc5b0b174f7ab462603e8ff65701501dfeae1
850
market-simulator
MIT License
app-kotlin/src/main/java/fudi/freddy/mokitosample/share/ShareFragment.kt
romellfudi
142,795,499
false
null
package fudi.freddy.mokitosample.share import android.annotation.SuppressLint import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView.OnItemClickListener import android.widget.ArrayAdapter import android.widget.Button import android.widget.EditText import android.widget.ListView import fudi.freddy.mokitosample.R import fudi.freddy.mokitosample.share.ShareContract.ShareView /** * @version 1.0 * @autor <NAME> * @date 7/25/20 */ class ShareFragment @SuppressLint("ValidFragment") internal constructor() : Fragment(), ShareView { var editText: EditText? = null var save: Button? = null var load: Button? = null var listView: ListView? = null var stringArrayAdapter: ArrayAdapter<String>? = null var sharePresent: SharePresent = SharePresent(this) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_share, container, false) editText = view.findViewById<View>(R.id.et) as EditText save = view.findViewById<View>(R.id.save) as Button load = view.findViewById<View>(R.id.load) as Button listView = view.findViewById<View>(R.id.list) as ListView stringArrayAdapter = ArrayAdapter(activity, android.R.layout.simple_list_item_1) listView!!.adapter = stringArrayAdapter save!!.setOnClickListener { stringArrayAdapter!!.add(editText!!.text.toString()) sharePresent.saveInput(editText!!.text.toString()) } load!!.setOnClickListener { sharePresent.loadInput() } listView!!.onItemClickListener = OnItemClickListener { adapterView, _, i, _ -> sharePresent.display(adapterView.getItemAtPosition(i) as String) } return view } override fun clearText() { editText!!.setText("") } override fun loadText(text: String?) { editText!!.setText(text) } override fun reLoadList() { stringArrayAdapter!!.notifyDataSetChanged() } companion object { val instance: ShareFragment get() = ShareFragment() } }
1
null
1
2
c753df77b037498cbc90cd5351d58002698809c7
2,277
MockitoSample
Apache License 2.0
app/src/main/java/com/pusatruq/muttabaah/ui/component/adapter/CommentAdapter.kt
halimbimantara
216,685,956
false
{"Gradle": 4, "XML": 103, "Java Properties": 4, "Shell": 1, "Text": 1, "Batchfile": 1, "Markdown": 1, "INI": 4, "Proguard": 1, "Ignore List": 1, "JSON": 4, "Kotlin": 114, "Java": 1}
package com.pusatruq.muttabaah.ui.component.adapter import androidx.databinding.DataBindingUtil import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.pusatruq.muttabaah.R import com.pusatruq.muttabaah.data.local.room.CommentEntity import com.pusatruq.muttabaah.databinding.ItemCommentBinding /** * Created by cuongpm on 12/10/18. */ class CommentAdapter( private var comments: List<CommentEntity> ) : RecyclerView.Adapter<CommentAdapter.CommentViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentViewHolder { val binding = DataBindingUtil.inflate<ItemCommentBinding>( LayoutInflater.from(parent.context), R.layout.item_comment, parent, false ) return CommentViewHolder(binding) } override fun getItemCount() = comments.size override fun onBindViewHolder(holder: CommentViewHolder, position: Int) = holder.bind(comments[position]) class CommentViewHolder(private val binding: ItemCommentBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(commentEntity: CommentEntity) { with(binding) { comment = commentEntity executePendingBindings() } } } fun setData(comments: List<CommentEntity>) { this.comments = comments notifyDataSetChanged() } }
1
null
1
1
c1b0f7e4e9a6d8bad50392e948e06b496ab7476d
1,450
rehab-hati-mtb
MIT License
app/src/main/java/com/ibashkimi/wheel/about/AboutFragment.kt
indritbashkimi
246,021,936
false
null
package com.ibashkimi.wheel.about import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.ibashkimi.wheel.R import com.ibashkimi.wheel.databinding.FragmentAboutBinding class AboutFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return FragmentAboutBinding.inflate(inflater, container, false).run { toolbar.apply { setTitle(R.string.title_about) setNavigationIcon(R.drawable.ic_back_nav) setNavigationOnClickListener { requireActivity().onBackPressed() } } sendFeedback.setOnClickListener { sendFeedback() } root } } private fun sendFeedback() { val address = getString(R.string.developer_email) val subject = getString(R.string.feedback_subject) val emailIntent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$address")) emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject) val chooserTitle = getString(R.string.feedback_chooser_title) startActivity(Intent.createChooser(emailIntent, chooserTitle)) } }
1
null
3
7
9ac7efc8ebca47bf6835bccd0b76e55e2d220fa7
1,392
wheel
MIT License
app/src/main/java/com/bleacher/reportclifford/list/ImageViewHolder.kt
cliffseriex
238,410,498
false
null
package com.bleacher.reportclifford.list import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ImageView import com.bleacher.reportclifford.R import com.bleacher.reportclifford.Data.PhotoSearchResultItem import com.squareup.picasso.Picasso internal class ImageViewHolder( itemView: View, private val imageClickListener: ImageAdapter.OnPhotoSearchResultClickListener, private val imageSize: Int) : RecyclerView.ViewHolder(itemView) { private val photoImageView: ImageView = itemView.findViewById(R.id.photoImageView) as ImageView fun setImage(image: PhotoSearchResultItem) { Picasso.with(photoImageView.context) .load(image.url) .centerCrop() .resize(imageSize, imageSize) .into(photoImageView) photoImageView.setOnClickListener { imageClickListener.onImageClicked(image) } photoImageView.contentDescription = image.title } }
1
null
1
1
d7b2c4886676cd741571ea5cd4d709b55015a675
994
Flickr
MIT License
kotlinpleaseanimate/src/main/java/com/github/florent37/kotlin/pleaseanimate/core/paddings/Padding.kt
florent37
125,015,293
false
{"Kotlin": 96221, "Java": 1272, "Shell": 165}
package com.github.florent37.kotlin.pleaseanimate.core.paddings enum class Padding { TOP, BOTTOM, LEFT, RIGHT }
4
Kotlin
40
556
e546fe4308b08e6394bdb56d3d595dcf4d412bb0
128
KotlinPleaseAnimate
Apache License 2.0
src/test/kotlin/com/leetcode/P98Test.kt
antop-dev
229,558,170
false
{"Maven POM": 1, "Text": 4, "Ignore List": 1, "Markdown": 1, "Java": 233, "Kotlin": 832, "Python": 10}
package com.leetcode import com.leetcode.P98.TreeNode import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` import org.junit.jupiter.api.Test internal class P98Test { val p = P98() @Test fun `example 1`() { val root = TreeNode(2).apply { left = TreeNode(1) right = TreeNode(3) } assertThat(p.isValidBST(root), `is`(true)) } @Test fun `example 2`() { val root = TreeNode(5).apply { left = TreeNode(1) right = TreeNode(4).apply { left = TreeNode(3) right = TreeNode(6) } } assertThat(p.isValidBST(root), `is`(false)) } @Test fun `example 3`() { val root = null assertThat(p.isValidBST(root), `is`(true)) } @Test fun `example 4`() { val root = TreeNode(1).apply { left = TreeNode(1) } assertThat(p.isValidBST(root), `is`(false)) } @Test fun `example 5`() { val root = TreeNode(10).apply { left = TreeNode(5) right = TreeNode(15).apply { left = TreeNode(6) right = TreeNode(20) } } assertThat(p.isValidBST(root), `is`(false)) } @Test fun `example 6`() { val root = TreeNode(3).apply { left = TreeNode(1).apply { left = TreeNode(0) right = TreeNode(2) } right = TreeNode(5).apply { left = TreeNode(4) right = TreeNode(6) } } assertThat(p.isValidBST(root), `is`(true)) } @Test fun `example 7`() { val root = TreeNode(24).apply { left = TreeNode(-60).apply { left = TreeNode(-60) right = TreeNode(-6) } } assertThat(p.isValidBST(root), `is`(false)) } @Test fun `example 8`() { val root = TreeNode(Int.MIN_VALUE) assertThat(p.isValidBST(root), `is`(true)) } }
1
Kotlin
0
0
ce932821ca5c3eb0822e0b77a32f608cd5401299
2,102
algorithm
MIT License
src/main/kotlin/br/com/zup/exception/handler/NotPermittedExceptionHandler.kt
walteralleyz
357,188,466
true
{"Gradle Kotlin DSL": 2, "Dockerfile": 1, "INI": 5, "Shell": 1, "YAML": 3, "Text": 2, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 64, "Protocol Buffer": 121, "XML": 20, "Java": 102, "SQL": 4, "Motorola 68K Assembly": 1, "HTML": 17, "CSS": 2, "JavaScript": 1, "Java Properties": 1}
package br.com.zup.exception.handler import br.com.zup.exception.ExceptionHandler import br.com.zup.exception.internal.NotPermittedException import io.grpc.Status import javax.inject.Singleton @Singleton class NotPermittedExceptionHandler : ExceptionHandler<NotPermittedException> { override fun handle(e: NotPermittedException): ExceptionHandler.StatusWithDetails { return ExceptionHandler.StatusWithDetails( Status.PERMISSION_DENIED .withDescription(e.message) .withCause(e) ) } override fun supports(e: Exception): Boolean = e is NotPermittedException }
0
Java
0
0
269d18b4e0d14c5950ce7b776661ffb9cb26e308
631
orange-talents-02-template-pix-keymanager-grpc
Apache License 2.0
emoji/src/androidMain/kotlin/com/vanniktech/emoji/EmojiReplacer.kt
vanniktech
53,511,222
false
{"Kotlin": 2552475, "JavaScript": 19229, "Ruby": 15950}
/* * Copyright (C) 2016 - <NAME>, <NAME>, <NAME> and contributors * * 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.vanniktech.emoji import android.content.Context import android.text.Spannable /** * EmojiProviders can implement this interface to perform text emoji image replacement in a more efficient way. * For instance, the GoogleCompatEmojiProvider calls the corresponding AppCompat Emoji * Support library replace method directly for emoji in the default size. * * @since 6.0.0 */ fun interface EmojiReplacer { fun replaceWithImages(context: Context, text: Spannable, emojiSize: Float, fallback: EmojiReplacer?) }
5
Kotlin
292
1,537
60efe8bbfe4f2900e424c4cdddf01dcc59e0b4bb
1,157
Emoji
Apache License 2.0
app/src/main/java/com/ab/ble/veiwmodel/BaseAndroidViewModel.kt
Sundeep1501
109,253,546
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 4, "XML": 33, "Kotlin": 14}
package com.ab.ble.veiwmodel import android.app.Application import android.arch.lifecycle.AndroidViewModel import com.ab.ble.BleApplication import com.ab.ble.repository.SPRepository /** * Created by sundeep on 29/10/17. */ open class BaseAndroidViewModel(application: Application) : AndroidViewModel(application) { var mSPRepository: SPRepository? = null init { this.mSPRepository = (application as BleApplication).spRepository } }
0
Kotlin
1
1
ae1425dacf5aa03d20bec8b0a0217d9f27865f96
461
ab-ble
MIT License
plugins/kotlin/idea/tests/testData/refactoring/bindToElement/docReference/FullyQualified.kt
ingokegel
72,937,917
false
null
// BIND_TO test.bar.B package test.bar class A { } class B { } fun foo() { val x = test.bar.<caret>A() }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
111
intellij-community
Apache License 2.0
core/src/main/java/com/eoa/tech/core/util/state/NetworkState.kt
anggit97
294,907,791
false
null
package com.eoa.tech.core.util.state /** * Created by <NAME> on 29,July,2020 * GitHub : https://github.com/anggit97 */ sealed class NetworkState { object Connected : NetworkState() object Disconnected : NetworkState() }
0
Kotlin
0
0
d0b11392329dc2215e37907c9521d95f4039885f
232
MovOn
MIT License
src/test/kotlin/dev/shtanko/algorithms/leetcode/LargestGoodIntegerTest.kt
ashtanko
203,993,092
false
null
/* * Copyright 2023 Oleksii Shtanko * * 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 dev.shtanko.algorithms.leetcode import java.util.stream.Stream import org.assertj.core.api.Assertions import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource abstract class LargestGoodIntegerTest<out T : LargestGoodInt>(private val strategy: T) { private class InputArgumentsProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of( Arguments.of("", ""), Arguments.of("1", ""), Arguments.of("6777133339", "777"), Arguments.of("2300019", "000"), Arguments.of("42352338", ""), ) } @ParameterizedTest @ArgumentsSource(InputArgumentsProvider::class) fun `largest good integer`(num: String, expected: String) { val actual = strategy(num) Assertions.assertThat(actual).isEqualTo(expected) } } class LargestGoodIntSingleIterationTest : LargestGoodIntegerTest<LargestGoodInt>(LargestGoodIntSingleIteration()) class LargestGoodIntCompareTest : LargestGoodIntegerTest<LargestGoodInt>(LargestGoodIntCompare())
6
null
0
19
c6e2befdce892e9f2caf1d98f54dc1dd9b2c89ba
1,912
kotlab
Apache License 2.0
data/movies-data/src/main/kotlin/com/sotti/watch/movies/data/MoviesDataModule.kt
Sottti
196,598,437
false
null
package com.sotti.watch.movies.data import com.sotti.watch.network.common.networkCommonModule import com.sotti.watch.movies.data.datasources.MoviesDataSources import com.sotti.watch.movies.data.datasources.local.MoviesRoomDS import com.sotti.watch.movies.data.datasources.remote.MoviesApiDS import com.sotti.watch.movies.data.datasources.remote.TmdbApiService import com.sotti.watch.movies.data.datasources.remote.TmdbApiServiceImpl import com.sotti.watch.movies.data.repository.MoviesRepository import com.sotti.watch.movies.data.repository.MoviesRepositoryImpl import org.koin.core.context.loadKoinModules import org.koin.dsl.module fun injectMoviesRepositoryModules() = loadMoviesRepositoryModules private val loadMoviesRepositoryModules by lazy { loadKoinModules(listOf(moviesRepositoryModule, networkCommonModule)) } private val moviesRepositoryModule = module { single<MoviesRepository> { MoviesRepositoryImpl( localDS = get(), remoteDS = get() ) } single<MoviesDataSources.LocalDS> { MoviesRoomDS() } single<MoviesDataSources.RemoteDS> { MoviesApiDS( service = get() ) } single<TmdbApiService> { TmdbApiServiceImpl( retrofit = get() ) } }
13
null
2
5
a26b41ff69d6ee1b13300d2fc454d6fbfbe5a360
1,277
Watch
MIT License
src/main/kotlin/io/github/smaugfm/lunchmoney/request/crypto/GetAllCryptoRequest.kt
smaugfm
609,011,135
false
null
package io.github.smaugfm.lunchmoney.request.crypto import io.github.smaugfm.lunchmoney.helper.PathAndQuery import io.github.smaugfm.lunchmoney.request.base.LunchmoneyAbstractGetRequest import io.github.smaugfm.lunchmoney.response.GetAllCryptoResponse internal class GetAllCryptoRequest : LunchmoneyAbstractGetRequest<GetAllCryptoResponse>( PathAndQuery.segment("crypto") )
0
Kotlin
0
1
2d0c0115252d76d141a12dd493c250f0b8ae6ad8
392
lunchmoney
MIT License
app/src/main/java/com/minervaai/summasphere/data/response/SignupResponse.kt
Summasphere
804,408,293
false
{"Kotlin": 94976}
package com.minervaai.summasphere.data.response data class SignupResponse( val statusCode: Int, val code: Int, val status: String, val message: String )
0
Kotlin
0
1
c124f471dbf53e4378c7bccc3a2c0d77f85febce
170
bangkit-mobile-development
MIT License
src/commonMain/kotlin/de/jensklingenberg/kt_dart_builder/main/specs/expression/CodeExpression.kt
Foso
171,142,071
false
null
package de.jensklingenberg.kt_dart_builder.main.specs.expression import de.jensklingenberg.kt_dart_builder.main.SpecVisitor import de.jensklingenberg.kt_dart_builder.main.specs.Code import de.jensklingenberg.kt_dart_builder.main.specs.Expression import de.jensklingenberg.kt_dart_builder.main.specs.ExpressionVisitor class CodeExpression(override val code: Code) : Expression { override fun <T> accept(visitor: SpecVisitor<T>, context: T?): T { visitor as ExpressionVisitor return visitor.visitCodeExpression(this, context) } }
0
Kotlin
0
1
beca489288dce4fa8d7c4f1bf536d5bad9591d06
557
kt_dart_builder
Apache License 2.0
utils/src/nativeCommonTest/kotlin/com/badoo/reaktive/utils/test/DoInBackground.kt
badoo
174,194,386
false
null
package com.badoo.reaktive.test import kotlin.native.concurrent.TransferMode import kotlin.native.concurrent.Worker internal actual fun doInBackground(block: () -> Unit) { Worker.start(errorReporting = true).execute(TransferMode.SAFE, { block }) { it() } }
8
null
58
956
c712c70be2493956e7057f0f30199994571b3670
263
Reaktive
Apache License 2.0
common-api/src/main/kotlin/io/net/api/enum/CmdEnum.kt
spcookie
671,080,496
false
null
package io.net.api.enum /** *@author Augenstern *@date 2023/6/1 */ enum class CmdEnum(val type: CmdType) { CHAT(CmdType.TEXT), IMG(CmdType.IMAGE), ST(CmdType.IMAGE), STEAM(CmdType.TEXT), HELP(CmdType.OTHER) }
0
Kotlin
0
0
9940ffc5f0f87f627681c9bb9868ff38c2237a0a
232
qq-robot
Apache License 2.0
twitlin/src/common/main/kotlin/com/sorrowblue/twitlin/utilities/help/impl/HelpApiImpl.kt
SorrowBlue
278,215,181
false
null
package com.sorrowblue.twitlin.utilities.help.impl import com.sorrowblue.twitlin.client.Response import com.sorrowblue.twitlin.client.TwitterClient import com.sorrowblue.twitlin.utilities.help.HelpApi import com.sorrowblue.twitlin.utilities.help.Language import com.sorrowblue.twitlin.utils.API_HELP import kotlinx.serialization.builtins.ListSerializer internal class HelpApiImpl(private val client: TwitterClient) : HelpApi { override suspend fun languages(): Response<List<Language>> { return client.get("$API_HELP/languages.json", Response.serializer(ListSerializer(Language.serializer()))) } }
0
Kotlin
0
1
d6a3fdf66dea3d44f95e6800d35031d9339293cd
617
Twitlin
MIT License
src/main/kotlin/gg/essential/elementa/effects/OutlineEffect.kt
Sk1erLLC
211,431,780
false
null
package gg.essential.elementa.effects import gg.essential.elementa.components.UIBlock import gg.essential.elementa.state.BasicState import gg.essential.elementa.state.State import java.awt.Color /** * Draws a basic, rectangular outline of the specified [color] and [width] around * this component. The outline will be drawn before this component's children are drawn, * so all children will render above the outline. */ class OutlineEffect @JvmOverloads constructor( color: Color, width: Float, var drawAfterChildren: Boolean = false, var drawInsideChildren: Boolean = false, sides: Set<Side> = setOf(Side.Left, Side.Top, Side.Right, Side.Bottom) ) : Effect() { private var hasLeft = Side.Left in sides private var hasTop = Side.Top in sides private var hasRight = Side.Right in sides private var hasBottom = Side.Bottom in sides private var colorState: State<Color> = BasicState(color) private var widthState: State<Float> = BasicState(width) var color: Color get() = colorState.get() set(value) { colorState.set(value) } var width: Float get() = widthState.get() set(value) { widthState.set(value) } fun bindColor(state: State<Color>) = apply { colorState = state } fun bindWidth(state: State<Float>) = apply { widthState = state } var sides = sides set(value) { field = value hasLeft = Side.Left in sides hasTop = Side.Top in sides hasRight = Side.Right in sides hasBottom = Side.Bottom in sides } fun addSide(side: Side) = apply { sides = sides + side } fun removeSide(side: Side) = apply { sides = sides - side } override fun beforeChildrenDraw() { if (!drawAfterChildren) drawOutline() } override fun afterDraw() { if (drawAfterChildren) drawOutline() } private fun drawOutline() { val color = colorState.get() val width = widthState.get() val left = boundComponent.getLeft().toDouble() val right = boundComponent.getRight().toDouble() val top = boundComponent.getTop().toDouble() val bottom = boundComponent.getBottom().toDouble() val leftBounds = if (drawInsideChildren) { left to (left + width) } else (left - width) to left val topBounds = if (drawInsideChildren) { top to (top + width) } else (top - width) to top val rightBounds = if (drawInsideChildren) { (right - width) to right } else right to (right + width) val bottomBounds = if (drawInsideChildren) { (bottom - width) to bottom } else bottom to (bottom + width) // Left outline block if (hasLeft) UIBlock.drawBlock(color, leftBounds.first, top, leftBounds.second, bottom) // Top outline block if (hasTop) UIBlock.drawBlock(color, left, topBounds.first, right, topBounds.second) // Right outline block if (hasRight) UIBlock.drawBlock(color, rightBounds.first, top, rightBounds.second, bottom) // Bottom outline block if (hasBottom) UIBlock.drawBlock(color, left, bottomBounds.first, right, bottomBounds.second) if (!drawInsideChildren) { // Top left square if (hasLeft && hasTop) UIBlock.drawBlock(color, leftBounds.first, topBounds.first, left, top) // Top right square if (hasRight && hasTop) UIBlock.drawBlock(color, right, topBounds.first, rightBounds.second, top) // Bottom right square if (hasRight && hasBottom) UIBlock.drawBlock(color, right, bottom, rightBounds.second, bottomBounds.second) // Bottom left square if (hasBottom && hasLeft) UIBlock.drawBlock(color, leftBounds.first, bottom, left, bottomBounds.second) } } enum class Side { Left, Top, Right, Bottom, } }
8
Kotlin
17
157
6f6b8259ddac9c39e9277eb8b7f799470afe60f4
4,198
Elementa
MIT License
application/src/main/kotlin/net/codebot/application/presentation/Editor.kt
irene-myan
641,283,120
false
null
// Copyright (c) 2023 Irene Martirosyan, Patrick Telfer, Stephen Cao, Tam Nguyen package net.codebot.application.presentation import com.gluonhq.richtextarea.RichTextArea import com.gluonhq.richtextarea.action.Action import com.gluonhq.richtextarea.action.ParagraphDecorateAction import com.gluonhq.richtextarea.action.TextDecorateAction import com.gluonhq.richtextarea.model.Document import com.gluonhq.richtextarea.model.ParagraphDecoration import com.gluonhq.richtextarea.model.TextDecoration import javafx.event.ActionEvent import javafx.event.EventHandler import javafx.geometry.Insets import javafx.geometry.Orientation import javafx.geometry.Pos import javafx.scene.control.* import javafx.scene.layout.* import javafx.scene.paint.Color import javafx.scene.text.Font import javafx.scene.text.FontPosture import javafx.scene.text.FontWeight import javafx.scene.text.TextAlignment import javafx.util.StringConverter import net.codebot.shared.domain.Note import org.kordamp.ikonli.Ikon import org.kordamp.ikonli.javafx.FontIcon import org.kordamp.ikonli.lineawesome.LineAwesomeSolid // Code Adapted from https://github.com/gluonhq/rich-text-area class Editor() : VBox() { private val editor = RichTextArea() private val editorArea = StackPane(editor) private val toolbar = ToolBar() private val secondaryToolbar = ToolBar() private val toolBox = VBox(toolbar, secondaryToolbar) private val cutButton = actionButton(LineAwesomeSolid.CUT, editor.actionFactory.cut()) private val copyButton = actionButton(LineAwesomeSolid.COPY, editor.actionFactory.copy()) private val pasteButton = actionButton(LineAwesomeSolid.PASTE, editor.actionFactory.paste()) private val undoButton = actionButton(LineAwesomeSolid.UNDO, editor.actionFactory.undo()) private val redoButton = actionButton(LineAwesomeSolid.REDO, editor.actionFactory.redo()) private val boldButton = createGraphicToggleButton(LineAwesomeSolid.BOLD) private val italicsButton = createGraphicToggleButton(LineAwesomeSolid.ITALIC) private val underlineButton = createGraphicToggleButton(LineAwesomeSolid.UNDERLINE) private val strikethroughButton = createGraphicToggleButton(LineAwesomeSolid.STRIKETHROUGH) private val alignLeftButton = createGraphicToggleButton(LineAwesomeSolid.ALIGN_LEFT) private val alignCenterButton = createGraphicToggleButton(LineAwesomeSolid.ALIGN_CENTER) private val alignRightButton = createGraphicToggleButton(LineAwesomeSolid.ALIGN_RIGHT) private val orderedListButton = createGraphicToggleButton(LineAwesomeSolid.LIST_OL) private val unorderedListButton = createGraphicToggleButton(LineAwesomeSolid.LIST_UL) private val fonts = ComboBox<String>() private val fontColor = ColorPicker() private val fontSize = ComboBox<Double>() init { editorArea.alignment = Pos.CENTER StackPane.setAlignment(editor, Pos.BOTTOM_CENTER) StackPane.setMargin(editor, Insets(10.0)) this.children.addAll(toolBox, editorArea) this.spacing = 10.0 setVgrow(editor, Priority.ALWAYS) setVgrow(editorArea, Priority.ALWAYS) editor.isAutoSave = true editor.styleClass.add("editor") editorArea.styleClass.add("editor-area") setTooltips() } // Bind the buttons to the editor init { // BOLD TextDecorateAction(editor, boldButton.selectedProperty().asObject(), {td: TextDecoration -> td.fontWeight == FontWeight.BOLD}, {builder: TextDecoration.Builder, property: Boolean -> builder.fontWeight( if (property) FontWeight.BOLD else FontWeight.NORMAL ).build() }) // ITALICS TextDecorateAction(editor, italicsButton.selectedProperty().asObject(), {td: TextDecoration -> td.fontPosture == FontPosture.ITALIC}, {builder: TextDecoration.Builder, property: Boolean -> builder.fontPosture( if (property) FontPosture.ITALIC else FontPosture.REGULAR ).build() }) // UNDERLINE TextDecorateAction(editor, underlineButton.selectedProperty().asObject(), {td: TextDecoration -> td.isUnderline}, {builder: TextDecoration.Builder, property: Boolean -> builder.underline( property ).build() }) // STRIKETHROUGH TextDecorateAction(editor, strikethroughButton.selectedProperty().asObject(), {td: TextDecoration -> td.isStrikethrough}, {builder: TextDecoration.Builder, property: Boolean -> builder.strikethrough( property ).build() }) // FONT COLOR TextDecorateAction(editor, fontColor.valueProperty(), { obj: TextDecoration -> obj.foreground }, { builder: TextDecoration.Builder, property: Color? -> builder.foreground( property ).build() }) fontColor.value = Color.BLACK // FONTS fonts.items.addAll(Font.getFamilies()) fonts.value = "Arial" fonts.prefWidth = 125.0 TextDecorateAction(editor, fonts.valueProperty(), { obj: TextDecoration -> obj.fontFamily }, { builder: TextDecoration.Builder, property: String -> builder.fontFamily( property ).build() }) // FONT SIZE fontSize.isEditable = true fontSize.items.addAll(5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 16.0, 18.0, 22.0, 24.0, 26.0, 28.0, 36.0, 48.0, 72.0) TextDecorateAction(editor, fontSize.valueProperty(), { td: TextDecoration -> td.fontSize }, { builder: TextDecoration.Builder, a: Double -> builder.fontSize( a ).build() }) fontSize.value = 12.0 fontSize.prefWidth = 80.0 fontSize.converter = object : StringConverter<Double>() { override fun toString(d: Double): String { return d.toInt().toString() } override fun fromString(s: String): Double { return s.toDouble() } } // ALIGN LEFT ParagraphDecorateAction(editor, alignLeftButton.selectedProperty().asObject(), { pd: ParagraphDecoration -> pd.alignment == TextAlignment.LEFT }, { builder: ParagraphDecoration.Builder, _: Boolean? -> builder.alignment( TextAlignment.LEFT ).build() }) // ALIGN CENTER ParagraphDecorateAction(editor, alignCenterButton.selectedProperty().asObject(), { pd: ParagraphDecoration -> pd.alignment == TextAlignment.CENTER }, { builder: ParagraphDecoration.Builder, _: Boolean? -> builder.alignment( TextAlignment.CENTER ).build() }) // ALIGN RIGHT ParagraphDecorateAction(editor, alignRightButton.selectedProperty().asObject(), { pd: ParagraphDecoration -> pd.alignment == TextAlignment.RIGHT }, { builder: ParagraphDecoration.Builder, _: Boolean? -> builder.alignment( TextAlignment.RIGHT ).build() }) // ORDERED LIST ParagraphDecorateAction(editor, orderedListButton.selectedProperty().asObject(), { pd: ParagraphDecoration -> pd.graphicType == ParagraphDecoration.GraphicType.NUMBERED_LIST}, { builder: ParagraphDecoration.Builder, a: Boolean -> builder.graphicType( if (a) ParagraphDecoration.GraphicType.NUMBERED_LIST else ParagraphDecoration.GraphicType.NONE ).build() }) // UNORDERED LIST ParagraphDecorateAction(editor, unorderedListButton.selectedProperty().asObject(), { pd: ParagraphDecoration -> pd.graphicType == ParagraphDecoration.GraphicType.BULLETED_LIST}, { builder: ParagraphDecoration.Builder, a: Boolean -> builder.graphicType( if (a) ParagraphDecoration.GraphicType.BULLETED_LIST else ParagraphDecoration.GraphicType.NONE ).build() }) } init { toolbar.items.setAll( cutButton, copyButton, pasteButton, Separator(Orientation.VERTICAL), undoButton, redoButton, Separator(Orientation.VERTICAL), boldButton, italicsButton, underlineButton, strikethroughButton, fontColor, ) secondaryToolbar.items.setAll( fonts, fontSize, Separator(Orientation.VERTICAL), alignLeftButton, alignCenterButton, alignRightButton, orderedListButton, unorderedListButton ) } private fun actionButton(ikon: Ikon, action: Action): Button { val button = Button() val icon = FontIcon(ikon) icon.iconSize = 20 button.graphic = icon button.disableProperty().bind(action.disabledProperty()) button.onAction = EventHandler { event: ActionEvent? -> action.execute(event) } return button } private fun createGraphicToggleButton( ikon: Ikon, ): ToggleButton { val toggleButton = ToggleButton() val icon = FontIcon(ikon) icon.iconSize = 20 toggleButton.graphic = icon return toggleButton } fun undo(event: ActionEvent?) { editor.actionFactory.undo().execute(event) } fun redo(event: ActionEvent?) { editor.actionFactory.redo().execute(event) } fun cut(event: ActionEvent?) { editor.actionFactory.cut().execute(event) } fun copy(event: ActionEvent?) { editor.actionFactory.copy().execute(event) } fun paste(event: ActionEvent?) { editor.actionFactory.paste().execute(event) } fun setContent(document: Document) { editor.document = document; } fun getContent() : Document { return editor.document; } fun hideToolbox() { this.children.remove(toolBox) } fun showToolbox() { this.children.add(0, toolBox) } private fun setTooltips() { cutButton.tooltip = Tooltip("Cut") copyButton.tooltip = Tooltip("Copy") pasteButton.tooltip = Tooltip("Paste") undoButton.tooltip = Tooltip("Undo") redoButton.tooltip = Tooltip("Redo") boldButton.tooltip = Tooltip("Bold") italicsButton.tooltip = Tooltip("Italic") underlineButton.tooltip = Tooltip("Underline") strikethroughButton.tooltip = Tooltip("Strikethrough") fontColor.tooltip = Tooltip("Font color") fonts.tooltip = Tooltip("Font") fontSize.tooltip = Tooltip("Font size") alignLeftButton.tooltip = Tooltip("Align left") alignCenterButton.tooltip = Tooltip("Align center") alignRightButton.tooltip = Tooltip("Align right") orderedListButton.tooltip = Tooltip("Numbering") unorderedListButton.tooltip = Tooltip("Bullets") } }
0
Kotlin
0
0
4cf307626b029bd25fa2d36f0afd3c36dc510196
11,515
JotJungle
MIT License
app/src/main/java/hu/tb/tasky/ui/notification/TaskNotificationService.kt
BTheofil
590,994,753
false
{"Kotlin": 80365}
package hu.tb.tasky.ui.notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import hu.tb.tasky.MainActivity import hu.tb.tasky.R import hu.tb.tasky.model.TaskEntity class TaskNotificationService( private val context: Context ) { private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager fun showNotification(task: TaskEntity) { val activityIntent = Intent(context, MainActivity::class.java) //define what activity open when user tap the notification val activityPendingIntent = PendingIntent.getActivity( context, OPEN_MAIN_ACTIVITY, activityIntent, PendingIntent.FLAG_IMMUTABLE ) val notification = NotificationCompat.Builder(context, TASK_CHANNEL_ID) .setSmallIcon(R.drawable.outline_alarm_24) .setContentTitle(task.title) .setContentIntent(activityPendingIntent) .build() notificationManager.notify(task.taskId!!, notification) } companion object { const val TASK_CHANNEL_ID = "task_channel" const val OPEN_MAIN_ACTIVITY = 1 } }
0
Kotlin
0
0
472946c888ffecd4bb9ca3f6b67523ac5015dc00
1,303
Tasky
Apache License 2.0
vkid/src/main/java/com/vk/id/internal/log/Logger.kt
VKCOM
696,297,549
false
{"Kotlin": 345109, "AIDL": 3429, "Shell": 1622}
package com.vk.id.internal.log /** * Simple logging */ internal interface Logger { fun info(message: String) fun debug(message: String) fun error(message: String, throwable: Throwable?) }
1
Kotlin
0
8
ac0870dd548c2c4bb0ac5a7cf4b973e7add590b2
203
vkid-android-sdk
MIT License
shared/domain/show/api/src/commonMain/kotlin/com/thomaskioko/tvmaniac/discover/api/repository/TvShowsRepository.kt
c0de-wizard
361,393,353
false
null
package com.thomaskioko.tvmaniac.discover.api.repository import com.kuuurt.paging.multiplatform.PagingData import com.thomaskioko.tvmaniac.datasource.cache.Show import com.thomaskioko.tvmaniac.shared.core.util.CommonFlow import com.thomaskioko.tvmaniac.shared.core.util.Resource import kotlinx.coroutines.flow.Flow interface TvShowsRepository { suspend fun updateWatchlist(showId: Int, addToWatchList: Boolean) fun observeShow(tvShowId: Int): Flow<Resource<Show>> fun observeWatchlist(): Flow<List<Show>> fun observeShowsByCategoryID( categoryId: Int ): Flow<Resource<List<Show>>> fun observePagedShowsByCategoryID( categoryId: Int ): CommonFlow<PagingData<Show>> }
2
Kotlin
1
16
d1f9432b58155a1f1e2deadc569aac122fcdbe83
717
tv-maniac
Apache License 2.0
android-app/src/googleplay/kotlin/fr/cph/chicago/core/model/marker/RefreshBusMarkers.kt
carlphilipp
16,032,504
false
null
/** * Copyright 2021 Carl-Philipp Harmant * * * 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 fr.cph.chicago.core.model.marker import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.Marker import fr.cph.chicago.R /** * Refresh buses and stop markers * * @author Carl-Philipp Harmant * @version 1 */ class RefreshBusMarkers : RefreshMarkers(R.drawable.bus) { fun refreshBusAndStation(position: CameraPosition, busMarkers: List<Marker>, busStationMarkers: List<Marker>) { refresh(position, busMarkers) var currentZoom = -1f if (position.zoom != currentZoom) { val oldZoom = currentZoom currentZoom = position.zoom // Handle stops markers if (isIn(currentZoom, 21f, 14.5f) && !isIn(oldZoom, 21f, 14.5f)) { busStationMarkers.forEach { marker -> marker.isVisible = true } } else { busStationMarkers.forEach { marker -> marker.isVisible = false } } } } }
3
null
1
9
1f6d4bc5855852fb0c343f04d13ef133b4419228
1,627
chicago-commutes
Apache License 2.0
project-signer-runnable/src/test/kotlin/org/jesperancinha/parser/projectsigner/service/FinderServiceTest.kt
jesperancinha
206,956,926
false
null
package org.jesperancinha.parser.projectsigner.service import io.kotest.matchers.shouldBe import io.mockk.confirmVerified import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.junit5.MockKExtension import io.mockk.mockk import io.mockk.verify import org.jesperancinha.parser.markdowner.model.Paragraphs import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.io.TempDir import java.io.IOException import java.nio.file.Path @ExtendWith(MockKExtension::class) internal class FinderServiceTest { @InjectMockKs lateinit var finderService: FinderService @MockK lateinit var readmeNamingService: ReadmeNamingService @MockK lateinit var mergeService: MergeService @MockK(relaxed = true) lateinit var templateService: TemplateService @MockK lateinit var readmeService: ReadmeService @MockK lateinit var optionsService: OptionsServiceMock @MockK lateinit var fileWriterService: FileWriterService @MockK(relaxed = true) lateinit var generatorService: GeneratorSevice @BeforeEach fun setUp() { System.getProperty("file.encoding") shouldBe "UTF-8" } @Test @Throws(IOException::class) fun testIterateThroughFilesAndFolders() { val mockParagraphs: Paragraphs = mockk() every { mockParagraphs.getParagraphCount() } returns 0 every { templateService.findAllParagraphs() } returns mockParagraphs every { templateService.findAllRedirectParagraphs() } returns mockParagraphs finderService.iterateThroughFilesAndFolders(tempDirectory) verify { templateService.findAllParagraphs() } verify { generatorService.processReadmeFile(tempDirectory, mockParagraphs) } confirmVerified(readmeNamingService, optionsService, fileWriterService, readmeService, mergeService) } companion object { @TempDir lateinit var tempDirectory: Path } }
0
null
0
3
d6b6451b03db2bbba274f302c7ce2f3a168e901a
2,072
project-signer
Apache License 2.0
app/src/main/java/com/bjelor/erste/data/RetrofitFactory.kt
Bjelor
542,591,414
false
{"Kotlin": 34837}
package com.bjelor.erste.data import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory class RetrofitFactory { fun create(): Retrofit { val client = OkHttpClient.Builder().build() val moshi = Moshi.Builder() .addLast(KotlinJsonAdapterFactory()) .build() return Retrofit.Builder() .baseUrl("https://api.flickr.com") .addConverterFactory(MoshiConverterFactory.create(moshi)) .client(client) .build() } }
0
Kotlin
0
0
0d758f388724121bb8699b975ce6a63c0358bb61
661
erste_entry_test
Apache License 2.0
3/LoadApp/app/src/main/java/com/udacity/Utils.kt
chiaz91
393,010,970
false
null
package com.udacity; import android.app.Activity import android.app.AlertDialog import android.app.DownloadManager import android.content.Context import android.content.Intent import android.database.Cursor import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.InputType import android.util.Log import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity fun Activity.toast(message: String): Toast { val toast = Toast.makeText(this, message, Toast.LENGTH_SHORT) toast.show() return toast } fun Context.queryDownloadStatus(id: Long): FileStatus?{ try{ val query = DownloadManager.Query() query.setFilterById(id) val manager = getSystemService(AppCompatActivity.DOWNLOAD_SERVICE) as DownloadManager manager.query(query).run { if (moveToFirst()){ log() val title = getString(getColumnIndex(DownloadManager.COLUMN_TITLE)) val status = getInt(getColumnIndex(DownloadManager.COLUMN_STATUS)) val reason = getInt(getColumnIndex(DownloadManager.COLUMN_REASON)) return FileStatus(title, status, reason) } } } catch (e: Exception){ e.printStackTrace() } return null } // debug fun LoadingButton.simulateLoading(){ loading = true Handler(Looper.getMainLooper()).postDelayed({ loading = false }, 10000) } fun Bundle.log() { Log.i("load.bundle", "{") keySet().forEach{key -> Log.i("load.bundle", " $key: ${this[key].toString()}" ) } Log.i("load.bundle", "}") } fun Cursor.log(){ Log.i("load.cursor", "{") columnNames.forEach {col-> try{ val idx = getColumnIndex(col) Log.i("load.cursor", " $idx $col: ${getString(idx)}") } catch (e: Exception){} } Log.i("load.cursor", "}") } fun Activity.toViewDownload(){ val viewDownloads = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS) startActivity(viewDownloads) } fun Activity.promptViewDownload(){ val inputId = EditText(this) inputId.hint = "Enter download id" inputId.inputType = InputType.TYPE_CLASS_NUMBER AlertDialog.Builder(this) .setTitle("DEBUG") .setMessage("View download status on DetailActivity.") .setView(inputId) .setPositiveButton("View"){ _,_ -> try{ var id = inputId.text.toString().toLong() val intent = Intent(this, DetailActivity::class.java) intent.putExtra("download_id", id) startActivity(intent) }catch (e:Exception){ toViewDownload( ) } } .show() } // dirty methods :P fun getStatusString(status: Int): String{ return when(status){ DownloadManager.STATUS_PENDING -> "Pending" DownloadManager.STATUS_RUNNING -> "Running" DownloadManager.STATUS_PAUSED -> "Paused" DownloadManager.STATUS_SUCCESSFUL -> "Success" DownloadManager.STATUS_FAILED -> "Failed" else -> "Unknown status" } } fun getReasonString(reason: Int): String{ return when(reason){ // pauses DownloadManager.PAUSED_WAITING_TO_RETRY -> "PAUSED_WAITING_TO_RETRY" DownloadManager.PAUSED_WAITING_FOR_NETWORK -> "PAUSED_WAITING_FOR_NETWORK" DownloadManager.PAUSED_QUEUED_FOR_WIFI -> "PAUSED_QUEUED_FOR_WIFI" DownloadManager.PAUSED_UNKNOWN -> "PAUSED_UNKNOWN" // error DownloadManager.ERROR_UNKNOWN -> "ERROR_UNKNOWN" DownloadManager.ERROR_FILE_ERROR -> "ERROR_FILE_ERROR" DownloadManager.ERROR_UNHANDLED_HTTP_CODE -> "ERROR_UNHANDLED_HTTP_CODE" DownloadManager.ERROR_HTTP_DATA_ERROR -> "ERROR_HTTP_DATA_ERROR" DownloadManager.ERROR_TOO_MANY_REDIRECTS -> "ERROR_TOO_MANY_REDIRECTS" DownloadManager.ERROR_INSUFFICIENT_SPACE-> "ERROR_INSUFFICIENT_SPACE" DownloadManager.ERROR_DEVICE_NOT_FOUND -> "ERROR_DEVICE_NOT_FOUND" DownloadManager.ERROR_CANNOT_RESUME -> "ERROR_CANNOT_RESUME" DownloadManager.ERROR_FILE_ALREADY_EXISTS -> "ERROR_FILE_ALREADY_EXISTS" else -> "Unknown reason" } }
0
Kotlin
0
0
670b2447b3826bd56bd29ad984871e267def9423
4,255
udacity-aos-learn
MIT License
gradle/plugins/src/main/kotlin/io/dotanuki/norris/gradle/modules/models/ProguardRules.kt
dotanuki-labs
192,096,771
false
null
package io.dotanuki.norris.gradle.modules.models import java.io.File internal class ProguardRules(private val pathToFiles: String) { val extras by lazy { File(pathToFiles).listFiles().toList().toTypedArray() } val androidDefault by lazy { "proguard-android-optimize.txt" } }
7
null
38
474
18d890ee7774b2387344534ea949c079c69730cc
311
norris
MIT License
examples/federation/extend-app/src/main/kotlin/com/expediagroup/graphql/examples/federation/extend/schema/Widget.kt
ExpediaGroup
148,706,161
false
null
/* * Copyright 2021 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.graphql.examples.federation.extend.schema import com.expediagroup.graphql.generator.federation.directives.ExtendsDirective import com.expediagroup.graphql.generator.federation.directives.ExternalDirective import com.expediagroup.graphql.generator.federation.directives.FieldSet import com.expediagroup.graphql.generator.federation.directives.KeyDirective /** * We do not own the "Widget" type in this service. We are extending it here with the new fields when we are given the @key "id" */ @KeyDirective(fields = FieldSet("id")) @ExtendsDirective class Widget( @ExternalDirective val id: Int, val randomValueFromExtend: Int ) { @Suppress("FunctionOnlyReturningConstant") fun extraStringFromExtend() = "This data is coming from extend-app!" }
21
null
273
1,420
a0a8bad009a4ddbf88ce5c30200f90a091bd3df7
1,385
graphql-kotlin
Apache License 2.0
infra/nats/src/main/kotlin/io/bluetape4k/nats/client/PushSubscriptionOptions.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.nats.client import io.nats.client.PushSubscribeOptions inline fun pushSubscriptionOptions( initializer: PushSubscribeOptions.Builder.() -> Unit, ): PushSubscribeOptions = PushSubscribeOptions.builder().apply(initializer).build() fun pushSubscriptionOf(stream: String): PushSubscribeOptions = PushSubscribeOptions.stream(stream) fun pushSubscriptionOf(stream: String, durable: String): PushSubscribeOptions = PushSubscribeOptions.bind(stream, durable)
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
494
bluetape4k
MIT License
app/src/main/java/gr/blackswamp/damagereports/app/Utils.kt
JMavrelos
212,301,077
false
null
package gr.blackswamp.damagereports.app import androidx.coordinatorlayout.widget.CoordinatorLayout import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.floatingactionbutton.FloatingActionButton.SIZE_MINI import gr.blackswamp.damagereports.R private var miniSize: Int = 0 private var normalSize: Int = 0 private var fabMargin: Int = 0 fun FloatingActionButton.moveBy(offset: Float, max: Int) { val fabSize: Int = if (this.size == SIZE_MINI) { if (miniSize == 0) { miniSize = (40 * this.resources.displayMetrics.density).toInt() } miniSize } else { if (normalSize == 0) { normalSize = (56 * this.resources.displayMetrics.density).toInt() } normalSize } if (fabMargin == 0) { fabMargin = this.resources.getDimensionPixelSize(R.dimen.fab_margin) } val maxOffset = max - (fabSize / 2) - fabMargin val params = layoutParams as CoordinatorLayout.LayoutParams params.marginEnd = ((offset * maxOffset) + fabMargin).toInt() layoutParams = params }
0
Kotlin
0
0
125ceef68db9554d9c047500e41f0fa96085ae64
1,117
DamageReportsKTX
Apache License 2.0
ui/src/main/java/com/kambo/klodian/ui/ui/model/UiWeather.kt
KlodianKambo
350,786,745
false
null
package com.kambo.klodian.ui.ui.model data class UiWeather( val id: Long, val title: String, val description: String, val iconPath: String )
0
Kotlin
1
0
5d28e1afa1c43082217fb2976a20d9f834d72a83
158
WeatherAndroid
The Unlicense
common/src/main/java/com/mallowigi/utils/StaticPatcher.kt
mallowigi
103,978,462
false
null
/* * The MIT License (MIT) * * Copyright (c) 2015-2021 <NAME>Mallowigi" Boukhobza * * 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.mallowigi.idea.utils import java.lang.reflect.Field import java.lang.reflect.Modifier /** Super hacking class to change static fields! */ object StaticPatcher { /** * Rewrites a class's static field with a new value by static field * name. * * Note that private fields will have their names changed at * compilation. * * @param cls the class * @param fieldName the name of the static field * @param newValue the new value */ @Throws(NoSuchFieldException::class, IllegalAccessException::class) @JvmStatic fun setFinalStatic(cls: Class<*>, fieldName: String, newValue: Any?) { val fields = cls.declaredFields for (field in fields) { if (field.name == fieldName) { setFinalStatic(field, newValue) return } } } /** * Rewrites a class's static field with a new value by field * * @param field the Field to change * @param newValue the new value */ @JvmStatic @Throws(NoSuchFieldException::class, IllegalAccessException::class) fun setFinalStatic(field: Field, newValue: Any?) { field.isAccessible = true val modifiersField = Field::class.java.getDeclaredField("modifiers") modifiersField.isAccessible = true modifiersField.setInt(field, field.modifiers and Modifier.FINAL.inv()) field[null] = newValue modifiersField.setInt(field, field.modifiers or Modifier.FINAL) modifiersField.isAccessible = false field.isAccessible = false } @JvmStatic @Throws(NoSuchFieldException::class, IllegalAccessException::class) fun setFinal(instance: Any, field: Field, newValue: Any) { field.isAccessible = true val modifiersField = Field::class.java.getDeclaredField("modifiers") modifiersField.isAccessible = true modifiersField.setInt(field, field.modifiers and Modifier.FINAL.inv()) field[instance] = newValue modifiersField.setInt(field, field.modifiers or Modifier.FINAL) modifiersField.isAccessible = false field.isAccessible = false } }
5
Kotlin
19
138
b392eb914bd4cfc12b68f5e1c58b869cb4ab5ba1
3,189
a-file-icon-idea
MIT License
classic/src/main/kotlin/dev/winx64/classicbridge/classic/network/clientbound/PositionClientboundPacket.kt
WinX64
278,368,926
false
null
package dev.winx64.classicbridge.classic.network.clientbound import dev.winx64.classicbridge.classic.cpe.ExtensionSettings import dev.winx64.classicbridge.classic.network.ClassicInboundPacket import dev.winx64.classicbridge.classic.network.callback.ClassicPacketCallback import io.netty.buffer.ByteBuf class PositionClientboundPacket(input: ByteBuf, settings: ExtensionSettings) : ClassicInboundPacket { val playerId = input.readByte() val deltaX = input.readByte() val deltaY = input.readByte() val deltaZ = input.readByte() override fun notifyCallback(callback: ClassicPacketCallback) = callback.onPosition(this) }
0
Kotlin
0
1
b4c1f806c35ff98a61eddae15da9837f9d091386
641
classic-bridge
MIT License
composeApp/src/commonMain/kotlin/com/carpisoft/guau/core/ui/screens/header/HeadScaffold.kt
wgcarvajal
683,392,078
false
{"Kotlin": 404670, "Swift": 1993, "Shell": 228}
package com.carpisoft.guau.core.ui.screens.header import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBackIos import androidx.compose.material.icons.automirrored.filled.Logout import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.TransitEnterexit import androidx.compose.material3.Divider import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import com.carpisoft.guau.core.utils.constants.PlatformConstants import com.carpisoft.guau.getPlatformName import guau.composeapp.generated.resources.Res import guau.composeapp.generated.resources.exit_center import guau.composeapp.generated.resources.my_profile import guau.composeapp.generated.resources.sign_off import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.stringResource import com.carpisoft.guau.ui.theme.BackgroundHead import com.carpisoft.guau.ui.theme.Green100 @OptIn(ExperimentalResourceApi::class) @Composable fun HeadScaffold( title: String, showAccountOptions: Boolean, showNavigation: Boolean, showExitCenter: Boolean, showButtonAddOnTopBar: Boolean, titleFontSize: TextUnit, iconSize: Dp, appBarHeight: Dp, dropdownMenuWidth: Dp, signOffOnClick: () -> Unit, onExitVet: () -> Unit, onBackOnClick: () -> Unit, onAddOnClick: () -> Unit, ) { var openMenu by rememberSaveable { mutableStateOf(false) } MyTopAppBar( title = { Text( text = title, fontSize = titleFontSize ) }, appBarHeight = appBarHeight, backgroundColor = BackgroundHead, navigationIcon = if (showNavigation) { { IconButton( onClick = onBackOnClick, colors = IconButtonDefaults.iconButtonColors( containerColor = Color.Transparent, contentColor = Green100, disabledContainerColor = Color.Transparent, disabledContentColor = Color.Gray ) ) { Icon( modifier = Modifier.size(iconSize), imageVector = Icons.AutoMirrored.Filled.ArrowBackIos, contentDescription = "" ) } } } else { null }, actions = { if (getPlatformName() == PlatformConstants.IOS && showButtonAddOnTopBar) { IconButton(onClick = onAddOnClick) { Icon( imageVector = Icons.Filled.Add, contentDescription = "" ) } } if (showAccountOptions) { IconButton(onClick = { openMenu = !openMenu }) { Icon( imageVector = Icons.Filled.AccountCircle, contentDescription = "" ) } DropdownMenu( modifier = Modifier.width(dropdownMenuWidth), expanded = openMenu, onDismissRequest = { openMenu = false }) { DropdownMenuItem(onClick = { openMenu = false }, text = { Row() { Icon(imageVector = Icons.Filled.Person, contentDescription = "") Spacer(modifier = Modifier.width(5.dp)) Text(text = stringResource(Res.string.my_profile)) } }) if (showExitCenter) { Divider() DropdownMenuItem(onClick = { openMenu = false onExitVet() }, text = { Row() { Icon( imageVector = Icons.Filled.TransitEnterexit, contentDescription = "" ) Spacer(modifier = Modifier.width(5.dp)) Text(text = stringResource(Res.string.exit_center)) } }) } Divider() DropdownMenuItem(onClick = { openMenu = false signOffOnClick() }, text = { Row() { Icon( imageVector = Icons.AutoMirrored.Filled.Logout, contentDescription = "" ) Spacer(modifier = Modifier.width(5.dp)) Text(text = stringResource(Res.string.sign_off)) } }) } } } ) }
0
Kotlin
0
0
7971f12e4a2b2763eb23dbfca8b56fdddc6db37e
6,082
guau-multiplatform
Apache License 2.0
plugins/kotlin/uast/uast-kotlin/tests/test/org/jetbrains/uast/test/kotlin/comparison/AbstractFE1LegacyUastResolveEverythingTest.kt
ingokegel
72,937,917
true
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.uast.test.kotlin.comparison import org.jetbrains.uast.test.common.kotlin.LegacyUastResolveEverythingTestBase abstract class AbstractFE1LegacyUastResolveEverythingTest : AbstractFE1UastResolveEverythingTest(), LegacyUastResolveEverythingTestBase
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
478
intellij-community
Apache License 2.0
src/test/kotlin/ru/job4j/lambda/SummingKtTest.kt
staskorobeynikov
315,352,877
false
{"Gradle": 2, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 51, "Java": 1}
package ru.job4j.lambda import io.kotlintest.shouldBe import io.kotlintest.specs.StringSpec internal class SummingKtTest : StringSpec ({ "Filter and map sum" { val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val sum = sum(list) sum shouldBe 35 } "Filter and map count" { val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val sum = count(list) sum shouldBe 5 } })
0
Kotlin
1
0
57af21679b44763a36335e6368554998571cc10f
430
job4j_kotlin
Apache License 2.0
api-server/src/test/kotlin/com/companimal/member/domain/port/SignUpRequestValidationTest.kt
roseoutz
609,769,119
false
null
package com.companimal.member.domain.port import jakarta.validation.Validation import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class SignUpRequestValidationTest { @Test fun `should pass validation`() { val signUpRequest = SignUpRequest(email = "test", password = "test") val violation = validator.validate(signUpRequest) Assertions.assertTrue(violation.isEmpty()) } @Test fun `should throw email is null`() { val signUpRequest = SignUpRequest(email = "", password = "test") val violation = validator.validate(signUpRequest) Assertions.assertTrue(violation.isNotEmpty()) violation.forEach { Assertions.assertEquals(it.message, "공백일 수 없습니다")} } @Test fun `should throw password is null`() { val signUpRequest = SignUpRequest(email = "test", password = "") val violation = validator.validate(signUpRequest) Assertions.assertTrue(violation.isNotEmpty()) violation.forEach { Assertions.assertEquals(it.message, "공백일 수 없습니다")} } companion object { private val factory = Validation.buildDefaultValidatorFactory() private val validator = factory.validator @AfterAll fun close() { factory.close() } } }
0
Kotlin
0
0
59418f593ccdc77fd0f5d3f9cf76390e6e510e32
1,354
companimal
MIT License
kaff4-rdf/src/main/kotlin/net/navatwo/kaff4/rdf/io/literals/ZonedDateTimeRdfConverter.kt
kaff4
555,850,412
false
null
package net.navatwo.kaff4.rdf.io.literals import net.navatwo.guice.typeLiteral import net.navatwo.kaff4.rdf.io.ConcreteRdfValueConverter import org.eclipse.rdf4j.model.Literal import org.eclipse.rdf4j.model.Value import java.time.ZonedDateTime import javax.inject.Inject import javax.inject.Singleton @Singleton internal class ZonedDateTimeRdfConverter @Inject constructor() : ConcreteRdfValueConverter<ZonedDateTime>(typeLiteral<ZonedDateTime>()) { override fun parse(value: Value): ZonedDateTime? { val calendarValue = (value as? Literal)?.calendarValue() ?: return null return calendarValue.toGregorianCalendar().toZonedDateTime() } override fun serialize(value: ZonedDateTime): Value? { return valueFactory.createLiteral(value) } }
9
Kotlin
0
1
b0df931c9be6378bd9fc7f6d182d1a35b3034c2f
761
kaff4
MIT License
kmqtt-common/src/posixMain/kotlin/socket/tcp/Socket.kt
davidepianca98
235,132,697
false
null
package socket.tcp import close import getEagain import getErrno import getEwouldblock import kotlinx.cinterop.addressOf import kotlinx.cinterop.convert import kotlinx.cinterop.usePinned import recv import send import shutdown import socket.SocketInterface actual open class Socket( private val socket: Int, private val writeRequest: MutableList<Int>, private val buffer: ByteArray ) : SocketInterface { private var pendingSendData = mutableListOf<UByteArray>() actual override fun send(data: UByteArray) { data.toByteArray().usePinned { pinned -> val length = send(socket, pinned.addressOf(0), data.size, 0) if (length < 0) { val error = getErrno() if (error == getEagain() || error == getEwouldblock()) { pendingSendData.add(data) writeRequest.add(socket) } else { close() throw IOException("Error in send $error") } } else if (length < data.size) { pendingSendData.add(data.copyOfRange(length, data.size)) writeRequest.add(socket) } pinned } } actual override fun sendRemaining() { val sendData = mutableListOf<UByteArray>() sendData.addAll(pendingSendData) pendingSendData.clear() sendData.forEach { send(it) } } actual override fun read(): UByteArray? { buffer.usePinned { pinned -> val length = recv(socket.convert(), pinned.addressOf(0), buffer.size.convert(), 0) when { length == 0 -> { close() throw SocketClosedException() } length > 0 -> { return pinned.get().toUByteArray().copyOfRange(0, length) } else -> { val error = getErrno() if (error != getEagain() && error != getEwouldblock()) { close() throw IOException("Error in recv: $error") } else { return null } } } } } actual override fun close() { shutdown(socket) close(socket) } }
2
null
19
92
eff347bc03c4093a974731d0974e5592bde5bb49
2,384
KMQTT
MIT License
app/src/main/java/com/na/dgsw/gongyou_android/data/repository/FileRepositoryImpl.kt
agvx124
256,236,304
false
{"Kotlin": 66985}
package com.na.dgsw.gongyou_android.data.repository import com.na.dgsw.gongyou_android.data.datasource.remote.file.FileDataSource import com.na.dgsw.gongyou_android.domain.entity.Response import com.na.dgsw.gongyou_android.domain.entity.file.request.FileRequest import com.na.dgsw.gongyou_android.domain.entity.file.response.FileResponse import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers /** * Created by NA on 2020-12-02 * <EMAIL> */ class FileRepositoryImpl(private val fileDataSource: FileDataSource): FileRepository { override fun postUrlUpload(fileRequest: FileRequest): Single<retrofit2.Response<Response<FileResponse>>> = fileDataSource.postUrlUpload(fileRequest).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) override fun getFiles(fileEigenValue: Int): Single<retrofit2.Response<Response<List<String>>>> = fileDataSource.getFiles(fileEigenValue).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) }
0
Kotlin
1
0
c49a8fb1c6024c9f129e2b65b0bcf39bd001aca0
1,066
GongYou_Android
Apache License 2.0
app/src/main/java/com/ibrahimcanerdogan/nasaspaceapp/data/repository/astronomy/datasource/AstronomyRemoteDataSource.kt
icanerdogan
615,759,461
false
{"Kotlin": 77576}
package com.ibrahimcanerdogan.nasaspaceapp.data.repository.astronomy.datasource import com.ibrahimcanerdogan.nasaspaceapp.model.astronomy.Astronomy import retrofit2.Response interface AstronomyRemoteDataSource { suspend fun getAstronomyDataFromRemote() : Response<List<Astronomy>> }
3
Kotlin
0
3
85ec745821d515a0f9334a60a811797b86d2e4ff
288
Nasa-Space-App
MIT License
account-query-service/src/main/kotlin/se/sbab/es/demo/query/kafka/Revision.kt
tnt-sbab
751,858,774
false
{"Kotlin": 145967}
package se.sbab.es.demo.query.kafka import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonCreator.Mode.DELEGATING import com.fasterxml.jackson.annotation.JsonValue import jakarta.persistence.AttributeConverter import jakarta.persistence.Converter import java.nio.ByteBuffer data class Revision @JsonCreator(mode = DELEGATING) constructor(@JsonValue val value: Int) { companion object { const val REVISION_HEADER = "revision" } // This constructor is used when consuming from the Kafka revision header constructor(value: ByteArray) : this(ByteBuffer.wrap(value).int) @JsonCreator(mode = JsonCreator.Mode.DELEGATING) constructor(id: String) : this(Integer.valueOf(id)) fun next() = Revision(value + 1) override fun toString() = value.toString() operator fun compareTo(revision: Revision): Int = value.compareTo(revision.value) } @Converter class RevisionConverter : AttributeConverter<Revision, Int> { override fun convertToDatabaseColumn(attribute: Revision): Int = attribute.value override fun convertToEntityAttribute(dbData: Int?): Revision? = dbData?.let { Revision(dbData) } }
0
Kotlin
1
4
09ca03d73fe03e429c3253073e4b899519b780f7
1,184
spring-boot-event-store
Apache License 2.0
app/src/main/java/com/syntex_error/jepackcompose/viewmodels/DogListViewModel.kt
rahat14
393,418,899
false
null
package com.syntex_error.jepackcompose.viewmodels import android.util.Log import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.syntex_error.jepackcompose.models.DogModel import com.syntex_error.jepackcompose.networking.ApiProvider import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.launch @ExperimentalCoroutinesApi class DogListViewModel : ViewModel() { private var page: Int = 1 var isLoading = mutableStateOf(false) var isEnd = mutableStateOf(false) var isError = mutableStateOf(false) var isMsg = mutableStateOf("") val dogList: MutableState<List<DogModel>> = mutableStateOf(ArrayList()) init { intialDogs() } private fun intialDogs() { viewModelScope.launch { isLoading.value = true isError.value = false try { val call = ApiProvider.dataApi.getDogsBreeds(1, 20) if (call.isSuccessful && call.code() == 200) { val dogs = call.body() if (dogs != null) { dogList.value = dogs isLoading.value = false } } else { isLoading.value = false isError.value = true isMsg.value = "Error : ${call.code()}" } } catch (ex: Exception) { isLoading.value = false Log.d("TAG", "getNews: ${ex.localizedMessage}") isError.value = true isMsg.value = "Error : ${ex.localizedMessage}" } } } fun getMoreDogs() { viewModelScope.launch { isError.value = false isLoading.value = true delay(1000) val call = ApiProvider.dataApi.getDogsBreeds(page + 1, 20) if (call.isSuccessful && call.code() == 200) { val dogs = call.body() if (dogs != null) { // this api send empty list when there is no dogs // if if (dogs.isEmpty()) { // its the end isEnd.value = true isLoading.value = false isMsg.value = "You Are At The Last Page !!" } else { addNewDogsToList(dogs) } } } else { isLoading.value = false isError.value = true isMsg.value = "Error : ${call.code()}" } } } private fun addNewDogsToList(dogs: MutableList<DogModel>) { val currentList = ArrayList(dogList.value) currentList.addAll(dogs) dogList.value = currentList page += 1 isLoading.value = false } }
0
Kotlin
0
4
73f47012fe6d8f4c0fd3a23139b0fe4a61431088
3,022
Infinte-List-JetPack-Compose
MIT License
app/src/main/java/com/github/yoviep/ktorserverexample/domain/usecases/GetPersonsUseCase.kt
yoviekaputra
496,838,941
false
{"Kotlin": 35498}
package com.github.yoviep.ktorserverexample.domain.usecases import com.github.yoviep.ktorserverexample.domain.model.PersonDomain /** * @created 04-06-2022 22:23 * @author yoviekaputra * @project KtorServerExample **/ interface GetPersonsUseCase { operator fun invoke(): List<PersonDomain> }
0
Kotlin
0
6
9bca4c973ba1fed0ce375b3a1e2bfa2c53d922fb
303
ktor_server_android_app
Apache License 2.0
dsl/src/main/kotlin/dsl/EffectsDSL.kt
pikalab-unibo-students
489,310,107
false
null
package dsl import core.Effect import core.Fluent import dsl.provider.PredicateProvider /** * Class representing multiple [Effect]s in the DSL. */ class EffectsDSL( predicateProvider: PredicateProvider ) : AbstractFluentDSL(predicateProvider) { /** * @property effects: set of [Effect] created. */ var effects: MutableSet<Effect> = mutableSetOf() /** * Method that updates the internal list of [effects] adding the last positive fluent created. */ operator fun Fluent.unaryPlus() = effects.add(core.Effect.positive(this)) /** * Method that create a positive [Fluent] from a [String] without arguments. */ operator fun String.unaryPlus() = effects.add(Effect.positive(this())) /** * Method that updates the internal list of [effects] adding the last negative fluent created. */ operator fun Fluent.unaryMinus() = effects.add(core.Effect.negative(this)) /** * Method that create a negative [Type] from a [String] without arguments. */ operator fun String.unaryMinus() = effects.add(Effect.negative(this())) }
9
Kotlin
1
0
d9dc9bfe252fd8cd9a9d601fe97efe3ccae26bb0
1,108
xaip-lib
Apache License 2.0
1674.Minimum Moves to Make Array Complementary.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
internal class Solution { fun minMoves(nums: IntArray, limit: Int): Int { val d = IntArray(2 * limit + 2) val n = nums.size for (i in 0 until n / 2) { val x: Int = min(nums[i], nums[n - i - 1]) val y: Int = max(nums[i], nums[n - i - 1]) d[2] += 2 d[x + 1] -= 2 d[x + 1] += 1 d[x + y] -= 1 d[x + y + 1] += 1 d[y + limit + 1] -= 1 d[y + limit + 1] += 2 } var ans = n var i = 2 var s = 0 while (i < d.size) { s += d[i] ans = min(ans, s) ++i } return ans } }
0
Kotlin
0
0
17a80985d970c8316fb694e4952692e598d700af
571
kotlin-leetcode
MIT License
app/src/main/java/com/cmuhatia/android/keepup/KeepupApplication.kt
cornelius-muhatia
338,019,581
false
null
package com.cmuhatia.android.keepup import android.app.Application import timber.log.Timber import timber.log.Timber.DebugTree class KeepupApplication : Application() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(DebugTree()) } } }
0
Kotlin
0
0
ebe711130ec19197de0e1ae9ce14c0fffe351394
315
keep-up
Apache License 2.0