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/me/robbin/wanandroid/app/event/EventViewModel.kt
ModestoMa
278,850,144
false
null
package me.robbin.wanandroid.app.event import androidx.lifecycle.ViewModel import com.kunminx.architecture.ui.callback.UnPeekLiveData import me.robbin.wanandroid.app.event.bus.CollectBus import me.robbin.wanandroid.app.event.bus.TodoBus import me.robbin.wanandroid.app.event.bus.TodoDetailBus import me.robbin.wanandroid.model.TodoBean /** * * Create by Robbin at 2020/8/2 */ class EventViewModel : ViewModel() { val userCollectUpdate: UnPeekLiveData<CollectBus> = UnPeekLiveData() val changeTodoStatus: UnPeekLiveData<TodoBus> = UnPeekLiveData() val deleteTodo: UnPeekLiveData<TodoBus> = UnPeekLiveData() val addTodo: UnPeekLiveData<Boolean> = UnPeekLiveData() val changeTodo: UnPeekLiveData<TodoDetailBus> = UnPeekLiveData() }
1
Kotlin
1
21
e8808e53b6a26110ea3e5d4e710a62545b237b0d
759
WanAndroidMVVM
Apache License 2.0
decoder/wasm/src/commonMain/kotlin/io/github/charlietap/chasm/decoder/type/limits/LimitsDecoder.kt
CharlieTap
743,980,037
false
{"Kotlin": 898736, "WebAssembly": 7119}
package io.github.charlietap.chasm.decoder.type.limits import com.github.michaelbull.result.Result import io.github.charlietap.chasm.ast.type.Limits import io.github.charlietap.chasm.error.WasmDecodeError import io.github.charlietap.chasm.reader.WasmBinaryReader typealias LimitsDecoder = (WasmBinaryReader) -> Result<Limits, WasmDecodeError>
2
Kotlin
1
16
1566c1b504b4e0a31ae5008f5ada463c47de71c5
345
chasm
Apache License 2.0
shared/src/commonMain/kotlin/di/CommonModule.kt
marazmone
632,133,133
false
null
package di import data.cache.entity.CountryEntity import data.datasource.CountryCacheDataSource import data.datasource.CountryCacheDataSourceImpl import data.datasource.CountryRemoteDataSource import data.datasource.CountryRemoteDataSourceImpl import data.mapper.CountryEntityToModelMapper import data.mapper.CountryResponseToEntityMapper import data.remote.RemoteConst import data.remote.response.CountryResponse import data.repository.CountryRepositoryImpl import domain.mapper.base.Mapper import domain.model.CountryModel import domain.repository.CountryRepository import domain.usecase.detail.DetailGetUseCase import domain.usecase.favorite.CountryObserveAllFavoriteUseCase import domain.usecase.favorite.CountryUpdateFavoriteUseCase import domain.usecase.list.CountryGetAllRemoteUseCase import domain.usecase.list.CountryObserveAllCacheUseCase import io.github.aakira.napier.DebugAntilog import io.github.aakira.napier.Napier import io.ktor.client.HttpClient import io.ktor.client.plugins.HttpTimeout import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.defaultRequest import io.ktor.client.plugins.logging.LogLevel import io.ktor.client.plugins.logging.Logger import io.ktor.client.plugins.logging.Logging import io.ktor.client.request.accept import io.ktor.http.ContentType import io.ktor.http.URLProtocol import io.ktor.http.contentType import io.ktor.serialization.kotlinx.json.json import io.realm.kotlin.Realm import io.realm.kotlin.RealmConfiguration import kotlinx.serialization.json.Json import org.koin.core.qualifier.named import org.koin.dsl.module import presentation.tabs.favorite.FavoriteViewStateModel import presentation.tabs.list.ListViewStateModel import presentation.tabs.list.detail.DetailViewStateModel fun cacheModule() = module { single { val builder = RealmConfiguration.Builder( schema = setOf( CountryEntity::class, ) ) builder.schemaVersion(1) builder.deleteRealmIfMigrationNeeded() Realm.open(builder.build()) } } fun remoteModule() = module { single { HttpClient(get()) { defaultRequest { url { host = RemoteConst.Url.Base protocol = URLProtocol.HTTPS contentType(ContentType.Application.Json) accept(ContentType.Application.Json) } } install(ContentNegotiation) { json( Json { prettyPrint = true isLenient = true ignoreUnknownKeys = true }, ) } install(Logging) { logger = object : Logger { override fun log(message: String) { Napier.d(tag = "HTTP Client", message = message) } } level = LogLevel.ALL } install(HttpTimeout) { requestTimeoutMillis = 30_000L connectTimeoutMillis = 30_000L socketTimeoutMillis = 30_000L } }.also { Napier.base(DebugAntilog()) } } } fun mapperModule() = module { factory<Mapper<CountryResponse, CountryEntity>>(named(CountryResponseToEntityMapper.NAMED)) { CountryResponseToEntityMapper() } factory<Mapper<CountryEntity, CountryModel>>(named(CountryEntityToModelMapper.NAMED)) { CountryEntityToModelMapper() } } fun dataSourceModule() = module { single<CountryRemoteDataSource> { CountryRemoteDataSourceImpl(get()) } single<CountryCacheDataSource> { CountryCacheDataSourceImpl(get()) } } fun repositoryModule() = module { single<CountryRepository> { CountryRepositoryImpl( remote = get(), cache = get(), responseToEntityMapper = get(named(CountryResponseToEntityMapper.NAMED)), entityToModelMapper = get(named(CountryEntityToModelMapper.NAMED)), ) } } fun useCaseModule() = module { factory { CountryGetAllRemoteUseCase(get()) } factory { CountryObserveAllCacheUseCase(get()) } factory { CountryObserveAllFavoriteUseCase(get()) } factory { CountryUpdateFavoriteUseCase(get()) } factory { DetailGetUseCase() } } fun screenStateModelModule() = module { single { ListViewStateModel( countryGetAllRemoteUseCase = get(), countryObserveAllCacheUseCase = get(), countryUpdateFavoriteUseCase = get(), ) } single { FavoriteViewStateModel( countryObserveAllFavoriteUseCase = get(), countryUpdateFavoriteUseCase = get(), ) } single { DetailViewStateModel(detailGetUseCase = get()) } }
2
Kotlin
0
22
dbf3d03961992b8ea1fca3c174823082757a4132
4,907
ios-compose-showcase
Apache License 2.0
buildSrc/src/main/kotlin/com/fluxchess/gladius/build/plugin/versioning/VersioningExtension.kt
fluxroot
3,110,222
false
null
/* * Copyright 2007-2019 The Java Chess Protocol Interface Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fluxchess.gladius.build.plugin.versioning open class VersioningExtension( val version: String, val buildNo: String, val commitId: String, val abbreviatedId: String)
1
Java
9
16
3cd487824d0165c49e6044d15577cf1ad85cbfb4
818
jcpi
Apache License 2.0
app/src/main/java/com/schwerzl/leftbehind/di/ApplicationHiltModule.kt
mschwerz
851,180,582
false
{"Kotlin": 41921}
package com.schwerzl.leftbehind.di import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothManager import android.content.Context import androidx.core.content.ContextCompat.getSystemService import com.schwerzl.leftbehind.datasource.AndroidBLEDataSource import com.schwerzl.leftbehind.datasource.BLEDataSource import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) abstract class ApplicationHiltModule { @Binds internal abstract fun bindsBLEDataSource( bleDataSource: AndroidBLEDataSource ) : BLEDataSource }
0
Kotlin
0
0
7afc7d8dbaca0a763fe08f0c47a18a560399da00
776
leftbehind
Apache License 2.0
src/main/java/club/redux/sunset/lavafishing/registry/ModBlockEntityTypes.kt
TeamSunset
511,115,168
false
{"Kotlin": 134265, "Java": 8962}
package club.redux.sunset.lavafishing.registry import club.redux.sunset.lavafishing.BuildConstants import club.redux.sunset.lavafishing.block.blockentity.BlockEntityPrometheusBounty import club.redux.sunset.lavafishing.util.UtilRegister import club.redux.sunset.lavafishing.util.registerKt import net.minecraft.core.BlockPos import net.minecraft.world.level.block.entity.BlockEntity import net.minecraft.world.level.block.entity.BlockEntityType import net.minecraft.world.level.block.state.BlockState import net.minecraftforge.registries.ForgeRegistries object ModBlockEntityTypes { @JvmField val REGISTER = UtilRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, BuildConstants.MOD_ID) @JvmField val PROMETHEUS_BOUNTY = REGISTER.registerKt("prometheus_bounty") { BlockEntityType.Builder.of( { pos: BlockPos, state: BlockState -> BlockEntityPrometheusBounty(pos, state) }, ModBlocks.PROMETHEUS_BOUNTY.get() ).build() } @Suppress("Type_mismatch") fun <T : BlockEntity> BlockEntityType.Builder<T>.build(): BlockEntityType<T> { return this.build(null) } }
0
Kotlin
1
4
f89e08efae3570d9e8d939175ea292a8486c0fd3
1,131
LavaFishing
MIT License
ktutils/src/main/kotlin/lyc/ktutils/libs/composeutils/aliases/Contents.kt
liu-yucheng
509,452,663
false
null
// Copyright 2022 <NAME>. Apache License Version 2.0. // Apache License Version 2.0 copy: http://www.apache.org/licenses/LICENSE-2.0 package lyc.ktutils.libs.composeutils.aliases import androidx.compose.runtime.Composable /** Compose content. */ typealias Content = @Composable () -> Unit /** Scoped compose content. */ typealias ScopedContent<Scope> = @Composable Scope.() -> Unit
0
Kotlin
0
1
b79cb889fd06ef03bd9507c8f079af95c5270fb5
386
LYC-KotlinUtils
Apache License 2.0
app/src/main/java/com/marverenic/reader/data/service/AuthCodeRefreshResponse.kt
marverenic
101,457,590
false
null
package com.marverenic.reader.data.service import com.marverenic.reader.model.Seconds data class AuthCodeRefreshResponse( val id: String, val access_token: String, val expires_in: Seconds, val plan: String )
0
Kotlin
1
5
e4ae8bda8a4f9f2ad73fcf95b2c3f759a60cd056
242
Paper
Apache License 2.0
src/main/kotlin/CommandHandler.kt
NanamiNakano
682,857,709
false
null
import dev.inmo.tgbotapi.bot.TelegramBot import dev.inmo.tgbotapi.extensions.api.send.reply import dev.inmo.tgbotapi.extensions.behaviour_builder.buildBehaviourWithLongPolling import dev.inmo.tgbotapi.extensions.behaviour_builder.filters.MessageFilterByChat import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommandWithArgs import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onContentMessage import dev.inmo.tgbotapi.extensions.utils.asTextContent import dev.inmo.tgbotapi.extensions.utils.extensions.raw.from import dev.inmo.tgbotapi.types.message.Markdown import dev.inmo.tgbotapi.utils.PreviewFeature import dev.inmo.tgbotapi.utils.RiskFeature import io.github.oshai.kotlinlogging.KLogger import io.ipinfo.api.errors.RateLimitedException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.datetime.Clock import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transaction import utils.* import utils.Database @OptIn(RiskFeature::class, PreviewFeature::class) class CommandHandler(private val bot: TelegramBot, private val logger: KLogger) { init { runBlocking(Dispatchers.Default) { bot.buildBehaviourWithLongPolling { onCommand("start", initialFilter = { it.content.textSources.size == 1 }) { logger.info { it.from?.username.toString() + "issued command: start" } Database.updateUseDate(it.chat.id.chatId.toInt()) reply(it, "Hi, I'm the bot of The Nanami(@thynanami)") } onCommand("getme", initialFilter = { it.content.textSources.size == 1 }) { message -> logger.info { message.from?.username.toString() + "issued command: start" } val userId = message.chat.id.chatId.toInt() val time = Clock.System.now() Database transaction { addLogger(StdOutSqlLogger) SchemaUtils.create(Users) val result = Users.select { Users.userid.eq(userId) } if (result.empty()) { Users.insert { it[userid] = userId it[lastUse] = time it[firstUse] = time it[role] = "user" } } else { Database.updateUseDate(userId) result.forEach { launch { reply( message, MessageBuilder.info(it, message, logger), Markdown ) } } } } } onCommandWithArgs("ip") { message, args -> if (args.size > 3) { reply(message, "You can only query 3 ips in one time.") } args.forEach { try { reply(message, IpInfo.getIpInfo(it).toString()) } catch (ex: RateLimitedException) { reply(message, "API rate limit reached! Please try again later.") return@onCommandWithArgs } } } onContentMessage(subcontextUpdatesFilter = MessageFilterByChat) { val content = it.content.asTextContent()?.text ?: return@onContentMessage if (!Bilibili.isBV(content)) { return@onContentMessage } reply(it, "https://bilibili.com/video/${content}") } }.join() } } }
0
Kotlin
0
0
5afc5e615249f7112553cf79d16d7fdefe485019
4,427
NanamiBot
MIT License
app/src/main/kotlin/jp/co/yumemi/android/code_check/features/screen/detail/DetailScreen.kt
MarcoDzuong
406,395,463
false
null
package jp.co.yumemi.android.code_check.features.screen.detail import android.content.Intent import android.webkit.WebSettings import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment.Companion.CenterHorizontally import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.annotation.ExperimentalCoilApi import coil.compose.rememberImagePainter import coil.transform.CircleCropTransformation import jp.co.yumemi.android.code_check.R import jp.co.yumemi.android.code_check.common.view.AppToast import jp.co.yumemi.android.code_check.common.view.ToastStyle import jp.co.yumemi.android.code_check.common.view.WebViewProgress import jp.co.yumemi.android.code_check.data.model.Item @ExperimentalCoilApi @Composable fun DetailScreen( viewModel: DetailViewModel, item: Item, onBack: () -> Unit, requestLogin: () -> Unit ) { viewModel.checkBookMark(url = "https://github.com/${item.name}") val uiState by viewModel.uiState.collectAsState() Box( modifier = Modifier .fillMaxSize() .background(Color.White) ) { val scrollState = rememberScrollState() Column( modifier = Modifier .fillMaxWidth() .verticalScroll(enabled = true, state = scrollState) ) { AppBar( onBack = onBack, item = item, isBookMarked = uiState.isBookMark, onBookMark = { viewModel.bookMarkGithubPage(it) }, requestLogin = requestLogin ) val context = LocalContext.current Spacer( modifier = Modifier .height(15.dp) .padding(horizontal = 20.dp) ) Image( painter = rememberImagePainter( data = item.ownerIconUrl, onExecute = { _, _ -> true }, builder = { crossfade(true) transformations(CircleCropTransformation()) } ), contentDescription = "", modifier = Modifier .size(150.dp) .align(CenterHorizontally), ) Spacer(modifier = Modifier.height(25.dp)) Row( modifier = Modifier .wrapContentWidth(), ) { Image( painter = painterResource(id = R.drawable.ic_star), contentDescription = "start", modifier = Modifier.size(20.dp, 20.dp) ) Text( text = context.getString( R.string.txt_count_stars, item.stargazersCount.toString() ), modifier = Modifier.padding(start = 5.dp) ) Spacer(modifier = Modifier.width(15.dp)) Image( painter = painterResource(id = R.drawable.ic_fork), contentDescription = "start", modifier = Modifier.size(20.dp, 20.dp) ) Text( text = context.getString( R.string.txt_count_forks, item.forksCount.toString() ), modifier = Modifier.padding(start = 5.dp) ) Spacer(modifier = Modifier.width(15.dp)) Image( painter = painterResource(id = R.drawable.ic_watcher), contentDescription = "start", modifier = Modifier .size(20.dp, 20.dp) ) Text( text = context.getString( R.string.txt_count_watchers, item.watchersCount.toString() ), modifier = Modifier.padding(start = 5.dp) ) } Row( modifier = Modifier .wrapContentWidth() ) { Image( painter = painterResource(id = R.drawable.ic_watcher), contentDescription = "start", modifier = Modifier .size(20.dp, 20.dp) ) Text( text = context.getString( R.string.txt_count_open_issues, item.openIssuesCount.toString() ), modifier = Modifier.padding(start = 5.dp) ) } Row( modifier = Modifier .wrapContentWidth() ) { Image( painter = painterResource(id = R.drawable.ic_watcher), contentDescription = "start", modifier = Modifier .size(20.dp, 20.dp) ) Text( text = context.getString( R.string.written_language, item.language ), modifier = Modifier.padding(start = 5.dp) ) } WebViewProgress( url = "https://github.com/${item.name}/blob/master/README.md", initSettings = { settings -> settings?.apply { javaScriptEnabled = true useWideViewPort = true loadWithOverviewMode = true setSupportZoom(true) builtInZoomControls = true displayZoomControls = true javaScriptCanOpenWindowsAutomatically = true cacheMode = WebSettings.LOAD_NO_CACHE } }, onBack = { webView -> if (webView?.canGoBack() == true) { webView.goBack() } else { onBack() } }, ) } } } @Composable fun AppBar( onBack: () -> Unit, item: Item, isBookMarked: Boolean, onBookMark: (String) -> Unit, requestLogin: () -> Unit ) { Row( modifier = Modifier .fillMaxWidth() .padding(15.dp), verticalAlignment = Alignment.CenterVertically, ) { Icon( Icons.Filled.ArrowBack, contentDescription = "Localized description", modifier = Modifier .size(30.dp) .clickable { onBack() }) Spacer(modifier = Modifier.width(20.dp)) Text( text = "詳細", fontSize = 20.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f) ) val context = LocalContext.current Image( painter = painterResource(id = if (isBookMarked) R.drawable.ic_bookmark_inactive else R.drawable.ic_bookmark), contentDescription = "share", modifier = Modifier .size(30.dp) .clickable { if (jp.co.yumemi.android.code_check.features.LoginManager.isLogin.value) { if (!isBookMarked){ onBookMark("https://github.com/${item.name}") }else{ AppToast.createToast(ToastStyle.DONE).setText("このページをフォローしています。").show(context = context) } } else { requestLogin() } } ) Spacer(modifier = Modifier.width(10.dp)) Image( painter = painterResource(id = R.drawable.ic_share), contentDescription = "share", modifier = Modifier .size(30.dp) .clickable { try { val shareMessage = "これは私が興味を持っているgithubページです。\n\n https://github.com/${item.name}" val sendIntent: Intent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, shareMessage) putExtra(Intent.EXTRA_SUBJECT, "Yumemi App") type = "text/plain" } val shareIntent = Intent.createChooser(sendIntent, null) context.startActivity(shareIntent) } catch (e: Exception) { } } ) } }
0
Kotlin
0
2
703e158b758aa7ddc05ab75a670b183d7c8d092f
9,574
yumemi-android-engineer-codecheck
Apache License 2.0
src/main/kotlin/learnOpenGL/d_advancedOpenGL/2 stencil testing.kt
jvm-graphics-labs
89,148,648
false
null
package learnOpenGL.d_advancedOpenGL /** * Created by elect on 13/05/17. */ import glm_.func.rad import glm_.glm import glm_.mat4x4.Mat4 import gln.draw.glDrawArrays import gln.get import gln.glClearColor import gln.glf.glf import gln.glf.semantic import gln.program.usingProgram import gln.set import gln.uniform.glUniform import gln.vertexArray.glBindVertexArray import gln.vertexArray.glEnableVertexAttribArray import gln.vertexArray.glVertexAttribPointer import learnOpenGL.a_gettingStarted.end import learnOpenGL.a_gettingStarted.swapAndPoll import learnOpenGL.a_gettingStarted.verticesCube import learnOpenGL.b_lighting.camera import learnOpenGL.b_lighting.clearColor0 import learnOpenGL.b_lighting.initWindow0 import learnOpenGL.b_lighting.processFrame import learnOpenGL.common.loadTexture import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL13.GL_TEXTURE0 import org.lwjgl.opengl.GL13.glActiveTexture import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20.glGetUniformLocation import org.lwjgl.opengl.GL30.* import uno.buffer.destroyBuf import uno.buffer.intBufferBig import uno.glsl.Program import uno.glsl.glDeletePrograms import uno.glsl.glUseProgram fun main(args: Array<String>) { with(StencilTesting()) { run() end() } } private class StencilTesting { val window = initWindow0("Depth Testing View") val program = ProgramB() val programSingleColor = ProgramA() enum class Object { Cube, Plane } val vao = intBufferBig<Object>() val vbo = intBufferBig<Object>() val tex = intBufferBig<Object>() inner open class ProgramA(vertex: String = "stencil-testing.vert", fragment: String = "stencil-single-color.frag") : Program("shaders/d/_2", vertex, fragment) { val model = glGetUniformLocation(name, "model") val view = glGetUniformLocation(name, "view") val proj = glGetUniformLocation(name, "projection") } inner class ProgramB(shader: String = "stencil-testing") : ProgramA("$shader.vert", "$shader.frag") { init { usingProgram(name) { "texture1".unit = semantic.sampler.DIFFUSE } } } init { glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glEnable(GL_STENCIL_TEST) glStencilFunc(GL_NOTEQUAL, 1, 0xFF) glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) glGenVertexArrays(vao) glGenBuffers(vbo) for (i in Object.values()) { glBindVertexArray(vao[i]) glBindBuffer(GL_ARRAY_BUFFER, vbo[i]) glBufferData(GL_ARRAY_BUFFER, if (i == Object.Cube) verticesCube else planeVertices, GL_STATIC_DRAW) glEnableVertexAttribArray(glf.pos3_tc2) glVertexAttribPointer(glf.pos3_tc2) glBindVertexArray() } // load textures tex[Object.Cube] = loadTexture("textures/marble.jpg") tex[Object.Plane] = loadTexture("textures/metal.png") } fun run() { while (window.open) { window.processFrame() // render glClearColor(clearColor0) glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT or GL_STENCIL_BUFFER_BIT) // don't forget to clear the stencil buffer! // set uniforms glUseProgram(programSingleColor) var model = Mat4() val view = camera.viewMatrix val projection = glm.perspective(camera.zoom.rad, window.aspect, 0.1f, 100f) glUniform(programSingleColor.proj, projection) glUniform(programSingleColor.view, view) glUseProgram(program) glUniform(program.proj, projection) glUniform(program.view, view) /* draw floor as normal, but don't write the floor to the stencil buffer, we only care about the containers. We set its mask to 0x00 to not write to the stencil buffer. */ glStencilMask(0x00) // floor glBindVertexArray(vao[Object.Plane]) glBindTexture(GL_TEXTURE_2D, tex[Object.Plane]) glUniform(program.model, model) glDrawArrays(GL_TRIANGLES, 6) glBindVertexArray() // 1st. render pass, draw objects as normal, writing to the stencil buffer glStencilFunc(GL_ALWAYS, 1, 0xFF) glStencilMask(0xFF) // cubes glBindVertexArray(vao[Object.Cube]) glActiveTexture(GL_TEXTURE0 + semantic.sampler.DIFFUSE) glBindTexture(GL_TEXTURE_2D, tex[Object.Cube]) model.translate_(-1f, 0f, -1f) glUniform(program.model, model) glDrawArrays(GL_TRIANGLES, 36) model = Mat4().translate_(2f, 0f, 0f) glUniform(program.model, model) glDrawArrays(GL_TRIANGLES, 36) /* 2nd. render pass: now draw slightly scaled versions of the objects, this time disabling stencil writing. Because the stencil buffer is now filled with several 1s. The parts of the buffer that are 1 are not drawn, thus only drawing the objects' size differences, making it look like borders. */ glStencilFunc(GL_NOTEQUAL, 1, 0xFF) glStencilMask(0x00) glDisable(GL_DEPTH_TEST) glUseProgram(programSingleColor) val scale = 1.1f // cubes glBindVertexArray(vao[Object.Cube]) model = Mat4() .translate_(-1f, 0f, -1f) .scale_(scale) glUniform(programSingleColor.model, model) glDrawArrays(GL_TRIANGLES, 36) model = Mat4() .translate_(2f, 0f, 0f) .scale_(scale) glUniform(programSingleColor.model, model) glDrawArrays(GL_TRIANGLES, 36) glBindVertexArray(0) glStencilMask(0xFF) glEnable(GL_DEPTH_TEST) window.swapAndPoll() } } fun end() { glDeletePrograms(program, programSingleColor) glDeleteVertexArrays(vao) glDeleteBuffers(vbo) glDeleteTextures(tex) destroyBuf(vao, vbo, tex) window.end() } }
1
Kotlin
5
35
41facb9896bd1bafdd545f3786601a0841469bac
6,198
learn-OpenGL
MIT License
app/src/main/java/io/horizontalsystems/bankwallet/modules/addressformat/AddressFormatViewModel.kt
fahimaltinordu
312,207,740
true
{"Kotlin": 1883211, "Java": 33448, "Ruby": 5803, "Shell": 2024}
package io.horizontalsystems.bankwallet.modules.addressformat import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.horizontalsystems.bankwallet.core.providers.StringProvider import io.horizontalsystems.bankwallet.entities.* import io.horizontalsystems.core.SingleLiveEvent import io.horizontalsystems.views.ListPosition import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers class AddressFormatViewModel( private val service: AddressFormatModule.IService, private val stringProvider: StringProvider ) : ViewModel() { val sections = MutableLiveData<List<AddressFormatModule.SectionItem>>() val showAddressFormatChangeAlert = SingleLiveEvent<Pair<String, String>>() private var disposables = CompositeDisposable() private var currentIndices: Pair<Int, Int>? = null init { service.itemsAsync .subscribeOn(Schedulers.io()) .subscribe { sync(it) } .let { disposables.add(it) } sync(service.items) } override fun onCleared() { disposables.clear() } fun onSelect(sectionIndex: Int, index: Int) { val item = service.items[sectionIndex] currentIndices = Pair(sectionIndex, index) when (item.type) { is AddressFormatModule.ItemType.Derivation -> { val selectedDerivation = item.type.derivations[index] if (selectedDerivation != item.type.current) { showAddressFormatChangeAlert.postValue(Pair(item.coinType.title, selectedDerivation.name.toUpperCase())) } } is AddressFormatModule.ItemType.BitcoinCashType -> { val selectedType = item.type.types[index] if (selectedType != item.type.current) { showAddressFormatChangeAlert.postValue(Pair(item.coinType.title, stringProvider.string(selectedType.title))) } } } } fun onConfirm() { val (sectionIndex, index) = currentIndices ?: return val item = service.items[sectionIndex] when (item.type) { is AddressFormatModule.ItemType.Derivation -> { service.set(item.type.derivations[index], item.coinType) } is AddressFormatModule.ItemType.BitcoinCashType -> { service.set(item.type.types[index]) } } } private fun sync(items: List<AddressFormatModule.Item>) { val sectionViewItems = items.map { AddressFormatModule.SectionItem(it.coinType.title, viewItems(it.type, it.coinType)) } sections.postValue(sectionViewItems) } private fun viewItems(itemType: AddressFormatModule.ItemType, coinType: CoinType): List<AddressFormatModule.ViewItem> { return when (itemType) { is AddressFormatModule.ItemType.Derivation -> { itemType.derivations.mapIndexed { index, derivation -> val title = "${derivation.addressType()} - ${derivation.title()}" val subtitle = stringProvider.string(derivation.description(), (derivation.addressPrefix(coinType) ?: "")) AddressFormatModule.ViewItem( title, subtitle, derivation == itemType.current, listPosition = ListPosition.getListPosition(itemType.derivations.size, index) ) } } is AddressFormatModule.ItemType.BitcoinCashType -> { itemType.types.mapIndexed { index, type -> AddressFormatModule.ViewItem( stringProvider.string(type.title), stringProvider.string(type.description), type == itemType.current, listPosition = ListPosition.getListPosition(itemType.types.size, index) ) } } } } }
0
Kotlin
0
4
d3094c4afaa92a5d63ce53583bc07c8fb343f90b
4,189
WILC-wallet-android
MIT License
core/data/src/main/java/com/niyaj/data/data/repository/DataDeletionRepositoryImpl.kt
skniyajali
579,613,644
false
{"Kotlin": 2220123}
package com.niyaj.data.data.repository import com.niyaj.common.utils.Resource import com.niyaj.common.utils.getCalculatedStartDate import com.niyaj.data.repository.DataDeletionRepository import com.niyaj.data.repository.SettingsRepository import com.niyaj.database.model.AddOnItemEntity import com.niyaj.database.model.AddressEntity import com.niyaj.database.model.AttendanceEntity import com.niyaj.database.model.CartEntity import com.niyaj.database.model.CartOrderEntity import com.niyaj.database.model.CategoryEntity import com.niyaj.database.model.ChargesEntity import com.niyaj.database.model.CustomerEntity import com.niyaj.database.model.EmployeeEntity import com.niyaj.database.model.ExpensesCategoryEntity import com.niyaj.database.model.ExpensesEntity import com.niyaj.database.model.PaymentEntity import com.niyaj.database.model.ProductEntity import com.niyaj.database.model.ReportsEntity import com.niyaj.database.model.SelectedCartOrderEntity import com.niyaj.database.model.SettingsEntity import io.realm.kotlin.Realm import io.realm.kotlin.RealmConfiguration import io.realm.kotlin.ext.query import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import timber.log.Timber class DataDeletionRepositoryImpl( config: RealmConfiguration, private val settingsRepository: SettingsRepository, private val ioDispatcher: CoroutineDispatcher, ) : DataDeletionRepository { val realm = Realm.open(config) init { Timber.d("Data Deletion Session") } /** * ### Prerequisites - Delete **CartOrder** data before today date. - Delete **Cart** data before today start date. - Generate **Report** Before Deleting Data * @return [Resource] of [Boolean] type */ override suspend fun deleteData(): Resource<Boolean> { return try { withContext(ioDispatcher) { val settings = settingsRepository.getSetting().data!! val expensesDate = getCalculatedStartDate(days = "-${settings.expensesDataDeletionInterval}") val cartDate = getCalculatedStartDate(days = "-${settings.cartDataDeletionInterval}") val cartOrderDate = getCalculatedStartDate(days = "-${settings.cartOrderDataDeletionInterval}") val reportDate = getCalculatedStartDate(days = "-${settings.reportDataDeletionInterval}") withContext(ioDispatcher) { realm.write { val expenses = this.query<ExpensesEntity>("createdAt < $0", reportDate).find() val carts = this.query<CartEntity>("createdAt < $0", cartDate).find() val cartOrder = this.query<CartOrderEntity>("updatedAt < $0", cartOrderDate).find() val reports = this.query<ReportsEntity>("createdAt < $0", expensesDate).find() delete(carts) delete(cartOrder) delete(reports) delete(expenses) } } } Resource.Success(true) } catch (e: Exception) { Resource.Error(e.message ?: "Unable to delete data") } } override suspend fun deleteAllRecords(): Resource<Boolean> { return try { withContext(ioDispatcher) { realm.write { delete(CategoryEntity::class) delete(ProductEntity::class) delete(AddressEntity::class) delete(CustomerEntity::class) delete(CartOrderEntity::class) delete(CartEntity::class) delete(AddOnItemEntity::class) delete(ChargesEntity::class) delete(EmployeeEntity::class) delete(ExpensesCategoryEntity::class) delete(ExpensesEntity::class) delete(SelectedCartOrderEntity::class) delete(PaymentEntity::class) delete(AttendanceEntity::class) delete(ReportsEntity::class) delete(SettingsEntity::class) } } Resource.Success(true) } catch (e: Exception) { Resource.Error(e.message ?: "Unable to delete all Records") } } }
34
Kotlin
0
1
2020b913df5030525c582218f6a91a7a3466ee2c
4,496
POS-Application
MIT License
app/src/main/java/com/shekharkg/githubpr/model/PullRequest.kt
shekharkg
487,332,479
false
null
package com.shekharkg.githubpr.model import com.google.gson.annotations.SerializedName data class PullRequest( val title: String?, @SerializedName("created_at") var createdAt: String?, @SerializedName("closed_at") var closedAt: String?, val user: RepoUser? )
0
Kotlin
0
0
9eec5e194678269356c90f8b5d36b7432dcba121
286
GitHub-PR
Apache License 2.0
app/src/main/java/com/shekharkg/githubpr/model/PullRequest.kt
shekharkg
487,332,479
false
null
package com.shekharkg.githubpr.model import com.google.gson.annotations.SerializedName data class PullRequest( val title: String?, @SerializedName("created_at") var createdAt: String?, @SerializedName("closed_at") var closedAt: String?, val user: RepoUser? )
0
Kotlin
0
0
9eec5e194678269356c90f8b5d36b7432dcba121
286
GitHub-PR
Apache License 2.0
data/src/main/java/com/kizitonwose/calendar/data/WeekData.kt
kizitonwose
182,417,603
false
{"Kotlin": 670112, "HTML": 343, "CSS": 102}
package com.kizitonwose.calendar.data import com.kizitonwose.calendar.core.Week import com.kizitonwose.calendar.core.WeekDay import com.kizitonwose.calendar.core.WeekDayPosition import java.time.DayOfWeek import java.time.LocalDate import java.time.temporal.ChronoUnit public data class WeekDateRange( val startDateAdjusted: LocalDate, val endDateAdjusted: LocalDate, ) public fun getWeekCalendarAdjustedRange( startDate: LocalDate, endDate: LocalDate, firstDayOfWeek: DayOfWeek, ): WeekDateRange { val inDays = firstDayOfWeek.daysUntil(startDate.dayOfWeek) val startDateAdjusted = startDate.minusDays(inDays.toLong()) val weeksBetween = ChronoUnit.WEEKS.between(startDateAdjusted, endDate).toInt() val endDateAdjusted = startDateAdjusted.plusWeeks(weeksBetween.toLong()).plusDays(6) return WeekDateRange(startDateAdjusted = startDateAdjusted, endDateAdjusted = endDateAdjusted) } public fun getWeekCalendarData( startDateAdjusted: LocalDate, offset: Int, desiredStartDate: LocalDate, desiredEndDate: LocalDate, ): WeekData { val firstDayInWeek = startDateAdjusted.plusWeeks(offset.toLong()) return WeekData(firstDayInWeek, desiredStartDate, desiredEndDate) } public data class WeekData internal constructor( private val firstDayInWeek: LocalDate, private val desiredStartDate: LocalDate, private val desiredEndDate: LocalDate, ) { val week: Week = Week((0 until 7).map { dayOffset -> getDay(dayOffset) }) private fun getDay(dayOffset: Int): WeekDay { val date = firstDayInWeek.plusDays(dayOffset.toLong()) val position = when { date < desiredStartDate -> WeekDayPosition.InDate date > desiredEndDate -> WeekDayPosition.OutDate else -> WeekDayPosition.RangeDate } return WeekDay(date, position) } } public fun getWeekIndex(startDateAdjusted: LocalDate, date: LocalDate): Int { return ChronoUnit.WEEKS.between(startDateAdjusted, date).toInt() } public fun getWeekIndicesCount(startDateAdjusted: LocalDate, endDateAdjusted: LocalDate): Int { // Add one to include the start week itself! return getWeekIndex(startDateAdjusted, endDateAdjusted) + 1 }
13
Kotlin
505
4,651
36de800a6c36a8f142f6432a0992e0ea4ae8a789
2,231
Calendar
MIT License
app/src/main/kotlin/it/scoppelletti/kb/app/MainApp.kt
dscoppelletti
385,976,384
false
null
/* * Copyright (C) 2021 Dario Scoppelletti, <http://www.scoppelletti.it/>. * * 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 it.scoppelletti.kb.app import it.scoppelletti.kb.app.inject.DaggerKbAppComponent import it.scoppelletti.kb.app.inject.KbAppComponent import javafx.application.Application import javafx.stage.Stage class MainApp : Application() { private lateinit var appComponent: KbAppComponent override fun start(primaryStage: Stage) { appComponent = DaggerKbAppComponent.factory().create(primaryStage) primaryStage.apply { title = appComponent.appMessages().appName() scene = appComponent.mainSceneBuilder().build() show() } } companion object { const val STAGE_PRIMARY = "primaryStage" @JvmStatic fun main(args: Array<String>) { launch(MainApp::class.java, *args) } } }
0
Kotlin
0
0
7bd27e2d7fd6aa06a4d0b89b3d81aa214e1a0de5
1,433
kb
Apache License 2.0
src/main/kotlin/eZmaxApi/apis/ObjectUserApi.kt
eZmaxinc
271,950,932
false
null
/** * eZmax API Definition (Full) * * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.16 * Contact: <EMAIL> * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package eZmaxApi.apis import java.io.IOException import okhttp3.OkHttpClient import eZmaxApi.models.CommonMinusGetAutocompleteMinusV1MinusResponse import eZmaxApi.models.HeaderMinusAcceptMinusLanguage import eZmaxApi.models.UserMinusGetAutocompleteMinusV2MinusResponse import com.squareup.moshi.Json import eZmaxApi.infrastructure.ApiClient import eZmaxApi.infrastructure.ApiResponse import eZmaxApi.infrastructure.ClientException import eZmaxApi.infrastructure.ClientError import eZmaxApi.infrastructure.ServerException import eZmaxApi.infrastructure.ServerError import eZmaxApi.infrastructure.MultiValueMap import eZmaxApi.infrastructure.PartConfig import eZmaxApi.infrastructure.RequestConfig import eZmaxApi.infrastructure.RequestMethod import eZmaxApi.infrastructure.ResponseType import eZmaxApi.infrastructure.Success import eZmaxApi.infrastructure.toMultiValue class ObjectUserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) { companion object { @JvmStatic val defaultBasePath: String by lazy { System.getProperties().getProperty(ApiClient.baseUrlKey, "https://prod.api.appcluster01.ca-central-1.ezmax.com/rest") } } /** * enum for parameter sSelector */ enum class SSelector_userGetAutocompleteV1(val value: kotlin.String) { @Json(name = "All") All("All"), @Json(name = "AgentBrokerEmployeeEzsignUserNormal") AgentBrokerEmployeeEzsignUserNormal("AgentBrokerEmployeeEzsignUserNormal"), @Json(name = "ClonableUsers") ClonableUsers("ClonableUsers"), @Json(name = "Normal") Normal("Normal"), @Json(name = "NormalEzsignSigner") NormalEzsignSigner("NormalEzsignSigner") } /** * enum for parameter eFilterActive */ enum class EFilterActive_userGetAutocompleteV1(val value: kotlin.String) { @Json(name = "All") All("All"), @Json(name = "Active") Active("Active"), @Json(name = "Inactive") Inactive("Inactive") } /** * Retrieve Users and IDs * Get the list of User to be used in a dropdown or autocomplete control. * @param sSelector The type of Users to return * @param eFilterActive Specify which results we want to display. (optional, default to Active) * @param sQuery Allow to filter the returned results (optional) * @param acceptLanguage (optional) * @return CommonMinusGetAutocompleteMinusV1MinusResponse * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun userGetAutocompleteV1(sSelector: SSelector_userGetAutocompleteV1, eFilterActive: EFilterActive_userGetAutocompleteV1? = Active, sQuery: kotlin.String? = null, acceptLanguage: HeaderMinusAcceptMinusLanguage? = null) : CommonMinusGetAutocompleteMinusV1MinusResponse { @Suppress("DEPRECATION") val localVarResponse = userGetAutocompleteV1WithHttpInfo(sSelector = sSelector, eFilterActive = eFilterActive, sQuery = sQuery, acceptLanguage = acceptLanguage) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as CommonMinusGetAutocompleteMinusV1MinusResponse ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Retrieve Users and IDs * Get the list of User to be used in a dropdown or autocomplete control. * @param sSelector The type of Users to return * @param eFilterActive Specify which results we want to display. (optional, default to Active) * @param sQuery Allow to filter the returned results (optional) * @param acceptLanguage (optional) * @return ApiResponse<CommonMinusGetAutocompleteMinusV1MinusResponse?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) @Deprecated(message = "This operation is deprecated.") fun userGetAutocompleteV1WithHttpInfo(sSelector: SSelector_userGetAutocompleteV1, eFilterActive: EFilterActive_userGetAutocompleteV1?, sQuery: kotlin.String?, acceptLanguage: HeaderMinusAcceptMinusLanguage?) : ApiResponse<CommonMinusGetAutocompleteMinusV1MinusResponse?> { @Suppress("DEPRECATION") val localVariableConfig = userGetAutocompleteV1RequestConfig(sSelector = sSelector, eFilterActive = eFilterActive, sQuery = sQuery, acceptLanguage = acceptLanguage) return request<Unit, CommonMinusGetAutocompleteMinusV1MinusResponse>( localVariableConfig ) } /** * To obtain the request config of the operation userGetAutocompleteV1 * * @param sSelector The type of Users to return * @param eFilterActive Specify which results we want to display. (optional, default to Active) * @param sQuery Allow to filter the returned results (optional) * @param acceptLanguage (optional) * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") fun userGetAutocompleteV1RequestConfig(sSelector: SSelector_userGetAutocompleteV1, eFilterActive: EFilterActive_userGetAutocompleteV1?, sQuery: kotlin.String?, acceptLanguage: HeaderMinusAcceptMinusLanguage?) : RequestConfig<Unit> { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>() .apply { if (eFilterActive != null) { put("eFilterActive", listOf(eFilterActive.toString())) } if (sQuery != null) { put("sQuery", listOf(sQuery.toString())) } } val localVariableHeaders: MutableMap<String, String> = mutableMapOf() acceptLanguage?.apply { localVariableHeaders["Accept-Language"] = this.toString() } localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, path = "/1/object/user/getAutocomplete/{sSelector}".replace("{"+"sSelector"+"}", sSelector.value.toString()), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } /** * enum for parameter sSelector */ enum class SSelector_userGetAutocompleteV2(val value: kotlin.String) { @Json(name = "All") All("All"), @Json(name = "AgentBrokerEmployeeEzsignUserNormal") AgentBrokerEmployeeEzsignUserNormal("AgentBrokerEmployeeEzsignUserNormal"), @Json(name = "ClonableUsers") ClonableUsers("ClonableUsers"), @Json(name = "Normal") Normal("Normal"), @Json(name = "NormalEzsignSigner") NormalEzsignSigner("NormalEzsignSigner") } /** * enum for parameter eFilterActive */ enum class EFilterActive_userGetAutocompleteV2(val value: kotlin.String) { @Json(name = "All") All("All"), @Json(name = "Active") Active("Active"), @Json(name = "Inactive") Inactive("Inactive") } /** * Retrieve Users and IDs * Get the list of User to be used in a dropdown or autocomplete control. * @param sSelector The type of Users to return * @param eFilterActive Specify which results we want to display. (optional, default to Active) * @param sQuery Allow to filter the returned results (optional) * @param acceptLanguage (optional) * @return UserMinusGetAutocompleteMinusV2MinusResponse * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun userGetAutocompleteV2(sSelector: SSelector_userGetAutocompleteV2, eFilterActive: EFilterActive_userGetAutocompleteV2? = Active, sQuery: kotlin.String? = null, acceptLanguage: HeaderMinusAcceptMinusLanguage? = null) : UserMinusGetAutocompleteMinusV2MinusResponse { val localVarResponse = userGetAutocompleteV2WithHttpInfo(sSelector = sSelector, eFilterActive = eFilterActive, sQuery = sQuery, acceptLanguage = acceptLanguage) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as UserMinusGetAutocompleteMinusV2MinusResponse ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Retrieve Users and IDs * Get the list of User to be used in a dropdown or autocomplete control. * @param sSelector The type of Users to return * @param eFilterActive Specify which results we want to display. (optional, default to Active) * @param sQuery Allow to filter the returned results (optional) * @param acceptLanguage (optional) * @return ApiResponse<UserMinusGetAutocompleteMinusV2MinusResponse?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun userGetAutocompleteV2WithHttpInfo(sSelector: SSelector_userGetAutocompleteV2, eFilterActive: EFilterActive_userGetAutocompleteV2?, sQuery: kotlin.String?, acceptLanguage: HeaderMinusAcceptMinusLanguage?) : ApiResponse<UserMinusGetAutocompleteMinusV2MinusResponse?> { val localVariableConfig = userGetAutocompleteV2RequestConfig(sSelector = sSelector, eFilterActive = eFilterActive, sQuery = sQuery, acceptLanguage = acceptLanguage) return request<Unit, UserMinusGetAutocompleteMinusV2MinusResponse>( localVariableConfig ) } /** * To obtain the request config of the operation userGetAutocompleteV2 * * @param sSelector The type of Users to return * @param eFilterActive Specify which results we want to display. (optional, default to Active) * @param sQuery Allow to filter the returned results (optional) * @param acceptLanguage (optional) * @return RequestConfig */ fun userGetAutocompleteV2RequestConfig(sSelector: SSelector_userGetAutocompleteV2, eFilterActive: EFilterActive_userGetAutocompleteV2?, sQuery: kotlin.String?, acceptLanguage: HeaderMinusAcceptMinusLanguage?) : RequestConfig<Unit> { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>() .apply { if (eFilterActive != null) { put("eFilterActive", listOf(eFilterActive.toString())) } if (sQuery != null) { put("sQuery", listOf(sQuery.toString())) } } val localVariableHeaders: MutableMap<String, String> = mutableMapOf() acceptLanguage?.apply { localVariableHeaders["Accept-Language"] = this.toString() } localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, path = "/2/object/user/getAutocomplete/{sSelector}".replace("{"+"sSelector"+"}", sSelector.value.toString()), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } }
0
Kotlin
0
0
fad1a7a8b3f744256968e67e5f60044063cb551c
14,412
eZmax-SDK-kotlin
MIT License
app/src/main/java/com/rviannaoliveira/marvelapp/favorite/FavoriteView.kt
rviannaoliveira
87,871,122
false
null
package com.rviannaoliveira.marvelapp.favorite import com.rviannaoliveira.marvelapp.base.BaseView import com.rviannaoliveira.marvelapp.model.Favorite /** * Criado por rodrigo on 15/04/17. */ interface FavoriteView : BaseView { fun loadFavorites(favorites: Favorite) }
0
Kotlin
3
5
40b5a147bd77a7930ee99c881764fe9340509e6a
275
MarvelApp
Apache License 2.0
src/jsMain/kotlin/main.js.kt
KenyOnFire
749,573,175
false
{"Kotlin": 77624, "Shell": 127}
import dev.gitlive.firebase.auth.* actual object FirebaseManagerObj { actual suspend fun startFirebaseAuth(): FirebaseAuth? { TODO("Not yet implemented") } actual suspend fun startFirebaseRealtimeDB() { } actual suspend fun startFB() { } actual suspend fun isJVMorJS(): Boolean { TODO("Not yet implemented") } actual suspend fun createUser(nombreUsuario: String, dineroActual: Int, email: String) { } actual suspend fun getActualUserDb(pathString: String): String { TODO("Not yet implemented") } actual suspend fun getAllUsersDb(pathString: String): List<String> { TODO("Not yet implemented") } actual suspend fun modifyActualMoney(money: String) { } }
0
Kotlin
0
1
75508a351aaafc16962d8ea8db2f8efef2193904
757
RuletaAdrianGabriel
MIT License
app/src/main/java/zaitsev/a/d/mirea/diplom/presentation/ui/main/newsToday/SavedNewsButton.kt
Anton-Zaitsev
816,037,410
false
{"Gradle Kotlin DSL": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 11, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Kotlin": 256, "TOML": 1, "CMake": 2, "C++": 8, "Proguard": 11, "XML": 36, "INI": 4, "Java": 3}
package zaitsev.a.d.mirea.diplom.presentation.ui.main.newsToday import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import zaitsev.a.d.mirea.diplom.R import zaitsev.a.d.mirea.diplom.presentation.ui.mainNavigation.Screen @Composable fun SavedNewsButton(navController: NavController, savedNewsCount: Int) { if (savedNewsCount > 0){ Button( onClick = { navController.navigate(Screen.NewsSaved.route) }, modifier = Modifier.defaultMinSize(minWidth = 1.dp, minHeight = 1.dp), shape = RoundedCornerShape(10.dp), colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent, contentColor = MaterialTheme.colorScheme.onSecondary), contentPadding = PaddingValues(horizontal = 5.dp, vertical = 0.dp), ) { Column( verticalArrangement = Arrangement.Absolute.spacedBy(2.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Icon( imageVector = ImageVector.vectorResource(id = R.drawable.ic_saved), contentDescription = "saved news" ) Text( text = savedNewsCount.toString(), color = Color.White, fontSize = 13.sp, fontWeight = FontWeight.Bold, lineHeight = 10.sp, modifier = Modifier .background(Color.Red, CircleShape) .padding(horizontal = 3.dp) ) } } } else { IconButton(onClick = { navController.navigate(Screen.NewsSaved.route) }, colors = IconButtonDefaults.iconButtonColors(contentColor = MaterialTheme.colorScheme.onSecondary)) { Icon( imageVector = ImageVector.vectorResource(id = R.drawable.ic_saved), contentDescription = "saved news" ) } } }
0
Java
0
0
08623c8850b0b301c7af9c7961d6436988f6d1a3
3,124
AI-News
MIT License
common/src/main/java/com/bcm/messenger/common/ui/activity/SearchActivity.kt
Era-CyberLabs
576,196,269
false
{"Java": 6276144, "Kotlin": 5427066, "HTML": 92928, "C": 30870, "Groovy": 12495, "C++": 6551, "CMake": 2728, "Python": 1600, "AIDL": 1267, "Makefile": 472}
package com.bcm.messenger.common.ui.activity import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.MotionEvent import android.view.View import androidx.fragment.app.Fragment import com.bcm.messenger.common.ARouterConstants import com.bcm.messenger.common.AccountContext import com.bcm.messenger.common.R import com.bcm.messenger.common.AccountSwipeBaseActivity import com.bcm.messenger.common.api.ISearchAction import com.bcm.messenger.common.api.ISearchCallback import com.bcm.messenger.common.finder.BcmFinderManager import com.bcm.messenger.common.finder.BcmFinderType import com.bcm.messenger.common.ui.CommonSearchBar import com.bcm.messenger.common.utils.* import com.bcm.messenger.utility.logger.ALog import kotlinx.android.synthetic.main.common_activity_search.* /** * * @created by wjh 2019-04-04 */ class SearchActivity : AccountSwipeBaseActivity(), ISearchCallback { companion object { private const val TAG = "SearchActivity" const val REQUEST_SEARCH_MORE = 1 /** * */ fun callSearchActivity(context: Context, accountContext: AccountContext, keyword: String, displayAll: Boolean, hasPrevious: Boolean, searchClass: String, recentClass: String?, requestCode: Int) { val intent = Intent(context, SearchActivity::class.java) intent.putExtra(ARouterConstants.PARAM.SEARCH.CURRENT_KEYWORD, keyword) intent.putExtra(ARouterConstants.PARAM.SEARCH.HAS_PREVIOUS, hasPrevious) intent.putExtra(ARouterConstants.PARAM.SEARCH.DISPLAY_ALL, displayAll) intent.putExtra(ARouterConstants.PARAM.SEARCH.RECENT_CLAZZ, recentClass) intent.putExtra(ARouterConstants.PARAM.SEARCH.CURRENT_CLAZZ, searchClass) intent.putExtra(ARouterConstants.PARAM.PARAM_ENTER_ANIM, R.anim.common_popup_alpha_in) intent.putExtra(ARouterConstants.PARAM.PARAM_EXIT_ANIM, R.anim.common_popup_alpha_out) intent.putExtra(ARouterConstants.PARAM.PARAM_PREVIOUS_EXIT_ANIM, R.anim.common_popup_alpha_out) intent.putExtra(ARouterConstants.PARAM.PARAM_PREVIOUS_ENTER_ANIM, R.anim.common_popup_alpha_in) if (context is Activity) { if (requestCode != 0) { context.startBcmActivityForResult(accountContext, intent, requestCode) } else { context.startBcmActivity(accountContext, intent) } } else { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startBcmActivity(accountContext, intent) } } } private var mHasPrevious = false private var mDisplayAll = false private var mRecentFragmentClazz: String? = null private var mCurrentFragmentClazz: String? = null private var mRecentSearchFragment: Fragment? = null private var mCurrentSearchFragment: Fragment? = null private var mDisplayFragment: Fragment? = null override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_SEARCH_MORE) { if (resultCode == Activity.RESULT_OK) { finish() } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.common_activity_search) init() } override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { if (ev?.action == MotionEvent.ACTION_DOWN) { val y = ev.y val targetY = search_bar_layout.y + search_bar_layout.height if (y > targetY) { hideKeyboard() } } return super.dispatchTouchEvent(ev) } private fun init() { ALog.d(TAG, "init") search_top_v.post { search_top_v.layoutParams = search_top_v.layoutParams.apply { height += getStatusBarHeight() } } mDisplayAll = intent.getBooleanExtra(ARouterConstants.PARAM.SEARCH.DISPLAY_ALL, false) mHasPrevious = intent.getBooleanExtra(ARouterConstants.PARAM.SEARCH.HAS_PREVIOUS, false) mCurrentFragmentClazz = intent.getStringExtra(ARouterConstants.PARAM.SEARCH.CURRENT_CLAZZ) mRecentFragmentClazz = intent.getStringExtra(ARouterConstants.PARAM.SEARCH.RECENT_CLAZZ) ALog.i(TAG, "init displayAll: $mDisplayAll, hasPrevious: $mHasPrevious, current: $mCurrentFragmentClazz, recent: $mRecentFragmentClazz") if (mCurrentFragmentClazz.isNullOrEmpty()) { finish() return } search_back_iv.setColorFilter(getAttrColor(R.attr.common_foreground_color)) if (mHasPrevious) { search_back_iv.visibility = View.VISIBLE } else { search_back_iv.visibility = View.GONE } if (mRecentFragmentClazz.isNullOrEmpty()) { displaySearch(search_main_sb.getSearchText().toString()) } else { displayRecent() } search_back_iv.setOnClickListener { onBackPressed() } search_cancel_tv.setOnClickListener { setResult(Activity.RESULT_OK) finish() } search_main_sb.setOnSearchActionListener(object : CommonSearchBar.OnSearchActionListener { override fun onJump() { } override fun onSearch(keyword: String) { ALog.d(TAG, "onSearch keyword: $keyword") displaySearch(keyword) } override fun onClear() { ALog.d(TAG, "onClear") if (!mRecentFragmentClazz.isNullOrEmpty()) { displayRecent() } else { displaySearch("") } } }) search_main_sb.setSearchText(intent.getStringExtra(ARouterConstants.PARAM.SEARCH.CURRENT_KEYWORD) ?: "") search_main_sb.post { search_main_sb.requestSearchFocus() } } /** * */ private fun displayRecent() { if (mDisplayFragment == mRecentSearchFragment && mDisplayFragment != null) { ALog.d(TAG, "displayRecent return, displayFragment is same") return } val tran = supportFragmentManager.beginTransaction() mDisplayFragment?.let { tran.hide(it) } var f = mRecentSearchFragment if (f == null) { f = supportFragmentManager.fragmentFactory.instantiate(classLoader, mRecentFragmentClazz.orEmpty()).apply { arguments = Bundle().apply { putSerializable(ARouterConstants.PARAM.PARAM_ACCOUNT_CONTEXT, accountContext) } } mRecentSearchFragment = f tran.add(R.id.search_main_layout, f) } else { tran.show(f) } mDisplayFragment = mRecentSearchFragment tran.commitAllowingStateLoss() } /** * */ private fun displaySearch(keyword: String) { if (mDisplayFragment == mCurrentSearchFragment && mDisplayFragment != null) { ALog.d(TAG, "displaySearch return, displayFragment is same") val f = mDisplayFragment if (f is ISearchAction) { f.setKeyword(keyword, !mDisplayAll) } return } val tran = supportFragmentManager.beginTransaction() mDisplayFragment?.let { tran.hide(it) } var f: Fragment? = mCurrentSearchFragment if (f == null) { f = supportFragmentManager.fragmentFactory.instantiate(classLoader, mCurrentFragmentClazz.orEmpty()).apply { arguments = Bundle().apply { putSerializable(ARouterConstants.PARAM.PARAM_ACCOUNT_CONTEXT, accountContext) } } mCurrentSearchFragment = f tran.add(R.id.search_main_layout, f) } else { tran.show(f) } if (f is ISearchAction) { f.setKeyword(keyword, !mDisplayAll) } mDisplayFragment = mCurrentSearchFragment tran.commitAllowingStateLoss() } override fun onSelect(type: BcmFinderType, key: String) { BcmFinderManager.get(accountContext).saveRecord(type, key) } override fun onMore(type: BcmFinderType, key: String) { } }
1
null
1
1
65a11e5f009394897ddc08f4252969458454d052
8,584
cyberland-android
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/internals/registration/xml/XmlActionMap.kt
XaverianTeamRobotics
635,157,880
true
{"Java Properties": 2, "PowerShell": 2, "XML": 45, "Shell": 2, "Gradle": 7, "Markdown": 7, "Git Attributes": 1, "Batchfile": 1, "Text": 5, "Ignore List": 2, "Java": 211, "INI": 1, "YAML": 3, "HTML": 3, "CSS": 4, "JavaScript": 7, "JSON": 2, "robots.txt": 1, "Kotlin": 90}
package org.firstinspires.ftc.teamcode.internals.registration.xml enum class XmlActionMap { TELEMETRY_LOG_LINE, VARIABLE_SET, VARIABLE_USAGE, VARIABLE_DECLARE, INT_CONSTANT, BINARY_EXPRESSION, PARENTHESES, CLEAR_TELEMETRY, MOTOR_SET_POWER, FLOAT_CONSTANT, WAIT; companion object { @JvmStatic fun mapFromMPSString(s: String): XmlActionMap { return when (s) { "TelemetryLogLine" -> TELEMETRY_LOG_LINE "VariableSetStatement" -> VARIABLE_SET "VariableUsageExpression" -> VARIABLE_USAGE "VariableStatement" -> VARIABLE_DECLARE "IntegerConstant" -> INT_CONSTANT "BinaryOperation" -> BINARY_EXPRESSION "ParenthesizedExpression" -> PARENTHESES "TelemetryClear" -> CLEAR_TELEMETRY "WaitStatement" -> WAIT "MotorSetStatement" -> MOTOR_SET_POWER "FloatingPointConstant" -> FLOAT_CONSTANT else -> throw IllegalArgumentException("Unknown action $s") } } } }
0
Java
0
0
9ff9971a97aaab032456eca0f7a30e8e823eb861
1,138
powerplay-archive
BSD 3-Clause Clear License
src/test/kotlin/org/jetbrains/lama/LamaMultiFileTest.kt
Mervap
457,621,178
false
{"Kotlin": 204355, "Lex": 4986, "HTML": 613}
package org.jetbrains.lama import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import java.io.File import java.nio.file.Path abstract class LamaMultiFileTest(private val group: String) : LamaBaseTest() { override fun getTestDataPath(): String = super.getTestDataPath() + "/multiFile/$group/" + getTestName(true) protected fun configureFiles(editorFileName: String = "main"): List<PsiFile> { val filePaths = collectFilePaths(editorFileName) val virtualFiles = filePaths.map { val relativePath = Path.of(testDataPath).relativize(Path.of(it)).toString() myFixture.copyFileToProject(relativePath) } myFixture.configureFromExistingVirtualFile(virtualFiles[0]) return virtualFiles.map { PsiManager.getInstance(project).findFile(it)!! } } private fun collectFilePaths(editorFileName: String): List<String> { val files = File(testDataPath) .walkTopDown() .filter { it.isFile } .map { it.path } .sortedByDescending { it.contains(editorFileName) } .toList() if (files.isEmpty()) error("No files at $testDataPath") return files } }
7
Kotlin
0
7
83bfcef88c5997e1e93181ab2f791f3ba0914719
1,123
LamaPlugin
MIT License
feature/museum/src/main/java/com/hanbikan/nook/feature/museum/navigation/MuseumNavigation.kt
hanbikan
737,877,468
false
{"Kotlin": 247435}
package com.hanbikan.nook.feature.museum.navigation import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.navigation.navigation import com.hanbikan.nook.feature.museum.CollectibleScreen import com.hanbikan.nook.feature.museum.MuseumScreen const val museumGraphRoute = "museum_graph_route" const val museumScreenRoute = "museum_screen_route" const val MONTHLY_COLLECTIBLE_SCREEN_ROUTE_BASE = "monthly_collectible_screen_route" const val COLLECTIBLE_SEQUENCE_INDEX = "collectibleSequenceIndex" const val monthlyCollectibleScreenRoute = "$MONTHLY_COLLECTIBLE_SCREEN_ROUTE_BASE/{$COLLECTIBLE_SEQUENCE_INDEX}" fun NavGraphBuilder.museumGraph( navigateToAddUser: () -> Unit, navigateToPhone: () -> Unit, navigateToMonthlyCollectible: (Int) -> Unit, navigateUp: () -> Unit, ) { navigation( route = museumGraphRoute, startDestination = museumScreenRoute, ) { composable( route = museumScreenRoute, ) { MuseumScreen( navigateToAddUser = navigateToAddUser, navigateToPhone = navigateToPhone, navigateToMonthlyCollectible = navigateToMonthlyCollectible, ) } composable( route = monthlyCollectibleScreenRoute, arguments = listOf( navArgument(COLLECTIBLE_SEQUENCE_INDEX) { type = NavType.IntType } ) ) { CollectibleScreen( navigateUp = navigateUp, ) } } } fun NavController.navigateToMuseum() { navigate(museumGraphRoute) } fun NavController.navigateToMonthlyCollectible(collectibleSequenceIndex: Int) { navigate("$MONTHLY_COLLECTIBLE_SCREEN_ROUTE_BASE/$collectibleSequenceIndex") }
0
Kotlin
0
0
c0d9dd3584778d98d39d546858a561343397ea43
1,919
Nook
Apache License 2.0
app/src/main/java/com/gjf/life_demo/ui/TypePlaceFragment.kt
blacknickwield
405,325,287
false
{"Kotlin": 105340}
package com.gjf.life_demo.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.gjf.life_demo.R import com.gjf.life_demo.adapter.TypePlaceAdapter import com.gjf.life_demo.utils.RecyclerViewAnimation import com.gjf.life_demo.utils.SpacingItemDecoration import com.gjf.life_demo.viewmodels.PlaceViewModel private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /*** * TypeFragment: 展示学习、生活、美食、其他类型place的页面 */ class TypePlaceFragment : Fragment() { /*** * 类型参数,判断该fragment显示何种类型的place * 0:学习 1:生活 2:美食 3:其他 */ private var type: Int? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { type = it.getInt(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } var placeViewModel: PlaceViewModel? = null lateinit var placeAdapter: TypePlaceAdapter lateinit var placeRecyclerView: RecyclerView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val root = inflater.inflate(R.layout.fragment_type_place, container, false) placeRecyclerView = root.findViewById(R.id.recyclerView) placeRecyclerView.layoutManager = LinearLayoutManager(activity) return root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) /*** * 根据不同类型参数获取不同类型的place数据 * 0:学习 1:生活 2:美食 3:其他 */ placeAdapter = TypePlaceAdapter( when (type) { 0 -> placeViewModel!!.studyPlaces 1 -> placeViewModel!!.lifeplaces 2 -> placeViewModel!!.eatPlaces 3 -> placeViewModel!!.otherPlaces else -> placeViewModel!!.places }, this ) placeRecyclerView.adapter = placeAdapter RecyclerViewAnimation.runLayoutAnimation(placeRecyclerView) // 修饰器 val topSpacingDecorator = SpacingItemDecoration(30) placeRecyclerView.addItemDecoration(topSpacingDecorator) } /*** * 回调函数获取place列表 * 数据库中place信息发生变动后在NearByFragment中回调该函数 * 获取到最新的place数据 * 更新recyclerview */ fun notifyDataSetChanged() { if (this::placeAdapter.isInitialized) { placeAdapter = TypePlaceAdapter( when (type) { 0 -> placeViewModel!!.studyPlaces 1 -> placeViewModel!!.lifeplaces 2 -> placeViewModel!!.eatPlaces 3 -> placeViewModel!!.otherPlaces else -> placeViewModel!!.places }, this ) placeRecyclerView.adapter = placeAdapter placeAdapter.notifyDataSetChanged() RecyclerViewAnimation.runLayoutAnimation(placeRecyclerView) } } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment TypePlaceFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(type: Int, param2: String) = TypePlaceFragment().apply { arguments = Bundle().apply { putInt(ARG_PARAM1, type) putString(ARG_PARAM2, param2) } } } }
0
Kotlin
0
0
62479c516374d6d0d77f9dc68f298eaec8bf012f
3,921
BITMap
MIT License
library/src/main/java/io/github/anderscheow/validator/rules/regex/AlphabetRule.kt
KirillAshikhmin
408,957,823
true
{"Kotlin": 129331, "Java": 99}
package io.github.anderscheow.validator.rules.regex import androidx.annotation.StringRes import io.github.anderscheow.validator.Validation import io.github.anderscheow.validator.rules.common.RegexRule class AlphabetRule : RegexRule { constructor() : super(ALPHABET_REGEX, "Value does not match alphabet regex") constructor(@StringRes errorRes: Int) : super(ALPHABET_REGEX, errorRes) constructor(errorMessage: String) : super(ALPHABET_REGEX, errorMessage) companion object { private const val ALPHABET_REGEX = "^[a-zA-Z]*$" } } fun Validation.alphabetOnly(): Validation { baseRules.add(AlphabetRule()) return this } fun Validation.alphabetOnly(@StringRes errorRes: Int): Validation { baseRules.add(AlphabetRule(errorRes)) return this } fun Validation.alphabetOnly(errorMessage: String): Validation { baseRules.add(AlphabetRule(errorMessage)) return this }
0
null
0
0
56c2e490fa06e491dd782b2bab0d222507b3eaf0
917
Validator
MIT License
domain/src/main/kotlin/app/web/drjackycv/domain/products/usecase/GetBeersListUseCase.kt
naylonmuhendis
342,738,988
false
{"Kotlin": 78557}
package app.web.drjackycv.domain.products.usecase import androidx.paging.PagingData import app.web.drjackycv.domain.base.RecyclerItem import app.web.drjackycv.domain.base.usecase.GeneralUseCase import app.web.drjackycv.domain.products.repository.ProductsListRepository import io.reactivex.Flowable import javax.inject.Inject class GetBeersListUseCase @Inject constructor( private val productsListRepository: ProductsListRepository ) : GeneralUseCase<Flowable<PagingData<RecyclerItem>>, GetBeersListParams> { override fun invoke(params: GetBeersListParams): Flowable<PagingData<RecyclerItem>> = productsListRepository.getBeersList(params.ids) } inline class GetBeersListParams(val ids: String)
0
Kotlin
0
0
bb642a5cb20fde26bcce2b13e0b339caab0f9c1c
713
WordsTemplete
MIT License
src/main/kotlin/br/com/zup/ot5/integracoes/sistema_pix_bcb/CreatePixKeyRequest.kt
DaviLevi
383,277,033
true
{"Kotlin": 84053, "Smarty": 2172}
package br.com.zup.ot5.integracoes.sistema_pix_bcb import br.com.zup.ot5.chave_pix.ChavePix import br.com.zup.ot5.chave_pix.TipoChave import br.com.zup.ot5.compartilhado.model.Conta import br.com.zup.ot5.compartilhado.model.Instituicoes import br.com.zup.ot5.compartilhado.model.TipoConta data class CreatePixKeyRequest( val keyType : TipoChaveBcb, val key: String, val bankAccount: ContaBcbRequest, val owner: TitularBcbRequest ){ companion object { fun of(chavePix : ChavePix) : CreatePixKeyRequest{ return CreatePixKeyRequest( keyType = chavePix.tipoChave.paraTipoChaveBcb(), key = chavePix.chave, bankAccount = ContaBcbRequest.of(chavePix.conta), owner = TitularBcbRequest.of(chavePix.conta) ) } } } data class TitularBcbRequest( val type: TipoPessoaBcb, val name: String, val taxIdNumber: String ){ companion object { fun of(conta : Conta) : TitularBcbRequest{ return TitularBcbRequest( type = TipoPessoaBcb.NATURAL_PERSON, name = conta.titularConta.nomeTitular, taxIdNumber = conta.titularConta.cpfTitular ) } } } data class ContaBcbRequest( val participant : String, val branch: String, val accountNumber: String, val accountType: TipoContaBcb ){ companion object { fun of(conta : Conta) : ContaBcbRequest{ return ContaBcbRequest( participant = Instituicoes.ispbDe(conta.instituicao).toString(), branch = conta.agencia, accountNumber = conta.numero, accountType = conta.tipoConta.paraTipoContaBcb() ) } } } enum class TipoContaBcb{ CACC { override fun paraTipoConta(): TipoConta { return TipoConta.CONTA_CORRENTE } }, SVGS { override fun paraTipoConta(): TipoConta { return TipoConta.CONTA_POUPANCA } }; companion object{ fun por(tipoConta: TipoConta): TipoContaBcb { return when(tipoConta){ TipoConta.CONTA_CORRENTE -> CACC TipoConta.CONTA_POUPANCA -> SVGS } } } abstract fun paraTipoConta() : TipoConta } enum class TipoPessoaBcb{ NATURAL_PERSON, LEGAL_PERSON } enum class TipoChaveBcb{ CPF { override fun paraTipoChave(): TipoChave { return TipoChave.CPF } }, CNPJ { override fun paraTipoChave(): TipoChave { TODO("Not yet implemented") } }, PHONE { override fun paraTipoChave(): TipoChave { return TipoChave.TELEFONE_CELULAR } }, EMAIL { override fun paraTipoChave(): TipoChave { return TipoChave.EMAIL } }, RANDOM { override fun paraTipoChave(): TipoChave { return TipoChave.ALEATORIA } }; abstract fun paraTipoChave() : TipoChave }
0
Kotlin
0
0
f00bfecba37e7f78e18c4d89e617d90c6fb13ea3
3,043
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/io/github/memydb/ui/modules/jbzd/JbzdViewModel.kt
Faierbel
176,805,921
false
{"Kotlin": 64104}
package io.github.memydb.ui.modules.jbzd import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.ViewModel import io.github.memydb.data.api.ApiResponse import io.github.memydb.data.pojos.Meme import io.github.memydb.data.repositories.JbzdRepository import javax.inject.Inject class JbzdViewModel @Inject constructor(private val jbzdRepository: JbzdRepository) : ViewModel() { val jbzdMemes: LiveData<List<Meme>> get() = mutableJbzdMemes private val memesList = mutableListOf<Meme>() private var currentPage = 0 private val mutableJbzdMemes = MediatorLiveData<List<Meme>>() fun initialize() { if (currentPage == 0) downloadNextPage() } fun downloadNextPage() { currentPage++ val page = jbzdRepository.getJbzdPage(currentPage) mutableJbzdMemes.addSource(page) { if (it is ApiResponse.SuccessApiResponse) { memesList.addAll(it.value.memes) mutableJbzdMemes.value = memesList } } page.refresh() } }
10
Kotlin
0
0
b7e51171ac9a8cb4bb8eb1a8c096fd0b83d25631
1,095
MemyDB
MIT License
message/src/main/kotlin/com/victor/oancea/hermes/message/service/KafkaEventReceiver.kt
victor-oancea1
203,662,155
false
null
package com.victor.oancea.hermes.message.service import com.victor.oancea.hermes.application.event.EventReceiver import com.victor.oancea.hermes.application.json.Extensions.deserializeToMap import com.victor.oancea.hermes.domain.Event import com.victor.oancea.hermes.domain.EventMetadata import com.victor.oancea.hermes.domain.ReceiverOption import org.apache.kafka.clients.consumer.ConsumerRecord import org.springframework.stereotype.Service import reactor.core.publisher.Flux import reactor.kafka.receiver.KafkaReceiver import reactor.kafka.receiver.ReceiverRecord typealias StringReceiverRecord = ReceiverRecord<String, String> typealias StringConsumerRecord = ConsumerRecord<String, String> @Service class KafkaEventReceiver(private val defaultReceiverFactory: (ReceiverOption) -> KafkaReceiver<String, String>) : EventReceiver { override fun receive(receiverOptions: List<ReceiverOption>): Flux<Event> { return Flux .fromIterable(receiverOptions) .map { receiverOption -> defaultReceiverFactory(receiverOption) .receive() .map { it.toEvent() } .let { receiverOption.sourceFluxInspector(it) } } .flatMap { it } } private fun <T : StringConsumerRecord> T.toEvent(): Event { val headers = headers().map { it.key() to String(it.value()!!) }.toMap() val metadata = EventMetadata(topic = topic(), partition = partition(), offset = offset(), timestamp = timestamp(), keySize = serializedKeySize(), valueSize = serializedValueSize(), headers = headers, requestId = headers["requestId"]) return Event(metadata = metadata, id = headers["id"], key = key(), value = value().deserializeToMap()) } }
0
Kotlin
0
0
12947d0d99498573a99651b2c6875aa9bbaac298
2,146
hermes
Apache License 2.0
features/schedules/schedules-presentation/src/main/kotlin/com/paligot/confily/schedules/presentation/ScheduleDetailViewModel.kt
GerardPaligot
444,230,272
false
null
package com.paligot.confily.schedules.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.ktx.Firebase import com.paligot.confily.core.schedules.SchedulesRepository import com.paligot.confily.models.ui.TalkUi import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn sealed class ScheduleUiState { data object Loading : ScheduleUiState() data class Success(val talk: TalkUi) : ScheduleUiState() data class Failure(val throwable: Throwable) : ScheduleUiState() } class ScheduleDetailViewModel( scheduleId: String, repository: SchedulesRepository ) : ViewModel() { val uiState: StateFlow<ScheduleUiState> = repository.scheduleItem(scheduleId) .map { ScheduleUiState.Success(it) } .catch { Firebase.crashlytics.recordException(it) ScheduleUiState.Failure(it) } .stateIn( scope = viewModelScope, initialValue = ScheduleUiState.Loading, started = SharingStarted.WhileSubscribed() ) }
9
null
6
143
8c0985b73422d6b388012d79c7ab33c054dc55c1
1,266
Confily
Apache License 2.0
src/main/kotlin/org/jetbrains/advocates/rider/plugins/dotnetwatch/run/DotNetWatchRunConfigurationProducer.kt
maartenba
418,503,336
false
{"Kotlin": 36559}
package org.jetbrains.advocates.rider.plugins.dotnetwatch.run import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.actions.LazyRunConfigurationProducer import com.intellij.execution.configurations.ConfigurationTypeUtil import com.intellij.openapi.util.Ref import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.systemIndependentPath import com.intellij.psi.PsiElement import com.jetbrains.rider.model.runnableProjectsModel import com.jetbrains.rider.projectView.solution import com.jetbrains.rider.projectView.workspace.getFile import com.jetbrains.rider.run.configurations.getSelectedProject // REVIEW this one overrides the default context menu | Run ..., which is not ideal - disabled for now class DotNetWatchRunConfigurationProducer : LazyRunConfigurationProducer<DotNetWatchRunConfiguration>() { override fun getConfigurationFactory() = ConfigurationTypeUtil.findConfigurationType(DotNetWatchRunConfigurationType::class.java) .configurationFactories .single() override fun isConfigurationFromContext( configuration: DotNetWatchRunConfiguration, context: ConfigurationContext ) : Boolean { val selectedProjectFilePathInvariant = context.getSelectedProject()?.getFile()?.systemIndependentPath ?: return false val projects = context.project.solution.runnableProjectsModel.projects.valueOrNull ?: return false val runnableProject = projects.firstOrNull { FileUtil.toSystemIndependentName(it.projectFilePath) == selectedProjectFilePathInvariant && FileUtil.toSystemIndependentName(configuration.watchOptions().projectFilePath) == selectedProjectFilePathInvariant } return runnableProject != null } override fun setupConfigurationFromContext( configuration: DotNetWatchRunConfiguration, context: ConfigurationContext, psiElement: Ref<PsiElement> ): Boolean { val selectedProjectFilePathInvariant = context.getSelectedProject()?.getFile()?.systemIndependentPath ?: return false val projects = context.project.solution.runnableProjectsModel.projects.valueOrNull ?: return false val runnableProject = projects.firstOrNull { FileUtil.toSystemIndependentName(it.projectFilePath) == selectedProjectFilePathInvariant } ?: return false if (configuration.name.isEmpty()) { configuration.name = runnableProject.name } configuration.watchOptions().projectFilePath = runnableProject.projectFilePath return true } }
1
Kotlin
4
27
693c326753a6141bae07dbaf7fe5016727fa1240
2,623
DotNetWatch
MIT License
src/main/kotlin/org/team1540/cluck/backend/Utils.kt
flamingchickens1540
142,687,525
false
null
@file:JvmName("Utils") package org.team1540.cluck.backend import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter fun Long.convertToISODate(): String = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(this), ZoneId.systemDefault()))
0
Kotlin
0
0
8b9339b5ff5e42758beefcdeef65e4c6a3c6f1f9
343
cluck-backend
MIT License
lcc-content-data/src/main/kotlin/com/joshmanisdabomb/lcc/data/factory/tag/HeartItemTagFactory.kt
joshmanisdabomb
537,458,013
false
{"Kotlin": 2724329, "Java": 138822}
package com.joshmanisdabomb.lcc.data.factory.tag import com.joshmanisdabomb.lcc.abstracts.heart.HeartType import com.joshmanisdabomb.lcc.data.DataAccessor import com.joshmanisdabomb.lcc.data.factory.ItemDataFactory import com.joshmanisdabomb.lcc.directory.tags.LCCItemTags import com.joshmanisdabomb.lcc.item.HeartContainerItem import com.joshmanisdabomb.lcc.item.HeartItem import net.minecraft.item.Item object HeartItemTagFactory : ItemDataFactory { override fun apply(data: DataAccessor, entry: Item) { if (entry !is HeartItem) return if (entry is HeartContainerItem) return data.tags.item(getTag(entry.heart)).attach(entry) } fun getTag(heart: HeartType) = LCCItemTags[heart.asString().plus("_hearts")] }
0
Kotlin
0
0
a836162eaf64a75ca97daffa02c1f9e66bdde1b4
750
loosely-connected-concepts
Creative Commons Zero v1.0 Universal
app/src/androidTest/java/uk/nhs/nhsx/sonar/android/app/testhelpers/robots/PostCodeRobot.kt
nhsx
261,523,644
false
null
/* * Copyright © 2020 NHSX. All rights reserved. */ package uk.nhs.nhsx.sonar.android.app.testhelpers.robots import androidx.core.text.HtmlCompat import androidx.test.espresso.Espresso.closeSoftKeyboard import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.typeText import androidx.test.espresso.assertion.ViewAssertions.doesNotExist import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import org.hamcrest.CoreMatchers.not import uk.nhs.nhsx.sonar.android.app.R import uk.nhs.nhsx.sonar.android.app.testhelpers.stringFromResId class PostCodeRobot { fun enterPostCode(postCode: String) { onView(withId(R.id.postCodeEditText)).perform(typeText(postCode)) closeSoftKeyboard() } fun clickContinue() { onView(withId(R.id.postCodeContinue)).perform(click()) } fun checkActivityIsDisplayed() { onView(withId(R.id.postCodeContinue)).check(matches(isDisplayed())) } fun checkActivityDoesNotExist() { onView(withId(R.id.postCodeContinue)).check(doesNotExist()) } fun checkTitleIsDisplayed() { onView(withText(R.string.post_code_title)).check(matches(isDisplayed())) } fun checkExampleIsDisplayed() { onView(withText(R.string.post_code_example)).check(matches(isDisplayed())) } fun checkInvalidHintIsNotDisplayed() { onView(withId(R.id.invalidPostCodeHint)).check(matches(not(isDisplayed()))) } fun checkInvalidHintIsDisplayed() { onView(withId(R.id.invalidPostCodeHint)).check(matches(isDisplayed())) } fun checkEditTextIs(expectedValue: String) { onView(withId(R.id.postCodeEditText)).check(matches(withText(expectedValue))) } fun checkRationaleIsVisible() { onView(withText(R.string.post_code_rationale_title)).check(matches(isDisplayed())) val postCodeRationaleRes: String = stringFromResId(R.string.post_code_rationale) val postCodeRationale = HtmlCompat.fromHtml(postCodeRationaleRes, HtmlCompat.FROM_HTML_MODE_COMPACT).toString() onView(withText(postCodeRationale)).check(matches(isDisplayed())) } }
0
Kotlin
146
793
ebcb3221b89333d9f555592aebc934d06608d784
2,405
COVID-19-app-Android-BETA
MIT License
android/codebase/app-compose/src/main/java/com/dailystudio/codebase/compose/Color.kt
dailystudio
203,761,006
false
{"Shell": 17731, "JavaScript": 12869, "Kotlin": 7446, "Vue": 4131, "SCSS": 2432, "HTML": 832}
package com.dailystudio.codebase.compose import androidx.compose.ui.graphics.Color val primaryColor = Color(0xff008577)
0
Shell
0
0
0ff37dc47ff30cf48a05ddd877519ae3d6c94019
121
project_generator
Apache License 2.0
azure-take-out-kt/src/main/kotlin/moe/scarlet/azure_take_out_kt/AzureTakeOutKtApplication.kt
MukjepScarlet
832,723,175
false
{"Kotlin": 120905}
package moe.scarlet.azure_take_out_kt import org.mybatis.spring.annotation.MapperScan import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.cache.annotation.EnableCaching import org.springframework.transaction.annotation.EnableTransactionManagement @SpringBootApplication @EnableTransactionManagement @EnableCaching @MapperScan("moe.scarlet.azure_take_out_kt.mapper") class AzureTakeOutKtApplication fun main(args: Array<String>) { runApplication<AzureTakeOutKtApplication>(*args) }
0
Kotlin
0
0
73a9050e8e29748c0cb77ac0b6d61c7ba5e090a3
578
AzureTakeOut-Kotlin
MIT License
app/src/main/java/com/example/proyectoinnovacionpdm2024_gt01_grupo3/AlarmReceiver.kt
Orellanna
806,324,174
false
{"Kotlin": 32180}
package com.example.proyectoinnovacionpdm2024_gt01_grupo3 import android.annotation.SuppressLint import android.app.AlarmManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.PowerManager import java.util.Calendar class AlarmReceiver : BroadcastReceiver() { @SuppressLint("ScheduleExactAlarm") override fun onReceive(context: Context, intent: Intent) { val pillName = intent.getStringExtra("pill_name") ?: "Pastilla" val pillDescription = intent.getStringExtra("pill_description") ?: "Hora de tomar la pastilla" val frequency = intent.getIntExtra("frequency", 1) val alarmTime = intent.getLongExtra("alarm_time", System.currentTimeMillis()) val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AlarmReceiver::WakeLock") wakeLock.acquire(10 * 60 * 1000L /*10 minutos*/) val alarmIntent = Intent(context, AlarmActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK putExtra("pill_name", pillName) putExtra("pill_description", pillDescription) } context.startActivity(alarmIntent) wakeLock.release() reprogramAlarm(context, pillName, pillDescription, frequency, alarmTime) } @SuppressLint("ScheduleExactAlarm") private fun reprogramAlarm(context: Context, pillName: String, pillDescription: String, frequency: Int, alarmTimeInMillis: Long) { val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager val nextAlarmTimeInMillis = alarmTimeInMillis + frequency * 60 * 60 * 1000 val alarmIntent = Intent(context, AlarmReceiver::class.java).apply { putExtra("pill_name", pillName) putExtra("pill_description", pillDescription) putExtra("frequency", frequency) putExtra("alarm_time", nextAlarmTimeInMillis) } val alarmPendingIntent = PendingIntent.getBroadcast( context, (nextAlarmTimeInMillis + 1).toInt(), alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextAlarmTimeInMillis, alarmPendingIntent) // Schedule the next notification 2 minutes before the next alarm val nextNotificationTimeInMillis = nextAlarmTimeInMillis - 2 * 60 * 1000 val notificationIntent = Intent(context, PastillaReceiver::class.java).apply { putExtra("pill_name", pillName) putExtra("pill_description", pillDescription) putExtra("frequency", frequency) putExtra("alarm_time", nextAlarmTimeInMillis) } val notificationPendingIntent = PendingIntent.getBroadcast( context, nextNotificationTimeInMillis.toInt(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextNotificationTimeInMillis, notificationPendingIntent) } }
0
Kotlin
0
0
14b2775f8a0bb33f298bb5cf4e81759e44754594
3,237
ProyectoInnovacionPDM2024-GT01-Grupo3
MIT License
12_NatureCollection/app/src/main/java/com/mboultoureau/naturecollection/PlantModel.kt
mboultoureau
125,827,712
false
{"JavaScript": 40939, "C": 19603, "Kotlin": 18454, "CSS": 12216, "C++": 11301, "HTML": 6700, "Java": 5779, "Vue": 3855, "SCSS": 3279, "Objective-C++": 1882, "Makefile": 164}
package com.mboultoureau.naturecollection class PlantModel( val id: String = "plant0", val name: String = "Tulipe", val description: String = "Petite description", val imageUrl: String = "https://cdn.pixabay.com/photo/2017/04/23/20/36/pink-2254970_960_720.jpg", val grow: String = "Faible", val water: String = "Moyenne", var liked: Boolean = false )
23
JavaScript
0
0
b93f732d23e45aecc71189f42194f8be3210fb13
407
coding-challenges
MIT License
src/main/kotlin/io/foxcapades/lib/cli/builder/flag/UIntFlag.fn.kt
Foxcapades
850,780,005
false
{"Kotlin": 253956}
package io.foxcapades.lib.cli.builder.flag import io.foxcapades.lib.cli.builder.arg.Argument import io.foxcapades.lib.cli.builder.flag.impl.UIntFlagImpl import io.foxcapades.lib.cli.builder.flag.impl.UniversalFlagImpl @Suppress("NOTHING_TO_INLINE") inline fun uintFlag(longForm: String, noinline action: FlagOptions<UInt>.() -> Unit = {}) = uintFlag { this.longForm = longForm; action() } @Suppress("NOTHING_TO_INLINE") inline fun uintFlag(shortForm: Char, noinline action: FlagOptions<UInt>.() -> Unit = {}) = uintFlag { this.shortForm = shortForm; action() } fun uintFlag(action: FlagOptions<UInt>.() -> Unit = {}): UIntFlag = UIntFlagImpl(FlagOptions(UInt::class).also(action)) fun nullableUIntFlag(action: NullableFlagOptions<UInt>.() -> Unit = {}): Flag<Argument<UInt?>, UInt?> = UniversalFlagImpl.of(NullableFlagOptions(UInt::class).also(action))
8
Kotlin
0
0
457d895219666963b70ac10df70092a7b778ebea
867
lib-kt-cli-builder
MIT License
src/main/kotlin/de/axelrindle/simplecoins/tasks/SyncTask.kt
axelrindle
48,488,884
false
null
package de.axelrindle.simplecoins.tasks import de.axelrindle.simplecoins.* import io.requery.sql.SchemaModifier import io.requery.sql.TableCreationMode import org.bukkit.Bukkit import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.BiConsumer import java.util.function.Supplier import java.util.logging.Logger import kotlin.math.ceil internal class SyncTask { companion object { private const val QUERY_LIMIT = 50 val VALID_DESTINATIONS = listOf("local", "remote") } private val logger = Logger.getLogger(javaClass.simpleName) var destination: String? = null set(value) { if (!VALID_DESTINATIONS.contains(value)) throw IllegalArgumentException("destination must be one of " + VALID_DESTINATIONS.joinToString(", ") + "!") field = value } var isRunning: Boolean = false private set fun isReady(): Boolean { return destination != null } fun run(callback: BiConsumer<Int, Throwable?>?): CompletableFuture<Int> { var future = CompletableFuture.supplyAsync( handleAsync(), Executor { Bukkit.getScheduler().runTaskAsynchronously(SimpleCoins.get(), it) } ) if (callback != null) { future = future.whenCompleteAsync( callback, Executor { Bukkit.getScheduler().runTask(SimpleCoins.get(), it) } ) } return future } private fun handleAsync() = Supplier { if (isRunning) throw IllegalStateException("Task already running!") isRunning = true logger.info("Synchronizing data to $destination...") val amount: Int = when (destination) { "local" -> syncToLocal() "remote" -> syncToRemote() else -> -1 } isRunning = false logger.info("Synchronized $amount entries.") amount } private fun syncToLocal(): Int { val store = CoinManager.dbStore!! val count = store.count(CoinUser::class).get().value() val iterations = if (count <= QUERY_LIMIT) 1 else ceil(count.toDouble() / QUERY_LIMIT).toInt() var offset = 0 logger.info("$count entries will be written to local file in $iterations iteration(s)...") SimpleCoins.get().pocketConfig.edit("database") { config -> repeat(iterations) { iteration -> logger.info("Iteration ${iteration + 1}...") val remoteList = CoinManager.dbStore!! .select(CoinUser::class) .limit(QUERY_LIMIT) .offset(offset) .get() remoteList.each { user -> config[user.uuid] = user.amount } remoteList.close() // increase offset by limit after each iteration offset += QUERY_LIMIT } } return count } private fun syncToRemote(): Int { val config = SimpleCoins.get().pocketConfig.access("database")!! val values = config.getValues(false) logger.info("${values.count()} entries will be written to the remote database...") // drop table SchemaModifier(CoinManager.dataSource!!, Models.DEFAULT) .createTables(TableCreationMode.DROP_CREATE) values.forEach { (uuid, amount) -> CoinManager.dbStore!! .insert(CoinUser::class) .value(CoinUserEntity.UUID, uuid) .value(CoinUserEntity.AMOUNT, amount as Double) .get().close() } return values.size } }
0
Kotlin
0
1
ecc14def3acc8e680f1b3d90203309e8430477fd
3,805
SimpleCoins
MIT License
connectors-core/src/main/kotlin/fund/cyber/markets/connectors/common/kafka/ConnectorKafkaProducer.kt
yvladimir
113,311,451
true
{"Kotlin": 142170, "JavaScript": 15976, "HTML": 6781, "Shell": 464}
package fund.cyber.markets.connectors.common.kafka import fund.cyber.markets.kafka.JsonSerializer import org.apache.kafka.clients.producer.KafkaProducer import org.apache.kafka.common.serialization.StringSerializer import java.util.Properties class ConnectorKafkaProducer<T>( props: Properties = KafkaConfiguration().tradesConsumersProperties("3"), keySerializer: StringSerializer = StringSerializer(), valueSerializer: JsonSerializer<T> = JsonSerializer<T>() ): KafkaProducer<String, T>(props, keySerializer, valueSerializer)
0
Kotlin
0
0
5ec8086ab33b1d44a4280cecda461de86966982a
552
cyber-markets
MIT License
app/src/main/java/com/example/storedemo/ui/products/ProductsActivity.kt
go-cristian
259,198,124
false
{"Kotlin": 12390}
package com.example.storedemo.ui.products import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import com.example.storedemo.R import com.example.storedemo.data.CartRepository import com.example.storedemo.ui.CartViewModel import com.example.storedemo.ui.ProductsViewModel import com.example.storedemo.ui.cart.CartActivity import org.koin.android.viewmodel.ext.android.viewModel class ProductsActivity : AppCompatActivity() { private val products: ProductsViewModel by viewModel() private val cart: CartViewModel by viewModel() private val productsView by lazy { findViewById<ProductsView>(R.id.products) } private val orderView by lazy { findViewById<Button>(R.id.order) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.products_layout) products.observe(this) { products: List<Product> -> productsView.add(products) } cart.observe(this) { cartRepository: CartRepository -> val products = cartRepository.products() productsView.addFromCart(products) orderView.isEnabled = cartRepository.total() != 0 if (cartRepository.total() == 0) { orderView.text = getString(R.string.order_format_zero) } else { orderView.text = resources.getString(R.string.order_format_other, cartRepository.total()) } } productsView.setOnProductTap { product -> cart.add(product) } orderView.setOnClickListener { startActivity(Intent(this, CartActivity::class.java)) } } }
0
Kotlin
0
1
9b040b6dcb0a81d5758581a788f15f9a75b68ca6
1,594
IceCreamStore
MIT License
src/main/kotlin/br/com/blu/bs2/sintetizador/contas/csv/utils/FormatterUtil.kt
NecoDan
291,710,416
false
null
package br.com.blu.bs2.sintetizador.contas.csv.utils import java.math.BigDecimal import java.math.RoundingMode import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.* /** * @author Daniel Santos */ object FormatterUtil { private const val MENSAGEM_VALIDACAO = "Parâmetro {DATA}, encontra-se inválida e/ou inexistente {NULL}." fun onlyBigDecimal(base: String): BigDecimal { return if (Objects.isNull(base) || base.isEmpty()) BigDecimal.ZERO else getOnlyBigDecimal(base) } private fun getOnlyBigDecimal(base: String): BigDecimal { var base = base if (base.contains(",")) base = base.replace(',', '.') return BigDecimal(base) } fun toStringLocalDateFormatada(data: LocalDateTime): String { if (Objects.nonNull(data)) return data.format(DateTimeFormatter.ofPattern("dd_MM_yyyy_HH_mm_ss")) throw IllegalArgumentException(MENSAGEM_VALIDACAO) } fun formatarNumero(valor: BigDecimal): String { var valor = valor valor = valor.setScale(2, RoundingMode.HALF_UP) val symbols = DecimalFormatSymbols(Locale("pt", "BR")) symbols.decimalSeparator = '.' val df = DecimalFormat("#0.00", symbols) return df.format(valor) } }
0
Kotlin
0
0
352b19084b027b14fd0fd087d87049b318e2e631
1,353
blu-bs2-sintetizador-contas-csv
Apache License 2.0
app/src/main/java/ca/on/hojat/gamenews/core/domain/entities/Video.kt
hojat72elect
574,228,468
false
null
package ca.on.hojat.gamenews.core.domain.entities data class Video( val id: String, val name: String?, )
0
Kotlin
2
4
b1c07551e90790ee3d273bc4c0ad3a5f97f71202
114
GameHub
MIT License
src/main/kotlin/net/casual/championships/minigame/uhc/gui/BorderDistanceRow.kt
CasualChampionships
334,382,250
false
{"Kotlin": 193728, "Java": 8404, "GLSL": 1196}
package net.casual.championships.minigame.uhc.gui import net.casual.arcade.gui.sidebar.SidebarComponent import net.casual.arcade.gui.sidebar.SidebarSupplier import net.casual.arcade.gui.suppliers.ComponentSupplier import net.casual.arcade.utils.ComponentUtils.literal import net.casual.arcade.utils.PlayerUtils.distanceToNearestBorder import net.casual.championships.util.Texts import net.casual.championships.util.Texts.monospaced import net.casual.championships.util.Texts.regular import net.minecraft.ChatFormatting.* import net.minecraft.network.chat.Component import net.minecraft.server.level.ServerPlayer class BorderDistanceRow(private val buffer: Component): SidebarSupplier { override fun getComponent(player: ServerPlayer): SidebarComponent { val vectorToBorder = player.distanceToNearestBorder() val multiplier = if (vectorToBorder.x < 0 || vectorToBorder.z < 0) -1 else 1 val distanceToBorder = multiplier * vectorToBorder.length().toInt() val percent = distanceToBorder / (player.level().worldBorder.size / 2.0) val colour = if (percent > 0.4) DARK_GREEN else if (percent > 0.2) YELLOW else if (percent > 0.1) RED else DARK_RED val display = Component.empty().append(this.buffer).append(Texts.UHC_DISTANCE_TO_WB) val score = distanceToBorder.toString().literal().append(this.buffer).withStyle(colour) return SidebarComponent.withCustomScore(display, score) } }
0
Kotlin
1
4
f064769da9e21a5b02ed20b96b887d90d84060ab
1,450
UHC-Mod
MIT License
capillary-kmp/src/jvmMain/kotlin/dev/baseio/security/CapillaryEncryption.kt
oianmol
528,898,439
false
{"Kotlin": 752408, "Swift": 113141, "Ruby": 11800, "Shell": 587, "Objective-C": 486, "C": 1}
@file:JvmName("CapillaryEncryptionJAva") package dev.baseio.security import java.util.Base64 import javax.crypto.Cipher actual object CapillaryEncryption { actual fun encrypt( plaintext: ByteArray, publicKey: PublicKey, ): EncryptedData { val cipher: Cipher = Cipher.getInstance(TRANSFORMATION_ASYMMETRIC) cipher.init(Cipher.ENCRYPT_MODE, publicKey.publicKey) val secretKey = CryptoChaCha20.createSymmetricKey() val payloadCiphertext = CryptoChaCha20.encrypt(plaintext, secretKey) val symmetricKeyCiphertext = cipher.doFinal(secretKey.encoded) return Pair(symmetricKeyCiphertext.base64(), payloadCiphertext.base64()) } actual fun decrypt( encryptedData: EncryptedData, privateKey: PrivateKey, ): ByteArray { val rsaCipher = Cipher.getInstance(TRANSFORMATION_ASYMMETRIC) rsaCipher.init(Cipher.DECRYPT_MODE, privateKey.privateKey) // Retrieve symmetric key. val symmetricKeyBytes = rsaCipher.doFinal(encryptedData.first.frombase64()) return CryptoChaCha20.decrypt( encryptedData.second.frombase64()!!, CryptoChaCha20 .secretFrom(symmetricKeyBytes) ) } } private fun String.frombase64(): ByteArray? { return Base64.getDecoder().decode(this) } private fun ByteArray.base64(): String { return Base64.getEncoder().encodeToString(this) }
3
Kotlin
21
235
143f06c11b757641fd3e67809f57dee9f2ffd04b
1,331
SlackComposeMultiplatform
Apache License 2.0
src/main/kotlin/tools/aqua/turnkey/plugin/util/Graphs.kt
tudo-aqua
860,027,153
false
{"Kotlin": 105116}
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2019-2024 The TurnKey Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tools.aqua.turnkey.plugin.util import org.jgrapht.Graph import org.jgrapht.Graphs.getOppositeVertex /** Get the set of nodes in this graph reachable from the nodes in [from], including these nodes. */ internal fun <V, E> Graph<V, E>.reachSet(from: Set<V>): Set<V> { val black = mutableSetOf<V>() val grey = from.toMutableSet() while (grey.isNotEmpty()) { val next = grey.first() grey -= next black += next outgoingEdgesOf(next).forEach { val adjacent = getOppositeVertex(this, it, next) if (adjacent !in black) { grey += adjacent } } } return black } /** Get the set of nodes in this graph reachable from the nodes in [from], including these nodes. */ internal fun <V, E> Graph<V, E>.reachSet(vararg from: V): Set<V> = reachSet(from.toSet())
0
Kotlin
0
0
ea7629e62fbbe2978bc20f90f3563e42934db560
1,462
turnkey-gradle-plugin
Creative Commons Attribution 4.0 International
idea/src/org/jetbrains/kotlin/idea/inspections/collections/ConvertCallChainIntoSequenceInspection.kt
arrow-kt
109,678,056
true
null
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections.collections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType class ConvertCallChainIntoSequenceInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = qualifiedExpressionVisitor(fun(expression) { val (targetQualified, targetCall) = expression.findTarget() ?: return val rangeInElement = targetCall.calleeExpression?.textRange?.shiftRight(-targetQualified.startOffset) ?: return holder.registerProblem( holder.manager.createProblemDescriptor( targetQualified, rangeInElement, "Call chain on collection should be converted into 'Sequence'", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, ConvertCallChainIntoSequenceFix() ) ) }) } private class ConvertCallChainIntoSequenceFix : LocalQuickFix { override fun getName() = "Convert call chain into 'Sequence'" override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val expression = descriptor.psiElement as? KtQualifiedExpression ?: return val context = expression.analyze(BodyResolveMode.PARTIAL) val calls = expression.collectCallExpression(context).reversed() val firstCall = calls.firstOrNull() ?: return val lastCall = calls.lastOrNull() ?: return val first = firstCall.getQualifiedExpressionForSelector() ?: return val last = lastCall.getQualifiedExpressionForSelector() ?: return val endWithTermination = lastCall.isTermination(context) val psiFactory = KtPsiFactory(expression) val dot = buildString { if (first.receiverExpression.siblings().filterIsInstance<PsiWhiteSpace>().any { it.textContains('\n') }) append("\n") if (first is KtSafeQualifiedExpression) append("?") append(".") } val firstCommentSaver = CommentSaver(first) val firstReplaced = first.replaced( psiFactory.buildExpression { appendExpression(first.receiverExpression) appendFixedText(dot) appendExpression(psiFactory.createExpression("asSequence()")) appendFixedText(dot) appendExpression(firstCall) } ) firstCommentSaver.restore(firstReplaced) if (!endWithTermination) { val lastCommentSaver = CommentSaver(last) val lastReplaced = last.replace( psiFactory.buildExpression { appendExpression(last) appendFixedText(dot) appendExpression(psiFactory.createExpression("toList()")) } ) lastCommentSaver.restore(lastReplaced) } } } private fun KtQualifiedExpression.findTarget(): Pair<KtQualifiedExpression, KtCallExpression>? { if (parent is KtQualifiedExpression) return null val context = analyze(BodyResolveMode.PARTIAL) val calls = collectCallExpression(context) if (calls.isEmpty()) return null val receiverType = (calls.last().getQualifiedExpressionForSelector())?.receiverExpression?.getResolvedCall(context)?.resultingDescriptor?.returnType if (receiverType?.isCollection() != true) return null val qualified = calls.first().getQualifiedExpressionForSelector() ?: return null return qualified to calls.last() } private fun KtQualifiedExpression.collectCallExpression(context: BindingContext): List<KtCallExpression> { val calls = mutableListOf<KtCallExpression>() fun collect(qualified: KtQualifiedExpression) { val call = qualified.callExpression ?: return calls.add(call) val receiver = qualified.receiverExpression if (receiver is KtQualifiedExpression) collect(receiver) } collect(this) if (calls.size < 2) return emptyList() val transformationCalls = calls .asSequence() .dropWhile { !it.isTransformationOrTermination(context) } .takeWhile { it.isTransformationOrTermination(context) && !it.hasReturn() } .toList() if (transformationCalls.size < 2) return emptyList() return transformationCalls } private fun KotlinType.isCollection(): Boolean { val classDescriptor = constructor.declarationDescriptor as? ClassDescriptor ?: return false val className = classDescriptor.name.asString() val builtIns = DefaultBuiltIns.Instance return className.endsWith("List") && classDescriptor.isSubclassOf(builtIns.list) || className.endsWith("Set") && classDescriptor.isSubclassOf(builtIns.set) } private fun KtCallExpression.hasReturn(): Boolean = valueArguments.any { arg -> arg.anyDescendantOfType<KtReturnExpression> { it.labelQualifier == null } } private fun KtCallExpression.isTransformationOrTermination(context: BindingContext): Boolean { val fqName = transformationAndTerminations[calleeExpression?.text] ?: return false return fqName == getResolvedCall(context)?.resultingDescriptor?.fqNameSafe } private fun KtCallExpression.isTermination(context: BindingContext): Boolean { val fqName = terminations[calleeExpression?.text] ?: return false return fqName == getResolvedCall(context)?.resultingDescriptor?.fqNameSafe } private val transformations = listOf( "chunked", "distinct", "distinctBy", "drop", "dropWhile", "filter", "filterIndexed", "filterIsInstance", "filterNot", "filterNotNull", "map", "mapIndexed", "mapIndexedNotNull", "mapNotNull", "minus", "minusElement", "onEach", "plus", "plusElement", "requireNoNulls", "sorted", "sortedBy", "sortedByDescending", "sortedDescending", "sortedWith", "take", "takeWhile", "windowed", "withIndex", "zipWithNext" ).associate { it to FqName("kotlin.collections.$it") } private val terminations = listOf( "all", "any", "asIterable", "asSequence", "associate", "associateBy", "associateByTo", "associateTo", "average", "contains", "count", "elementAt", "elementAtOrElse", "elementAtOrNull", "filterIndexedTo", "filterIsInstanceTo", "filterNotNullTo", "filterNotTo", "filterTo", "find", "findLast", "first", "firstOrNull", "fold", "foldIndexed", "groupBy", "groupByTo", "groupingBy", "indexOf", "indexOfFirst", "indexOfLast", "joinTo", "joinToString", "last", "lastIndexOf", "lastOrNull", "mapIndexedNotNullTo", "mapIndexedTo", "mapNotNullTo", "mapTo", "max", "maxBy", "maxWith", "min", "minBy", "minWith", "none", "partition", "reduce", "reduceIndexed", "single", "singleOrNull", "sum", "sumBy", "sumByDouble", "toCollection", "toHashSet", "toList", "toMutableList", "toMutableSet", "toSet", "toSortedSet" ).associate { val pkg = if (it in listOf("contains", "indexOf", "lastIndexOf")) "kotlin.collections.List" else "kotlin.collections" it to FqName("$pkg.$it") } private val transformationAndTerminations = transformations + terminations
12
Kotlin
1
43
d2a24985b602e5f708e199aa58ece652a4b0ea48
8,875
kotlin
Apache License 2.0
app/src/main/java/payment/sdk/android/demo/data/DataStoreImpl.kt
network-international
187,156,001
false
{"Kotlin": 546070, "Java": 39575}
package payment.sdk.android.demo.data import android.content.Context import payment.sdk.android.demo.getPreferences import payment.sdk.android.demo.model.Environment import payment.sdk.android.demo.model.MerchantAttribute import payment.sdk.android.demo.model.Product import com.google.gson.Gson import payment.sdk.android.core.SavedCard import payment.sdk.android.demo.model.AppCurrency class DataStoreImpl(private val context: Context) : DataStore { override fun saveEnvironment(environment: Environment) { val environments = Environment.getEnvironments(context) Environment.saveEnvironments(context, environments + environment) } override fun getEnvironments() = Environment.getEnvironments(context) override fun setSelectedEnvironment(environment: Environment) { Environment.setSelectedEnvironment(context, environmentId = environment.id) } override fun getSelectedEnvironment() = Environment.getSelectedEnvironment(context) override fun getSavedCard() = context.getPreferences().getString(KEY_SAVED_CARD, null)?.let { Gson().fromJson(it, SavedCard::class.java) } override fun deleteEnvironment(environment: Environment) { val environments = Environment.getEnvironments(context).toMutableList() environments.remove(environment) Environment.saveEnvironments(context, environments) } override fun getMerchantAttributes() = MerchantAttribute.getMerchantAttributes(context) override fun saveMerchantAttribute(merchantAttribute: MerchantAttribute) { val merchantAttributes = MerchantAttribute.getMerchantAttributes(context).toMutableList() merchantAttributes.add(merchantAttribute) MerchantAttribute.saveMerchantAttribute(context, merchantAttributes) } override fun deleteMerchantAttribute(merchantAttribute: MerchantAttribute) { val merchantAttributes = MerchantAttribute.getMerchantAttributes(context).toMutableList() merchantAttributes.remove(merchantAttribute) MerchantAttribute.saveMerchantAttribute(context, merchantAttributes) } override fun setOrderAction(action: String) { context.getPreferences().edit().putString(KEY_ORDER_ACTION, action).apply() } override fun getOrderAction() = context.getPreferences().getString(KEY_ORDER_ACTION, "SALE") ?: "SALE" override fun addProduct(product: Product) { val products = Product.getProducts(context).toMutableList() products.add(product) Product.saveProducts(context, products) } override fun deleteProduct(product: Product) { val products = Product.getProducts(context).toMutableList() products.remove(product) Product.saveProducts(context, products) } override fun getProducts() = Product.getProducts(context) + products override fun getSavedCards(): List<SavedCard> { val json = context.getPreferences().getString(KEY_SAVED_CARDS, null) return if (json != null) { Gson().fromJson(json, Array<SavedCard>::class.java).toList() } else { emptyList() } } override fun setSavedCard(savedCard: SavedCard) { context.getPreferences() .edit().putString(KEY_SAVED_CARD, Gson().toJson(savedCard)).apply() } override fun deleteSavedCard(savedCard: SavedCard) { val savedCards = getSavedCards().toMutableList() if (savedCards.contains(savedCard)) { savedCards.remove(savedCard) context.getPreferences() .edit().putString(KEY_SAVED_CARDS, Gson().toJson(savedCards)).apply() } } override fun updateMerchantAttribute(merchantAttribute: MerchantAttribute) { val attributes = MerchantAttribute.getMerchantAttributes(context).toMutableList() val index = attributes.indexOfFirst { it.id == merchantAttribute.id } if (index != -1) { attributes[index] = merchantAttribute MerchantAttribute.saveMerchantAttribute(context, attributes) } } override fun getCurrency(): AppCurrency { val currency = context.getPreferences().getString(KEY_CURRENCY, "") return AppCurrency.entries.firstOrNull { it.code == currency } ?: AppCurrency.AED } override fun setCurrency(currency: AppCurrency) { context.getPreferences().edit().putString(KEY_CURRENCY, currency.code).apply() } override fun saveCard(savedCard: SavedCard) { val savedCards = getSavedCards().toMutableList() if (savedCards.firstOrNull { it.cardToken == savedCard.cardToken } == null) { savedCards.add(savedCard) context.getPreferences() .edit().putString(KEY_SAVED_CARDS, Gson().toJson(savedCards)).apply() } } companion object { const val KEY_CURRENCY = "currency" const val KEY_SAVED_CARDS = "saved_cards" const val KEY_SAVED_CARD = "saved_card" const val KEY_ORDER_ACTION = "order_action" private val products = listOf( Product(name = "🐊", amount = 1.0), Product(name = "🦏", amount = 450.0), Product(name = "🐋", amount = 450.12), Product(name = "🦠", amount = 700.0), Product(name = "🐙", amount = 1500.0), Product(name = "🐡", amount = 2200.0), Product(name = "🐶", amount = 3000.0), Product(name = "🦊", amount = 3000.12), ) } }
3
Kotlin
7
5
dea297485b5bc45c1f1263a9c406abec3d72f497
5,484
payment-sdk-android
MIT No Attribution
app/src/androidTest/java/com/mapbox/maps/testapp/integration/texture/MapViewTextureModeTest.kt
mapbox
330,365,289
false
{"Kotlin": 3982759, "Java": 98572, "Python": 18705, "Shell": 11465, "C++": 10129, "JavaScript": 4344, "Makefile": 2413, "CMake": 1201, "EJS": 1194}
package com.mapbox.maps.testapp.integration.texture import androidx.test.ext.junit.runners.AndroidJUnit4 import com.mapbox.maps.testapp.examples.TextureViewActivity import com.mapbox.maps.testapp.integration.BaseReuseIntegrationTest import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class MapViewTextureModeTest : BaseReuseIntegrationTest(TextureViewActivity::class.java)
181
Kotlin
131
472
2700dcaf18e70d23a19fc35b479bff6a2d490475
386
mapbox-maps-android
Apache License 2.0
app/src/main/java/com/vishalag53/pokedex/response/GenerationViii.kt
vishalag53
659,343,908
false
null
package com.vishalag53.pokedex.response data class GenerationViii( val icons: com.vishalag53.pokedex.response.Icons )
0
Kotlin
0
0
fba5e4a083cd3e9d4e04de7f85949ce8a8cc95da
122
Pokedex
Apache License 2.0
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/types/KaFirType.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.fir.types import org.jetbrains.kotlin.analysis.api.lifetime.KaLifetimeOwner import org.jetbrains.kotlin.fir.types.ConeKotlinType internal interface KaFirType : KaLifetimeOwner { val coneType: ConeKotlinType } internal fun KaFirType.typeEquals(other: Any?): Boolean { if (other !is KaFirType) return false return this.coneType == other.coneType } internal fun KaFirType.typeHashcode(): Int = coneType.hashCode()
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
679
kotlin
Apache License 2.0
app/src/main/java/com/bluehub/mixi/common/fragments/BaseDialogFragment.kt
ashfaq1701
275,871,797
false
null
package com.bluehub.fastmixer.common.fragments import android.app.AlertDialog import android.app.Dialog import android.view.View import android.view.Window import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModel import com.bluehub.fastmixer.R abstract class BaseDialogFragment <T: ViewModel> : DialogFragment() { protected abstract val viewModel: T protected fun createDialog(view: View) : Dialog { return activity?.let { parentActivity -> val builder = AlertDialog.Builder(parentActivity, R.style.ThemeOverlay_AppCompat_Dialog) builder.setView(view) val dialog = builder.create() dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setCanceledOnTouchOutside(false) dialog } ?: throw IllegalStateException("Activity cannot be null") } protected fun closeDialog() { dialog?.dismiss() } }
0
C
9
48
dc9b650d8a07afb9da27057aa1336482b83e2010
942
fast-mixer
Creative Commons Zero v1.0 Universal
ktan/src/main/java/com/ktan/extra/CharSequenceExtra.kt
adef145
529,180,943
false
null
package com.ktan.extra import android.content.Intent import android.os.Bundle class CharSequenceExtra @JvmOverloads constructor( key: String, value: CharSequence? = null ) : AbstractExtra<CharSequence?>( key, value ) { override fun put(bundle: Bundle) { value?.also { bundle.putCharSequence(key, it) } } override fun put(intent: Intent) { intent.putExtra(key, value) } override fun get(bundle: Bundle): CharSequence? { return value?.let { bundle.getCharSequence(key, it) } ?: bundle.getCharSequence(key) } }
0
Kotlin
0
3
391a44440bf9a1ce88c3da09b02ae12887452135
575
Ktan
MIT License
app/src/main/java/kz/sozdik/login/data/api/model/LoginInfo.kt
sozdik-kz
290,830,901
false
null
package kz.sozdik.login.data.api.model import com.google.gson.annotations.SerializedName data class LoginInfo( @SerializedName("auth_token") val authToken: String? )
5
Kotlin
5
43
cfbdffe47253c14ec75d0fba166d1077e028328c
175
sozdik-android
MIT License
app/src/main/java/com/joshuacerdenia/android/nicefeed/ui/fragment/EntryListFragment.kt
kitlith
297,803,241
true
{"Kotlin": 207296}
package com.joshuacerdenia.android.nicefeed.ui.fragment import android.content.Context import android.content.res.Configuration.ORIENTATION_LANDSCAPE import android.net.Uri import android.os.Bundle import android.os.Handler import android.view.* import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.Toolbar import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import com.joshuacerdenia.android.nicefeed.R import com.joshuacerdenia.android.nicefeed.data.local.NiceFeedPreferences import com.joshuacerdenia.android.nicefeed.data.model.EntryLight import com.joshuacerdenia.android.nicefeed.data.model.Feed import com.joshuacerdenia.android.nicefeed.ui.OnHomePressed import com.joshuacerdenia.android.nicefeed.ui.OnToolbarInflated import com.joshuacerdenia.android.nicefeed.ui.adapter.EntryListAdapter import com.joshuacerdenia.android.nicefeed.ui.dialog.AboutFeedFragment import com.joshuacerdenia.android.nicefeed.ui.dialog.ConfirmRemoveFragment import com.joshuacerdenia.android.nicefeed.ui.dialog.EditCategoryFragment import com.joshuacerdenia.android.nicefeed.ui.dialog.FilterEntriesFragment import com.joshuacerdenia.android.nicefeed.ui.menu.EntryPopupMenu import com.joshuacerdenia.android.nicefeed.ui.viewmodel.EntryListViewModel import com.joshuacerdenia.android.nicefeed.utils.Utils class EntryListFragment : VisibleFragment(), EntryListAdapter.OnEntrySelected, EntryPopupMenu.OnPopupMenuItemClicked, FilterEntriesFragment.Callbacks, AboutFeedFragment.Callbacks, EditCategoryFragment.Callbacks, ConfirmRemoveFragment.Callbacks { interface Callbacks: OnHomePressed, OnToolbarInflated { fun onFeedLoaded(feedId: String) fun onEntrySelected(entryId: String) fun onCategoriesNeeded(): Array<String> fun onFeedRemoved() } private lateinit var viewModel: EntryListViewModel private lateinit var toolbar: Toolbar private lateinit var noItemsTextView: TextView private lateinit var masterProgressBar: ProgressBar private lateinit var progressBar: ProgressBar private lateinit var searchItem: MenuItem private lateinit var recyclerView: RecyclerView private lateinit var adapter: EntryListAdapter private var markAllOptionsItem: MenuItem? = null private var starAllOptionsItem: MenuItem? = null private var autoUpdateIsEnabled = true private var feedId: String? = null private var callbacks: Callbacks? = null private val fragment = this@EntryListFragment override fun onAttach(context: Context) { super.onAttach(context) callbacks = context as Callbacks? } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.getString(ARG_ENTRY_ID)?.let { entryId -> arguments?.remove(ARG_ENTRY_ID) // So it doesn't get loaded more than once callbacks?.onEntrySelected(entryId) } viewModel = ViewModelProvider(this).get(EntryListViewModel::class.java) viewModel.setOrder(NiceFeedPreferences.getEntriesOrder(requireContext())) autoUpdateIsEnabled = NiceFeedPreferences.getAutoUpdateSetting(requireContext()) adapter = EntryListAdapter(this) feedId = arguments?.getString(ARG_FEED_ID) val blockAutoUpdate = arguments?.getBoolean(ARG_BLOCK_AUTOUPDATE) ?: false if (blockAutoUpdate || !autoUpdateIsEnabled) viewModel.isAutoUpdating = false } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_entry_list, container, false) toolbar = view.findViewById(R.id.toolbar) noItemsTextView = view.findViewById(R.id.empty_message_text_view) masterProgressBar = view.findViewById(R.id.master_progress_bar) progressBar = view.findViewById(R.id.progress_bar) recyclerView = view.findViewById(R.id.recycler_view) recyclerView.layoutManager = if (resources.configuration.orientation == ORIENTATION_LANDSCAPE) { GridLayoutManager(context, 2) } else LinearLayoutManager(context) recyclerView.adapter = adapter toolbar.title = getString(R.string.loading) callbacks?.onToolbarInflated(toolbar, false) setHasOptionsMenu(feedId != null) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.feedLiveData.observe(viewLifecycleOwner, { feed -> if (feed != null) { viewModel.onFeedLoaded() callbacks?.onFeedLoaded(feed.url) } else feedId?.let { feedId -> if (!feedId.startsWith(FOLDER)) callbacks?.onFeedRemoved() } // Check if not currently updating if (toolbar.title != getString(R.string.updating)) { toolbar.title = when (feedId) { FOLDER_NEW -> getString(R.string.new_entries) FOLDER_STARRED -> getString(R.string.starred_entries) else -> feed?.title } } }) viewModel.entriesLightLiveData.observe(viewLifecycleOwner, { entries -> noItemsTextView.visibility = if (entries.isNullOrEmpty()) View.VISIBLE else View.GONE masterProgressBar.visibility = View.GONE adapter.submitList(entries) toggleOptionsItems() if (adapter.latestClickedPosition == 0) { Handler().postDelayed({ recyclerView.scrollToPosition(0) }, 250) } // Show update notice, if any if (viewModel.updateValues.isNotEmpty()) viewModel.updateValues.let { values -> showUpdatedNotice(values.added, values.updated) viewModel.updateValues.clear() } }) viewModel.updateResultLiveData.observe(viewLifecycleOwner, { results -> progressBar.visibility = View.GONE if (results != null) { viewModel.onUpdatesDownloaded(results) toolbar.title = results.feed.title } else toolbar.title = viewModel.getCurrentFeed()?.title }) } override fun onStart() { super.onStart() feedId?.let { feedId -> viewModel.getFeedWithEntries(feedId) if (feedId.startsWith(FOLDER)) { viewModel.isAutoUpdating = false callbacks?.onFeedLoaded(feedId) } // Auto-update on launch if (viewModel.isAutoUpdating) Handler().postDelayed({ viewModel.requestUpdate(feedId) toolbar.title = context?.getString(R.string.updating) progressBar.visibility = View.VISIBLE }, 750) } ?: let { masterProgressBar.visibility = View.GONE noItemsTextView.visibility = View.VISIBLE toolbar.title = getString(R.string.app_name) } toolbar.apply { setNavigationIcon(R.drawable.ic_menu) setNavigationOnClickListener { callbacks?.onHomePressed() } setOnClickListener { recyclerView.smoothScrollToPosition(0) } } } override fun onResume() { super.onResume() context?.let { viewModel.setOrder(NiceFeedPreferences.getEntriesOrder(it)) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.fragment_entry_list, menu) searchItem = menu.findItem(R.id.menuItem_search) markAllOptionsItem = menu.findItem(R.id.menuItem_mark_all) starAllOptionsItem = menu.findItem(R.id.menuItem_star_all) toggleOptionsItems() if (feedId?.startsWith(FOLDER) == true) { menu.findItem(R.id.menuItem_refresh).isVisible = false menu.findItem(R.id.menuItem_visit_website).isVisible = false menu.findItem(R.id.menuItem_about_feed).isVisible = false menu.findItem(R.id.menuItem_delete_feed).isVisible = false } (searchItem.actionView as SearchView).apply { if (viewModel.currentQuery.isNotEmpty()) { searchItem.expandActionView() setQuery(viewModel.currentQuery, false) clearFocus() } setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(queryText: String): Boolean { viewModel.submitQuery(queryText) clearFocus() return true } override fun onQueryTextChange(queryText: String): Boolean { return if (queryText.isEmpty()) { viewModel.submitQuery(queryText) true } else false } }) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menuItem_refresh -> handleCheckForUpdates(feedId) R.id.menuItem_about_feed -> handleShowFeedInfo(viewModel.getCurrentFeed()) R.id.menuItem_filter -> handleFilter() R.id.menuItem_mark_all -> handleMarkAll() R.id.menuItem_star_all -> handleStarAll() R.id.menuItem_visit_website -> handleVisitWebsite(viewModel.getCurrentFeed()?.website) R.id.menuItem_delete_feed -> handleRemoveFeed() else -> super.onOptionsItemSelected(item) } } private fun toggleOptionsItems() { markAllOptionsItem?.apply { if (viewModel.allIsRead()) { title = getString(R.string.mark_all_as_unread) setIcon(R.drawable.ic_check_circle_outline) } else { title = getString(R.string.mark_all_as_read) setIcon(R.drawable.ic_check_circle) } } starAllOptionsItem?.apply { if (viewModel.allIsStarred()) { title = getString(R.string.unstar_all) setIcon(R.drawable.ic_star) } else { title = getString(R.string.star_all) setIcon(R.drawable.ic_star_border) } } } private fun handleCheckForUpdates(url: String?): Boolean { return if (url != null) { progressBar.visibility = View.VISIBLE viewModel.submitQuery("") viewModel.requestUpdate(url) toolbar.title = getString(R.string.updating) searchItem.collapseActionView() true } else false } private fun showUpdatedNotice(newCount: Int, updatedCount: Int) { val entriesAdded = resources.getQuantityString(R.plurals.numberOfNewEntries, newCount, newCount) val entriesUpdated = resources.getQuantityString(R.plurals.numberOfEntries, updatedCount, updatedCount) val message = when { newCount > 0 && updatedCount == 0 -> getString(R.string.added, entriesAdded) newCount == 0 && updatedCount > 0 -> getString(R.string.updated, entriesUpdated) else -> getString(R.string.added_and_updated, entriesAdded, updatedCount) } Snackbar.make(recyclerView, message as CharSequence, Snackbar.LENGTH_SHORT).show() } private fun handleShowFeedInfo(feed: Feed?): Boolean { return if (feed != null) { AboutFeedFragment.newInstance(feed).apply { setTargetFragment(fragment, 0) show(fragment.parentFragmentManager, "about") } true } else false } override fun onEditCategoryClicked() { val categories = callbacks?.onCategoriesNeeded() ?: emptyArray() val title = viewModel.getCurrentFeed()?.title EditCategoryFragment.newInstance(categories, title).apply { setTargetFragment(fragment, 0) show(fragment.parentFragmentManager, "edit") } } override fun onEditCategoryConfirmed(category: String) { viewModel.updateCategory(category) Handler().postDelayed({ Snackbar.make( recyclerView, getString(R.string.category_assigned, category, viewModel.getCurrentFeed()?.title), Snackbar.LENGTH_SHORT ).show() }, 250) } private fun handleFilter(): Boolean { FilterEntriesFragment.newInstance(viewModel.currentFilter).apply { setTargetFragment(fragment, 0) show(fragment.parentFragmentManager, "filter") } return true } private fun handleMarkAll(): Boolean { viewModel.markAllCurrentEntriesAsRead() adapter.notifyDataSetChanged() return true } private fun handleStarAll(): Boolean { viewModel.starAllCurrentEntries() adapter.notifyDataSetChanged() return true } private fun handleVisitWebsite(website: String?): Boolean { return if (website != null) { Utils.openLink(requireActivity(), recyclerView, Uri.parse(website)) true } else false } private fun handleRemoveFeed(): Boolean { val feed = viewModel.getCurrentFeed() return if (feed != null) { ConfirmRemoveFragment.newInstance(feed.title).apply { setTargetFragment(fragment, 0) show(fragment.parentFragmentManager,"unsubscribe") } true } else false } override fun onRemoveConfirmed() { val title = viewModel.getCurrentFeed()?.title Snackbar.make(recyclerView, getString(R.string.unsubscribed_message, title), Snackbar.LENGTH_SHORT).show() viewModel.deleteFeedAndEntries() callbacks?.onFeedRemoved() } override fun onEntryClicked(entryId: String) { if (NiceFeedPreferences.getBrowserSetting(requireContext())) { Utils.openLink(requireContext(), recyclerView, Uri.parse(entryId)) viewModel.updateEntryIsRead(entryId, true) } else callbacks?.onEntrySelected(entryId) } override fun onEntryLongClicked(entry: EntryLight, view: View?) { view?.let { EntryPopupMenu(requireContext(), it, this, entry).show() } } override fun onPopupMenuItemClicked(entry: EntryLight, action: Int) { val url = entry.url when (action) { EntryPopupMenu.ACTION_STAR -> viewModel.updateEntryIsStarred(url, !entry.isStarred) EntryPopupMenu.ACTION_MARK_AS -> viewModel.updateEntryIsRead(url, !entry.isRead) else -> { onEntryClicked(entry.url) return } } adapter.notifyDataSetChanged() } override fun onFilterSelected(filter: Int) { viewModel.setFilter(filter) } override fun onStop() { super.onStop() context?.let { NiceFeedPreferences.saveLastViewedFeedId(it, feedId) } } override fun onDetach() { super.onDetach() callbacks = null } companion object { const val FOLDER = "FOLDER" const val FOLDER_NEW = "FOLDER_NEW" const val FOLDER_STARRED = "FOLDER_STARRED" private const val ARG_FEED_ID = "ARG_FEED_ID" private const val ARG_ENTRY_ID = "ARG_ENTRY_ID" private const val ARG_BLOCK_AUTOUPDATE = "ARG_BLOCK_AUTOUPDATE" fun newInstance( feedId: String?, entryId: String? = null, blockAutoUpdate: Boolean = false ): EntryListFragment { return EntryListFragment().apply { arguments = Bundle().apply { putString(ARG_FEED_ID, feedId) putString(ARG_ENTRY_ID, entryId) putBoolean(ARG_BLOCK_AUTOUPDATE, blockAutoUpdate) } } } } }
0
null
0
0
8a81efe5886b27efbce15b817d2eab9704543550
16,380
NiceFeed
MIT License
app/src/main/java/com/example/compose_mvvm_weather_app/utils/ExtensionFunction.kt
SaadKhanJadoon
714,546,065
false
{"Kotlin": 26842}
package com.example.compose_mvvm_weather_app.utils import com.example.compose_mvvm_weather_app.R import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale import java.util.regex.Pattern fun todayDate(): String { val calendar = Calendar.getInstance().time val df = SimpleDateFormat("EEEE, MMMM d", Locale.getDefault()) return df.format(calendar) } fun fahrenheitToCelsius(temperatureInFahrenheit: Double): Int { val celsius = (temperatureInFahrenheit - 32) * 5 / 9 return celsius.toInt() } fun metersToKilometers(meters: Int): Int { return meters / 1000 } fun capitalize(capString: String): String { val capBuffer = StringBuffer() val capMatcher = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(capString) while (capMatcher.find()) { capMatcher.appendReplacement( capBuffer, (capMatcher.group(1)?.uppercase(Locale.ROOT)) + (capMatcher.group(2) ?.lowercase(Locale.ROOT)) ) } return capMatcher.appendTail(capBuffer).toString() } fun getWeatherIcon(weather: String): Int { return when (weather) { "clear sky" -> R.drawable.clear_sky "few clouds" -> R.drawable.few_clouds "shower rain" -> R.drawable.shower_rain "thunderstorm" -> R.drawable.thunderstorm "broken clouds" -> R.drawable.broken_clouds "overcast clouds" -> R.drawable.scattered_clouds "scattered clouds" -> R.drawable.scattered_clouds "rain" -> R.drawable.rain "snow" -> R.drawable.snow "mist" -> R.drawable.mist else -> R.drawable.few_clouds } }
0
Kotlin
0
2
65ec8fdc2af5188996b462288ef7ad6980a66f38
1,661
Compose-MVVM-Weather-App
MIT License
src/main/kotlin/com/baulsupp/oksocial/services/uber/UberAuthInterceptor.kt
MaTriXy
129,725,910
true
{"Kotlin": 426653, "Shell": 9764}
package com.baulsupp.oksocial.services.uber import com.baulsupp.oksocial.authenticator.AuthInterceptor import com.baulsupp.oksocial.authenticator.ValidatedCredentials import com.baulsupp.oksocial.authenticator.oauth2.Oauth2ServiceDefinition import com.baulsupp.oksocial.authenticator.oauth2.Oauth2Token import com.baulsupp.oksocial.completion.ApiCompleter import com.baulsupp.oksocial.completion.BaseUrlCompleter import com.baulsupp.oksocial.completion.CompletionVariableCache import com.baulsupp.oksocial.completion.UrlList import com.baulsupp.oksocial.credentials.CredentialsStore import com.baulsupp.oksocial.credentials.NoToken import com.baulsupp.oksocial.credentials.Token import com.baulsupp.oksocial.credentials.TokenValue import com.baulsupp.oksocial.kotlin.queryMap import com.baulsupp.oksocial.kotlin.requestBuilder import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.oksocial.secrets.Secrets import okhttp3.FormBody import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response class UberAuthInterceptor : AuthInterceptor<Oauth2Token>() { override fun serviceDefinition(): Oauth2ServiceDefinition { return Oauth2ServiceDefinition(host(), "Uber API", "uber", "https://developer.uber.com/docs/riders/references/api", "https://developer.uber.com/dashboard/") } private fun host(): String = "api.uber.com" override fun intercept(chain: Interceptor.Chain, credentials: Oauth2Token): Response { var request = chain.request() val token = credentials.accessToken request = request.newBuilder().addHeader("Authorization", "Bearer $token").build() return chain.proceed(request) } override suspend fun authorize( client: OkHttpClient, outputHandler: OutputHandler<Response>, authArguments: List<String> ): Oauth2Token { val clientId = Secrets.prompt("Uber Client Id", "uber.clientId", "", false) val clientSecret = Secrets.prompt("Uber Client Secret", "uber.clientSecret", "", true) return UberAuthFlow.login(client, outputHandler, clientId, clientSecret) } override fun apiCompleter( prefix: String, client: OkHttpClient, credentialsStore: CredentialsStore, completionVariableCache: CompletionVariableCache, tokenSet: Token ): ApiCompleter { return BaseUrlCompleter(UrlList.fromResource(name())!!, hosts(), completionVariableCache) } override suspend fun validate( client: OkHttpClient, credentials: Oauth2Token ): ValidatedCredentials { val map = client.queryMap<Any>("https://api.uber.com/v1/me", TokenValue(credentials)) return ValidatedCredentials("${map["first_name"]} ${map["last_name"]}") } override fun hosts(): Set<String> = setOf("api.uber.com", "login.uber.com", "sandbox-api.uber.com") override fun canRenew(credentials: Oauth2Token): Boolean = credentials.isRenewable() override suspend fun renew(client: OkHttpClient, credentials: Oauth2Token): Oauth2Token? { val tokenUrl = "https://login.uber.com/oauth/v2/token" val body = FormBody.Builder().add("client_id", credentials.clientId!!) .add("client_secret", credentials.clientSecret!!) .add("refresh_token", credentials.refreshToken!!) .add("grant_type", "refresh_token") .build() val request = requestBuilder(tokenUrl, NoToken).method("POST", body).build() val responseMap = client.queryMap<Any>(request) return Oauth2Token(responseMap["access_token"] as String, responseMap["refresh_token"] as String, credentials.clientId, credentials.clientSecret) } }
0
Kotlin
0
0
c4da9b2858cb9477b96fabb36b31a60f716e3e86
3,570
oksocial
Apache License 2.0
internalServer/src/main/java/ru/rpuxa/internalserver/wireless/AbstractWirelessDevice.kt
rpuxa
162,908,097
false
null
package ru.rpuxa.internalserver.wireless import ru.rpuxa.internalserver.wifi.WifiDevice abstract class AbstractWirelessDevice(val wifiDevice: WifiDevice) : WirelessDevice { override lateinit var passport: Passport override var isAdbConnected = false abstract fun updateDevicePassport(): WirelessPromise<Passport> abstract fun checkAdbConnection(): WirelessPromise<Boolean> protected fun setPassport() { @Suppress("LeakingThis") passport = updateDevicePassport().getAnswerBlocking() ?: run { wifiDevice.close() return } } protected fun <T> sendMessage(command: Int, data: Any? = null): WirelessPromise<T> { val promise = WirelessPromiseImpl<T>() wifiDevice.stream.sendMessage<T>(command, data) .onMessage(promise::answer) .onTimeout { promise.error(WirelessErrors.TIMEOUT) } return promise } protected fun <T> toBlockingPromise(value: T) = WirelessPromiseImpl<T>().apply { answer(value) } override fun equals(other: Any?): Boolean { if (other === this) return true if (other !is AbstractWirelessDevice) return false return other.wifiDevice.lastAddressByte == wifiDevice.lastAddressByte } override fun hashCode(): Int { return wifiDevice.lastAddressByte } }
0
Kotlin
2
8
26074194e3df70e673f4595bdbc7090f2ba07593
1,399
SuperWirelessAdb
Apache License 2.0
src/all/unionmangas/src/eu/kanade/tachiyomi/extension/all/unionmangas/UnionMangasFactory.kt
komikku-app
720,497,299
false
{"Kotlin": 6732685, "JavaScript": 2160}
package eu.kanade.tachiyomi.extension.all.unionmangas import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceFactory class UnionMangasFactory : SourceFactory { override fun createSources(): List<Source> = languages.map { UnionMangas(it) } } class LanguageOption(val lang: String, val infix: String = lang, val mangaSubstring: String = infix) val languages = listOf( LanguageOption("pt-BR", "manga-br"), LanguageOption("ru", "manga-ru", "mangas"), )
21
Kotlin
5
73
87609401d853a38484e0e4c4f1f30c7bdb42b172
491
komikku-extensions
Apache License 2.0
core/data/src/main/kotlin/io/github/edwinchang24/salvage/core/data/repository/DefaultItemRepository.kt
EdwinChang24
653,775,661
false
null
package io.github.edwinchang24.salvage.core.data.repository import io.github.edwinchang24.salvage.core.data.model.asEntity import io.github.edwinchang24.salvage.core.database.dao.ItemDao import io.github.edwinchang24.salvage.core.database.model.asExternalModel import io.github.edwinchang24.salvage.core.model.Item import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject class DefaultItemRepository @Inject constructor(private val itemDao: ItemDao) : ItemRepository { override fun getItem(id: String) = itemDao.getItemEntity(id).map { it.asExternalModel() } override fun getItems(): Flow<List<Item>> = itemDao.getAll().map { it.map { itemEntity -> itemEntity.asExternalModel() } } override suspend fun addItem(item: Item) = itemDao.insertAll(item.asEntity()) override suspend fun deleteItem(item: Item) = itemDao.delete(item.asEntity()) override suspend fun updateItem(item: Item) = itemDao.update(item.asEntity()) }
7
Kotlin
0
0
d3f348aed90b38aad1811d32e1a0bf7bf47bb6ed
992
salvage
MIT License
app/src/main/java/com/example/androiddevchallenge/ui/screens/home/YogaList.kt
moinkhan-in
347,319,206
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.androiddevchallenge.ui.screens.home import androidx.annotation.DrawableRes import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.paddingFromBaseline import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Text 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.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.R import java.util.Locale val yogaItems = arrayListOf( AlignBodyOrMindItem("Inversions", R.drawable.yoga1), AlignBodyOrMindItem("Quick yoga", R.drawable.yoga2), AlignBodyOrMindItem("Stretching", R.drawable.yoga3), AlignBodyOrMindItem("Tabata", R.drawable.yoga4), AlignBodyOrMindItem("HIIT", R.drawable.yoga5), AlignBodyOrMindItem("Pre-natal yoga", R.drawable.yoga6), ) val mindItems = arrayListOf( AlignBodyOrMindItem("Meditade", R.drawable.mind1), AlignBodyOrMindItem("With kids", R.drawable.mind2), AlignBodyOrMindItem("Aromatherapy", R.drawable.mind3), AlignBodyOrMindItem("On the go", R.drawable.mind4), AlignBodyOrMindItem("With pets", R.drawable.mind5), AlignBodyOrMindItem("High stress", R.drawable.mind6), ) @Composable fun AlignBodyMindList( modifier: Modifier = Modifier, label: String, yogaBodyOfMindList: List<AlignBodyOrMindItem> ) { Text( modifier = modifier .padding(top = 8.dp) .paddingFromBaseline(top = 40.dp), style = MaterialTheme.typography.h2, text = label.toUpperCase(Locale.getDefault()) ) LazyRow { items(yogaBodyOfMindList) { item -> AlignBodyMind(item = item) } } } @Composable fun AlignBodyMind(item: AlignBodyOrMindItem) { Column( Modifier .padding(vertical = 4.dp) .padding(end = 8.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Image( modifier = Modifier .size(88.dp) .clip(CircleShape), painter = painterResource(item.drawableId), contentDescription = item.label, contentScale = ContentScale.FillBounds ) Text( modifier = Modifier.paddingFromBaseline(top = 24.dp), text = item.label, style = MaterialTheme.typography.h3 ) } } @Composable @Preview fun YogaItemPreview() { AlignBodyMind(item = yogaItems[0]) } data class AlignBodyOrMindItem( val label: String, @DrawableRes val drawableId: Int )
0
Kotlin
0
0
b52a3a22031ae01f5c70b62538ebd4d2f0fce4b5
3,676
android-dev-challange-compose-w3
Apache License 2.0
src/main/kotlin/tech/alexib/plaid/client/model/SandboxProcessorTokenCreateRequestOptions.kt
ruffCode
353,222,079
false
null
/* * Copyright 2020 Alexi Bre * * 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 tech.alexib.plaid.client.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * An optional set of options to be used when configuring the Item. If specified, must not be * `null`. * @param overrideUsername Test username to use for the creation of the Sandbox Item. Default value * is `user_good`. * @param overridePassword Test password to use for the creation of the Sandbox Item. Default value * is `pass_good`. */ @Serializable data class SandboxProcessorTokenCreateRequestOptions( @SerialName("override_username") val overrideUsername: SandboxOverrideUsername? = null, @SerialName("override_password") val overridePassword: SandboxOverridePassword? = null )
0
Kotlin
0
0
f937243bdd86fc656097f2154c08e8aa3dad399a
1,329
plaid-kotlin
Apache License 2.0
app/src/main/java/asia/fourtitude/recipe/data/model/search/SearchResponse.kt
wafi89
639,276,475
false
null
package asia.fourtitude.recipe.data.model.search import com.google.gson.annotations.SerializedName data class SearchResponse( @SerializedName("results") val results: List<Photo> ) data class Photo( @SerializedName("urls") val urls: Urls ) data class Urls( @SerializedName("regular") val regular: String )
0
Kotlin
0
0
196163a4e59a2b91ead456264ff914dd4b8a56f5
334
Recipe-Book
Apache License 2.0
tv/src/main/java/online/noxilab/tmdb/ui/presenters/HeaderIconItemPresenter.kt
Tiarait
306,028,357
false
null
package online.noxilab.tmdb.ui.presenters import android.content.Context import androidx.leanback.widget.Presenter import android.view.ViewGroup import androidx.leanback.widget.RowHeaderPresenter import android.widget.TextView import android.view.LayoutInflater import android.widget.ImageView import androidx.leanback.widget.PageRow import online.noxilab.tmdb.models.HeaderIconItem import android.text.TextUtils import android.view.View import androidx.core.content.ContextCompat import online.noxilab.tmdb.AppConstants import online.noxilab.tmdb.R /** * A CardPresenter is used to generate Views and bind Objects to them on demand. * It contains an ImageCardView. */ class HeaderIconItemPresenter : RowHeaderPresenter() { override fun onCreateViewHolder(viewGroup: ViewGroup): ViewHolder { val inflater = viewGroup.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val view = inflater.inflate(R.layout.header_icon_item, null) val label = view.findViewById<TextView>(R.id.header_label) val icon = view.findViewById<ImageView>(R.id.header_icon) icon.setColorFilter(ContextCompat.getColor(view.context, R.color.card_secondary_text ), android.graphics.PorterDuff.Mode.MULTIPLY); label.setTextColor(ContextCompat.getColor(view.context, R.color.card_secondary_text )) label.ellipsize = TextUtils.TruncateAt.END view.setOnFocusChangeListener { v, b -> if (b) { icon.setColorFilter(ContextCompat.getColor(v.context, R.color.card_primary_text ), android.graphics.PorterDuff.Mode.MULTIPLY); label.setTextColor(ContextCompat.getColor(v.context, R.color.card_primary_text )) label.ellipsize = TextUtils.TruncateAt.MARQUEE } else { icon.setColorFilter(ContextCompat.getColor(v.context, R.color.card_secondary_text ), android.graphics.PorterDuff.Mode.MULTIPLY); label.setTextColor(ContextCompat.getColor(v.context, R.color.card_secondary_text )) label.ellipsize = TextUtils.TruncateAt.END } } return ViewHolder(view) } override fun onBindViewHolder(viewHolder: Presenter.ViewHolder, o: Any?) { val iconHeaderItem = (o as PageRow).headerItem as HeaderIconItem val rootView = viewHolder.view rootView.alpha = .7f val iconView = rootView.findViewById(R.id.header_icon) as ImageView val iconResId = iconHeaderItem.iconResId if (iconResId != HeaderIconItem.ICON_NONE) { // Show icon only when it is set. val icon = rootView.resources.getDrawable(iconResId, null) iconView.setImageDrawable(icon) } val label = rootView.findViewById(R.id.header_label) as TextView val space = rootView.findViewById<View>(R.id.space) if (iconHeaderItem.name == AppConstants.SPACE_TEXT) { iconView.visibility = View.GONE label.visibility = View.GONE space.visibility = View.VISIBLE rootView.isFocusable = false } else { space.visibility = View.GONE iconView.visibility = View.VISIBLE label.visibility = View.VISIBLE rootView.isFocusable = true label.text = iconHeaderItem.name } } override fun onUnbindViewHolder(viewHolder: Presenter.ViewHolder) { } override fun onSelectLevelChanged(holder: ViewHolder) { holder.view.alpha = .7f } }
0
Kotlin
2
7
081388fa8e1507ae318e11849c57cd6a63417e26
3,717
Android_Tv_TMDB
Apache License 2.0
app/src/main/java/com/otikev/codecensus/widget/SquareCardView.kt
otikev
160,915,938
false
null
package com.otikev.codecensus.widget import android.content.Context import android.support.v7.widget.CardView import android.util.AttributeSet /** * Created by kevin on 08/12/18 at 19:37 */ class SquareCardView(context: Context, attrs: AttributeSet) : CardView(context, attrs) { override fun onMeasure(widthMeasureSpec: Int, ignoredHeightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, widthMeasureSpec) } }
0
Kotlin
0
0
8166dc6e7e49ff50f39eac3ec5becfa6e0d5daab
436
code-census
MIT License
pyrexia-android/app/src/main/java/com/cryptomcgrath/pyrexia/thermostat/ThermostatViewModel.kt
cryptomcgrath
541,272,434
false
{"Kotlin": 218872}
package com.cryptomcgrath.pyrexia.thermostat import android.util.Log import androidx.databinding.ObservableBoolean import androidx.databinding.ObservableInt import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.cryptomcgrath.pyrexia.AUTO_REFRESH_INTERVAL import com.cryptomcgrath.pyrexia.CentralEvent import com.cryptomcgrath.pyrexia.CentralState import com.cryptomcgrath.pyrexia.DevicesRepo import com.cryptomcgrath.pyrexia.R import com.cryptomcgrath.pyrexia.model.Program import com.cryptomcgrath.pyrexia.model.PyDevice import com.cryptomcgrath.pyrexia.model.VirtualStat import com.cryptomcgrath.pyrexia.service.isUnauthorized import com.edwardmcgrath.blueflux.core.Dispatcher import com.edwardmcgrath.blueflux.core.EventQueue import com.edwardmcgrath.blueflux.core.RxStore import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.rxkotlin.addTo import io.reactivex.rxkotlin.subscribeBy import io.reactivex.schedulers.Schedulers import java.util.* import java.util.concurrent.TimeUnit internal class ThermostatViewModel( private val repo: DevicesRepo, private val dispatcher: Dispatcher, private val store: RxStore<CentralState>, val pyDevice: PyDevice, val stat: VirtualStat): ViewModel() { class Factory(private val repo: DevicesRepo, private val dispatcher: Dispatcher, private val store: RxStore<CentralState>, private val pyDevice: PyDevice, private val stat: VirtualStat) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return ThermostatViewModel(repo, dispatcher, store, pyDevice, stat) as T } } internal val eventQueue = EventQueue.create() private val disposables = CompositeDisposable() private var autoRefreshDisposable: Disposable? = null private val statId = stat.program.id val backgroundColor = ObservableInt(R.color.black) val showError = ObservableBoolean(false) init { subscribeToStateChanges() dispatcher.getEventBus() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onNext = { event -> when (event) { is ThermostatEvent.OnClickRefill -> refill(event.pyDevice, event.controlId) is ThermostatEvent.RequestDisableStat -> disableStat(event.pyDevice, event.statId) is ThermostatEvent.RequestEnableStat -> enableStat(event.pyDevice, event.statId) is ThermostatEvent.RequestIncreaseTemp -> increaseTemp(event.pyDevice, event.statId) is ThermostatEvent.RequestDecreaseTemp -> decreaseTemp(event.pyDevice, event.statId) is ThermostatEvent.RequestHistoryBefore -> fetchMoreHistoryIfNeeded(event.pyDevice, event.statId, event.beforeTs.toLong()) } eventQueue.post(event) }, onError = { // ignore } ).addTo(disposables) } private fun subscribeToStateChanges() { store.stateStream.subscribeBy( onNext = { updateUi(it.getDeviceState(pyDevice)) }, onError = { // ignore } ).addTo(disposables) } private fun updateUi(deviceState: CentralState.DeviceState) { showError.set( deviceState.connectionError != null ) deviceState.stats.firstOrNull { it.program.id == statId }?.let { backgroundColor.set( when { !it.program.enabled -> R.color.grey42 it.control.controlOn && it.program.mode == Program.Mode.HEAT -> R.color.heating it.control.controlOn && it.program.mode == Program.Mode.COOL -> R.color.cooling else -> R.color.cobalt } ) } } fun refreshStats() { repo.refreshStats(pyDevice) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onComplete = { if (autoRefreshDisposable == null) { setupAutoRefresh() } }, onError = { if (it.isUnauthorized()) { dispatcher.post(CentralEvent.GoToLogin(pyDevice)) } else { eventQueue.post(ThermostatEvent.ShowNetworkError(it, true)) } } ).addTo(disposables) } private fun setupAutoRefresh() { autoRefreshDisposable = Observable.interval(AUTO_REFRESH_INTERVAL, TimeUnit.SECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onNext = { refreshStats() }, onError = { // ignore } ) } fun cancelAutoRefresh() { autoRefreshDisposable?.dispose() } private fun fetchMoreHistoryIfNeeded(pyDevice: PyDevice, statId: Int, timeStamp: Long) { Single.create { val pages = store.state.getDeviceState(pyDevice).historyPages.filter { it.statId == statId && it.minTs != null && it.maxTs != null }.sortedBy { it.minTs } val isAlreadyInPage = pages.any { timeStamp >= (it.minTs ?: Int.MAX_VALUE) && timeStamp <= (it.maxTs ?: Int.MIN_VALUE) } val pageAbove = pages.filter { timeStamp < (it.minTs ?: 0) }.minByOrNull { (it.minTs ?: Int.MAX_VALUE) - timeStamp } val minPage = store.state.getDeviceState(pyDevice).getMinHistoryPageForStat(statId) //val isTsNeeded = timeStamp < (minPage?.minTs ?: Int.MAX_VALUE) val isTsNeeded = !isAlreadyInPage val isAllDataLoaded = minPage?.pageend == true //val requestBeforeTs = minPage?.minTs val requestBeforeTs = pageAbove?.minTs ?: timeStamp.toInt() it.onSuccess(Pair(requestBeforeTs ?: 0, !isAllDataLoaded && isTsNeeded)) }.flatMapCompletable { (ts, needed) -> if (needed) { Log.d(TAG, "fetchMoreHistory timeStamp = ${ts}") repo.fetchHistory( pyDevice = pyDevice, statId = statId, startTs = null, endTs = ts ).toCompletable() } else { Completable.complete() } }.subscribeOn(Schedulers.single()).observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onComplete = { // success }, onError = { // ignore } ).addTo(disposables) } fun onClickConnectionError() { //store.state.connectionError?.let { // eventQueue.post(UiEvent.ServiceError(it)) // } } private fun refill(pyDevice: PyDevice, controlId: Int) { repo.refill(pyDevice, controlId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onComplete = { // ignore }, onError = { eventQueue.post(ThermostatEvent.ShowNetworkError(it, false)) } ).addTo(disposables) } private fun disableStat(pyDevice: PyDevice, statId: Int) { repo.disableStat(pyDevice, statId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onComplete = { // ignore }, onError = { eventQueue.post(ThermostatEvent.ShowNetworkError(it, false)) } ).addTo(disposables) } private fun enableStat(pyDevice: PyDevice, statId: Int) { repo.enableStat(pyDevice, statId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onComplete = { // ignore }, onError = { eventQueue.post(ThermostatEvent.ShowNetworkError(it, false)) } ).addTo(disposables) } private fun increaseTemp(pyDevice: PyDevice, statId: Int) { repo.increaseTemp(pyDevice,statId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onComplete = { // ignore }, onError = { eventQueue.post(ThermostatEvent.ShowNetworkError(it, false)) } ).addTo(disposables) } private fun decreaseTemp(pyDevice: PyDevice, statId: Int) { repo.decreaseTemp(pyDevice,statId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onComplete = { // ignore }, onError = { eventQueue.post(ThermostatEvent.ShowNetworkError(it, false)) } ).addTo(disposables) } override fun onCleared() { super.onCleared() disposables.clear() } } private const val TAG="ThermostatViewModel" fun String.sentenceCase(): String { return this.lowercase(Locale.getDefault()).replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } }
2
Kotlin
0
2
5c854f70d51a1427e26616b4a96ef074dc345aa3
10,252
pyrexia-android
MIT License
syftlib/src/main/java/org/openmined/syft/networking/requests/MessageTypes.kt
rav1kantsingh
262,021,619
true
{"Kotlin": 139892, "Java": 657}
package org.openmined.syft.networking.requests import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import org.openmined.syft.networking.datamodels.NetworkModels interface MessageTypes { val value: String } interface ResponseMessageTypes : MessageTypes { val jsonParser: Json fun parseJson(jsonString: String): NetworkModels fun serialize(obj: NetworkModels): JsonElement } enum class DOWNLOAD( override val value: String ) : MessageTypes { TRAININGPLAN("federated/get-training-plan"), PROTOCOL("federated/get-protocol"), MODEL("federated/get-model") } enum class WebRTCMessageTypes(override val value: String) : MessageTypes { CANDIDATE("candidate"), OFFER("offer"), ANSWER("answer"), WEBRTC_JOIN_ROOM("webrtc: join-room"), WEBRTC_INTERNAL_MESSAGE("webrtc: internal-message") }
0
Kotlin
0
0
be671626ec777ccfcd7985496a144250f2425053
868
KotlinSyft
Apache License 2.0
app/src/main/java/com/md/sadman/oneplustwoequalsthreeremake/interpreter/node/EquationNode.kt
PsykickSam
521,997,041
false
null
package com.md.sadman.oneplustwoequalsthreeremake.interpreter.node import com.md.sadman.oneplustwoequalsthreeremake.interpreter.constants.Constant import com.md.sadman.oneplustwoequalsthreeremake.interpreter.constants.MathOperatorEnum /** * This is the base equation node form factor, contains number, left number item (A), * right number item (B), left equation node (A), right equation node (B) and operator * (Math Operator). It is used for creating equation of number and node with operator * or number only formation equation to evaluate basic mathematical operation. This is * basically the main structure of the binary tree. * * @author Md. Sadman * * @param number * @param itemA * @param itemB * @param nodeA * @param nodeB * @param mathOperatorEnum */ class EquationNode(private val number: NumberNode?, private val itemA: NumberNode?, private val itemB: NumberNode?, private val nodeA: EquationNode?, private val nodeB: EquationNode?, private val mathOperatorEnum: MathOperatorEnum?) { fun getNumber(): NumberNode? { return this.number } fun getItemA(): NumberNode? { return this.itemA } fun getItemB(): NumberNode? { return this.itemB } fun getNodeA(): EquationNode? { return this.nodeA } fun getNodeB(): EquationNode? { return this.nodeB } fun getOperator(): MathOperatorEnum? { return mathOperatorEnum; } override fun toString(): String { var tOperator = "" when (mathOperatorEnum) { MathOperatorEnum.PLUS -> { tOperator = Constant.OP_PLS.toString() } MathOperatorEnum.MINUS -> { tOperator = Constant.OP_MIN.toString() } MathOperatorEnum.MULTIPLY -> { tOperator = Constant.OP_MUL.toString() } MathOperatorEnum.DIVIDE -> { tOperator = Constant.OP_DIV.toString() } null -> { tOperator = Constant.OP_NONE.toString() } } if (number != null) return number.toString() return "(${if (this.itemA == null) this.nodeA.toString() else this.itemA.toString()} ${tOperator} ${if (this.itemB == null) { if (mathOperatorEnum == MathOperatorEnum.MULTIPLY || mathOperatorEnum == MathOperatorEnum.DIVIDE) { this.nodeA.toString() } else { this.nodeB.toString() } } else this.itemB.toString()})" } }
0
Kotlin
0
0
852630bc8ffef7020e20dfcf57b1751544eecd69
2,551
OnePlusTwoEqualsThree
MIT License
app/src/main/java/com/doro/marsweatherapp/main/domain/repository/WeatherRepository.kt
beetsolutions
336,288,689
true
{"Kotlin": 38292}
package com.doro.marsweatherapp.main.domain.repository import com.doro.marsweatherapp.main.data.repository.model.Resource import com.doro.marsweatherapp.main.domain.model.WeatherInformation import kotlinx.coroutines.flow.Flow interface WeatherRepository { fun getWeatherDetails(): Flow<Resource<List<WeatherInformation>>> }
0
Kotlin
0
0
8d7327735f32c68fc903ce2ad64a6689790798fd
329
code-challenge-frontend
MIT License
app/src/main/java/com/doro/marsweatherapp/main/domain/repository/WeatherRepository.kt
beetsolutions
336,288,689
true
{"Kotlin": 38292}
package com.doro.marsweatherapp.main.domain.repository import com.doro.marsweatherapp.main.data.repository.model.Resource import com.doro.marsweatherapp.main.domain.model.WeatherInformation import kotlinx.coroutines.flow.Flow interface WeatherRepository { fun getWeatherDetails(): Flow<Resource<List<WeatherInformation>>> }
0
Kotlin
0
0
8d7327735f32c68fc903ce2ad64a6689790798fd
329
code-challenge-frontend
MIT License
graph/graph-adapter-output-spring-data-neo4j-sdn6/src/main/kotlin/org/orkg/graph/adapter/output/neo4j/ModelIDs.kt
TIBHannover
197,416,205
false
{"Kotlin": 6124464, "Cypher": 220623, "Python": 4881, "Shell": 2904, "Groovy": 1936, "HTML": 240, "Batchfile": 82}
package org.orkg.graph.adapter.output.neo4j const val BENCHMARK_CLASS = "C14022" const val BENCHMARK_PREDICATE = "PWC_HAS_BENCHMARK" const val DATASET_CLASS = "BENCHMARK_DATASET" const val DATASET_PREDICATE = "P2005"
0
Kotlin
0
4
80f66b3b43fa199dedeffc4732c2d82720699ee7
218
orkg-backend
MIT License
src/main/kotlin/variables/DataTypeChar.kt
softbluecursoscode
603,710,984
false
{"Kotlin": 53437}
package variables fun main() { val c: Char = 'A' println(c) println(c.code) val i = 65 println(i.toChar()) val c2 = '1' println(c2.isDigit()) println(c2.isUpperCase()) println(c2.digitToInt()) }
0
Kotlin
2
5
d9d3b179af5fcf851947fe59fe4e13a825532417
241
kotlin
MIT License
data/src/main/java/com/kennyc/dashweather/data/model/WeatherIcon.kt
Kennyc1012
105,380,988
false
null
package com.kennyc.dashweather.data.model enum class WeatherIcon { CLEAR, CLEAR_NIGHT, PARTLY_CLOUDY, PARTLY_CLOUDY_NIGHT, CLOUDY, RAIN_SHOWERS, RAIN_SHOWERS_NIGHT, RAIN, RAIN_NIGHT, THUNDER_STORM, SNOW, FOG }
0
Kotlin
2
0
212ce9f0dc434a537530b3904b1763684f7f6915
258
DashWeatherExtension
Apache License 2.0
src/main/kotlin/com/bcnc/photoalbum/exceptions/ExceptionHandler.kt
MVCx9
836,230,362
false
{"Kotlin": 14441}
package com.bcnc.photoalbum.exceptions import org.springframework.http.HttpStatus import org.springframework.web.ErrorResponse import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.ResponseStatus // General API Exception open class ApiException(message: String) : RuntimeException(message) // Specific Exception for Resource Not Found class ResourceNotFoundException(message: String) : ApiException(message) // Specific Exception for API Call Failure class ApiCallException(message: String) : ApiException(message) @ControllerAdvice class GlobalExceptionHandler { @ExceptionHandler(ApiException::class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) fun handleApiException(ex: ApiException): ErrorResponse { return ErrorResponse.create(ex, HttpStatus.INTERNAL_SERVER_ERROR, ex.message.toString()) } @ExceptionHandler(ResourceNotFoundException::class) @ResponseStatus(HttpStatus.NOT_FOUND) fun handleResourceNotFoundException(ex: ResourceNotFoundException): ErrorResponse { return ErrorResponse.create(ex, HttpStatus.NOT_FOUND, ex.message.toString()) } @ExceptionHandler(ApiCallException::class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) fun handleApiCallException(ex: ApiCallException): ErrorResponse { return ErrorResponse.create(ex, HttpStatus.INTERNAL_SERVER_ERROR, ex.message.toString()) } }
0
Kotlin
0
0
7c2e37a76e16d8dce33e21ab5fd3b8f222aac0da
1,509
PhotoAlbumJsonPlacerholder
MIT License
src/main/kotlin/com/bcnc/photoalbum/exceptions/ExceptionHandler.kt
MVCx9
836,230,362
false
{"Kotlin": 14441}
package com.bcnc.photoalbum.exceptions import org.springframework.http.HttpStatus import org.springframework.web.ErrorResponse import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.ResponseStatus // General API Exception open class ApiException(message: String) : RuntimeException(message) // Specific Exception for Resource Not Found class ResourceNotFoundException(message: String) : ApiException(message) // Specific Exception for API Call Failure class ApiCallException(message: String) : ApiException(message) @ControllerAdvice class GlobalExceptionHandler { @ExceptionHandler(ApiException::class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) fun handleApiException(ex: ApiException): ErrorResponse { return ErrorResponse.create(ex, HttpStatus.INTERNAL_SERVER_ERROR, ex.message.toString()) } @ExceptionHandler(ResourceNotFoundException::class) @ResponseStatus(HttpStatus.NOT_FOUND) fun handleResourceNotFoundException(ex: ResourceNotFoundException): ErrorResponse { return ErrorResponse.create(ex, HttpStatus.NOT_FOUND, ex.message.toString()) } @ExceptionHandler(ApiCallException::class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) fun handleApiCallException(ex: ApiCallException): ErrorResponse { return ErrorResponse.create(ex, HttpStatus.INTERNAL_SERVER_ERROR, ex.message.toString()) } }
0
Kotlin
0
0
7c2e37a76e16d8dce33e21ab5fd3b8f222aac0da
1,509
PhotoAlbumJsonPlacerholder
MIT License
core/src/main/kotlin/io/github/restioson/kettle/entity/component/BodyComponentBuilder.kt
Restioson
91,720,429
false
null
package io.github.restioson.kettle.entity.component import com.badlogic.ashley.core.PooledEngine import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.Body import com.badlogic.gdx.physics.box2d.BodyDef import com.badlogic.gdx.physics.box2d.FixtureDef import com.badlogic.gdx.physics.box2d.JointDef import com.badlogic.gdx.physics.box2d.PolygonShape import com.badlogic.gdx.physics.box2d.Shape import com.badlogic.gdx.physics.box2d.World import com.badlogic.gdx.utils.Array /** * Builder for [BodyComponent]s * * Allows serialization of the component, due to storing definitions (e.g BodyDefs) */ class BodyComponentBuilder(jointDefSize: Int = 2, fixtureDefSize: Int = 1) { /** * Class representing a joint between a body definition and the builder's body definition */ class BodyDefJoint(val otherBodyDef: BodyDef, val type: JointDef.JointType, val collideConnected: Boolean = false) /** * Class representing a joint between a body and the builders body definition */ class BodyJoint(val otherBody: Body, val type: JointDef.JointType, val collideConnected: Boolean = false) var bodyDef: BodyDef? = null val bodyDefJoints = Array<BodyDefJoint>(false, jointDefSize) val bodyJoints = Array<BodyJoint>(false, jointDefSize) val fixtures = Array<FixtureDef>(false, fixtureDefSize) val shapesToDispose = Array<Shape>(false, fixtureDefSize) /** * Sets the body definition * * @param definition the definition * * @return builder */ fun withBody(definition: BodyDef): BodyComponentBuilder { this.bodyDef = definition return this } /** * Sets the body definition to be a definition with the following parameters: * * @param type type of the body * @param position the position of the body, defaultedly 0, 0 * @param angle the angle of the body, defaultedly 0, 0 * * @return builder */ fun withBody( type: BodyDef.BodyType, position: Vector2 = Vector2(0f, 0f), angle: Float = 0f ): BodyComponentBuilder { this.bodyDef = BodyDef() this.bodyDef?.type = type this.bodyDef?.position?.set(position) this.bodyDef?.angle = angle return this } /** * Adds a [BodyDefJoint] to the builder * * @param definition the joint definition * * @return builder */ fun withJoint(definition: BodyDefJoint): BodyComponentBuilder { this.bodyDefJoints.add(definition) return this } /** * Adds a [BodyDefJoint] with the following params: * * @param type type of the joint * @param otherBody the other body definition * @param collideConnected collideConnected whether all connected bodies receive collision events, defaultedly false * * @return builder */ fun withJoint(type: JointDef.JointType, otherBody: BodyDef, collideConnected: Boolean = false): BodyComponentBuilder { this.bodyDefJoints.add(BodyDefJoint(otherBody, type, collideConnected)) return this } /** * Adds an array of joint definitions * * @param definitions the definitions */ fun withJoints(definitions: kotlin.Array<BodyDefJoint>): BodyComponentBuilder { this.bodyDefJoints.addAll(*definitions) return this } /** * Adds a [BodyJoint] to the builder * * @param definition the joint definition * * @return builder */ fun withJoint(definition: BodyJoint): BodyComponentBuilder { this.bodyJoints.add(definition) return this } /** * Adds a [BodyDefJoint] with the following params: * * @param type type of the joint * @param otherBody the other body definition * @param collideConnected collideConnected whether all connected bodies receive collision events, defaultedly false * * @return builder */ fun withJoint(type: JointDef.JointType, otherBody: Body, collideConnected: Boolean = false): BodyComponentBuilder { this.bodyJoints.add(BodyJoint(otherBody, type, collideConnected)) return this } /** * Adds an array of joint definitions * * @param definitions the definitions */ fun withJoints(definitions: kotlin.Array<BodyJoint>): BodyComponentBuilder { this.bodyJoints.addAll(*definitions) return this } /** * Adds a fixture * * @param definition fixture definition * * @return builder */ fun withFixture(definition: FixtureDef): BodyComponentBuilder { this.fixtures.add(definition) return this } /** * Adds a fixture with the following parameters: * * @param density density of the fixture, defaultedly 1f * @param points the points of the shape for the fixture * * @return builder */ fun withFixture(density: Float = 1f, points: kotlin.Array<Vector2>): BodyComponentBuilder { val shape = PolygonShape() shape.set(points) this.withFixture(shape, density) this.shapesToDispose.add(shape) return this } fun withFixture(density: Float = 1f, points: FloatArray): BodyComponentBuilder { val shape = PolygonShape() shape.set(points) this.withFixture(shape, density) this.shapesToDispose.add(shape) return this } /** * Adds a fixture with the following parameters: * * @param shape the shape for the fixture * @param density the density of the fixture, defaultedly 1f */ fun withFixture(shape: Shape, density: Float = 1f): BodyComponentBuilder { val fixture = FixtureDef() fixture.shape = shape fixture.density = density this.fixtures.add(fixture) return this } /** * Adds a array of fixtures * * @param fixtures fixtures to add * * @return builder */ fun withFixtures(fixtures: kotlin.Array<FixtureDef>): BodyComponentBuilder { this.fixtures.addAll(*fixtures) return this } /** * Adds a box fixture with the following parameters: * * @param width the width of the box's shape (passed directly to setAsBox) * @param height the height of the box's shape (passed directly to setAsBox) * @param density the density of the box, defaultedly 1f * * @return builder */ fun withBoxFixture(width: Float, height: Float, density: Float = 1f): BodyComponentBuilder { val shape = PolygonShape() shape.setAsBox(width, height) this.withFixture(shape, density) this.shapesToDispose.add(shape) return this } /** * Builds the builder into a [BodyComponent] * * @param engine entity engine to create component with * @param world Box2D world to create body with * * @return BodyComponent built */ fun build(engine: PooledEngine, world: World): BodyComponent { val component = engine.createComponent(BodyComponent::class.java) component.bodyDef = this.bodyDef ?: throw IllegalArgumentException("Builder requires BodyDefinition") component.body = world.createBody(this.bodyDef) for (joint in this.bodyDefJoints) { world.createJoint(JointDef().apply { type = joint.type collideConnected = joint.collideConnected bodyA = component.body bodyB = world.createBody(joint.otherBodyDef) }) } for (joint in this.bodyJoints) { world.createJoint(JointDef().apply { type = joint.type collideConnected = joint.collideConnected bodyA = component.body bodyB = joint.otherBody }) } for (fixture in this.fixtures) { component.body?.createFixture(fixture) component.fixtureDefs.add(fixture) } for (shape in this.shapesToDispose) { shape.dispose() } return component } }
0
Kotlin
0
4
84c2fb79c920144ed25f72bbdc6918213de39e94
8,200
kettle-engine
Apache License 2.0
app/src/main/java/com/sefford/artdrian/datasources/WallpaperDataSource.kt
Sefford
562,415,198
false
{"Kotlin": 86829}
package com.sefford.artdrian.datasources import arrow.core.Either import com.sefford.artdrian.datasources.WallpaperRepository.RepositoryError import com.sefford.artdrian.data.dto.MetadataDto import com.sefford.artdrian.model.Metadata interface WallpaperDataSource { suspend fun getAllMetadata(): Either<RepositoryError, List<Metadata>> suspend fun saveMetadata(metadataDtoList: List<Metadata>) suspend fun getWallpaperMetadata(id: String): Either<RepositoryError, Metadata> }
1
Kotlin
1
2
341cd0a2d30936aa40f6f00cf184a8aac6b8a39d
494
Artdrian
Apache License 2.0
src/main/kotlin/com/feliperodrigues/metodosdeajuste/Main.kt
pimbosi
745,949,513
false
{"Kotlin": 19654}
package com.feliperodrigues.metodosdeajuste import java.util.* // Função para limpar o terminal fun limparTerminal() { ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor() } // Função para exibir o menu principal fun menu() { limparTerminal() val scanner = Scanner(System.`in`) var input = 0 while (input != 6) { println("\t\tAjustes de funções por mínimos quadrados".uppercase()) println("\n\nEscolha uma opção de ajuste:") println("1. Ajuste Quadrático") println("2. Ajuste Linear") println("3. Ajuste Exponencial") println("4. Ajuste Polinomial") println("5. Ajuste Lei da Potência") println("6. Encerrar") try { input = scanner.nextInt() when (input) { 1 -> { limparTerminal() println("\t\t\t\tAJUSTE QUADRÁTICO\n\n") println("Digite o caminho do seu arquivo de dados ou arraste.") val nomeArquivo = scanner.next() val ajusteMinSquare = AjusteMinSquare() ajusteMinSquare.funcaoDeAjuste(nomeArquivo, grauPolinomial = 2) } 2 -> { limparTerminal() println("\t\t\t\tAJUSTE LINEAR\n\n") println("Digite o caminho do seu arquivo de dados ou arraste.") val nomeArquivo = scanner.next() val ajusteLinear = AjusteMinSquare() ajusteLinear.funcaoDeAjuste(nomeArquivo, grauPolinomial = 1) } 3 -> { limparTerminal() println("\t\t\t\tAJUSTE EXPONENCIAL\n\n") println("Digite o caminho do seu arquivo de dados ou arraste.") val nomeArquivo = scanner.next() val ajusteExp = AjusteExp() ajusteExp.funcaoDeAjuste(nomeArquivo, tipoAjuste = "exp") } 4 -> { limparTerminal() println("\t\t\t\tAJUSTE POLINOMIAL\n\n") println("Digite o caminho do seu arquivo de dados ou arraste.") val nomeArquivo = scanner.next() println("Digite o grau do polinômio: ") val grauPolinomial = scanner.nextInt() val ajusteQuadratico = AjusteMinSquare() ajusteQuadratico.funcaoDeAjuste(nomeArquivo, grauPolinomial) } 5 -> { limparTerminal() println("\t\t\t\tAJUSTE LEI DA POTÊNCIA\n\n") println("Digite o caminho do seu arquivo de dados ou arraste.") val nomeArquivo = scanner.next() val ajustePL = AjusteExp() ajustePL.funcaoDeAjuste(nomeArquivo, tipoAjuste = "powerlaw") } 6 -> { limparTerminal() println("Encerrando o programa...") } else -> println("Opção inválida. Por favor, escolha uma opção válida.") } } catch (e: InputMismatchException) { println("Erro: Entrada inválida. Certifique-se de inserir um número inteiro.") scanner.nextLine() // Limpar o buffer do scanner para evitar loop infinito } catch (e: Exception) { println("Erro inesperado: ${e.message}") scanner.nextLine() // Limpar o buffer do scanner para evitar loop infinito } } scanner.close() } // Função principal que inicia o programa fun main() { menu() }
0
Kotlin
0
0
ec458265eace13e085c9cf351bb29255351508ea
3,717
AjustePorMinimosQuadrados
Apache License 2.0
graphics/src/main/kotlin/matt/fx/graphics/wrapper/node/parent/parent.kt
mgroth0
497,866,693
false
null
package matt.fx.graphics.wrapper.node.parent import javafx.scene.Parent import matt.fx.graphics.service.wrapped import matt.fx.graphics.wrapper.node.NodeWrapper import matt.fx.graphics.wrapper.node.attachTo import matt.fx.graphics.wrapper.node.impl.NodeWrapperImpl import matt.fx.graphics.wrapper.node.line.poly.PolylineWrapper import matt.fx.graphics.wrapper.node.line.quad.QuadCurveWrapper import matt.fx.graphics.wrapper.node.shape.poly.PolygonWrapper import matt.fx.base.wrapper.obs.collect.list.createImmutableWrapper import matt.fx.base.wrapper.obs.obsval.toNullableROProp import matt.obs.bind.binding import matt.obs.col.olist.mappedlist.toMappedList interface ParentWrapper<C: NodeWrapper>: NodeWrapper { override val node: Parent fun polygon(vararg points: Number, op: PolygonWrapper.()->Unit = {}) = PolygonWrapper(*points.map(Number::toDouble).toDoubleArray()).attachTo(this, op) fun polyline(vararg points: Number, op: PolylineWrapper.()->Unit = {}) = PolylineWrapper(*points.map(Number::toDouble).toDoubleArray()).attachTo(this, op) fun quadcurve( startX: Number = 0.0, startY: Number = 0.0, controlX: Number = 0.0, controlY: Number = 0.0, endX: Number = 0.0, endY: Number = 0.0, op: QuadCurveWrapper.()->Unit = {} ) = QuadCurveWrapper( startX.toDouble(), startY.toDouble(), controlX.toDouble(), controlY.toDouble(), endX.toDouble(), endY.toDouble() ).attachTo(this, op) fun <CC: C> addr(child: CC, op: (CC.()->Unit)? = null): CC { op?.invoke(child) add(child) return child } } abstract class ParentWrapperImpl<out N: Parent, C: NodeWrapper>(node: N): NodeWrapperImpl<N>(node), ParentWrapper<C> { val childrenUnmodifiable by lazy { @Suppress("UNCHECKED_CAST") node.childrenUnmodifiable.createImmutableWrapper().toMappedList { it.wrapped() as C } } fun requestLayout() = node.requestLayout() } val NodeWrapper.parent get() : ParentWrapper<*>? = node.parent?.wrapped() as ParentWrapper<*>? fun NodeWrapper.parentProperty() = node.parentProperty().toNullableROProp().binding { it?.wrapped() } //@Suppress("UNCHECKED_CAST", "PLATFORM_CLASS_MAPPED_TO_KOTLIN") //private fun Parent.getChildrenReflectively(): MutableList<Node>? { // val getter = this.javaClass.findMethodByName("getChildren") // if (getter != null && java.util.List::class.java.isAssignableFrom(getter.returnType)) { // getter.isAccessible = true // return getter.invoke(this) as MutableList<Node> // } // return null //}
0
Kotlin
0
0
1e53b5a9ee3284fde6aa8205f056c011d1991d1b
2,484
fx
MIT License
domain/src/main/java/com/example/domain/usecase/auth/RegisterUseCase.kt
HUITDDURU
468,589,462
false
null
package com.example.domain.usecase.auth import com.example.domain.entity.auth.RegisterRequestEntity import com.example.domain.repository.AuthRepository import javax.inject.Inject class RegisterUseCase @Inject constructor( private val authRepository: AuthRepository ) { suspend fun invoke(body: RegisterRequestEntity) = authRepository.register(body) }
1
Kotlin
1
0
4d390a361b75289f76e4ce427a07e28a8c19d909
367
RUMA_Android
MIT License
example/test/kotlin/example/LeaveAcceptingTest.kt
CodeFabrikGmbH
350,377,385
false
null
package example import com.github.codefabrikgmbh.scenarios.given import example.setup.* import org.junit.Test class LeaveAcceptingTest : BasicTest() { @Test fun `accepting a leave as supervisor should work`() { given(::`employee with pending leave`) { `when the supervisor accepts the pending leave`() `then the employee should have an accepted leave`() }.run() } @Test fun `accepting a leave as an employee should result in an error`() { given(::`employee with pending leave`) { `when the employee accepts the pending leave`() }.runExpecting(IllegalArgumentException::class) } }
2
Kotlin
1
0
e52b6b13af689a463270794c0f49debfed4277a8
675
scenarios-kotlin
MIT License
libraries/config/src/package.kt
featurea
407,517,337
false
null
package featurea.config import featurea.content.contentTypes import featurea.rml.reader.RmlContent import featurea.runtime.Artifact /*dependencies*/ val artifact = Artifact("featurea.config") { "ConfigContent" to ConfigContent::class "ConfigReader" to ConfigReader::class static { val rmlContent: RmlContent = import() val configContent: ConfigContent = ConfigContent(rmlContent) provideComponent(configContent) provideComponent(ConfigReader(configContent)) } contentTypes { "ConfigContentType" to ::ConfigContentType } }
24
Kotlin
1
6
07074dc37a838f16ece90c19a4e8d45e743013d3
592
engine
MIT License
gto-support-snowplow/src/test/kotlin/org/ccci/gto/android/common/snowplow/events/CustomScreenViewTest.kt
CruGlobal
30,609,844
false
null
package org.ccci.gto.android.common.snowplow.events class CustomScreenViewTest : CustomEventTest<CustomScreenView>() { override fun event() = CustomScreenView("screen") }
9
Kotlin
2
8
529634f181da6f2c1394d07ed05594caf178706c
176
android-gto-support
MIT License
examples/src/test/java/com/markodevcic/samples/MainViewModelTest.kt
deva666
122,677,732
false
{"Kotlin": 15636}
package com.markodevcic.samples import com.markodevcic.peko.PermissionRequester import com.markodevcic.peko.PermissionResult import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.runBlocking import org.junit.Test import org.mockito.Mockito class MainViewModelTest { private val requester = Mockito.mock(PermissionRequester::class.java) private val sut = MainViewModel(requester) @Test fun testSingleGranted() { Mockito.`when`(requester.request("A")).thenReturn(flowOf(PermissionResult.Granted("A"))) Mockito.`when`(requester.request("B")).thenReturn(flowOf(PermissionResult.Denied.DeniedPermanently("B"))) runBlocking { assert(sut.isPermissionGranted("A")) assert(!sut.isPermissionGranted("B")) } } }
7
Kotlin
10
149
3d8c8c732f3d23e8132d888808fd89f28b992a6e
735
Peko
Apache License 2.0
app/src/main/java/com/kopai/shinkansen/view/authentication/register/RegisterViewModel.kt
kopiai
805,653,375
false
{"Kotlin": 147674}
package com.kopai.shinkansen.view.authentication.register import androidx.lifecycle.ViewModel import com.kopai.shinkansen.data.repository.ProductsRepository import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class RegisterViewModel @Inject constructor( private val productsRepository: ProductsRepository, ) : ViewModel() { fun register( name: String, email: String, password: String, ) = productsRepository.register(name, email, password) }
0
Kotlin
0
0
47442dcfa5771aa09b8c9d74ef42921ac3f4f88d
565
kopai-android
MIT License
app/src/main/java/com/memoir/base/MemoirApplication.kt
dbof10
509,308,735
false
null
package com.memoir.base import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MemoirApplication : Application() { }
0
Kotlin
0
0
1a657040416ff5dda569855f45c697e048769a02
161
ListNab
Apache License 2.0
src/main/kotlin/com/kilchichakov/fiveletters/model/dto/AuthRefreshRequest.kt
augur
194,393,890
false
{"Kotlin": 306716, "JavaScript": 3426, "Dockerfile": 135, "HTML": 9}
package com.kilchichakov.fiveletters.model.dto data class AuthRefreshRequest( val login: String, val refreshToken: String ) { override fun toString(): String { return "AuthRefreshRequest(login='$login', refreshToken(hash)=${refreshToken.hashCode()})" } }
0
Kotlin
0
0
64734f93bef1c36309caaece5b04fe8852872498
287
five-letters
MIT License
common/build/generated/sources/schemaCode/kotlin/main/io/portone/sdk/server/schemas/PaymentEscrow.kt
portone-io
809,427,199
false
{"Kotlin": 385115, "Java": 331}
package io.portone.sdk.server.schemas import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonClassDiscriminator /** * 에스크로 정보 * * V1 결제 건의 경우 타입이 REGISTERED 로 고정됩니다. */ @Serializable @JsonClassDiscriminator("status") public sealed interface PaymentEscrow
0
Kotlin
0
2
f984c4cc31aa64aad5cd0fa0497bdd490a0fe33a
286
server-sdk-jvm
MIT License
core/model/src/main/kotlin/com/espressodev/gptmap/core/model/palm/PalmTextPrompt.kt
f-arslan
714,072,263
false
{"Kotlin": 312117, "Dockerfile": 852}
package com.espressodev.gptmap.core.model.palm import com.google.gson.annotations.SerializedName import kotlinx.serialization.Serializable @Serializable data class PalmTextPrompt( val prompt: PalmText, @SerializedName("safety_settings") val safetySettings: List<SafetySetting> = SafetyCategory.entries.map { SafetySetting(it.name) }, @SerializedName("candidate_count") val candidateCount: Int = 1, @SerializedName("max_output_tokens") val maxOutputTokens: Int = 1024, val temperature: Double = 0.4, )
0
Kotlin
0
2
dcc8c8c7a2d40a19e08dd7c4f1c56c7d18e59518
535
GptMap
MIT License
yabapi-core/src/commonMain/kotlin/moe/sdl/yabapi/data/info/VipStatGetResponse.kt
SDLMoe
437,756,989
false
null
@file:UseSerializers(BooleanJsSerializer::class) package moe.sdl.yabapi.data.info import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers import moe.sdl.yabapi.data.GeneralCode import moe.sdl.yabapi.data.GeneralCode.UNKNOWN import moe.sdl.yabapi.serializer.BooleanJsSerializer /** * 獲取大會員狀態的返回 * @param code [GeneralCode] * @param message 錯誤信息 * @param data 信息本體 [VipStatGetData] */ @Serializable public data class VipStatGetResponse( @SerialName("code") val code: GeneralCode = UNKNOWN, @SerialName("message") val message: String? = null, @SerialName("ttl") val ttl: Int? = null, @SerialName("data") val data: VipStatGetData? = null, ) /** * @param mid 用戶 mid * @param vipType [VipType] 月度/年度 * @param vipStatus [VipStatus] vip狀態 是否異常 * @param isPaid 是否購買 * @param themeType 未知 */ @Serializable public data class VipStatGetData( @SerialName("mid") val mid: Long? = null, @SerialName("vip_type") val vipType: VipType? = null, @SerialName("vip_status") val vipStatus: VipStatus? = null, @SerialName("vip_due_date") val vipDueDate: Long? = null, @SerialName("vip_pay_type") val isPaid: Boolean? = null, @SerialName("theme_type") val themeType: Int? = null, @SerialName("label") val label: VipLabel? = null, @SerialName("avatar_subscript") val isShowSubscript: Boolean? = null, @SerialName("avatar_subscript_url") val avatarSubscriptUrl: String? = null, @SerialName("nickname_color") val nicknameColor: String? = null, @SerialName("is_new_user") val isNewUser: Boolean? = null, )
0
null
1
26
c8be46f9b5e4db1e429c33b0821643fd94789fa1
1,622
Yabapi
Creative Commons Zero v1.0 Universal
gui/proxy-tool/src/main/kotlin/net/rsprox/gui/ProxyToolGui.kt
blurite
822,339,098
false
null
package net.rsprox.gui import net.rsprox.gui.splash.SplashScreen import java.util.Locale import javax.swing.ImageIcon import javax.swing.SwingUtilities import javax.swing.UIManager public fun main() { Locale.setDefault(Locale.US) SplashScreen.init() SplashScreen.stage(0.0, "Preparing", "Setting up environment") App.service.start { percentage, actionText, subActionText, progressText -> SplashScreen.stage(percentage, actionText, subActionText, progressText) } SplashScreen.stop() SwingUtilities.invokeLater { // Disable icons in all trees. val emptyIcon = ImageIcon() UIManager.put("Tree.leafIcon", emptyIcon) UIManager.put("Tree.openIcon", emptyIcon) UIManager.put("Tree.closedIcon", emptyIcon) val app = App() app.init() // Apply the theme here, as applying it too early causes some artefacting // This ensures that the theme you see is the same on initial boot as well as swapping back and forth AppThemes.applyThemeEdt(App.service.getAppTheme()) app.start() } }
9
null
12
31
78fb08c23ec5bedd194371627586005b50b01ada
1,099
rsprox
MIT License
photoeditor/src/main/java/com/allthingsandroid/android/photoeditor/DefaultScaleTouchListener.kt
manish-badger
635,615,935
false
null
package com.allthingsandroid.android.photoeditor import android.view.MotionEvent import android.view.View import android.widget.ImageView class DefaultScaleTouchListener: BaseScaleTouchListener { private val mScaleGestureDetector: ScaleGestureDetector constructor(mIsPinchScalable: Boolean) : super(mIsPinchScalable) constructor( photoEditor: PhotoEditor, photoEditorView: PhotoEditorView, sourceImageView: ImageView, onPhotoEditorListener: OnPhotoEditorListener?, viewState: PhotoEditorViewState, mIsPinchScalable: Boolean ) : super( photoEditor, photoEditorView, sourceImageView, onPhotoEditorListener, viewState, mIsPinchScalable ) init { mScaleGestureDetector = ScaleGestureDetector(ScaleGestureListener()) } override fun onTouch(tag: String, view: View, event: MotionEvent): Boolean { mScaleGestureDetector.onTouchEvent(view, event) return true } private inner class ScaleGestureListener : ScaleGestureDetector.SimpleOnScaleGestureListener() { private var mPivotX = 0f private var mPivotY = 0f private val mPrevSpanVector = Vector2D() override fun onScaleBegin(view: View, detector: ScaleGestureDetector): Boolean { mPivotX = detector.getFocusX() mPivotY = detector.getFocusY() mPrevSpanVector.set(detector.getCurrentSpanVector()) return mIsPinchScalable } override fun onScale(view: View, detector: ScaleGestureDetector): Boolean { val info = TransformInfo() info.deltaScale = if (isScaleEnabled) detector.getScaleFactor() else 1.0f info.deltaAngle = if (isRotateEnabled) Vector2D.getAngle( mPrevSpanVector, detector.getCurrentSpanVector() ) else 0.0f info.deltaX = if (isTranslateEnabled) detector.getFocusX() - mPivotX else 0.0f info.deltaY = if (isTranslateEnabled) detector.getFocusY() - mPivotY else 0.0f info.pivotX = mPivotX info.pivotY = mPivotY info.minimumScale = minimumScale info.maximumScale = maximumScale MultiTouchListener.move(view, info) return !mIsPinchScalable } } }
0
Kotlin
0
0
fe92c8843a9215e1e74e5e90fa19003fe86707d7
2,347
PhotoEditor
MIT License
src/main/kotlin/io/hexlabs/kloudformation/module/serverless/Path.kt
hexlabsio
178,242,802
false
null
package io.hexlabs.kloudformation.module.serverless import io.kloudformation.KloudFormation import io.kloudformation.Value import io.kloudformation.function.plus import io.kloudformation.module.Modification import io.kloudformation.resource.aws.apigateway.Resource import io.kloudformation.resource.aws.apigateway.resource import io.kloudformation.module.Module import io.kloudformation.module.OptionalModification import io.kloudformation.module.Properties import io.kloudformation.module.SubModuleBuilder import io.kloudformation.module.modification import io.kloudformation.module.optionalModification import io.kloudformation.module.submodules import io.kloudformation.property.aws.apigateway.method.integrationResponse import io.kloudformation.property.aws.apigateway.method.methodResponse import io.kloudformation.resource.aws.apigateway.RestApi import io.kloudformation.resource.aws.apigateway.method import io.kloudformation.unaryPlus class Path(val resource: Map<String, Resource>, val subPaths: List<Path>, val methods: List<HttpMethod>) : Module { data class CorsConfig( var origin: Value<String> = +"'*'", var headers: Value<String> = +"'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'", var credentials: Value<String> = +"'false'", var methods: Value<String> = +"'*'" ) : Properties() class PathBuilder(val pathParts: List<String> = emptyList()) { operator fun div(path: String) = PathBuilder(pathParts + path) operator fun div(parameter: () -> String) = PathBuilder(pathParts + "{${parameter()}}") operator fun String.div(path: String) = PathBuilder(listOf(this, path)) operator fun String.div(parameter: () -> String) = PathBuilder(listOf(this, "{${parameter()}}")) operator fun (() -> String).div(path: String) = PathBuilder(listOf("{${this()}}", path)) operator fun (() -> String).div(parameter: () -> String) = PathBuilder(listOf("{${this()}}", "{${parameter()}}")) } class Predefined(var parentId: Value<String>, var restApi: RestApi, var integrationUri: Value<String>, var cors: Boolean, var authProps: AuthProps?) : Properties() class Props(pathBuilder: PathBuilder.() -> PathBuilder = { this }) : Properties() { constructor(path: String) : this({ PathBuilder(if (path.isEmpty() || path == "/") emptyList() else (if (path.startsWith("/")) path.substring(1) else path).split("/")) }) val pathParts: List<String> = pathBuilder(PathBuilder()).pathParts } class Parts( val httpResource: Map<String, Modification<Resource.Builder, Resource, ResourceProps>> = emptyMap(), val cors: OptionalModification<CorsConfig, CorsConfig, CorsConfig> = optionalModification(absent = true) ) : io.kloudformation.module.Parts() { val httpMethod = submodules { pre: HttpMethod.Predefined, props: HttpMethod.Props -> HttpMethod.Builder(pre, props) } fun httpMethod( httpMethod: String, modifications: HttpMethod.Parts.(HttpMethod.Predefined) -> Unit = {} ) = httpMethod(HttpMethod.Props(httpMethod), modifications) fun httpMethod( httpMethod: Method, modifications: HttpMethod.Parts.(HttpMethod.Predefined) -> Unit = {} ) = httpMethod(httpMethod.name, modifications) operator fun Method.invoke( modifications: HttpMethod.Parts.(HttpMethod.Predefined) -> Unit = {} ) = httpMethod(name, modifications) val path = submodules { pre: Path.Predefined, props: Path.Props -> Path.Builder(pre, props) } fun path( pathBuilder: Path.PathBuilder.() -> Path.PathBuilder = { this }, modifications: Path.Parts.(Path.Predefined) -> Unit = {} ) = path(Path.Props(pathBuilder), modifications) fun path( path: String, modifications: Path.Parts.(Path.Predefined) -> Unit = {} ) = path(Path.Props(path), modifications) class ResourceProps(var path: Value<String>, var parentId: Value<String>, var restApi: Value<String>) : Properties() } class Builder(pre: Predefined, val props: Props) : SubModuleBuilder<Path, Parts, Predefined>(pre, Parts( httpResource = props.pathParts.map { it to modification<Resource.Builder, Resource, Parts.ResourceProps>() }.toMap() )) { override fun KloudFormation.buildModule(): Parts.() -> Path = { val pathParts = props.pathParts var normalizedPath = "" fun append(part: String) { normalizedPath += part.let { (if (it.contains("{")) it.substringAfter("{").substringBeforeLast("}") + "Var" else it).replace(Regex("[^0-9A-Za-z]"), "") } } val apiResources = pathParts.foldIndexed(emptyList<Pair<String, Resource>>()) { index, acc, pathPart -> val parentId = if (index == 0) pre.parentId else acc.last().second.ref() acc + (pathPart to httpResource[pathPart]!!(Parts.ResourceProps(Value.Of(pathPart), parentId, pre.restApi.ref())) { props -> append(pathPart) resource(parentId = props.parentId, restApiId = props.restApi, pathPart = props.path, logicalName = allocateLogicalName("ApiGatewayResource$normalizedPath")) { modifyBuilder(props) } }) }.toMap() val endResource: Value<String> = apiResources.toList().lastOrNull()?.second?.ref() ?: pre.restApi.RootResourceId() val apiMethods = httpMethod.modules().mapNotNull { build(it, HttpMethod.Predefined(pre.cors, pre.restApi.ref(), endResource, pre.integrationUri, normalizedPath, pre.authProps)) } val corsMethodsForPath = apiMethods.map { it.method.httpMethod } val methodsValue: Value<String> = when { corsMethodsForPath.isEmpty() -> +"''" corsMethodsForPath.all { it is Value.Of<*> } -> +("'" + corsMethodsForPath.map { (it as Value.Of<String>).value }.reduce { acc, method -> "$acc,$method" } + "'") else -> +"'" + corsMethodsForPath.reduce { acc, method -> acc + "," + method } + "'" } var optionsMethod: HttpMethod? = null if (pre.cors) cors.keep() cors(CorsConfig(methods = methodsValue)) { val corsConfig = it.modifyBuilder(it) val corsOrigin = "method.response.header.Access-Control-Allow-Origin" val corsHeaders = "method.response.header.Access-Control-Allow-Headers" val corsMethods = "method.response.header.Access-Control-Allow-Methods" val corsCredentials = "method.response.header.Access-Control-Allow-Credentials" val method = method(+"OPTIONS", endResource, pre.restApi.ref(), logicalName = allocateLogicalName("Method${normalizedPath}Options")) { authorizationType("NONE") methodResponses(listOf( methodResponse(statusCode = +"200") { responseParametersMap(mapOf(corsOrigin to true, corsHeaders to true, corsMethods to true, corsCredentials to true)) responseModels(emptyMap()) } )) requestParameters(emptyMap()) integration { type("MOCK") requestTemplatesMap(mapOf("application/json" to "{statusCode:200}")) contentHandling("CONVERT_TO_TEXT") integrationResponses(listOf( integrationResponse(+"200") { responseParameters(mapOf( corsOrigin to corsConfig.origin, corsHeaders to corsConfig.headers, corsMethods to corsConfig.methods, corsCredentials to corsConfig.credentials )) responseTemplatesMap(mapOf( "application/json" to "#set(\$origin = \$input.params(\"Origin\"))\n#if(\$origin == \"\") #set(\$origin = \$input.params(\"origin\")) #end\n#if(\$origin == \"*\") #set(\$context.responseOverride.header.Access-Control-Allow-Origin = \$origin) #end" )) } )) } } optionsMethod = HttpMethod(method, true) corsConfig } val paths = path.modules().mapNotNull { build(it, Path.Predefined(endResource, pre.restApi, pre.integrationUri, pre.cors, pre.authProps)) } Path(apiResources, paths, apiMethods + (optionsMethod?.let { listOf(it) } ?: emptyList())) } } }
0
Kotlin
0
1
8c7c7021757ae35d50435c6b86bfc12c02730f1d
9,039
kloudformation-serverless-module
Apache License 2.0
android/src/main/java/com/superwallreactnative/models/RestorationResult.kt
superwall
756,562,038
false
{"TypeScript": 83812, "Kotlin": 57101, "Swift": 41390, "Ruby": 7610, "Objective-C++": 5598, "JavaScript": 3969, "Objective-C": 2755, "C": 206}
package com.superwallreactnative.models import com.facebook.react.bridge.ReadableMap import com.superwall.sdk.delegate.RestorationResult class RestorationResult { companion object { fun fromJson(json: ReadableMap): RestorationResult { return when (json.getString("result")) { "restored" -> RestorationResult.Restored() "failed" -> { val errorMessage = json.getString("errorMessage") ?: "Unknown error" RestorationResult.Failed(Error(errorMessage)) } else -> RestorationResult.Failed(Error("Unknown restoration result")) } } } }
4
TypeScript
0
15
86638759f13c4c73dea0d60b03a0198413197f9f
606
react-native-superwall
MIT License
src/main/kotlin/no/nav/klage/oppgave/api/controller/KodeverkController.kt
navikt
297,650,936
false
{"Kotlin": 1155151, "Dockerfile": 133}
package no.nav.klage.oppgave.api.controller import io.swagger.v3.oas.annotations.tags.Tag import no.nav.klage.oppgave.config.SecurityConfiguration.Companion.ISSUER_AAD import no.nav.klage.oppgave.domain.kodeverk.LandInfo import no.nav.klage.oppgave.domain.kodeverk.PostInfo import no.nav.klage.oppgave.service.InnloggetSaksbehandlerService import no.nav.klage.oppgave.service.KodeverkService import no.nav.klage.oppgave.util.getLogger import no.nav.klage.oppgave.util.logMethodDetails import no.nav.security.token.support.core.api.ProtectedWithClaims import org.springframework.web.bind.annotation.* @RestController @Tag(name = "kabal-api") @ProtectedWithClaims(issuer = ISSUER_AAD) class KodeverkController( private val kodeverkService: KodeverkService, private val innloggetSaksbehandlerService: InnloggetSaksbehandlerService ) { companion object { @Suppress("JAVA_CLASS_ON_COMPANION") private val logger = getLogger(javaClass.enclosingClass) } @GetMapping("/postinfo") fun getPostInfo(): List<PostInfo> { logMethodDetails( ::getPostInfo.name, innloggetSaksbehandlerService.getInnloggetIdent(), logger ) return kodeverkService.getPostInfo() } @GetMapping("/landinfo") fun getLandInfo(): List<LandInfo> { logMethodDetails( ::getLandInfo.name, innloggetSaksbehandlerService.getInnloggetIdent(), logger ) return kodeverkService.getLandkoder() } }
4
Kotlin
3
0
7b93a8940276c371b5859d116ffe4d89f596c92e
1,527
kabal-api
MIT License
vitrivr-engine-core/src/main/kotlin/org/vitrivr/engine/core/model/content/impl/InMemoryImageContent.kt
vitrivr
679,355,326
false
{"Kotlin": 608109}
package org.vitrivr.engine.core.model.content.impl import org.vitrivr.engine.core.model.content.element.ImageContent import java.awt.image.BufferedImage /** * A naive in-memory implementation of the [ImageContent] interface. * * Warning: Usage of [InMemoryImageContent] may lead to out-of-memory situations in large extraction pipelines. * * @author Luca Rossetto. * @version 1.0.0 */ data class InMemoryImageContent(override val content: BufferedImage) : ImageContent
35
Kotlin
1
4
1af88808f815237018eec48ede0f9c36d22b6145
478
vitrivr-engine
MIT License
library/src/main/java/co/zsmb/materialdrawerkt/draweritems/expandable/ExpandableDrawerItemKt.kt
idebasishbose
115,329,625
false
null
package co.zsmb.materialdrawerkt.draweritems.expandable import co.zsmb.materialdrawerkt.builders.Builder import co.zsmb.materialdrawerkt.draweritems.base.BaseDescribeableDrawerItemKt import co.zsmb.materialdrawerkt.nonReadable import com.mikepenz.materialdrawer.model.ExpandableDrawerItem /** * Adds a new ExpandableDrawerItem with the given [name] and [description]. * @return The created ExpandableDrawerItem instance */ fun Builder.expandableItem(name: String = "", description: String? = null, setup: ExpandableDrawerItemKt.() -> Unit = {}): ExpandableDrawerItem { val item = ExpandableDrawerItemKt() item.name = name description?.let { item.description = it } item.setup() return item.build().apply { attachItem(this) } } /** * Adds a new ExpandableDrawerItem with the given [nameRes] and [descriptionRes]. * @return The created ExpandableDrawerItem instance */ fun Builder.expandableItem(nameRes: Int, descriptionRes: Int? = null, setup: ExpandableDrawerItemKt.() -> Unit = {}): ExpandableDrawerItem { val item = ExpandableDrawerItemKt() item.nameRes = nameRes descriptionRes?.let { item.descriptionRes = it } item.setup() return item.build().apply { attachItem(this) } } class ExpandableDrawerItemKt : BaseDescribeableDrawerItemKt() { /* Builder basics */ private val item = ExpandableDrawerItem() init { super.setItem(item) } internal fun build() = item /* ExpandableDrawerItem methods */ /** * The color of the expand arrow, as an argb Long. * * Non readable property. Wraps the [ExpandableDrawerItem.withArrowColor] method. */ var arrowColor: Long @Deprecated(level = DeprecationLevel.ERROR, message = "Non readable property.") get() = nonReadable() set(value) { item.withArrowColor(value.toInt()) } /** * The color of the expand arrow, as a color resource. * * Non readable property. Wraps the [ExpandableDrawerItem.withArrowColorRes] method. */ var arrowColorRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non readable property.") get() = nonReadable() set(value) { item.withArrowColorRes(value) } /** * Convenience for setting both [arrowRotationAngleStart] and [arrowRotationAngleEnd] at the same time. See those * properties for details. * * Non readable property. Wraps the [ExpandableDrawerItem.withArrowRotationAngleStart] and * [ExpandableDrawerItem.withArrowRotationAngleEnd] methods. */ var arrowRotationAngle: Pair<Int, Int> @Deprecated(level = DeprecationLevel.ERROR, message = "Non readable property.") get() = nonReadable() set(value) { item.withArrowRotationAngleStart(value.first) .withArrowRotationAngleEnd(value.second) } /** * The rotation of the expand arrow when the item is open, in degrees. * Default value is 180, which corresponds to an upward pointing arrow. * * See [arrowRotationAngle] as an alternative. * * Non readable property. Wraps the [ExpandableDrawerItem.withArrowRotationAngleEnd] method. */ var arrowRotationAngleEnd: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non readable property.") get() = nonReadable() set(value) { item.withArrowRotationAngleEnd(value) } /** * The rotation of the expand arrow when the item is closed, in degrees. * Default value is 0, which corresponds to a downward pointing arrow. * * See [arrowRotationAngle] as an alternative. * * Non readable property. Wraps the [ExpandableDrawerItem.withArrowRotationAngleStart] method. */ var arrowRotationAngleStart: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non readable property.") get() = nonReadable() set(value) { item.withArrowRotationAngleStart(value) } }
0
Kotlin
0
0
fbebb7b0464f5ecbefc325198b3acc0b45b806ff
4,150
MaterialDrawerKt
Apache License 2.0