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
src/main/kotlin/net/valorhcf/trojan/util/entity/EntityUtil.kt
hardcorefactions
741,980,668
false
{"Maven POM": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Java": 71, "YAML": 1, "Kotlin": 35}
package cc.fyre.shard.util.entity import cc.fyre.shard.Shard import cc.fyre.shard.util.bukkit.NMSUtil import net.minecraft.server.v1_8_R3.EntityTypes import org.apache.commons.lang.WordUtils import org.bukkit.Chunk import org.bukkit.entity.Entity import org.bukkit.entity.EntityType import org.bukkit.entity.LivingEntity /** * @project carnage * * @date 15/02/2021 * @author <EMAIL> */ object EntityUtil { private val names = hashMapOf<EntityType,String>() private var count = Integer.MAX_VALUE /*private val ENTITY_COUNT_FIELD = NMSUtil.getNMSClass("Entity").getDeclaredField("entityCount") init { ENTITY_COUNT_FIELD.isAccessible = true }*/ init { names[EntityType.ARROW] = "Arrow" names[EntityType.BAT] = "Bat" names[EntityType.BLAZE] = "Blaze" names[EntityType.BOAT] = "Boat" names[EntityType.CAVE_SPIDER] = "Cave Spider" names[EntityType.CHICKEN] = "Chicken" names[EntityType.COW] = "Cow" names[EntityType.CREEPER] = "Creeper" names[EntityType.DROPPED_ITEM] = "Item" names[EntityType.EGG] = "Egg" names[EntityType.ENDER_CRYSTAL] = "Ender Crystal" names[EntityType.ENDER_DRAGON] = "Ender Dragon" names[EntityType.ENDER_PEARL] = "Ender Pearl" names[EntityType.ENDER_SIGNAL] = "Ender Signal" names[EntityType.ENDERMAN] = "Enderman" names[EntityType.EXPERIENCE_ORB] = "Experience Orb" names[EntityType.FALLING_BLOCK] = "Falling Block" names[EntityType.FIREBALL] = "Fireball" names[EntityType.FIREWORK] = "Firework" names[EntityType.FISHING_HOOK] = "Fishing Rod Hook" names[EntityType.GHAST] = "Ghast" names[EntityType.GIANT] = "Giant" names[EntityType.HORSE] = "Horse" names[EntityType.IRON_GOLEM] = "Iron Golem" names[EntityType.ITEM_FRAME] = "Item Frame" names[EntityType.LEASH_HITCH] = "Lead Hitch" names[EntityType.LIGHTNING] = "Lightning" names[EntityType.MAGMA_CUBE] = "Magma Cube" names[EntityType.MINECART] = "Minecart" names[EntityType.MINECART_CHEST] = "Chest Minecart" names[EntityType.MINECART_FURNACE] = "Furnace Minecart" names[EntityType.MINECART_HOPPER] = "Hopper Minecart" names[EntityType.MINECART_MOB_SPAWNER] = "Spawner Minecart" names[EntityType.MINECART_TNT] = "TNT Minecart" names[EntityType.OCELOT] = "Ocelot" names[EntityType.PAINTING] = "Painting" names[EntityType.PIG] = "Pig" names[EntityType.PIG_ZOMBIE] = "Zombie Pigman" names[EntityType.PLAYER] = "Player" names[EntityType.PRIMED_TNT] = "TNT" names[EntityType.SHEEP] = "Sheep" names[EntityType.SILVERFISH] = "Silverfish" names[EntityType.SKELETON] = "Skeleton" names[EntityType.SLIME] = "Slime" names[EntityType.SMALL_FIREBALL] = "Fireball" names[EntityType.SNOWBALL] = "Snowball" names[EntityType.SNOWMAN] = "Snowman" names[EntityType.SPIDER] = "Spider" names[EntityType.SPLASH_POTION] = "Potion" names[EntityType.SQUID] = "Squid" names[EntityType.THROWN_EXP_BOTTLE] = "Experience Bottle" names[EntityType.UNKNOWN] = "Custom" names[EntityType.VILLAGER] = "Villager" names[EntityType.WITCH] = "Witch" names[EntityType.WITHER] = "Wither" names[EntityType.WITHER_SKULL] = "Wither Skull" names[EntityType.WOLF] = "Wolf" names[EntityType.ZOMBIE] = "Zombie" } @JvmStatic fun getName(type: EntityType):String { return this.names.getOrPut(type) { WordUtils.capitalizeFully(type.name.lowercase().replace(" ", "")) } } //TODO optimize, faster lookups @JvmStatic fun getByName(input: String): EntityType? { return this.names.entries.firstOrNull{it.value.replace(" ","").equals(input,true)}?.key ?: EntityType.values().firstOrNull{it.name.equals(input,true)} } @JvmStatic fun getEntityCount():Int { //return ENTITY_COUNT_FIELD.getInt(null) return this.count } @JvmStatic fun getNewEntityId():Int { return this.count-- } @JvmStatic fun registerEntity(clazz: Class<*>,name: String,id: Int) { this.setField("f",clazz,id) this.setField("d",clazz,name) } private fun <K,V> setField(field: String,key: K, value: V) { try { NMSUtil.getNMSClass("EntityTypes").getDeclaredField(field).also{ it.isAccessible = true val map = it.get(null) as HashMap<K,V> map[key] = value } } catch (ex: SecurityException) { ex.printStackTrace() } catch (ex: IllegalArgumentException) { ex.printStackTrace() } catch (ex: IllegalAccessException) { ex.printStackTrace() } catch (ex: NoSuchFieldException) { ex.printStackTrace() } } fun isActive(entity: Entity): Boolean { return Shard.AI.getNmsAI().isActive(entity) } fun isMobSpawner(entity: Entity): Boolean { return Shard.AI.getNmsAI().isMobSpawner(entity) } fun setMobSpawner(entity: Entity, spawner: Boolean) { Shard.AI.getNmsAI().setMobSpawner(entity,spawner) } fun getEntityCountByChunk(chunk: Chunk): Int { return chunk.entities.count{it is LivingEntity} } }
0
Java
0
1
0218b00d5518c22c42b5b2dde38ebd3f716b8de4
5,441
TrojanAC
MIT License
src/main/kotlin/org/smarthata/service/CronMqttUpdater.kt
smarthata
127,398,623
false
{"Java": 59208, "Kotlin": 48264, "HTML": 3021, "Makefile": 2129}
package org.smarthata.service import org.smarthata.service.message.EndpointType import org.smarthata.service.message.SmarthataMessage import org.smarthata.service.message.SmarthataMessageBroker import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Service import java.time.LocalTime import java.time.ZoneId @Service class CronMqttUpdater(private val messageBroker: SmarthataMessageBroker) { @Scheduled(cron = "0 * * * * *") fun sendSecondOfDay() { val secondOfDay = calcSecondOfDay() messageBroker.broadcast( SmarthataMessage( "/time/second-of-day", secondOfDay.toString(), EndpointType.SYSTEM, EndpointType.MQTT, true ) ) } @Scheduled(cron = "0 * * * * *") fun sendMinuteOfDay() { val minuteOfDay = calcSecondOfDay() / 60 messageBroker.broadcast( SmarthataMessage( "/time/minute-of-day", minuteOfDay.toString(), EndpointType.SYSTEM, EndpointType.MQTT, true ) ) } private fun calcSecondOfDay(): Int = LocalTime.now(ZoneId.systemDefault()).toSecondOfDay() }
1
null
1
1
53c35a9946f3179150a06013fe9738f95178cb94
1,287
smarthata-java-server
Apache License 2.0
kotlin-ir-plugin/src/test/kotlin/com/bnorm/template/IrPluginTest.kt
Jolanrensen
321,790,604
false
null
/* * Copyright (C) 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bnorm.template import com.tschuchort.compiletesting.KotlinCompilation import com.tschuchort.compiletesting.SourceFile import org.intellij.lang.annotations.Language import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar import org.junit.Test import kotlin.test.assertEquals const val `$` = '$' class IrPluginTest { @Test fun `IR plugin success`() { @Language("kotlin") val contents = """ annotation class SuspendProp fun main() { val test1 = "abc" println("Hello $`$`test1") println(test) } @SuspendProp var test: Int get() = 4 set(value) { println(value) } """.trimIndent() val result = compile( sourceFile = SourceFile.kotlin( name = "main.kt", contents = contents, ) ) assertEquals(KotlinCompilation.ExitCode.OK, result.exitCode) } } fun compile( sourceFiles: List<SourceFile>, plugin: ComponentRegistrar = TemplateComponentRegistrar(), ): KotlinCompilation.Result { return KotlinCompilation().apply { sources = sourceFiles useIR = true compilerPlugins = listOf(plugin) inheritClassPath = true }.compile() } fun compile( sourceFile: SourceFile, plugin: ComponentRegistrar = TemplateComponentRegistrar(), ): KotlinCompilation.Result { return compile(listOf(sourceFile), plugin) }
0
Kotlin
0
0
f3033f7c0712b5e9a8f8ce13c0c9730a5d3b2df7
2,040
suspend-prop-plugin
Apache License 2.0
app/src/main/java/com/guau_guau/guau_guau/data/repositories/PostRepository.kt
luisccc99
330,788,012
false
null
package com.guau_guau.guau_guau.data.repositories import com.guau_guau.guau_guau.data.network.GuauguauApi class PostRepository( private val api: GuauguauApi ) : BaseRepository() { suspend fun createPost(id: String, title: String, body: String, latitude: Double?, longitude: Double?) = safeApiCall { api.createPost(id, title, body, longitude, latitude) } suspend fun deletePost(postId: String) = safeApiCall { api.deletePost(postId) } suspend fun patchPost( postId: String, resolved: Boolean, resolvedReason: String ) = safeApiCall { api.patchPost(postId, resolved, resolvedReason) } suspend fun getPost( postId: String ) = safeApiCall { api.getPost(postId) } suspend fun getUserById( userId: String ) = safeApiCall { api.getUser(userId) } }
0
Kotlin
0
1
105ebe01d82dbfc90f2b6dc06dafd37d02fcef0e
884
guau-guau
Apache License 2.0
server/src/main/kotlin/nl/knaw/huc/annorepo/auth/Role.kt
knaw-huc
473,687,323
false
null
package nl.knaw.huc.annorepo.auth enum class Role(val roleName: String) { GUEST(roleName = "guest"), USER(roleName = "user"), ADMIN(roleName = "admin"), ROOT(roleName = "root") }
8
Kotlin
0
4
f5853b36306b76218ef731fd089b5d270fe3f033
195
annorepo
Apache License 2.0
app/src/main/java/com/zzr/jetpacktest/navigation/Page1Fragment.kt
zrzhong
288,220,143
false
{"Gradle Kotlin DSL": 2, "Java Properties": 2, "Gradle": 3, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 173, "XML": 104, "Java": 22, "HTML": 3, "INI": 1}
package com.zzr.jetpacktest.navigation import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.navigation.Navigation import androidx.navigation.fragment.findNavController import com.zzr.jetpacktest.R import com.zzr.jetpacktest.databinding.FragmentPage1Binding import com.zzr.jetpacktest.utils.inflate /** * @Author zzr * @Desc * @Date 2021/1/8 */ class Page1Fragment : Fragment() { private val binding by inflate<FragmentPage1Binding>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val action = Page1FragmentDirections.actionFragmentPage1ToFragmentPage2("hello", 1) binding.btnGotoPage2.setOnClickListener { // findNavController().navigate(R.id.action_fragment_page_1_to_fragment_page_2) findNavController().navigate(action) } binding.btnBundle.setOnClickListener { val bundle = bundleOf("key" to "I am form page1") findNavController().navigate(R.id.action_fragment_page_1_to_fragment_page_2, bundle) } binding.gotoIncludeGraph.setOnClickListener { findNavController().navigate(R.id.action_fragment_page_1_to_include_graph) } binding.gotoGameModule.setOnClickListener { findNavController().navigate(R.id.action_fragment_page_1_to_game_module) } } }
1
null
1
1
7765544fd6df3d615dadbe03f7df1daaac7aa1ab
1,721
JetpackTest
Apache License 2.0
site/src/jsMain/kotlin/com/prashant/blog/utils/css/EditorKeyStyle.kt
prashant17d97
707,855,780
false
{"Kotlin": 463892, "CSS": 4204, "Dockerfile": 2765, "JavaScript": 795, "Swift": 592, "Shell": 228}
package com.prashant.blog.utils.css import com.prashant.blog.utils.css.CssStyleRegistration.colorScheme import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.graphics.Colors import com.varabyte.kobweb.compose.ui.modifiers.backgroundColor import com.varabyte.kobweb.compose.ui.modifiers.transition import com.varabyte.kobweb.silk.components.style.ComponentStyle import com.varabyte.kobweb.silk.components.style.hover import org.jetbrains.compose.web.css.ms val EditorKeyStyle by ComponentStyle { base { Modifier .backgroundColor(Colors.Transparent) .transition(CSSTransition(property = "background", duration = 300.ms)) } hover { Modifier.backgroundColor(colorScheme.action) } }
0
Kotlin
0
0
e5fe0b05d7dab2755c436ebe8d5742a2ebec2f6b
820
Blog
Apache License 2.0
app/src/main/java/com/example/mediaplayer/audioPlayer/notification/NotificationActions.kt
AbdelrhmanSror
205,750,290
false
null
package com.example.mediaplayer.audioPlayer.notification import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Bundle import androidx.core.app.NotificationCompat import androidx.navigation.NavDeepLinkBuilder import com.example.mediaplayer.R import com.example.mediaplayer.audioForegroundService.AudioForegroundService import com.example.mediaplayer.intent.CHOSEN_SONG_INDEX import com.example.mediaplayer.intent.NOTIFICATION_ID import com.example.mediaplayer.intent.NotificationAction import com.example.mediaplayer.intent.NotificationAction.NOTIFICATION object NotificationActions { fun playPause(context: Context, isPlaying: Boolean): NotificationCompat.Action { val icon = if (isPlaying) R.drawable.vd_pause_big else R.drawable.vd_play_big return NotificationCompat.Action.Builder( icon, "Toggle play pause", buildMediaPendingIntent(context, NotificationAction.PLAY_PAUSE) ).build() } fun skipPrevious(context: Context): NotificationCompat.Action { return NotificationCompat.Action.Builder( R.drawable.vd_skip_previous, "Skip to previous", buildMediaPendingIntent(context, NotificationAction.PREVIOUS) ).build() } fun skipNext(context: Context): NotificationCompat.Action { return NotificationCompat.Action.Builder( R.drawable.vd_skip_next, "Skip to next", buildMediaPendingIntent(context, NotificationAction.NEXT) ).build() } fun stop(context: Context): PendingIntent { return buildMediaPendingIntent( context, NotificationAction.STOP ) } fun contentIntentNotification(context: Context, index: Int): PendingIntent { val bundle = Bundle() //bundle.putParcelableArrayList(LIST_SONG, songModels) bundle.putInt(CHOSEN_SONG_INDEX, index) bundle.putBoolean(NOTIFICATION, true) //using deep links to navigate to chosen song fragment return NavDeepLinkBuilder(context) .setGraph(R.navigation.navigaion) .setDestination(R.id.chosenSong_dest) .setArguments(bundle) .createPendingIntent() } private fun buildMediaPendingIntent(context: Context, action: String): PendingIntent { val intent = Intent(context, AudioForegroundService::class.java) intent.action = action return PendingIntent.getService(context, NOTIFICATION_ID, intent, 0) } }
0
Kotlin
0
0
0485e592998b4a2818f69a86294dad113faf7354
2,648
MediaPlayer
Apache License 2.0
src/main/kotlin/com/rose/gateway/config/markers/CommonExtensionConfig.kt
nicholasgrose
377,028,896
false
{"Kotlin": 261314}
package com.rose.gateway.config.markers import com.rose.gateway.discord.bot.DiscordBotController import com.rose.gateway.shared.concurrency.PluginCoroutineScope import kotlinx.coroutines.launch import kotlinx.serialization.Transient import org.koin.core.component.KoinComponent import org.koin.core.component.inject /** * Represents a config object for a Discord extension * * @property extensionName The name of the extension * @constructor Creates a common extension config for the given extension * * @param enabled Whether the extension will start enabled */ open class CommonExtensionConfig( enabled: Boolean, @Transient val extensionName: String = "None", ) : KoinComponent, ConfigObject { private val bot: DiscordBotController by inject() private val pluginsScope: PluginCoroutineScope by inject() /** * Whether the extension is enabled */ @ConfigItem("Whether the extension is enabled.") var enabled = enabled set(value) { field = value modifyExtensionLoadedStatus(value) } /** * Modifies whether an extension is enabled in the bot or not * * @param enabled The extensions new status */ private fun modifyExtensionLoadedStatus(enabled: Boolean) { pluginsScope.launch { if (enabled) { bot.discordBot.kordexBot .await() ?.loadExtension(extensionName) } else { bot.discordBot.kordexBot .await() ?.unloadExtension(extensionName) } } } }
26
Kotlin
1
4
896a6e99b74c97128c74fd166b80c31d183fb36c
1,630
Gateway
MIT License
app/src/main/java/com/goldenowl/ecommerceapp/adapters/ListReviewAdapter2.kt
Catelt
556,541,382
false
{"Kotlin": 403481, "Batchfile": 284}
package com.goldenowl.ecommerceapp.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.goldenowl.ecommerceapp.data.Review import com.goldenowl.ecommerceapp.databinding.ItemReview2Binding import com.goldenowl.ecommerceapp.utilities.DateFormat class ListReviewAdapter2( private val setRecyclerView: (RecyclerView, Review) -> Unit, ) : ListAdapter<Review, ListReviewAdapter2.ItemViewHolder>(DiffCallback) { class ItemViewHolder( private val setRecyclerVIew: (RecyclerView, Review) -> Unit, private val binding: ItemReview2Binding, ) : RecyclerView.ViewHolder(binding.root) { fun bind(review: Review) { binding.apply { txtName.text = "ID Product: ${review.idProduct}" txtDescription.text = review.description ratingBar.rating = review.star.toFloat() val timeCreated = review.createdTimer?.toDate() timeCreated?.let { txtCreated.text = DateFormat.review.format(it).toString() } setRecyclerVIew(recyclerViewImageReview, review) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { return ItemViewHolder( setRecyclerView, ItemReview2Binding.inflate( LayoutInflater.from( parent.context ), parent, false ) ) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { val current = getItem(position) holder.bind(current) } companion object { private val DiffCallback = object : DiffUtil.ItemCallback<Review>() { override fun areItemsTheSame(oldItem: Review, newItem: Review): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: Review, newItem: Review): Boolean { return oldItem == newItem } } } }
1
Kotlin
0
0
80cf0e9e084cb43b6d9e0f5dbbd582e41202abe8
2,241
E-Commerce-Application
MIT License
feature/timers/presentation/src/commonMain/kotlin/org/timemates/app/timers/ui/timer_creation/TimerCreationScreen.kt
timemates
575,537,317
false
{"Kotlin": 329102}
package org.timemates.app.timers.ui.timer_creation import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.ArrowBack import androidx.compose.material3.Checkbox import androidx.compose.material3.CheckboxDefaults import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Snackbar import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import org.timemates.app.feature.common.MVI import org.timemates.app.feature.common.failures.getDefaultDisplayMessage import org.timemates.app.feature.common.getFailuresIfPresent import org.timemates.app.feature.common.isInvalid import org.timemates.app.localization.compose.LocalStrings import org.timemates.app.style.system.appbar.AppBar import org.timemates.app.style.system.button.ButtonWithProgress import org.timemates.app.style.system.text_field.SizedOutlinedTextField import org.timemates.app.style.system.theme.AppTheme import org.timemates.app.timers.ui.timer_creation.mvi.TimerCreationScreenComponent.* import org.timemates.sdk.timers.types.value.TimerDescription import org.timemates.sdk.timers.types.value.TimerName import pro.respawn.flowmvi.essenty.compose.subscribe import kotlin.time.Duration.Companion.minutes import kotlin.time.DurationUnit @Composable fun TimerCreationScreen( mvi: MVI<State, Intent, Action>, navigateToTimersScreen: () -> Unit, ) { val strings = LocalStrings.current val snackBarData = remember { SnackbarHostState() } val state by mvi.subscribe { action -> when (action) { is Action.ShowFailure -> snackBarData.showSnackbar( message = action.throwable.getDefaultDisplayMessage(strings) ) Action.NavigateToTimersScreen -> navigateToTimersScreen() } } val nameSize = remember(state.name) { state.name.value.length } val descriptionSize = remember(state.description) { state.description.value.length } Scaffold( topBar = { AppBar( title = LocalStrings.current.timerCreation, navigationIcon = { IconButton( onClick = { navigateToTimersScreen() }, ) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = null) } }, ) } ) { rootPaddings -> val nameSupportText = state.name.getFailuresIfPresent(strings) val descriptionYouSupportText = state.description.getFailuresIfPresent(strings) Column( modifier = Modifier.fillMaxSize() .padding(rootPaddings) .padding(horizontal = 16.dp) .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp), ) { Spacer(Modifier.height(4.dp)) SizedOutlinedTextField( modifier = Modifier.fillMaxWidth(), value = state.name.value, onValueChange = { mvi.store.intent(Intent.NameIsChanged(it)) }, label = { Text(LocalStrings.current.name) }, isError = state.name.isInvalid() || nameSize > TimerName.LENGTH_RANGE.last, singleLine = true, supportingText = { if (nameSupportText != null) { Text(nameSupportText) } }, size = IntRange(nameSize, TimerName.LENGTH_RANGE.last), enabled = !state.isLoading, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send), ) SizedOutlinedTextField( modifier = Modifier.fillMaxWidth(), value = state.description.value, onValueChange = { mvi.store.intent(Intent.DescriptionIsChanged(it)) }, label = { Text(LocalStrings.current.description) }, isError = state.description.isInvalid() || descriptionSize > TimerDescription.LENGTH_RANGE.last, maxLines = 5, supportingText = { if (descriptionYouSupportText != null) { Text(descriptionYouSupportText) } }, size = IntRange(descriptionSize, TimerDescription.LENGTH_RANGE.last), enabled = !state.isLoading, ) HorizontalDivider( color = AppTheme.colors.secondary, thickness = 1.dp, modifier = Modifier .padding(8.dp) .width(60.dp) .align(Alignment.CenterHorizontally), ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp), ) { OutlinedTextField( modifier = Modifier .weight(1f), value = state.workTime.toInt(unit = DurationUnit.MINUTES).toString(), onValueChange = { mvi.store.intent( Intent.WorkTimeIsChanged(it.toIntOrNull()?.minutes ?: state.workTime) ) }, label = { Text(LocalStrings.current.workTime) }, singleLine = true, enabled = !state.isLoading, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number ), ) OutlinedTextField( modifier = Modifier .weight(1f), value = state.restTime.toInt(unit = DurationUnit.MINUTES).toString(), onValueChange = { mvi.store.intent(Intent.RestTimeIsChanged(it.toInt().minutes)) }, label = { Text(LocalStrings.current.restTime) }, singleLine = true, enabled = !state.isLoading, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number ), ) } Row( modifier = Modifier.fillMaxWidth(), ) { Checkbox( checked = state.bigRestEnabled, onCheckedChange = { mvi.store.intent(Intent.BigRestModeIsChanged(!state.bigRestEnabled)) }, modifier = Modifier.align(Alignment.CenterVertically), colors = CheckboxDefaults.colors(checkedColor = AppTheme.colors.primary), enabled = !state.isLoading, ) Text( text = LocalStrings.current.advancedRestSettingsDescription, modifier = Modifier.align(Alignment.CenterVertically), color = if (!state.isLoading) AppTheme.colors.primary else AppTheme.colors.secondary, ) } if (state.bigRestEnabled) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp), ) { OutlinedTextField( modifier = Modifier.weight(1f), value = state.bigRestPer.value.toString(), onValueChange = { mvi.store.intent(Intent.BigRestPerIsChanged(it.toInt())) }, label = { Text(LocalStrings.current.every) }, singleLine = true, enabled = !state.isLoading, ) OutlinedTextField( modifier = Modifier.weight(1f), value = state.bigRestTime.toInt(unit = DurationUnit.MINUTES).toString(), onValueChange = { mvi.store.intent(Intent.BigRestTimeIsChanged(it.toInt().minutes)) }, label = { Text(LocalStrings.current.minutes) }, singleLine = true, enabled = !state.isLoading, ) } } Spacer(modifier = Modifier.padding(8.dp)) HorizontalDivider( color = AppTheme.colors.secondary, thickness = 1.dp, modifier = Modifier .width(60.dp) .align(Alignment.CenterHorizontally), ) Row( modifier = Modifier.fillMaxWidth(), ) { Checkbox( checked = state.isEveryoneCanPause, onCheckedChange = { mvi.store.intent(Intent.TimerPauseControlAccessIsChanged(!state.isEveryoneCanPause)) }, modifier = Modifier.align(Alignment.CenterVertically), colors = CheckboxDefaults.colors(checkedColor = AppTheme.colors.primary), enabled = !state.isLoading, ) Text( text = LocalStrings.current.publicManageTimerStateDescription, modifier = Modifier.align(Alignment.CenterVertically), color = if (!state.isLoading) AppTheme.colors.primary else AppTheme.colors.secondary, ) } Row( modifier = Modifier.fillMaxWidth(), ) { Checkbox( checked = state.isConfirmationRequired, onCheckedChange = { mvi.store.intent(Intent.ConfirmationRequirementChanged(!state.isConfirmationRequired)) }, modifier = Modifier.align(Alignment.CenterVertically), colors = CheckboxDefaults.colors(checkedColor = AppTheme.colors.primary), enabled = !state.isLoading, ) Text( text = LocalStrings.current.confirmationRequiredDescription, modifier = Modifier.align(Alignment.CenterVertically), color = if (!state.isLoading) AppTheme.colors.primary else AppTheme.colors.secondary, ) } Spacer(Modifier.weight(1f)) Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp), ) { SnackbarHost( hostState = snackBarData ) { Snackbar(it) } ButtonWithProgress( primary = true, modifier = Modifier.fillMaxWidth(), onClick = { mvi.store.intent(Intent.OnDoneClicked) }, enabled = !state.isLoading && state.canAddMoreTimers, isLoading = state.isLoading ) { Text(LocalStrings.current.save) } } Spacer(Modifier.height(16.dp)) } } }
19
Kotlin
0
28
bec7508d38e87149005c57a98f10a0eb4dbd4891
12,400
app
MIT License
mobiuskt-update-generator/src/main/kotlin/UpdateGeneratorSymbolProcessor.kt
DrewCarlson
147,952,971
false
null
package kt.mobius.gen import com.google.devtools.ksp.processing.* import com.google.devtools.ksp.symbol.* import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.ksp.* import kt.mobius.* class UpdateGeneratorSymbolProcessor( private val codeGenerator: CodeGenerator, ) : SymbolProcessor { override fun process(resolver: Resolver): List<KSAnnotated> { val targets = resolver.getSymbolsWithAnnotation(GenerateUpdate::class.qualifiedName!!) targets.map(::generateSpecFile).forEach { specFile -> specFile.writeTo(codeGenerator, specFile.kspDependencies(true)) } return emptyList() } private fun generateSpecFile(updateSymbol: KSAnnotated): FileSpec { val updateParent = (updateSymbol as KSClassDeclaration).superTypes.firstOrNull { typeRef -> typeRef.element?.typeArguments?.size == 3 } checkNotNull(updateParent) { "Classes annotated with @GenerateUpdate must implement Update<M, E, F>: ${updateSymbol.simpleName}" } val typeArgs = updateParent.element?.typeArguments.orEmpty() val modelClassDec = checkNotNull(typeArgs[0].type?.resolve()).declaration as KSClassDeclaration val eventClassDec = checkNotNull(typeArgs[1].type?.resolve()).declaration as KSClassDeclaration val effectClassDec = checkNotNull(typeArgs[2].type?.resolve()).declaration as KSClassDeclaration val modelClassName = modelClassDec.toClassName() val eventClassName = eventClassDec.toClassName() val effectClassName = effectClassDec.toClassName() val eventSubclasses = eventClassDec.getSealedSubclasses() val objects = eventSubclasses.filter { it.classKind == ClassKind.OBJECT } val dataClasses = eventSubclasses.filter { it.classKind == ClassKind.CLASS } val sealedClasses = eventSubclasses.filter { it.modifiers.contains(Modifier.SEALED) } val nextReturnTypeName = Next::class.asTypeName() .parameterizedBy(modelClassName, effectClassName) val specName = "${modelClassDec.simpleName.asString().removeSuffix("Model")}GeneratedUpdate" return FileSpec.builder(modelClassDec.packageName.asString(), specName) .addType( TypeSpec.interfaceBuilder(specName) .addModifiers(KModifier.INTERNAL) .addSuperinterface( Update::class.asTypeName() .parameterizedBy(modelClassName, eventClassName, effectClassName) ) .addFunction(FunSpec.builder("update") .addModifiers(KModifier.OVERRIDE) .addParameter("model", modelClassName) .addParameter("event", eventClassName) .returns(nextReturnTypeName) .addCode(CodeBlock.builder() .add("@Suppress(\"REDUNDANT_ELSE_IN_WHEN\")") .add("\nreturn when (event) {\n") .indent() .apply { objects.forEach { addStatement( "%T -> ${it.asFunName()}(%L)", it.toClassName(), "model" ) } (dataClasses + sealedClasses).forEach { addStatement( "is %T -> ${it.asFunName()}(%L, %L)", it.toClassName(), "model", "event", ) } add("else -> error(\"unexpected missing branch\")") } .unindent() .add("\n}\n") .build()) .build()) .addFunctions(objects.map { FunSpec.builder(it.asFunName()) .addModifiers(KModifier.PUBLIC, KModifier.ABSTRACT) .addParameter("model", modelClassName) .returns(nextReturnTypeName) .build() }.toList()) .addFunctions(dataClasses.map { FunSpec.builder(it.asFunName()) .addModifiers(KModifier.PUBLIC, KModifier.ABSTRACT) .addParameter("model", modelClassName) .addParameter("event", it.toClassName()) .returns(nextReturnTypeName) .build() }.toList()) .addFunctions(sealedClasses.map { FunSpec.builder(it.asFunName()) .addModifiers(KModifier.PUBLIC, KModifier.ABSTRACT) .addParameter("model", modelClassName) .addParameter("event", it.toClassName()) .returns(nextReturnTypeName) .build() }.toList()) .addOriginatingKSFile(updateSymbol.containingFile!!) .addOriginatingKSFile(modelClassDec.containingFile!!) .addOriginatingKSFile(eventClassDec.containingFile!!) .addOriginatingKSFile(effectClassDec.containingFile!!) .build() ) .build() } private fun KSDeclaration.asFunName(): String { return simpleName.asString().replaceFirstChar(Char::lowercaseChar) } }
7
Kotlin
3
39
3b9c8fb9a94fec495bb2dab609178e165a90432d
6,029
mobius.kt
Apache License 2.0
app/src/main/java/com/jojalvo/mcapp/di/AppModule.kt
jose-ojalvo
619,971,179
false
null
package com.jojalvo.mcapp.di import android.content.Context import com.jojalvo.framework.base.pref.CacheManager import com.jojalvo.mcapp.application.MCApplication 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 /** * @author jojalvo * @since 1/4/23 * @email <EMAIL> */ @Module @InstallIn(SingletonComponent::class) class AppModule { @Provides @Singleton fun providesApplication() = MCApplication() @Provides @Singleton fun providesCacheManager(@ApplicationContext context: Context) = CacheManager(context) }
0
Kotlin
0
0
dce692be3868f044ce810f18903f0587d36acdac
714
MobileChallenge
Apache License 2.0
app/src/main/java/com/mahmoud/mohammed/movieapp/koin/AppModule.kt
hchihoang
328,573,886
false
null
package com.mahmoud.mohammed.movieapp.koin import android.content.Context import com.google.gson.Gson import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import com.mahmoud.mohammed.movieapp.BuildConfig import com.mahmoud.mohammed.movieapp.data.remote.api.MovieService import com.mahmoud.mohammed.movieapp.presentation.ui.popmovies.fragments.PopularMoviesViewModel import com.mahmoud.mohammed.movieapp.data.Repository import com.mahmoud.mohammed.movieapp.data.RepositoryImpl import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.android.viewmodel.dsl.viewModel import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit val appModule = module { single { Gson() } single { httpLoggingInterceptor() } single { okHttpClient(get(), get()) } single { retrofit(get(), get(), get()) } single { restApi(get()) } single<Repository> { RepositoryImpl(get()) } viewModel { PopularMoviesViewModel(get()) } } private fun httpLoggingInterceptor(): HttpLoggingInterceptor { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY return logging } private fun okHttpClient( context: Context, loggingInterceptor: HttpLoggingInterceptor ): OkHttpClient { val okHttpBuilder = OkHttpClient.Builder() .connectTimeout(10000, TimeUnit.MILLISECONDS) if (BuildConfig.DEBUG) okHttpBuilder.addInterceptor(loggingInterceptor) return okHttpBuilder.build() } private fun retrofit( context: Context, gson: Gson, httpClient: OkHttpClient ): Retrofit { return Retrofit.Builder() .baseUrl(Endpoint.BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(httpClient) .build() } private fun restApi(retrofit: Retrofit): MovieService = retrofit.create(MovieService::class.java)
0
Kotlin
0
0
5e470ad4b16de1e483c5ee06ad246db7ad89ee0d
2,030
MovieApp-Clean-Architecture
Apache License 2.0
libraries/tools/kotlin-maven-plugin-test/src/test/resources/kotlinSimple/src/A.kt
gigliovale
89,726,097
false
{"Java": 23302590, "Kotlin": 21941511, "JavaScript": 137521, "Protocol Buffer": 56992, "HTML": 49980, "Lex": 18051, "Groovy": 14093, "ANTLR": 9797, "IDL": 7706, "Shell": 5152, "CSS": 4679, "Batchfile": 3721}
class A { fun foo(s: String) = s + s }
0
Java
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
42
kotlin
Apache License 2.0
neoforge/src/main/kotlin/io/github/techtastic/witcheryrewoven/neoforge/datagen/WRNeoForgeRecipes.kt
TechTastic
760,206,863
false
{"Kotlin": 120169, "Java": 1768}
package io.github.techtastic.witcheryrewoven.neoforge.datagen import io.github.techtastic.witcheryrewoven.datagen.WRCommonRecipes import net.minecraft.core.HolderLookup import net.minecraft.data.PackOutput import net.minecraft.data.recipes.RecipeOutput import net.minecraft.data.recipes.RecipeProvider import java.util.concurrent.CompletableFuture class WRNeoForgeRecipes(output: PackOutput, provider: CompletableFuture<HolderLookup.Provider>) : RecipeProvider(output, provider) { override fun buildRecipes(exporter: RecipeOutput) { WRCommonRecipes.buildRecipes(exporter) } }
0
Kotlin
0
0
da17ab38949531f016e0988ffdd43dd3e527df39
593
WitcheryRewoven
MIT License
redwood-yoga/src/commonMain/kotlin/app/cash/redwood/yoga/internal/detail/Log.kt
cashapp
305,409,146
false
{"Kotlin": 2089205, "Swift": 20649, "Objective-C": 4497, "Java": 1583, "Shell": 253, "HTML": 235, "C": 129}
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package app.cash.redwood.yoga.internal.detail import app.cash.redwood.yoga.internal.YGConfig import app.cash.redwood.yoga.internal.YGNode import app.cash.redwood.yoga.internal.enums.YGLogLevel internal object Log { fun log( node: YGNode?, level: YGLogLevel, context: Any?, format: String, vararg args: Any?, ) { GlobalMembers.vlog(node?.config, node, level, context, format, *args) } fun log( config: YGConfig?, level: YGLogLevel, context: Any?, format: String, vararg args: Any?, ) { GlobalMembers.vlog(config, null, level, context, format, *args) } }
108
Kotlin
73
1,648
3f14e622c2900ec7e0dfaff5bd850c95a7f29937
806
redwood
Apache License 2.0
app/src/main/java/com/noto/app/components/BottomSheetDialog.kt
alialbaali
245,781,254
false
{"Kotlin": 882792, "Ruby": 953}
package com.noto.app.components import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.rememberNestedScrollInteropConnection import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import com.noto.app.settings.SettingsViewModel import com.noto.app.theme.NotoTheme import com.noto.app.theme.dialog import org.koin.androidx.viewmodel.ext.android.viewModel private val TipHeight = 5.dp private val TipWidth = 30.dp @Composable fun BaseDialogFragment.BottomSheetDialog( title: String, modifier: Modifier = Modifier, headerColor: Color? = null, painter: Painter? = null, content: @Composable ColumnScope.() -> Unit, ) { val contentScrollState = rememberScrollState() val headerScrollState = rememberScrollState() val nestedScrollConnection = rememberNestedScrollInteropConnection() val viewModel by viewModel<SettingsViewModel>() val theme by viewModel.theme.collectAsState() val isContentScrolling by remember { derivedStateOf { contentScrollState.value > 0 } } val elevation by animateDpAsState( targetValue = if (isContentScrolling) NotoTheme.dimensions.extraSmall else 0.dp, animationSpec = tween(ElevationAnimationDuration) ) NotoTheme(theme = theme) { Surface( shape = MaterialTheme.shapes.dialog, color = MaterialTheme.colorScheme.background, modifier = Modifier ) { Column { Header( title = title, painter = painter, headerColor = headerColor, elevation = elevation, modifier = Modifier .nestedScroll(nestedScrollConnection) .verticalScroll(headerScrollState) ) Column( modifier = modifier .nestedScroll(nestedScrollConnection) .verticalScroll(contentScrollState) .padding(NotoTheme.dimensions.medium), horizontalAlignment = Alignment.CenterHorizontally, ) { content() } } } } } @Composable private fun Header( title: String, painter: Painter?, headerColor: Color?, elevation: Dp, modifier: Modifier = Modifier, ) { Surface( modifier = Modifier.zIndex(1F), color = MaterialTheme.colorScheme.background, shadowElevation = elevation, ) { Box( modifier .fillMaxWidth() .padding(NotoTheme.dimensions.medium), contentAlignment = Alignment.Center ) { if (painter != null) Icon( painter = painter, contentDescription = title, modifier = Modifier.align(Alignment.TopStart) ) Column(horizontalAlignment = Alignment.CenterHorizontally) { Tip(headerColor ?: MaterialTheme.colorScheme.primary) Title(title, headerColor ?: MaterialTheme.colorScheme.primary) } } } } @Composable private fun Tip(color: Color, modifier: Modifier = Modifier) { Box( modifier .padding(bottom = NotoTheme.dimensions.extraSmall) .size(TipWidth, TipHeight) .background(color, MaterialTheme.shapes.extraLarge) ) } @Composable private fun Title(title: String, color: Color, modifier: Modifier = Modifier) { Text( text = title, modifier = modifier.padding(top = NotoTheme.dimensions.extraSmall), style = MaterialTheme.typography.titleMedium, color = color, ) }
60
Kotlin
21
428
a1863c169f12d6852edc1c03d080a050647d3964
4,459
Noto
Apache License 2.0
app/src/main/java/com/nobodysapps/septimanapp/dependencyInjection/SeptimanappApplicationModule.kt
BananaNosh
200,501,226
false
{"Kotlin": 129330, "HTML": 28538, "Python": 5475}
package com.nobodysapps.septimanapp.dependencyInjection import android.content.Context import com.nobodysapps.septimanapp.activity.MainActivity import com.nobodysapps.septimanapp.fragments.EnrolmentFragment import com.nobodysapps.septimanapp.fragments.HorariumFragment import com.nobodysapps.septimanapp.fragments.MapFragment import com.nobodysapps.septimanapp.notifications.AlarmReceiver import com.nobodysapps.septimanapp.notifications.NotificationActionReceiver import com.nobodysapps.septimanapp.utils.CalendarUtils import dagger.Module import dagger.Provides import dagger.android.ContributesAndroidInjector import javax.inject.Scope @Scope @Retention(AnnotationRetention.BINARY) annotation class SeptimanappApplicationScope @Module class ContextModule(private val context: Context) { @Provides @SeptimanappApplicationScope fun provideContext() = context } @Module abstract class MainActivityModule { @ContributesAndroidInjector abstract fun contributeMainActivityInjector(): MainActivity } @Module abstract class HorariumFragmentModule { @ContributesAndroidInjector abstract fun contributeHorariumFragmentInjector(): HorariumFragment } @Module abstract class EnrolFragmentModule { @ContributesAndroidInjector abstract fun contributeEnrolmentFragmentInjector(): EnrolmentFragment } @Module abstract class MapFragmentModule { @ContributesAndroidInjector abstract fun contributeMapFragmentInjector(): MapFragment } @Module abstract class BroadcastReceiverModule { @ContributesAndroidInjector abstract fun contributeAlarmReceiverInjector(): AlarmReceiver @ContributesAndroidInjector abstract fun contributeNotificationActionReceiverInjector(): NotificationActionReceiver } @Module class TimeUtilsModule { @Provides fun providesCalendarUtils(): CalendarUtils { return CalendarUtils() } }
14
Kotlin
2
0
aa8e7df4fb806176553e9b80001d72ef8de25d60
1,879
Septimanapp
MIT License
keel-clouddriver/src/main/kotlin/com/netflix/spinnaker/keel/clouddriver/MemoryCloudDriverCache.kt
amitkhurdhara1990
126,823,024
true
{"Kotlin": 358363, "Shell": 2094}
package com.netflix.spinnaker.keel.clouddriver import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder import com.netflix.spinnaker.keel.clouddriver.model.Credential import com.netflix.spinnaker.keel.clouddriver.model.Network import com.netflix.spinnaker.keel.clouddriver.model.SecurityGroupSummary import java.util.concurrent.TimeUnit class MemoryCloudDriverCache( private val cloudDriver: CloudDriverService ) : CloudDriverCache { private val securityGroupSummaries = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(30, TimeUnit.SECONDS) .build<String, SecurityGroupSummary>() private val networks = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(30, TimeUnit.SECONDS) .build<String, Network>() private val availabilityZones = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(30, TimeUnit.SECONDS) .build<String, Set<String>>() private val credentials = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterWrite(1, TimeUnit.HOURS) .build<String, Credential>() private fun credentialBy(name: String): Credential = credentials.getOrNotFound(name, "Credentials with name $name not found") { cloudDriver .getCredential(name) } override fun securityGroupSummaryBy(account: String, region: String, id: String): SecurityGroupSummary = securityGroupSummaries.getOrNotFound( "$account:$region:$id", "Security group with id $id not found in the $account account and $region region" ) { val credential = credentialBy(account) // TODO-AJ should be able to swap this out for a call to `/search` cloudDriver .getSecurityGroupSummaries(account, credential.type, region) .firstOrNull { it.id == id } } override fun networkBy(id: String): Network = networks.getOrNotFound(id, "VPC network with id $id not found") { cloudDriver .listNetworks()["aws"] ?.firstOrNull { it.id == id } } // TODO rz - caches here aren't very efficient // TODO rz - caches here aren't very efficient override fun networkBy(name: String?, account: String, region: String): Network = networks.getOrNotFound("$name:$account:$region", "VPC network named $name not found in $region") { cloudDriver .listNetworks()["aws"] ?.firstOrNull { it.name == name && it.account == account && it.region == region } } override fun availabilityZonesBy(account: String, vpcId: String, region: String): Set<String> = availabilityZones.get("$account:$vpcId:$region") { cloudDriver .listSubnets("aws") .filter { it.account == account && it.vpcId == vpcId && it.region == region } .map { it.availabilityZone } .toSet() } private fun <T> Cache<String, T>.getOrNotFound(key: String, notFoundMessage: String, loader: () -> T?): T { var v = getIfPresent(key) if (v == null) { v = loader.invoke() if (v == null) { throw ResourceNotFound(notFoundMessage) } put(key, v) } return v } }
0
Kotlin
0
0
db755ed4b692a38dcb53d3e5290a36c702ea0ef0
3,112
keel
Apache License 2.0
madman/src/main/java/com/flipkart/madman/component/enums/AdEventType.kt
flipkart-incubator
235,603,923
false
null
/* * Copyright (C) 2020 Flipkart Internet Pvt Ltd * * 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.flipkart.madman.component.enums /** * List of all ad events sent to the client. */ enum class AdEventType { STARTED, PAUSED, RESUMED, LOADED, CONTENT_PAUSE_REQUESTED, CONTENT_RESUME_REQUESTED, PROGRESS, TAPPED, FIRST_QUARTILE, MIDPOINT, THIRD_QUARTILE, COMPLETED, SKIPPED, AD_BREAK_STARTED, AD_BREAK_ENDED, AD_BREAK_READY, CLICKED, ALL_AD_COMPLETED }
8
null
8
66
ded0a7a5d50bdf2b60e5a31a41943266bb677041
1,052
madman-android
Apache License 2.0
buildSrc/src/main/java/Utils.kt
simplekjl
525,306,955
false
null
object Utils { private const val easyPermissionsVersion = "1.0.0" // Easy Permissions const val easyPermissions = "com.vmadalin:easypermissions-ktx:${easyPermissionsVersion}" }
1
Kotlin
0
0
cc5f780165fabf9d9b5fe5c3caf2228a776993d3
190
TrackMe
Apache License 2.0
src/main/kotlin/org/opensearch/indexmanagement/indexstatemanagement/model/action/ReplicaCountActionConfig.kt
opensearch-project
354,094,562
false
null
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package org.opensearch.indexmanagement.indexstatemanagement.model.action import org.opensearch.client.Client import org.opensearch.cluster.service.ClusterService import org.opensearch.common.io.stream.StreamInput import org.opensearch.common.io.stream.StreamOutput import org.opensearch.common.settings.Settings import org.opensearch.common.xcontent.ToXContent import org.opensearch.common.xcontent.ToXContentObject import org.opensearch.common.xcontent.XContentBuilder import org.opensearch.common.xcontent.XContentParser import org.opensearch.common.xcontent.XContentParser.Token import org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken import org.opensearch.indexmanagement.indexstatemanagement.action.Action import org.opensearch.indexmanagement.indexstatemanagement.action.ReplicaCountAction import org.opensearch.indexmanagement.indexstatemanagement.model.ManagedIndexMetaData import org.opensearch.script.ScriptService import java.io.IOException data class ReplicaCountActionConfig( val numOfReplicas: Int, val index: Int ) : ToXContentObject, ActionConfig(ActionType.REPLICA_COUNT, index) { init { require(numOfReplicas >= 0) { "ReplicaCountActionConfig number_of_replicas value must be a non-negative number" } } override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { builder.startObject() super.toXContent(builder, params).startObject(ActionType.REPLICA_COUNT.type) builder.field(NUMBER_OF_REPLICAS_FIELD, numOfReplicas) return builder.endObject().endObject() } override fun isFragment(): Boolean = super<ToXContentObject>.isFragment() override fun toAction( clusterService: ClusterService, scriptService: ScriptService, client: Client, settings: Settings, managedIndexMetaData: ManagedIndexMetaData ): Action = ReplicaCountAction(clusterService, client, managedIndexMetaData, this) @Throws(IOException::class) constructor(sin: StreamInput) : this( numOfReplicas = sin.readInt(), index = sin.readInt() ) @Throws(IOException::class) override fun writeTo(out: StreamOutput) { super.writeTo(out) out.writeInt(numOfReplicas) out.writeInt(index) } companion object { const val NUMBER_OF_REPLICAS_FIELD = "number_of_replicas" @JvmStatic @Throws(IOException::class) fun parse(xcp: XContentParser, index: Int): ReplicaCountActionConfig { var numOfReplicas: Int? = null ensureExpectedToken(Token.START_OBJECT, xcp.currentToken(), xcp) while (xcp.nextToken() != Token.END_OBJECT) { val fieldName = xcp.currentName() xcp.nextToken() when (fieldName) { NUMBER_OF_REPLICAS_FIELD -> numOfReplicas = xcp.intValue() else -> throw IllegalArgumentException("Invalid field: [$fieldName] found in ReplicaCountActionConfig.") } } return ReplicaCountActionConfig( numOfReplicas = requireNotNull(numOfReplicas) { "$NUMBER_OF_REPLICAS_FIELD is null" }, index = index ) } } }
74
Kotlin
31
17
bab2b5a9cfa550f19b2eb87b7051423f74e12132
3,356
index-management
Apache License 2.0
src/main/kotlin/nz/hailwood/inertiajs/settings/InertiaSettingsInterface.kt
hailwood
390,622,057
false
null
package nz.hailwood.inertiajs.settings import com.intellij.ide.BrowserUtil import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.project.Project import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.DocumentAdapter import com.intellij.ui.HyperlinkLabel import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBTextField import com.intellij.uiDesigner.core.Spacer import com.intellij.util.ui.FormBuilder import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.Color import java.io.File import javax.swing.JComponent import javax.swing.JTextField import javax.swing.UIManager import javax.swing.event.DocumentEvent class InertiaSettingsInterface(project: Project) : SearchableConfigurable { private val settings = project.getService(InertiaSettingsService::class.java) private val inertiaPagesRootField = TextFieldWithBrowseButton() override fun getPreferredFocusedComponent(): JComponent = inertiaPagesRootField init { inertiaPagesRootField.addBrowseFolderListener( "Path to Pages Root", null, project, FileChooserDescriptorFactory.createSingleFolderDescriptor() ) setupTextFieldDefaultValue( inertiaPagesRootField.textField, settings.defaultInertiaPagesRoot(project).replace("/", File.separator) ) } @Suppress("DialogTitleCapitalization") override fun getDisplayName(): String = "Inertia.js" override fun isModified(): Boolean { return settings?.customInertiaPagesRoot != inertiaPagesRootField.text } override fun apply() { settings?.customInertiaPagesRoot = inertiaPagesRootField.text } fun getDefaultValueColor(): Color { return UIManager.getColor("TextField.inactiveForeground") ?: UIManager.getColor("nimbusDisabledText") } fun getChangedValueColor(): Color { return UIManager.getColor("TextField.foreground") } private fun setupTextFieldDefaultValue(textField: JTextField, defaultValue: String) { if (StringUtil.isEmptyOrSpaces(defaultValue)) return textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { textField.foreground = if (defaultValue == textField.text) getDefaultValueColor() else getChangedValueColor() } }) if (textField is JBTextField) { textField.emptyText.text = defaultValue } } override fun createComponent(): JComponent { return FormBuilder.createFormBuilder() .addLabeledComponent(JBLabel("Path to pages root:"), inertiaPagesRootField, 1, false) .addComponentToRightColumn(HyperlinkLabel().apply { @Suppress("UnstableApiUsage") setTextWithHyperlink("This should be set to the same location Inertia.js <hyperlink>resolves your pages from</hyperlink>.") JBUI.CurrentTheme.ContextHelp.FOREGROUND UIUtil.applyStyle(UIUtil.ComponentStyle.SMALL, this) addHyperlinkListener { BrowserUtil.browse("https://inertiajs.com/client-side-setup#initialize-app") } }, 1) .addComponentFillVertically(Spacer(), 0) .panel } override fun reset() { inertiaPagesRootField.text = settings?.customInertiaPagesRoot ?: "" } override fun getHelpTopic(): String? = null override fun getId(): String = "inertia-js" }
8
Kotlin
1
18
250e48ab5c082c032a9cf75f0bff29184ebc6903
3,708
idea-inertiajs-plugin
Apache License 2.0
presentation/presentation_detail/src/main/java/com/serj113/presentation/detail/datasource/ReviewPagingDataSource.kt
serj113
260,604,628
false
null
package com.serj113.presentation.detail.datasource import androidx.paging.PagingSource import androidx.paging.PagingSource.LoadResult.Page import androidx.paging.PagingSource.LoadResult.Error import androidx.paging.PagingState import com.serj113.domain.base.Entity.Success import com.serj113.domain.interactor.FetchMovieReviewUseCase import com.serj113.model.Review import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import java.io.IOException class ReviewPagingDataSource constructor( private val movieId: Long, private val useCase: FetchMovieReviewUseCase ) : PagingSource<Long, Review>() { override suspend fun load(params: LoadParams<Long>): LoadResult<Long, Review> { return try { val mutableListReview = mutableListOf<Review>() val pageKey = params.key ?: 1L var totalPages = 0 useCase.invoke(FetchMovieReviewUseCase.Args(movieId, pageKey)) .onEach { entity -> when (entity) { is Success -> { totalPages = entity.data.totalPages mutableListReview.addAll(entity.data.results) } } } .collect() val nextKey = if (pageKey + 1 > totalPages) null else pageKey + 1 Page( data = mutableListReview, prevKey = null, nextKey = nextKey ) } catch (exception: IOException) { return Error(exception) } } override fun getRefreshKey(state: PagingState<Long, Review>): Long? { return state.anchorPosition?.toLong() } }
0
Kotlin
0
4
b3a201623fc7f3f67866dad5bdbad8c9882f93e4
1,729
Imagine-Movies
Apache License 2.0
core/src/commonMain/kotlin/org/kobjects/greenspun/core/types/FuncType.kt
kobjects
340,712,554
false
{"Kotlin": 43685, "Ruby": 1673}
package org.kobjects.greenspun.core.types import org.kobjects.greenspun.core.func.Func import org.kobjects.greenspun.core.tree.Node data class FuncType( val index: Int, val returnType: Type, val parameterTypes: List<Type>, ) : Type { override fun createConstant(value: Any): Node { return Func.Const(value as Func) } fun matches(returnType: Type, parameterTypes: List<Type>) = this.returnType == returnType && this.parameterTypes == parameterTypes }
0
Kotlin
0
0
5956a46c3e53260363c683967fbcf014082cb4de
494
greenspun
Apache License 2.0
lib/src/main/java/se/warting/billy/flow/SkuStatus.kt
warting
416,844,833
false
{"Kotlin": 37311, "Shell": 1487}
package se.warting.billy.flow import com.android.billingclient.api.BillingFlowParams import com.android.billingclient.api.Purchase import com.android.billingclient.api.SkuDetails /** * Defines the status of a given [Sku] */ sealed class SkuStatus { /** * The given [Sku] from this status */ abstract val type: Sku data class Owned(override val type: Sku, val purchase: List<Purchase>) : SkuStatus() data class Loading(override val type: Sku) : SkuStatus() data class Available(override val type: Sku, val skuDetails: SkuDetails) : SkuStatus() { fun buy() { val flowParams = BillingFlowParams.newBuilder() .setSkuDetails(skuDetails) .build() buy(flowParams) } // maybe public? private fun buy(billingFlowParams: BillingFlowParams) { BillingProvider.instance.buy(billingFlowParams) } } data class Unavailable(override val type: Sku) : SkuStatus() }
22
Kotlin
0
20
ca00f4e9d0f032906a2184b4420da58e83a25bfe
1,003
billy
MIT License
core/src/main/kotlin/com/antwerkz/gridfs/GridFSFileAttributeView.kt
evanchooly
54,803,646
false
null
package com.antwerkz.gridfs import java.nio.file.attribute.BasicFileAttributeView import java.nio.file.attribute.BasicFileAttributes import java.nio.file.attribute.FileTime class GridFSFileAttributeView(private val path: GridFSPath) : BasicFileAttributeView { override fun readAttributes(): BasicFileAttributes { return GridsFSFileAttributes(path) } override fun setTimes(lastModifiedTime: FileTime?, lastAccessTime: FileTime?, createTime: FileTime?) { } override fun name(): String? { return "gridfs" } }
0
Kotlin
0
2
58a720d9dd347e06315562f42bac90213c658da1
549
gridfs-provider
Apache License 2.0
navigator-compose/samples/basic-sample/src/androidTest/java/com/kpstv/navigation/compose/sample/test/UnifiedTests.kt
KaustubhPatange
356,920,997
false
{"Kotlin": 360524, "Shell": 205}
@file:Suppress("invisible_reference", "invisible_member") package com.kpstv.navigation.compose.sample.test import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.AndroidComposeTestRule import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.lifecycle.Lifecycle import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.platform.app.InstrumentationRegistry import com.kpstv.navigation.compose.LifecycleControllerStore import com.kpstv.navigation.compose.sample.MainActivity import com.kpstv.navigation.compose.sample.ui.componenets.MenuItem import com.kpstv.navigation.compose.sample.ui.screens.MainFirstRoute import com.kpstv.navigation.compose.sample.ui.screens.MainRoute import com.kpstv.navigation.compose.sample.ui.screens.MenuHomeRoute import com.kpstv.navigation.compose.sample.ui.screens.MenuHomeRouteKey import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class UnifiedTests { @get:Rule val composeTestRule: AndroidComposeTestRule<ActivityScenarioRule<MainActivity>, MainActivity> = createAndroidComposeRule() // Found that "Go to root" button was crashing app on device due to incorrect lifecycle events // handling like onDestroy() when app is not initialized. @Test fun goBackToRootTest() { composeTestRule.activity.apply { composeTestRule.onNodeWithText("Go to second screen").performClick() composeTestRule.waitForIdle() composeTestRule.onNodeWithText("Settings").assertIsDisplayed() composeTestRule.onNodeWithText("Settings").performClick() composeTestRule.waitForIdle() composeTestRule.onNodeWithText("Go to Settings:Second").assertIsDisplayed() composeTestRule.onNodeWithText("Go to Settings:Second").performClick() composeTestRule.waitForIdle() composeTestRule.onNodeWithText("Go to Root").assertIsDisplayed() val routesAndLifecycles = navigator.getAllHistory().map { it to it.lifecycleController.lifecycle } composeTestRule.onNodeWithText("Go to Root").performClick() composeTestRule.waitForIdle() composeTestRule.onNodeWithText("Go to second screen").assertIsDisplayed() InstrumentationRegistry.getInstrumentation().waitForIdleSync() routesAndLifecycles.forEach { (route, lifecycle) -> if (route is MainFirstRoute.Primary || route is MainRoute.First) { assert(route.lifecycleController.lifecycle.currentState == Lifecycle.State.RESUMED) } else { assert(lifecycle.currentState == Lifecycle.State.DESTROYED) } } } } @Test fun correctLifecycleEventsTest() { composeTestRule.activity.apply { var states = navigator.getAllHistory().map { it.lifecycleController.lifecycle.currentState } // When application starts all states should be resumed. assert(states.all { it == Lifecycle.State.RESUMED }) // Activity onPause() composeTestRule.activityRule.scenario.moveToState(Lifecycle.State.STARTED) composeTestRule.waitForIdle() // Verify if all incoming states are onPaused() states = navigator.getAllHistory().map { it.lifecycleController.lifecycle.currentState } assert(states.all { it == Lifecycle.State.STARTED }) // Activity onResume() composeTestRule.activityRule.scenario.moveToState(Lifecycle.State.RESUMED) composeTestRule.onNodeWithText("Go to second screen").performClick() composeTestRule.waitForIdle() val mainFirstRouteHistory = navigator.getHistory(MainFirstRoute.key) val mainFirstRoutePrimary = mainFirstRouteHistory.last() assert(mainFirstRoutePrimary is MainFirstRoute.Primary) // onPause() assert(mainFirstRoutePrimary.lifecycleController.lifecycle.currentState == Lifecycle.State.CREATED) with(navigator.getHistory(MainRoute.key)) { assert(last() is MainRoute.Second) assert(last().lifecycleController.lifecycle.currentState == Lifecycle.State.RESUMED) } with(navigator.getHistory(MenuItem.key)) { assert(last() is MenuItem.Home) assert(last().lifecycleController.lifecycle.currentState == Lifecycle.State.RESUMED) } with(navigator.getHistory(MenuHomeRouteKey.key)) { assert(last() is MenuHomeRoute.Primary) assert(last().lifecycleController.lifecycle.currentState == Lifecycle.State.RESUMED) } onBackPressed() composeTestRule.waitForIdle() // MenuHomeRoute.Primary, MenuItem.Home should be removed from LifecycleControllerStore assert(LifecycleControllerStore.getSnapshot().keys.none { it is MenuHomeRoute.Primary }) assert(LifecycleControllerStore.getSnapshot().keys.none { it is MenuItem.Home }) // onResume() assert(mainFirstRoutePrimary.lifecycleController.lifecycle.currentState == Lifecycle.State.RESUMED) } } }
3
Kotlin
5
97
d4f7327c4ff77883c4708d2a941e3ecad8f15daf
5,520
navigator
Apache License 2.0
app/src/main/java/no/divvun/packageobserver/SpellerArchiveWatcher.kt
divvun
24,789,155
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 2, "XML": 875, "Kotlin": 131, "Java": 212}
package no.divvun.packageobserver import android.content.Context import io.sentry.Sentry import no.divvun.Spellers import no.divvun.divvunspell.SpellerArchive import timber.log.Timber import java.io.File import java.io.IOException import java.util.* class SpellerArchiveWatcher(private val context: Context, private val locale: Locale) : OnPackageUpdateListener { var archive: SpellerArchive? = null var hasMetadata = true init { PackageObserver.listener = this updateArchive() } private fun cleanupInvalidFile(path: String) { val file = File(path) try { if (file.exists()) { Timber.d("File exists at $path") } file.delete() } catch(e: SecurityException) { Timber.e(e) } catch(e: IOException) { Timber.e(e) } } private fun updateArchive() { if (!hasMetadata) { // Don't bother trying to load an archive again since it doesn't exist. return } Timber.d("Retrieving speller for languageTag: ${locale.language}") val spellerPath = Spellers[locale.toLanguageTag()]?.spellerPath(context) if (spellerPath == null) { Timber.w("No speller found for ${locale.toLanguageTag()} in ${Spellers.config}") hasMetadata = false return } Timber.d("Speller path: $spellerPath") Timber.d("Updating speller archive") archive = try { Timber.d("Opening archive") SpellerArchive.open(spellerPath) } catch (ex: Exception) { Timber.e("Failed to open archive $ex") Sentry.captureException(ex) cleanupInvalidFile(spellerPath) null } } override fun onPackageUpdate() { updateArchive() } }
22
Java
6
9
5e71829dd991105f19aaec1d65dfff06c65b946a
1,871
giellakbd-android
Apache License 2.0
plugins/kotlin/idea/tests/testData/inspectionsLocal/canBeParameter/modifiedInInit.kt
JetBrains
2,489,216
false
null
// PROBLEM: none class ModifiedInInit(<caret>var x: Int) { init { x += 2 } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
92
intellij-community
Apache License 2.0
app/src/main/java/com/eneskayiklik/word_diary/feature/settings/presentation/component/FontFamilyPickerDialog.kt
Enes-Kayiklik
651,794,521
false
null
package com.eneskayiklik.word_diary.feature.settings.presentation.component import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.MaterialTheme import androidx.compose.material3.RadioButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton 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.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import com.eneskayiklik.word_diary.R import com.eneskayiklik.word_diary.core.data_store.data.FontFamilyStyle @Composable fun FontFamilyPickerDialog( activeStyle: FontFamilyStyle, onSelected: (FontFamilyStyle) -> Unit, onDismiss: () -> Unit ) { Dialog(onDismissRequest = onDismiss) { Column( modifier = Modifier .fillMaxWidth() .clip(MaterialTheme.shapes.extraLarge) .background(MaterialTheme.colorScheme.surface) .padding(vertical = 24.dp), ) { Text( text = stringResource(id = R.string.font_family), style = MaterialTheme.typography.headlineSmall, modifier = Modifier.padding(horizontal = 24.dp), color = MaterialTheme.colorScheme.onSurface ) LazyColumn( modifier = Modifier .padding(top = 24.dp) .heightIn(max = 192.dp) ) { FontFamilyStyle.values().forEach { style -> item(key = style) { Row( modifier = Modifier .fillMaxWidth() .clickable { onSelected(style) } .padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically ) { RadioButton( selected = style == activeStyle, onClick = { onSelected(style) } ) Text( text = style.title, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant ) } } } } TextButton( onClick = onDismiss, modifier = Modifier .align(Alignment.End) .padding(end = 16.dp) ) { Text(text = stringResource(id = R.string.dialog_ok)) } } } }
0
Kotlin
0
3
c40d2b7fe1ce9b8926b660dcbbaa088fbca05f11
3,303
WordDiary
MIT License
app/src/main/java/com/bulletapps/candypricer/presentation/ui/scenes/main/user/supplies/SuppliesUIState.kt
jvsena42
485,055,339
false
{"Kotlin": 265086}
package com.bulletapps.candypricer.presentation.ui.scenes.main.user.supplies import com.bulletapps.candypricer.domain.model.SupplyModel import com.bulletapps.candypricer.presentation.ui.scenes.main.user.supplies.SuppliesViewModel.ScreenActions import kotlinx.coroutines.flow.MutableStateFlow class SuppliesUIState( val screenState: MutableStateFlow<ScreenState> = MutableStateFlow(ScreenState.Loading), val suppliesList: MutableStateFlow<List<SupplyModel>> = MutableStateFlow(emptyList()), val isLoading: MutableStateFlow<Boolean> = MutableStateFlow(false) ) { fun onSuccess(supplies: List<SupplyModel>) { suppliesList.value = supplies.sortedBy { it.name } isLoading.value = false screenState.value = ScreenState.ShowScreen } fun onFailure(retry: ScreenActions, logout: ScreenActions) { isLoading.value = false screenState.value = ScreenState.Failure(retry, logout) } sealed class ScreenState { object Loading : ScreenState() object ShowScreen : ScreenState() data class Failure(val retry: ScreenActions, val logout: ScreenActions): ScreenState() } }
18
Kotlin
0
2
c89da3d248d32f976ad7f0d918815822787ae33a
1,155
baking_calculator
MIT License
flutter/aoe_flutter_plugin/android/src/main/kotlin/com/didi/aoe/aoeflutter/model/model/DeviceInfo.kt
didi
199,149,606
false
{"C++": 387625, "Objective-C": 203073, "C": 197767, "Java": 123392, "Kotlin": 104237, "Objective-C++": 19387, "Ruby": 9735, "Python": 7961, "Dart": 5232, "Shell": 2242, "CMake": 1600}
package com.didi.aoe.aoeflutter.model.model /** * * * @author noctis * @since 1.1.0 */ data class DeviceInfo @JvmOverloads constructor( var uuid: String = "", var name: String = "", var model: String = "", var system: String = "", var version: String = "", var disk: String = "", var memory: String = "", var ip: String = "", var macAddress: String = "" ) { fun toMap(): Map<String, Any?> { return mapOf( Pair("uuid", uuid), Pair("name", name), Pair("model", model), Pair("system", system), Pair("version", version), Pair("disk", disk), Pair("memory", memory), Pair("ip", ip), Pair("macAddress", macAddress) ) } }
11
C++
128
869
2b4ddd38462eca4ca3a6e939067187504084d1fa
859
AoE
Apache License 2.0
src/main/kotlin/io/sixtysix/happenings/utils/PasswordUtil.kt
adrianeriksen
190,924,032
false
null
package io.sixtysix.happenings.utils import de.mkammerer.argon2.Argon2Factory import de.mkammerer.argon2.Argon2Helper object PasswordUtil { private const val TIME_IN_MS = 500L private const val MEMORY_COST = 65536 private const val PARALLELISM = 1 private var argon2hasher = Argon2Factory.create() private var iterations = Argon2Helper.findIterations(argon2hasher, TIME_IN_MS, MEMORY_COST, PARALLELISM) fun hashPassword(password: String): String = argon2hasher.hash(iterations, MEMORY_COST, PARALLELISM, password.toCharArray()) fun verifyPassword(hashedPassword: String, password: String): Boolean = argon2hasher.verify(hashedPassword, password.toCharArray()) }
1
Kotlin
0
1
ae8170cba4bc6988f8c0ef87ee08fb81f4017c08
712
happenings
MIT License
app/src/main/java/com/flixclusive/data/database/watch_history/WatchHistoryDatabase.kt
rhenwinch
659,237,375
false
null
package com.flixclusive.data.database.watch_history import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.flixclusive.data.database.common.FilmDataConverter import com.flixclusive.data.database.watch_history.converter.WatchHistoryItemConverter import com.flixclusive.domain.model.entities.WatchHistoryItem @Database(entities = [WatchHistoryItem::class], version = 1, exportSchema = false) @TypeConverters(WatchHistoryItemConverter::class, FilmDataConverter::class) abstract class WatchHistoryDatabase : RoomDatabase() { abstract fun watchHistoryDao(): WatchHistoryDao companion object { @Volatile private var INSTANCE: WatchHistoryDatabase? = null fun getInstance(context: Context): WatchHistoryDatabase { return INSTANCE ?: synchronized(this) { Room.databaseBuilder( context, WatchHistoryDatabase::class.java, "watch_history_database" ) .build() .also { INSTANCE = it } } } } }
2
Kotlin
2
18
2eef4c82655294eb3b277c00b3d8f7bea3f6961e
1,240
Flixclusive
MIT License
app/src/main/java/eu/tkacas/smartalert/ui/screen/settings/SettingsScreen.kt
thkox
755,205,761
false
{"Kotlin": 339161}
package eu.tkacas.smartalert.ui.screen.settings import android.annotation.SuppressLint import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import eu.tkacas.smartalert.R import eu.tkacas.smartalert.ui.component.SettingCard import eu.tkacas.smartalert.ui.navigation.AppBarBackView import eu.tkacas.smartalert.ui.screen.screensInSettings import eu.tkacas.smartalert.viewmodel.settings.SettingsViewModel @SuppressLint("UnusedMaterialScaffoldPaddingParameter", "CoroutineCreationDuringComposition") @Composable fun SettingsScreen(navController: NavController) { val viewModel = SettingsViewModel(LocalContext.current) val sharedPrefManager = viewModel.sharedPrefManager Scaffold( topBar = { AppBarBackView( title = stringResource(id = R.string.settings), navController = navController, enableSettingsButton = false ) }, content = { LazyColumn( modifier = Modifier.fillMaxSize() ) { items(screensInSettings) { screen -> if (!(sharedPrefManager.isEmployee() && screen.route == "MyReportsHistory")) { SettingCard(screen = screen) { navController.navigate(screen.route) } } } } } ) } @Preview @Composable fun SettingsScreenPreview() { SettingsScreen(navController = rememberNavController()) }
0
Kotlin
1
2
bfdad11c4cf73478e897105ef5467e964e3453c8
1,975
uni_2023-smart-alert
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/createandvaryalicenceapi/service/probation/Identifiers.kt
ministryofjustice
384,371,667
false
{"Kotlin": 2241425, "Shell": 12714, "Dockerfile": 1384, "PLpgSQL": 863}
package uk.gov.justice.digital.hmpps.createandvaryalicenceapi.service.probation data class Identifiers( val crn: String, val noms: String?, )
3
Kotlin
0
1
481532c3f259e1261adc5bbbdd6c67a4ba07c134
147
create-and-vary-a-licence-api
MIT License
shared/src/iosMain/kotlin/com/myapplication/di/modules/DbModule.kt
mobidroid92
642,819,457
false
{"Kotlin": 51119, "Swift": 580, "Shell": 228, "Ruby": 101}
package com.myapplication.di.modules import com.myapplication.di.createAppDatabase import org.koin.dsl.module actual val databaseModule = module { single { createAppDatabase() } }
0
Kotlin
0
1
25047d6e01799172880cd366a7762c9a0ea86e78
198
Compose-Multiplatform-Demo
Apache License 2.0
app/src/main/java/com/manoj/dlt/interfaces/IDeepLinkHistory.kt
ManojMadanmohan
52,667,086
false
null
package com.manoj.dlt.interfaces import com.manoj.dlt.models.DeepLinkInfo interface IDeepLinkHistory { abstract fun addLinkToHistory(deepLinkInfo: DeepLinkInfo) abstract fun removeLinkFromHistory(deepLink: String) abstract fun clearAllHistory() abstract fun getLinkHistoryFromFileSystem() : List<DeepLinkInfo> }
2
null
1
19
d8688cdb280290fa0c8e32ba6eb1164c020563fb
329
dlt
MIT License
java/kotlin/src/main/kotlin/cosmos/staking/v1beta1/StakeAuthorizationKt.kt
furysport
798,989,200
true
{"Git Config": 1, "Text": 1, "Ignore List": 3, "Makefile": 3, "Markdown": 3, "Gradle Kotlin DSL": 5, "INI": 2, "Shell": 3, "Batchfile": 1, "Java": 181, "Kotlin": 917, "JSON with Comments": 1, "JSON": 3, "Git Attributes": 1, "EditorConfig": 1}
//Generated by the protocol buffer compiler. DO NOT EDIT! // source: cosmos/staking/v1beta1/authz.proto package cosmos.staking.v1beta1; @kotlin.jvm.JvmSynthetic inline fun stakeAuthorization(block: cosmos.staking.v1beta1.StakeAuthorizationKt.Dsl.() -> Unit): cosmos.staking.v1beta1.Authz.StakeAuthorization = cosmos.staking.v1beta1.StakeAuthorizationKt.Dsl._create(cosmos.staking.v1beta1.Authz.StakeAuthorization.newBuilder()).apply { block() }._build() object StakeAuthorizationKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker class Dsl private constructor( @kotlin.jvm.JvmField private val _builder: cosmos.staking.v1beta1.Authz.StakeAuthorization.Builder ) { companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: cosmos.staking.v1beta1.Authz.StakeAuthorization.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): cosmos.staking.v1beta1.Authz.StakeAuthorization = _builder.build() /** * <pre> * max_tokens specifies the maximum amount of tokens can be delegate to a validator. If it is * empty, there is no spend limit and any amount of coins can be delegated. * </pre> * * <code>.cosmos.base.v1beta1.Coin max_tokens = 1 [(.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin"];</code> */ var maxTokens: cosmos.base.v1beta1.CoinOuterClass.Coin @JvmName("getMaxTokens") get() = _builder.getMaxTokens() @JvmName("setMaxTokens") set(value) { _builder.setMaxTokens(value) } /** * <pre> * max_tokens specifies the maximum amount of tokens can be delegate to a validator. If it is * empty, there is no spend limit and any amount of coins can be delegated. * </pre> * * <code>.cosmos.base.v1beta1.Coin max_tokens = 1 [(.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin"];</code> */ fun clearMaxTokens() { _builder.clearMaxTokens() } /** * <pre> * max_tokens specifies the maximum amount of tokens can be delegate to a validator. If it is * empty, there is no spend limit and any amount of coins can be delegated. * </pre> * * <code>.cosmos.base.v1beta1.Coin max_tokens = 1 [(.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin"];</code> * @return Whether the maxTokens field is set. */ fun hasMaxTokens(): kotlin.Boolean { return _builder.hasMaxTokens() } /** * <pre> * allow_list specifies list of validator addresses to whom grantee can delegate tokens on behalf of granter's * account. * </pre> * * <code>.cosmos.staking.v1beta1.StakeAuthorization.Validators allow_list = 2;</code> */ var allowList: cosmos.staking.v1beta1.Authz.StakeAuthorization.Validators @JvmName("getAllowList") get() = _builder.getAllowList() @JvmName("setAllowList") set(value) { _builder.setAllowList(value) } /** * <pre> * allow_list specifies list of validator addresses to whom grantee can delegate tokens on behalf of granter's * account. * </pre> * * <code>.cosmos.staking.v1beta1.StakeAuthorization.Validators allow_list = 2;</code> */ fun clearAllowList() { _builder.clearAllowList() } /** * <pre> * allow_list specifies list of validator addresses to whom grantee can delegate tokens on behalf of granter's * account. * </pre> * * <code>.cosmos.staking.v1beta1.StakeAuthorization.Validators allow_list = 2;</code> * @return Whether the allowList field is set. */ fun hasAllowList(): kotlin.Boolean { return _builder.hasAllowList() } /** * <pre> * deny_list specifies list of validator addresses to whom grantee can not delegate tokens. * </pre> * * <code>.cosmos.staking.v1beta1.StakeAuthorization.Validators deny_list = 3;</code> */ var denyList: cosmos.staking.v1beta1.Authz.StakeAuthorization.Validators @JvmName("getDenyList") get() = _builder.getDenyList() @JvmName("setDenyList") set(value) { _builder.setDenyList(value) } /** * <pre> * deny_list specifies list of validator addresses to whom grantee can not delegate tokens. * </pre> * * <code>.cosmos.staking.v1beta1.StakeAuthorization.Validators deny_list = 3;</code> */ fun clearDenyList() { _builder.clearDenyList() } /** * <pre> * deny_list specifies list of validator addresses to whom grantee can not delegate tokens. * </pre> * * <code>.cosmos.staking.v1beta1.StakeAuthorization.Validators deny_list = 3;</code> * @return Whether the denyList field is set. */ fun hasDenyList(): kotlin.Boolean { return _builder.hasDenyList() } /** * <pre> * authorization_type defines one of AuthorizationType. * </pre> * * <code>.cosmos.staking.v1beta1.AuthorizationType authorization_type = 4;</code> */ var authorizationType: cosmos.staking.v1beta1.Authz.AuthorizationType @JvmName("getAuthorizationType") get() = _builder.getAuthorizationType() @JvmName("setAuthorizationType") set(value) { _builder.setAuthorizationType(value) } /** * <pre> * authorization_type defines one of AuthorizationType. * </pre> * * <code>.cosmos.staking.v1beta1.AuthorizationType authorization_type = 4;</code> */ fun clearAuthorizationType() { _builder.clearAuthorizationType() } val validatorsCase: cosmos.staking.v1beta1.Authz.StakeAuthorization.ValidatorsCase @JvmName("getValidatorsCase") get() = _builder.getValidatorsCase() fun clearValidators() { _builder.clearValidators() } } @kotlin.jvm.JvmSynthetic inline fun validators(block: cosmos.staking.v1beta1.StakeAuthorizationKt.ValidatorsKt.Dsl.() -> Unit): cosmos.staking.v1beta1.Authz.StakeAuthorization.Validators = cosmos.staking.v1beta1.StakeAuthorizationKt.ValidatorsKt.Dsl._create(cosmos.staking.v1beta1.Authz.StakeAuthorization.Validators.newBuilder()).apply { block() }._build() object ValidatorsKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker class Dsl private constructor( @kotlin.jvm.JvmField private val _builder: cosmos.staking.v1beta1.Authz.StakeAuthorization.Validators.Builder ) { companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: cosmos.staking.v1beta1.Authz.StakeAuthorization.Validators.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): cosmos.staking.v1beta1.Authz.StakeAuthorization.Validators = _builder.build() /** * An uninstantiable, behaviorless type to represent the field in * generics. */ @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) class AddressProxy private constructor() : com.google.protobuf.kotlin.DslProxy() /** * <code>repeated string address = 1;</code> * @return A list containing the address. */ val address: com.google.protobuf.kotlin.DslList<kotlin.String, AddressProxy> @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) get() = com.google.protobuf.kotlin.DslList( _builder.getAddressList() ) /** * <code>repeated string address = 1;</code> * @param value The address to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("addAddress") fun com.google.protobuf.kotlin.DslList<kotlin.String, AddressProxy>.add(value: kotlin.String) { _builder.addAddress(value) } /** * <code>repeated string address = 1;</code> * @param value The address to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("plusAssignAddress") operator fun com.google.protobuf.kotlin.DslList<kotlin.String, AddressProxy>.plusAssign(value: kotlin.String) { _builder.addAddress(value) } /** * <code>repeated string address = 1;</code> * @param values The address to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("addAllAddress") fun com.google.protobuf.kotlin.DslList<kotlin.String, AddressProxy>.addAll(values: kotlin.collections.Iterable<kotlin.String>) { _builder.addAllAddress(values) } /** * <code>repeated string address = 1;</code> * @param values The address to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("plusAssignAllAddress") operator fun com.google.protobuf.kotlin.DslList<kotlin.String, AddressProxy>.plusAssign(values: kotlin.collections.Iterable<kotlin.String>) { _builder.addAllAddress(values) } /** * <code>repeated string address = 1;</code> * @param index The index to set the value at. * @param value The address to set. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("setAddress") operator fun com.google.protobuf.kotlin.DslList<kotlin.String, AddressProxy>.set(index: kotlin.Int, value: kotlin.String) { _builder.setAddress(index, value) }/** * <code>repeated string address = 1;</code> */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("clearAddress") fun com.google.protobuf.kotlin.DslList<kotlin.String, AddressProxy>.clear() { _builder.clearAddress() }} } } @kotlin.jvm.JvmSynthetic inline fun cosmos.staking.v1beta1.Authz.StakeAuthorization.copy(block: cosmos.staking.v1beta1.StakeAuthorizationKt.Dsl.() -> Unit): cosmos.staking.v1beta1.Authz.StakeAuthorization = cosmos.staking.v1beta1.StakeAuthorizationKt.Dsl._create(this.toBuilder()).apply { block() }._build() @kotlin.jvm.JvmSynthetic inline fun cosmos.staking.v1beta1.Authz.StakeAuthorization.Validators.copy(block: cosmos.staking.v1beta1.StakeAuthorizationKt.ValidatorsKt.Dsl.() -> Unit): cosmos.staking.v1beta1.Authz.StakeAuthorization.Validators = cosmos.staking.v1beta1.StakeAuthorizationKt.ValidatorsKt.Dsl._create(this.toBuilder()).apply { block() }._build()
0
null
0
0
ddd9cd1abce2d51cf273be478c2b614960ace761
10,526
terra.proto
Apache License 2.0
plugin-build/src/test/kotlin/okhttp3/Interceptor.kt
getsentry
241,145,606
false
null
package okhttp3 interface Interceptor { interface Chain }
36
null
31
99
054a2aa8c8da13553c8fad034b2cebb05e733092
63
sentry-android-gradle-plugin
MIT License
app/src/main/java/com/github/andiim/plantscan/app/ui/screens/home/settings/SettingsUiState.kt
Andi-IM
675,329,578
false
{"Kotlin": 136413}
package com.github.andiim.plantscan.app.ui.screens.home.settings class SettingsUiState(val isAnonymousAccount: Boolean = true)
10
Kotlin
0
0
9fa7ba99cd3d1dda70f57d21e815216aab2b725d
127
PlantScan
MIT License
app/src/main/java/com/andruhavuho/man/like/kcalcalc/AddSportActivity.kt
Andrey-Kachow
453,090,583
false
{"Kotlin": 24654}
package com.andruhavuho.man.like.kcalcalc import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import android.os.Bundle import android.os.VibrationEffect import android.os.Vibrator import android.text.Editable import android.view.animation.AnimationUtils import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.andruhavuho.man.like.kcalcalc.contracts.* import com.andruhavuho.man.like.kcalcalc.models.Sport import com.andruhavuho.man.like.kcalcalc.models.SportTime import com.andruhavuho.man.like.kcalcalc.ui.SportOptionsAdapter import com.andruhavuho.man.like.kcalcalc.ui.TextChangedListener import com.google.android.material.snackbar.Snackbar import org.json.JSONException import org.json.JSONObject import java.io.IOException import java.io.InputStream class AddSportActivity : AppCompatActivity() { private var pickedSport: Sport? = null private lateinit var btnCancelAddingSport: Button private lateinit var btnConfirmAddingSport: Button private lateinit var etNumMinutes: EditText private lateinit var etNumHours: EditText private lateinit var tvChosenActivity: TextView private lateinit var clAddSportRoot: ConstraintLayout private lateinit var sportOptionsAdapter: SportOptionsAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_sport) if (savedInstanceState != null) { pickedSport = savedInstanceState.getParcelable(SAVED_PICKED_SPORT) } setupPickedSportsRecyclerView() initializeViews() btnConfirmAddingSport.setOnClickListener { if (sportIsPicked() && minutesArePicked() && hoursArePicked()) { confirmSportAndReturnToCalc() } else { indicateThatAllFieldsMustBeFilled() } } btnCancelAddingSport.setOnClickListener { onBackPressed() } etNumHours.addTextChangedListener(object : TextChangedListener<EditText?>(etNumHours) { override fun onTextChanged(target: EditText?, s: Editable?) { onTimeTextChanged(target, s) if (getEnteredHours() ?: 0 > MAX_HOURS) { target?.setText("$MAX_HOURS", TextView.BufferType.EDITABLE) } } }) etNumMinutes.addTextChangedListener(object : TextChangedListener<EditText?>(etNumMinutes) { override fun onTextChanged(target: EditText?, s: Editable?) { onTimeTextChanged(target, s) if (getEnteredHours() ?: 0 > MAX_MINUTES) { target?.setText("$MAX_MINUTES", TextView.BufferType.EDITABLE) } } }) sportOptionsAdapter.sports = extractSportsFromJSON() sportOptionsAdapter.notifyDataSetChanged() } private fun initializeViews() { btnConfirmAddingSport = findViewById(R.id.btnConfirmAddingSport) btnCancelAddingSport = findViewById(R.id.btnCancelAddingSport) tvChosenActivity = findViewById(R.id.tvChosenActivity) clAddSportRoot = findViewById(R.id.clAddSportRoot) etNumMinutes = findViewById(R.id.etNumMinutes) etNumHours = findViewById(R.id.etNumHours) } override fun onSaveInstanceState(icicle: Bundle) { super.onSaveInstanceState(icicle) icicle.putParcelable(SAVED_PICKED_SPORT, pickedSport) } fun onTimeTextChanged(target: EditText?, s: Editable?) { target?.setTextColor(ContextCompat.getColor(this, R.color.green_dark_text)) } override fun onBackPressed() { finish() overridePendingTransition(R.anim.slide_in_back, R.anim.slide_out_back) } fun receivePickedSport(sport: Sport?) { if (sport != null) { pickedSport = sport tvChosenActivity.text = "Выбрано: \"${sport.name}\"" tvChosenActivity.setTextColor(ContextCompat.getColor(this, R.color.green_dark_text)) } else { Snackbar.make(clAddSportRoot, "Something went wrong", Snackbar.LENGTH_SHORT).show() } } private fun confirmSportAndReturnToCalc() { val result = Intent().apply { putExtra(PICKED_SPORT_ID, pickedSport?.id ?: -1) putExtra(PICKED_SPORT_NAME, pickedSport?.name ?: "Error") putExtra(PICKED_SPORT_KCAL_PER_HOUR, pickedSport?.kcalPerHour ?: -1) putExtra(PICKED_SPORT_NUM_HOURS, getEnteredHours() ?: -1) putExtra(PICKED_SPORT_NUM_MINUTES, getEnteredMinutes() ?: -1) } setResult(Activity.RESULT_OK, result) finish() overridePendingTransition(R.anim.slide_in_back, R.anim.slide_out_back) } private fun getEnteredHours(): Int? { return etNumHours.text.toString().toIntOrNull() } private fun getEnteredMinutes(): Int? { return etNumMinutes.text.toString().toIntOrNull() } private fun setupPickedSportsRecyclerView() { sportOptionsAdapter = SportOptionsAdapter(this) val rvAllSportsOptions = findViewById<RecyclerView>(R.id.rvAllSportsOptions) rvAllSportsOptions.adapter = sportOptionsAdapter } private fun indicateThatAllFieldsMustBeFilled() { // Vibrate val v = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { v.vibrate(VibrationEffect.createOneShot(VIBRATION_TIME, VibrationEffect.DEFAULT_AMPLITUDE)) } else { //deprecated in API 26 v.vibrate(VIBRATION_TIME) } if (!sportIsPicked()) { // Red Color tvChosenActivity.setTextColor(Color.RED) // Shake label tvChosenActivity.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake)) } if (!hoursArePicked()) { etNumHours.setHintTextColor(Color.RED) } if (!minutesArePicked()) { etNumMinutes.setHintTextColor(Color.RED) } } private fun sportIsPicked(): Boolean { return pickedSport != null } private fun hoursArePicked(): Boolean { return !etNumHours.text.isNullOrBlank() } private fun minutesArePicked(): Boolean { return !etNumMinutes.text.isNullOrBlank() } private fun extractSportsFromJSON(): List<Sport> { return try { val obj = JSONObject(loadJSONFromAsset()) val sports = obj.getJSONArray("sports") val sportList = mutableListOf<Sport>() for (i in 0 until sports.length()) { val sport = sports.getJSONObject(i) val id = sport.getLong("id") val sportName = sport.getString("name") val kcalPerHour = sport.getInt("kcalPerHour") sportList.add(Sport(id, sportName, kcalPerHour)) } sportList } catch (e: JSONException) { e.printStackTrace() listOf() } } private fun loadJSONFromAsset(): String { val jsonString: String? = try { val stream: InputStream = assets.open("sports.json") val size: Int = stream.available() val buffer = ByteArray(size) stream.read(buffer) stream.close() String(buffer, charset("UTF-8")) } catch (e: IOException) { e.printStackTrace() return EMPTY_SPORTS_JSON_STRING } return jsonString ?: EMPTY_SPORTS_JSON_STRING } companion object { const val EMPTY_SPORTS_JSON_STRING = "{\"sports\": []}" const val SAVED_PICKED_SPORT = "SAVED_PICKED_SPORT" const val MAX_MINUTES = 59 const val MAX_HOURS = 23 const val VIBRATION_TIME = 500L } }
0
Kotlin
0
0
2977096804dbe2f63b07d2bfa6ade18288a31f75
8,162
KcalCalc
MIT License
src/main/kotlin/com/badger/familyorgbe/service/users/UserService.kt
Artem-Yakovlev
445,531,524
false
{"Kotlin": 109555}
package com.badger.familyorgbe.service.users import com.badger.familyorgbe.models.entity.TokenEntity import com.badger.familyorgbe.models.entity.UserStatus import com.badger.familyorgbe.models.usual.User import com.badger.familyorgbe.repository.token.ITokenRepository import com.badger.familyorgbe.repository.users.IUsersRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class UserService : UserDetailsService { @Autowired private lateinit var userRepository: IUsersRepository @Autowired private lateinit var tokenRepository: ITokenRepository suspend fun saveUser(user: User): Boolean { return if (with(Dispatchers.IO) { userRepository.findByEmail(user.name) } != null) { false } else { val entity = user.toEntity() with(Dispatchers.IO) { userRepository.save(entity) } true } } fun findUserByEmail(email: String): User? { return userRepository.findByEmail(email = email)?.let(User::fromEntity) } override fun loadUserByUsername(email: String): UserDetails { val userEntity = userRepository.findByEmail(email) if (userEntity != null) { return userEntity.toUserDetails() } else { throw UsernameNotFoundException("User $email not found") } } @Transactional suspend fun updateNameOfUser(email: String, name: String): User? { return findUserByEmail(email)?.let { user -> userRepository.updateName( email = user.email, name = name ) user.copy(name = name) } } @Transactional suspend fun updateStatusOfUser(email: String, status: UserStatus): User? { return findUserByEmail(email)?.let { user -> userRepository.updateStatus( email = user.email, status = status ) user.copy(status = status) } } suspend fun getTokensForEmails(emails: List<String>): List<TokenEntity> { return with(Dispatchers.IO) { tokenRepository.getAllByEmails(emails) } } suspend fun saveToken(email: String, token: String) { val entity = TokenEntity(email, token) with(Dispatchers.IO) { tokenRepository.save(entity) } } @Transactional suspend fun saveImageAddress(email: String, imagePath: String) { with(Dispatchers.IO) { userRepository.updateImagePath(email = email, imagePath = imagePath) } } }
0
Kotlin
0
1
131e3e8841d55a9a14995aa6b254976c89d2c336
2,995
FamilyOrganizerBackend
MIT License
shared/src/commonMain/kotlin/com/norrisboat/ziuq/domain/utils/EndpointUtils.kt
norrisboat
746,362,661
false
{"Kotlin": 225770, "Swift": 70758}
package com.norrisboat.ziuq.domain.utils object Endpoint { fun Path.makeEndpoint(vararg parameters: String): String { var endpoint = this.value parameters.forEach { param -> endpoint = endpoint.replaceFirst("%", param) } return endpoint } enum class Path(val value: String) { LOGIN("/v1/auth/login"), REGISTER("/v1/auth/register"), QUIZ_SETUP("/v1/quiz/setup"), CREATE_QUIZ("/v1/quiz/create/%"), CREATE_LIVE_QUIZ("/v1/quiz/live/quiz/create/%"), JOIN_LIVE_QUIZ("/v1/quiz/live/quiz/join/%"), } }
0
Kotlin
2
7
94140c28aae2621f87b77a79edd66ea66519b047
605
Ziuq
MIT License
app/src/main/java/ru/nbsp/pushka/presentation/subscription/params/control/Control.kt
dimorinny
51,604,851
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 11, "Java": 14, "XML": 102, "Kotlin": 258}
package ru.nbsp.pushka.presentation.subscription.params.control /** * Created by egor on 16.03.16. */ interface Control { interface OnChangeListener { fun onChange(newValue: String?) } fun getValue(): String? fun setValue(value: String?) fun setOnChangeListener(onChangeListener: OnChangeListener) fun setError() fun setNoError() }
0
Kotlin
0
0
71ac416b33f628bbcec12fad4776f7abc242c882
372
pushka-android
MIT License
app/src/main/java/com/pingerx/gankit/ui/news/NewsData.kt
lehdutil
182,000,434
false
null
package com.pingerx.gankit.ui.news /** * @author Pinger * @since 2018/12/10 20:43 */ // 新闻频道 data class NewsChannelBean(val channelId: String, val name: String) data class NewsChannelResponse(val totalNum: Int, val ret_code: Int, val channelList: List<NewsChannelBean>?) // 新闻内容 data class NewsContentResponse(val ret_code: Int, val pagebean: NewsPageBean) data class NewsPageBean(val currentPage: Int, val allNum: Int, val maxResult: Int, val allPages: Int, val contentlist: List<NewsContentBean>) data class NewsContentBean( val link: String, val id: String, val channelId: String, val havePic: Boolean, val pubDate: String, val title: String, val channelName: String, val source: String, val imageurls: List<NewsImageBean>? ) data class NewsImageBean(val height: Int, val width: Int, val url: String)
0
Kotlin
1
0
494ab8e1806c80d52dc5f545206ef10199f95fbc
886
RxNetGo
Apache License 2.0
app/src/main/java/com/finogeeks/finclip/base/BaseActivity.kt
finogeeks
762,226,722
false
{"Kotlin": 107805}
package com.finogeeks.finclip.base import android.os.Bundle import android.view.LayoutInflater import androidx.appcompat.app.AppCompatActivity import com.blankj.utilcode.util.BarUtils import com.blankj.utilcode.util.ColorUtils import com.finogeeks.finclip.R abstract class BaseActivity : AppCompatActivity() { abstract fun getLayoutId(): Int open fun isStatusBarLightMode() = true open fun configStatusBarColor() = R.color.white open fun isFullscreen() = false override fun onCreate(savedInstanceState: Bundle?) { beforeSetView() super.onCreate(savedInstanceState) val contentView = LayoutInflater.from(this).inflate(getLayoutId(), null) setContentView(contentView) BarUtils.setStatusBarLightMode(this, isStatusBarLightMode()) BarUtils.setStatusBarColor(this, ColorUtils.getColor(configStatusBarColor())) if (!isFullscreen()) { BarUtils.addMarginTopEqualStatusBarHeight(contentView) } configView(savedInstanceState) configData() configEvent() } open fun beforeSetView() {} abstract fun configView(savedInstanceState: Bundle?) open fun configData() {} open fun configEvent() {} }
0
Kotlin
0
0
43a52370bdfe346b5dae8adf02c85e3e73d02ced
1,231
FinClipBroswer-Android
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/EventSeatSharp.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/EventSeatSharp") package mui.icons.material @JsName("default") external val EventSeatSharp: SvgIconComponent
10
null
5
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
192
kotlin-wrappers
Apache License 2.0
src/main/kotlin/jp/ac/titech/cs/se/changeBeadsPreprocessor/model/SourceContentData.kt
salab
241,070,560
false
null
package jp.ac.titech.cs.se.changeBeadsPreprocessor.model class SourceASTData () { val classData: MutableList<ClassASTData> = mutableListOf() override fun toString(): String { return "class$classData" } } data class ClassASTData ( val name: String, val start: Int, val length: Int, val methodData: MutableList<MethodASTData> = mutableListOf() ) { override fun toString(): String { return "($name: start=$start length=$length method=${methodData})" } } data class MethodASTData (val name: String, val start: Int, val length: Int) { override fun toString(): String { return "($name: start=$start length=$length)" } }
0
Kotlin
0
0
f31caf8cb557a8279db211e99f4d7ccd44908387
674
ChangeBeadsPreprocessor
Apache License 2.0
app/src/main/java/com/example/tophair/app/screen/menu/tabs/UserComponent.kt
TOP-HAIR
774,715,222
false
{"Kotlin": 248739}
package com.example.tophair.app.screen.menu.tabs import android.util.Log import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.tophair.R import com.example.tophair.app.data.entities.UserUpdate import com.example.tophair.app.data.viewmodel.UserViewModel import com.example.tophair.app.utils.CustomButton import com.example.tophair.app.utils.MarginSpace import com.example.tophair.ui.theme.TopHairTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun UserComponent(userViewModel: UserViewModel) { val user = userViewModel.user.observeAsState().value!! var nomeCompleto by remember { mutableStateOf("") } var email by remember { mutableStateOf("") } var telefone by remember { mutableStateOf("") } var senha by remember { mutableStateOf("") } val userDataState by userViewModel.user.observeAsState() LaunchedEffect(userDataState) { userDataState?.let { user -> nomeCompleto = user.nomeCompleto ?: "" email = user.email ?: "" telefone = user.telefone ?: "" } } Column( modifier = Modifier .verticalScroll(rememberScrollState()) ) { Column( modifier = Modifier .fillMaxSize() .padding(20.dp), verticalArrangement = Arrangement.Center ) { // Row( // modifier = Modifier // .fillMaxWidth(), // verticalAlignment = Alignment.CenterVertically, // horizontalArrangement = Arrangement.Center // ) { // Image( // painter = painterResource(id = R.mipmap.icon_user), // contentDescription = "Descrição da imagem", // contentScale = ContentScale.Crop, // modifier = Modifier // .size(150.dp) // .clip(shape = CircleShape) // .shadow(4.dp, shape = CircleShape) // ) // } // // MarginSpace(8.dp) Text( text = stringResource(R.string.titulo_perfil_user), style = TextStyle(textAlign = TextAlign.Center), fontSize = 28.sp, color = Color.Black, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) OutlinedTextField( value = nomeCompleto, onValueChange = { nomeCompleto = it }, label = { Text( stringResource(R.string.txt_nome_completo), style = TextStyle(color = Color.Black) ) }, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Text, imeAction = ImeAction.Next ), modifier = Modifier .fillMaxWidth(), textStyle = TextStyle(color = Color.Black), colors = TextFieldDefaults.outlinedTextFieldColors( focusedBorderColor = Color.Black, unfocusedBorderColor = Color.Black, cursorColor = Color.Black ), singleLine = true ) OutlinedTextField( value = email, onValueChange = { email = it }, label = { Text( stringResource(R.string.txt_email), style = TextStyle(color = Color.Black) ) }, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Email, imeAction = ImeAction.Next ), modifier = Modifier .fillMaxWidth(), textStyle = TextStyle(color = Color.Black), colors = TextFieldDefaults.outlinedTextFieldColors( focusedBorderColor = Color.Black, unfocusedBorderColor = Color.Black, cursorColor = Color.Black ), singleLine = true ) OutlinedTextField( value = telefone, onValueChange = { telefone = it }, label = { Text( stringResource(R.string.txt_telefone), style = TextStyle(color = Color.Black) ) }, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Phone, imeAction = ImeAction.Next ), modifier = Modifier .fillMaxWidth(), textStyle = TextStyle(color = Color.Black), colors = TextFieldDefaults.outlinedTextFieldColors( focusedBorderColor = Color.Black, unfocusedBorderColor = Color.Black, cursorColor = Color.Black ), singleLine = true ) Divider( modifier = Modifier .fillMaxWidth() .padding(vertical = 32.dp) .background(color = Color.DarkGray) ) CustomButton(stringResource(R.string.btn_txt_update_user), onClick = { if ((nomeCompleto.isNotBlank() || email.isNotBlank() || telefone.isNotBlank())) { val obj = UserUpdate(nomeCompleto, email, telefone, false) val result = userViewModel.putUser(obj) Log.d("putUser", "Resultado: $result") } }) MarginSpace(8.dp) CustomButton( stringResource(R.string.btn_txt_deletar_perfil), onClick = { userViewModel.deleteUser() }, color = Color(0xFFDC3545) ) } } } @Preview(showBackground = true) @Composable fun UserComponentPreview() { val fakeUserViewModel = UserViewModel() TopHairTheme { UserComponent( fakeUserViewModel ) } }
0
Kotlin
1
0
4219e8ed9922f3cb0fed332cfd31a276152c797d
7,780
MB_TopHair.Android
MIT License
chat-sdk/src/main/java/ru/usedesk/chat_sdk/data/repository/api/loader/file/FileLoader.kt
usedesk
127,645,126
false
null
package ru.usedesk.chat_sdk.data.repository.api.loader.file import android.content.Context import android.net.Uri import androidx.core.net.toFile import ru.usedesk.common_sdk.entity.exceptions.UsedeskDataNotFoundException import ru.usedesk.common_sdk.utils.UsedeskFileUtil.getFileName import java.io.File import java.io.FileOutputStream import javax.inject.Inject internal class FileLoader @Inject constructor( appContext: Context ) : IFileLoader { private val contentResolver = appContext.contentResolver private val cacheDir = appContext.cacheDir override suspend fun save(uri: Uri) = when { uri.toString().startsWith("file://" + cacheDir.absolutePath) -> uri else -> { var outputUri: Uri? = null contentResolver.openInputStream(uri).use { inputStream -> if (inputStream == null) { throw UsedeskDataNotFoundException("Can't read file: $uri") } val fileName = contentResolver.getFileName(uri) val name = "${System.currentTimeMillis()}${fileName.hashCode()}" val newFileName = fileName.replaceBeforeLast( '.', name, missingDelimiterValue = name ) val outputFile = File(cacheDir, newFileName) FileOutputStream(outputFile).use(inputStream::copyTo) outputUri = Uri.fromFile(outputFile) } outputUri ?: throw RuntimeException("Something wrong with caching file") } } override suspend fun remove(cachedUri: Uri) { try { val cachedFile = cachedUri.toFile() if (cachedFile.exists()) { cachedFile.delete() } } catch (e: Exception) { e.printStackTrace() } } }
0
Kotlin
6
3
d5407fad7b03e9522750938965ea8210d21373e3
1,869
Android_SDK
MIT License
shared/src/androidMain/kotlin/com/br/kmmdemo/WeatherMapScreen.android.kt
BottleRocketStudios
663,198,654
false
{"Kotlin": 57148, "Swift": 412}
package com.br.kmmdemo import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.material3.Switch import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.google.android.gms.maps.model.LatLng import com.google.maps.android.compose.GoogleMap import com.google.maps.android.compose.MapProperties import com.google.maps.android.compose.MapType import com.google.maps.android.compose.MapUiSettings import com.google.maps.android.compose.TileOverlay import com.google.maps.android.compose.rememberTileOverlayState import com.google.maps.android.heatmaps.HeatmapTileProvider import com.google.maps.android.heatmaps.WeightedLatLng @Composable actual fun WeatherMapScreen() { Column(modifier = Modifier.fillMaxSize()) { var uiSettings by remember { mutableStateOf(MapUiSettings()) } var properties by remember { mutableStateOf(MapProperties(mapType = MapType.SATELLITE)) } // var tileState by rememberTileOverlayState { // pos // } val data = WeightedLatLng(LatLng(32.949480, -96.823970), 2.0) val weightedLatLngs = ArrayList<WeightedLatLng>() weightedLatLngs.add(data) Box(Modifier.fillMaxSize()) { GoogleMap( modifier = Modifier.fillMaxSize(), properties = properties, uiSettings = uiSettings, onMapLoaded = { // TileOverlay( // tileProvider = HeatmapTileProvider.Builder().weightedData(weightedLatLngs).build(), // state = tileState, // fadeIn = true, // transparency = 0f, // visible = true, // zIndex = 0f, // onClick = {}, // ) } ) Switch( checked = uiSettings.myLocationButtonEnabled, onCheckedChange = { uiSettings = uiSettings.copy(myLocationButtonEnabled = it) } ) } } } @Preview @Composable private fun WeatherHomePreview() { WeatherMapScreen() }
0
Kotlin
0
0
250456862dcedf3ff73775b7f0f8e1086c1620fa
2,835
Kmp-demo
Apache License 2.0
bidrag-sivilstand/src/main/kotlin/no/nav/bidrag/sivilstand/response/SivilstandBeregnet.kt
navikt
248,744,235
false
{"Kotlin": 1721576}
package no.nav.bidrag.sivilstand.response import no.nav.bidrag.domene.enums.person.Sivilstandskode import no.nav.bidrag.domene.enums.person.SivilstandskodePDL import java.time.LocalDate data class SivilstandBo(val periodeFom: LocalDate, val periodeTom: LocalDate?, val sivilstandskodePDL: SivilstandskodePDL?) data class SivilstandBeregnet(val status: Status, val sivilstandListe: List<SivilstandV1>) data class SivilstandV1(val periodeFom: LocalDate, val periodeTom: LocalDate?, val sivilstandskode: Sivilstandskode) enum class Status { OK, MANGLENDE_DATOINFORMASJON, LOGISK_FEIL_I_TIDSLINJE, ALLE_FOREKOMSTER_ER_HISTORISKE, SIVILSTANDSTYPE_MANGLER, }
1
Kotlin
0
1
53026fde009ab712d8250b7eb549b5915f91f7f8
678
bidrag-beregn-felles
MIT License
forage-android/src/main/java/com/joinforage/forage/android/ui/ForagePanTextUtils.kt
teamforage
554,343,430
false
{"Kotlin": 325889}
package com.joinforage.forage.android.core.ui import android.content.Context import android.content.res.TypedArray import android.util.TypedValue internal fun getThemeAccentColor(context: Context): Int { val outValue = TypedValue() context.theme.resolveAttribute(android.R.attr.colorAccent, outValue, true) return outValue.data } internal fun TypedArray.getBoxCornerRadiusBottomStart(boxCornerRadius: Float): Float { val boxCornerRadiusBottomStart = getDimension(com.joinforage.forage.android.R.styleable.ForagePANEditText_boxCornerBottomStart, 0f) return if (boxCornerRadiusBottomStart == 0f) boxCornerRadius else boxCornerRadiusBottomStart } internal fun TypedArray.getBoxCornerRadiusTopEnd(boxCornerRadius: Float): Float { val boxCornerRadiusTopEnd = getDimension(com.joinforage.forage.android.R.styleable.ForagePANEditText_boxCornerTopEnd, 0f) return if (boxCornerRadiusTopEnd == 0f) boxCornerRadius else boxCornerRadiusTopEnd } internal fun TypedArray.getBoxCornerRadiusBottomEnd(boxCornerRadius: Float): Float { val boxCornerRadiusBottomEnd = getDimension(com.joinforage.forage.android.R.styleable.ForagePANEditText_boxCornerBottomEnd, 0f) return if (boxCornerRadiusBottomEnd == 0f) boxCornerRadius else boxCornerRadiusBottomEnd } internal fun TypedArray.getBoxCornerRadiusTopStart(boxCornerRadius: Float): Float { val boxCornerRadiusTopStart = getDimension(com.joinforage.forage.android.R.styleable.ForagePANEditText_boxCornerTopStart, 0f) return if (boxCornerRadiusTopStart == 0f) boxCornerRadius else boxCornerRadiusTopStart } internal fun TypedArray.getBoxCornerRadius(styleIndex: Int, defaultBoxCornerRadius: Float): Float { val styledBoxCornerRadius = getDimension(styleIndex, 0f) return if (styledBoxCornerRadius == 0f) defaultBoxCornerRadius else styledBoxCornerRadius }
3
Kotlin
0
0
69494180c7617f1b8a5053d97cfd6ab45b370069
1,872
forage-android-sdk
MIT License
src/main/kotlin/com/github/hanseter/json/editor/types/UnsupportedTypeModel.kt
Hanseter
265,563,400
false
null
package com.github.hanseter.json.editor.types import com.github.hanseter.json.editor.extensions.EffectiveSchema import com.github.hanseter.json.editor.util.BindableJsonType class UnsupportedTypeModel(override val schema: EffectiveSchema<*>) : TypeModel<Any?, SupportedType.SimpleType.UnsupportedType> { override val supportedType: SupportedType.SimpleType.UnsupportedType get() = SupportedType.SimpleType.UnsupportedType override var bound: BindableJsonType? = null override val defaultValue: Any? get() = schema.defaultValue override var value: Any? get() = bound?.let { BindableJsonType.convertValue(it.getValue(schema), schema, CONVERTER) } set(value) { bound?.setValue(schema, value) } companion object { val CONVERTER: (Any?) -> Any? = { it } } }
1
Kotlin
1
1
e5875a170cc462c6bb6b4f51cb9dec7233119ac9
839
JSONPropertyEditorFx
MIT License
src/Day22.kt
zt64
572,594,597
false
null
private object Day22 : Day(22) { override fun part1(): Any { TODO("Not yet implemented") } override fun part2(): Any { TODO("Not yet implemented") } } private fun main() = Day22.main()
0
Kotlin
0
0
4e4e7ed23d665b33eb10be59670b38d6a5af485d
218
aoc-2022
Apache License 2.0
app/src/main/java/pl/wmariusz/hedgehopt/theme/Typo.kt
WMariusz
343,868,949
false
{"Kotlin": 20781}
package pl.wmariusz.hedgehopt.theme import androidx.compose.material.Typography import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import pl.wmariusz.hedgehopt.R private val Montserrat = FontFamily( Font(R.font.montserrat) ) val HedgehoptTypography = Typography( defaultFontFamily = Montserrat )
5
Kotlin
0
0
08a9f53a5a160150a79d9e58ed8c0c520874e740
345
hedgehopt
Apache License 2.0
kool-editor/src/commonMain/kotlin/de/fabmax/kool/editor/PlatformCallbacks.kt
fabmax
81,503,047
false
null
package de.fabmax.kool.editor import de.fabmax.kool.KoolContext expect object PlatformCallbacks { fun onEditorStarted(ctx: KoolContext) fun onWindowCloseRequest(ctx: KoolContext): Boolean }
9
Kotlin
12
194
b7aa86ad70483a6d6ccef1290c3bad6c2f62e212
200
kool
Apache License 2.0
buildSrc/src/main/kotlin/ru/surfstudio/android/build/exceptions/project_snapshot/ConfigurationIsProjectSnapshotException.kt
surfstudio
175,407,898
false
null
package ru.surfstudio.android.build.exceptions.project_snapshot import org.gradle.api.GradleException /** * Throw if project configuration is project snapshot */ class ConfigurationIsProjectSnapshotException : GradleException( "Configuration is project snapshot. But this task can't be use for this pipeline." )
1
Kotlin
2
27
5f68262ac148bc090c600121295f81c7ce3486c0
323
EasyAdapter
Apache License 2.0
compose-multiplatform-material/src/commonMain/kotlin/com/huanshankeji/compose/material/Icon.kt
huanshankeji
570,509,992
false
{"Kotlin": 46672}
package com.huanshankeji.compose.material import androidx.compose.runtime.Composable import com.huanshankeji.compose.material.icon.MaterialIcon import com.huanshankeji.compose.ui.Element import com.huanshankeji.compose.ui.ModifierOrAttrs expect abstract class IconElement : Element @Composable expect fun Icon( materialIcon: MaterialIcon, contentDescription: String?, modifierOrAttrs: ModifierOrAttrs<IconElement> = null )
12
Kotlin
0
6
cca2836ceeeab708cb0e1effa637faac6267084c
430
compose-multiplatform-material
Apache License 2.0
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/map/Pushpin2Line.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.remix.remix.map import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.remix.remix.MapGroup public val MapGroup.Pushpin2Line: ImageVector get() { if (_pushpin2Line != null) { return _pushpin2Line!! } _pushpin2Line = Builder(name = "Pushpin2Line", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.0f, 3.0f) verticalLineTo(5.0f) horizontalLineTo(17.0f) verticalLineTo(11.0f) lineTo(19.0f, 14.0f) verticalLineTo(16.0f) horizontalLineTo(13.0f) verticalLineTo(23.0f) horizontalLineTo(11.0f) verticalLineTo(16.0f) horizontalLineTo(5.0f) verticalLineTo(14.0f) lineTo(7.0f, 11.0f) verticalLineTo(5.0f) horizontalLineTo(6.0f) verticalLineTo(3.0f) horizontalLineTo(18.0f) close() moveTo(9.0f, 5.0f) verticalLineTo(11.606f) lineTo(7.404f, 14.0f) horizontalLineTo(16.596f) lineTo(15.0f, 11.606f) verticalLineTo(5.0f) horizontalLineTo(9.0f) close() } } .build() return _pushpin2Line!! } private var _pushpin2Line: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,244
compose-icon-collections
MIT License
src/main/kotlin/org.domaintbn.sommd.core/parsing/parserimplementations/VelocityParser.kt
user00e00
163,682,297
false
null
package org.domaintbn.sommd.core.parsing.parserimplementations import org.domaintbn.sommd.core.musical.Playhead import org.domaintbn.sommd.core.musical.TimelineNote import org.domaintbn.sommd.core.parsing.* import org.domaintbn.sommd.core.parsing.RegexRepo as r class VelocityParser() : IParser { override val parserSignature: String = "Velocity" private val percentageUniParser = PercentageUniParser(this) private fun buildInstrumentCommand(): Command { return object : Command { override val commandType = CommandType.REGULAR override fun applyOn(pl: Playhead): List<TimelineNote> { pl.loadVelocity(percentageUniParser.data.toList()) return emptyList() } } } override fun getCommandSequence(): CommandSeq { if (this.percentageUniParser.data.isEmpty()) { error("Meh") } return CommandSeq(listOf(buildInstrumentCommand())) } override fun start(lex: Lexer) { val out = percentageUniParser.start(lex) return } }
0
Kotlin
2
0
60c6784e53eb38894272f74616c9484019cc3ab4
1,090
sommd
MIT License
src/main/kotlin/com/github/kory33/kalgebra/structures/instances/monoid/IntMultiplicativeMonoid.kt
kory33
135,460,140
false
null
package com.github.kory33.kalgebra.structures.instances.monoid import com.github.kory33.kalgebra.operations.MonoidOperation import com.github.kory33.kalgebra.structures.Monoid import com.github.kory33.kalgebra.structures.ProductComposable class IntMultiplicativeMonoid(value: Int) : Monoid<Int, IntMultiplicativeMonoid>(value), ProductComposable<IntMultiplicativeMonoid> { override val operation: MonoidOperation<Int> = IntMultiplicativeMonoid override fun lift(value: Int): IntMultiplicativeMonoid = IntMultiplicativeMonoid(value) companion object: MonoidOperation<Int> { override fun invoke(p1: Int, p2: Int): Int = p1 * p2 override val identity = 1 } }
0
Kotlin
0
2
ae2420a27ef848c13fd5728d6c5cfeae3901f905
696
Kalgebra
MIT License
js/js.libraries/src/jquery/common.kt
chirino
3,596,099
true
null
package js.jquery; import js.dom.core.Element native public public class JQuery() { public fun addClass(className : String) : JQuery = js.noImpl; public fun addClass(f : Element.(Int, String)->String) = js.noImpl; public fun attr(attrName : String) = ""; public fun attr(attrName : String, value : String) = this; public fun html() : String = ""; public fun html(s : String) = this; public fun html(f : Element.(Int, String)->String) = this; public fun hasClass(className : String) = true public fun removeClass(className : String) = this public fun height() = 0 public fun width() = 0 public fun click() = this; public fun mousedown(handler : Element.(MouseEvent)->Unit) = this; public fun mouseup(handler : Element.(MouseEvent)->Unit) = this; public fun mousemove(handler : Element.(MouseEvent)->Unit) = this; public fun dblclick(handler : Element.(MouseClickEvent)->Unit) = this; public fun click(handler : Element.(MouseClickEvent)->Unit) = this; public fun load(handler : Element.()->Unit) = this; public fun change(handler : Element.()->Unit) = this; public fun append(str : String) = this; public fun ready(handler : ()->Unit) = this; public fun text(text : String) = this; public fun slideUp() = this; public fun hover(handlerInOut : Element.() -> Unit) = this; public fun hover(handlerIn : Element.() -> Unit, handlerOut : Element.() -> Unit) = this; public fun next() : JQuery = js.noImpl public fun parent() : JQuery = js.noImpl public fun `val`() : String? = js.noImpl } native open public class MouseEvent() { public val pageX : Double = 0.0; public val pageY : Double = 0.0; public fun preventDefault() {} public fun isDefaultPrevented() : Boolean = true; } native public class MouseClickEvent() : MouseEvent() { val which : Int = 0; } native("$") public fun jq(selector : String) = JQuery(); native("$") public fun jq(selector : String, context : Element) = JQuery(); native("$") public fun jq(callback : () -> Unit) = JQuery(); native("$") public fun jq(obj : JQuery) = JQuery(); native("$") public fun jq(el : Element) = JQuery(); native("$") public fun jq() = JQuery();
0
Java
28
71
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
2,236
kotlin
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/PetDetailActivity.kt
and2long
343,263,409
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 import android.os.Bundle import android.widget.Toast import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.FloatingActionButton import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Favorite import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.model.PetBean import com.example.androiddevchallenge.ui.theme.MyTheme class PetDetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val item = intent.getSerializableExtra("item") as PetBean setContent { MyTheme { Scaffold( topBar = { TopAppBar( title = { Text(text = item.name) }, navigationIcon = { IconButton(onClick = { finish() }) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = "" ) } } ) }, content = { PetDetail(item) }, floatingActionButton = { FloatingActionButton( onClick = { Toast.makeText(this, "喜欢!", Toast.LENGTH_LONG).show() } ) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = "", tint = Color(0xffffffff) ) } } ) } } } } @Composable fun PetDetail(item: PetBean) { Column(modifier = Modifier.fillMaxWidth()) { Image( painter = painterResource(id = item.rid), contentDescription = item.name, modifier = Modifier .fillMaxWidth() .height(300.dp), ) Box(modifier = Modifier.padding(top = 20.dp)) { PetTags(item = item) } Text( text = item.desc, style = MaterialTheme.typography.body2, modifier = Modifier.padding(15.dp) ) } }
0
Kotlin
0
0
f02fc47fc1f33589334035e26400c175ce14d3d6
3,975
pet-home
Apache License 2.0
Kotlin/src/main/kotlin/org/algorithm/structures/Heap.kt
walterjgsp
88,624,237
false
null
package org.algorithm.structures class Heap<T : Comparable<T>>(val isMinHeap: Boolean = false) { private val heap: MutableList<T> = mutableListOf<T>() private fun heapifyUp(index: Int) { if (index >= 0) { val parent: Int = (index - 1) / 2 if (heap[index] > heap[parent]) { heap.swap(index, parent) heapifyUp(parent) } } } private fun heapifyDown(index: Int) { if (index < heap.size) { val left = 2 * index + 1 val right = 2 * index + 2 val children = mutableListOf<Pair<T, Int>>() if (left < heap.size) { children.add(Pair(heap[left], left)) } if (right < heap.size) { children.add(Pair(heap[right], right)) } if (!children.isEmpty()) { var swapIndex = 0 for (i in 1 until children.size) { if (children[swapIndex].first < children[i].first) { swapIndex = i } } val toHeapify = children[swapIndex].second if (heap[toHeapify] > heap[index]) { heap.swap(index, toHeapify); heapifyDown(toHeapify); } } } } fun printHeap() { println(heap) } fun push(value: T) { heap.add(value) heapifyUp(heap.size - 1) } fun peek(): T { return heap.first() } fun isEmpty(): Boolean { return heap.isEmpty() } fun pop() { if (!heap.isEmpty()) { heap.removeAt(0) if (heap.isNotEmpty()) { heapifyDown(0) } } } fun <T> MutableList<T>.swap(index1: Int, index2: Int) { val tmp = this[index1] this[index1] = this[index2] this[index2] = tmp } }
1
null
3
6
b3bc2fa5e105762bb8aafbe47c1d92bbe794b90d
1,969
algorithms
MIT License
graph/graph-adapter-output-spring-data-neo4j-sdn6/src/main/kotlin/eu/tib/orkg/prototype/statements/adapter/output/neo4j/spring/internal/Neo4jPredicate.kt
TIBHannover
197,416,205
false
null
package eu.tib.orkg.prototype.statements.adapter.output.neo4j.spring.internal import eu.tib.orkg.prototype.contributions.domain.model.ContributorId import eu.tib.orkg.prototype.statements.domain.model.Predicate import eu.tib.orkg.prototype.statements.domain.model.ThingId import java.time.OffsetDateTime import org.springframework.data.neo4j.core.schema.Node import org.springframework.data.neo4j.core.schema.Property import org.springframework.data.neo4j.core.schema.Relationship.* @Node("Predicate") class Neo4jPredicate : Neo4jThing() { @Property("created_by") var createdBy: ContributorId = ContributorId.createUnknownContributor() @Property("created_at") var createdAt: OffsetDateTime? = null fun toPredicate() = Predicate( id = id!!, label = label!!, createdAt = createdAt!!, createdBy = createdBy // TODO: predicate description ) override fun toThing() = toPredicate() }
0
Kotlin
2
5
ed9c62bb8656672a5fcb7f0f2eb2bca1905d1daa
951
orkg-backend
MIT License
realm/src/main/java/xyz/truenight/databinding/realm/RealmObservableList.kt
TrueNight
103,163,113
false
null
package xyz.truenight.databinding.realm import androidx.databinding.ListChangeRegistry import androidx.databinding.ObservableList import io.realm.* import java.util.* import java.util.concurrent.CopyOnWriteArraySet /** * An [ObservableList] that uses [OrderedRealmCollectionChangeListener] to calculate and dispatch it's change * updates. */ class RealmObservableList<T : RealmModel> private constructor(private val realmConfig: RealmConfiguration, private val cls: Class<T>, private val query: (RealmQuery<T>) -> RealmResults<T>, private val updateOnModification: Boolean) : AbstractList<T>(), ObservableList<T> { private val count = CopyOnWriteArraySet<ObservableList.OnListChangedCallback<*>>() private var realm: Realm? = null private var items: RealmResults<T>? = null private val listener: OrderedRealmCollectionChangeListener<RealmResults<T>> = createListener() private val listeners = ListChangeRegistry() private var mirror: List<T> = emptyList() @Deprecated("Method not supported") override fun set(index: Int, element: T): T { return super.set(index, element) } @Deprecated("Method not supported") override fun clear() { super.clear() } @Deprecated("Method not supported") override fun add(t: T): Boolean { return super.add(t) } @Deprecated("Method not supported") override fun add(index: Int, element: T) { super.add(index, element) } @Deprecated("Method not supported") override fun addAll(c: Collection<T>): Boolean { return super.addAll(c) } @Deprecated("Method not supported") override fun addAll(index: Int, c: Collection<T>): Boolean { return super.addAll(index, c) } @Deprecated("Method not supported") override fun removeRange(fromIndex: Int, toIndex: Int) { super.removeRange(fromIndex, toIndex) } @Deprecated("Method not supported") override fun remove(element: T?): Boolean { return super.remove(element) } @Deprecated("Method not supported") override fun removeAll(c: Collection<T>): Boolean { return super.removeAll(c) } @Deprecated("Method not supported") override fun removeAt(index: Int): T { return super.removeAt(index) } @Deprecated("Method not supported") override fun retainAll(elements: Collection<T>): Boolean { return super.retainAll(elements) } private fun createListener(): OrderedRealmCollectionChangeListener<RealmResults<T>> { return object : OrderedRealmCollectionChangeListener<RealmResults<T>> { // mirror list state and apply new only after onChange called override fun onChange(collection: RealmResults<T>, changeSet: OrderedCollectionChangeSet) { mirror = ArrayList(items!!) // null Changes means the async query returns the first time. if (changeSet == null) { listeners.notifyChanged(this@RealmObservableList) return } // For deletions, the adapter has to be notified in reverse order. val deletions = changeSet.deletionRanges for (i in deletions.indices.reversed()) { val range = deletions[i] modCount += 1 listeners.notifyRemoved(this@RealmObservableList, range.startIndex, range.length) } val insertions = changeSet.insertionRanges for (range in insertions) { modCount += 1 listeners.notifyInserted(this@RealmObservableList, range.startIndex, range.length) } if (!updateOnModification) { return } val modifications = changeSet.changeRanges for (range in modifications) { listeners.notifyChanged(this@RealmObservableList, range.startIndex, range.length) } } } } override fun addOnListChangedCallback(listener: ObservableList.OnListChangedCallback<out ObservableList<T>>) { listeners.add(listener) if (!EXCLUDE.contains(listener.javaClass.name)) { if (count.isEmpty()) { val realm = Realm.getInstance(realmConfig) this.realm = realm val results = query(realm.where(cls)) mirror = ArrayList(items) results.addChangeListener(this.listener) items = results listeners.notifyChanged(this@RealmObservableList) } count.add(listener) } } override fun removeOnListChangedCallback(listener: ObservableList.OnListChangedCallback<out ObservableList<T>>) { listeners.remove(listener) count.remove(listener) if (count.isEmpty()) { items?.removeChangeListener(this.listener) items = null mirror = emptyList() realm?.close() } } override fun get(index: Int): T { return mirror[index] } override val size: Int get() = mirror.size companion object { private val EXCLUDE = HashSet<String>() fun excludeCallback(cls: Class<out ObservableList.OnListChangedCallback<*>>) { EXCLUDE.add(cls.name) } fun removeExclusion(cls: Class<out ObservableList.OnListChangedCallback<*>>) { EXCLUDE.remove(cls.name) } fun excludeCallback(className: String) { EXCLUDE.add(className) } fun removeExclusion(className: String) { EXCLUDE.remove(className) } inline fun <reified T : RealmModel> create( realmConfig: RealmConfiguration = Realm.getDefaultConfiguration()!!, noinline query: (RealmQuery<T>) -> RealmResults<T>, updateOnModification: Boolean = true ) = create(realmConfig, T::class.java, query, updateOnModification) @JvmStatic @JvmOverloads fun <T : RealmModel> create( realmConfig: RealmConfiguration = Realm.getDefaultConfiguration()!!, cls: Class<T>, query: (RealmQuery<T>) -> RealmResults<T>, updateOnModification: Boolean = true ) = RealmObservableList(realmConfig, cls, query, updateOnModification) } }
0
Kotlin
0
0
a770bf084af0d6c2a411c59b9dfdb3368597df69
6,473
DataBinding
Apache License 2.0
app/src/main/java/com/bsuir/bsuirschedule/presentation/fragments/WelcomeFragment.kt
Saydullin
526,953,048
false
{"Kotlin": 572249, "HTML": 7301}
package com.bsuir.bsuirschedule.presentation.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.navigation.Navigation import androidx.viewpager2.widget.ViewPager2 import com.bsuir.bsuirschedule.R import com.bsuir.bsuirschedule.databinding.FragmentWelcomeBinding import com.bsuir.bsuirschedule.domain.models.WelcomeText import com.bsuir.bsuirschedule.presentation.adapters.WelcomeAdapter import com.google.android.material.tabs.TabLayoutMediator class WelcomeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentWelcomeBinding.inflate(inflater) var prevPosition = 0 val welcomeTextList = ArrayList<WelcomeText>() welcomeTextList.add( WelcomeText( title = getString(R.string.welcome_title_bsuir_schedule), caption = getString(R.string.welcome_caption_bsuir_schedule), image = resources.getDrawable(R.drawable.ic_logo_icon_primary, null) ) ) welcomeTextList.add( WelcomeText( title = getString(R.string.welcome_title_search), caption = getString(R.string.welcome_caption_search), image = resources.getDrawable(R.drawable.ic_search_primary, null) ) ) welcomeTextList.add( WelcomeText( title = getString(R.string.welcome_title_info), caption = getString(R.string.welcome_caption_info), image = resources.getDrawable(R.drawable.ic_info_primary, null) ) ) welcomeTextList.add( WelcomeText( title = getString(R.string.welcome_title_functionality), caption = getString(R.string.welcome_caption_functionality), image = resources.getDrawable(R.drawable.ic_settings_primary, context?.theme) ) ) welcomeTextList.add( WelcomeText( title = getString(R.string.welcome_title_localization), caption = getString(R.string.welcome_caption_localization), image = resources.getDrawable(R.drawable.ic_language_primary, null) ) ) welcomeTextList.add( WelcomeText( title = getString(R.string.welcome_title_etc), caption = getString(R.string.welcome_caption_etc), image = resources.getDrawable(R.drawable.ic_tune_primary, null) ) ) binding.getStartedButton.setOnClickListener { Navigation.findNavController(binding.root).navigate(R.id.action_welcomeFragment_to_firstScheduleAddFragment) Toast.makeText(context, getString(R.string.welcome_load_schedule), Toast.LENGTH_SHORT).show() } binding.viewPager.adapter = WelcomeAdapter(context!!, welcomeTextList) TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position -> tab.view.background = resources.getDrawable(R.drawable.dot, null) }.attach() binding.nextButton.setOnClickListener { binding.viewPager.currentItem += 1 } binding.viewPager.registerOnPageChangeCallback(object: ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { super.onPageSelected(position) val tab = binding.tabLayout.getTabAt(position) val prevTab = binding.tabLayout.getTabAt(prevPosition) if (prevTab != null) { prevTab.view.background = resources.getDrawable(R.drawable.dot, null) } if (tab != null) { tab.view.background = resources.getDrawable(R.drawable.dot_selected, null) } prevPosition = position if (position == welcomeTextList.size - 1) { binding.nextButton.visibility = View.GONE binding.getStartedButton.visibility = View.VISIBLE } } }) return binding.root } }
0
Kotlin
0
4
49dc7e7551a4c0df2ada93648291e24aecb3bda5
4,353
BSUIR_Schedule
Creative Commons Zero v1.0 Universal
app/src/main/java/com/chrynan/launcher/ui/grid/SpanProvider.kt
chRyNaN
161,240,007
false
null
package com.chrynan.launcher.ui.grid import com.chrynan.launcher.util.* interface SpanProvider { fun getColumnCount(position: Position, viewType: ViewType, spanColumnSize: SpanColumnSize): ColumnCount fun getRowCount(position: Position, viewType: ViewType, spanRowSize: SpanRowSize): RowCount fun getGridPosition(position: Position, viewType: ViewType): GridPosition }
0
Kotlin
0
0
c226fc3997b0e76bcb237e2d09ee47ceed5bad2e
385
Launcher
Apache License 2.0
app/src/main/java/com/mystical/wildlegion/screens/main/models/News.kt
DeveloperXY
145,738,735
false
null
package com.mystical.wildlegion.screens.main.models import java.io.Serializable class News(var _id: String, var title: String, var postDate: String, var postedBy: String, var newsStory: String) : Serializable
1
null
1
1
3743e5e88fe95c0722f98334f8799cb11111e59a
254
WildLegion
MIT License
uploadservice/src/main/java/net/gotev/uploadservice/placeholders/DefaultPlaceholdersProcessor.kt
gotev
13,067,111
false
{"Kotlin": 231339, "Shell": 1643}
package net.gotev.uploadservice.placeholders import net.gotev.uploadservice.data.UploadElapsedTime import net.gotev.uploadservice.data.UploadInfo import net.gotev.uploadservice.data.UploadRate open class DefaultPlaceholdersProcessor : PlaceholdersProcessor { open fun uploadElapsedTime(uploadElapsedTime: UploadElapsedTime) = when { uploadElapsedTime.minutes == 0 -> "${uploadElapsedTime.seconds} sec" else -> "${uploadElapsedTime.minutes} min ${uploadElapsedTime.seconds} sec" } open fun uploadRate(uploadRate: UploadRate): String { val suffix = when (uploadRate.unit) { UploadRate.UploadRateUnit.BitPerSecond -> "b/s" UploadRate.UploadRateUnit.KilobitPerSecond -> "kb/s" UploadRate.UploadRateUnit.MegabitPerSecond -> "Mb/s" } return "${uploadRate.value} $suffix" } open fun uploadProgress(percent: Int) = "$percent %" open fun uploadedFiles(uploadedFiles: Int) = "$uploadedFiles" open fun remainingFiles(remainingFiles: Int) = "$remainingFiles" open fun totalFiles(totalFiles: Int) = "$totalFiles" override fun processPlaceholders(message: String?, uploadInfo: UploadInfo): String { val safeMessage = message ?: return "" val uploadedFiles = uploadInfo.successfullyUploadedFiles val totalFiles = uploadInfo.files.size val remainingFiles = totalFiles - uploadedFiles return safeMessage .replace(Placeholder.ElapsedTime.value, uploadElapsedTime(uploadInfo.elapsedTime)) .replace(Placeholder.UploadRate.value, uploadRate(uploadInfo.uploadRate)) .replace(Placeholder.Progress.value, uploadProgress(uploadInfo.progressPercent)) .replace(Placeholder.UploadedFiles.value, uploadedFiles(uploadedFiles)) .replace(Placeholder.RemainingFiles.value, remainingFiles(remainingFiles)) .replace(Placeholder.TotalFiles.value, totalFiles(totalFiles)) } }
3
Kotlin
693
2,819
447a839a53898d1759c35afa8efef8a6ab9be212
1,978
android-upload-service
Apache License 2.0
app/src/main/java/com/example/movieapp/model/Categoria.kt
guihroch
725,145,273
false
{"Kotlin": 20563}
package com.example.movieapp.model import com.google.gson.annotations.SerializedName data class Categoria( @SerializedName("titulo") val titulo: String? = null, @SerializedName("capas") val filme: MutableList<Filme> = mutableListOf() ) data class Filme( @SerializedName("nome") val nome:String? = null, @SerializedName("url_imagem") val capa: String? = null, @SerializedName("id") var id: Int = 0, @SerializedName("descricao") val descricao: String? = null, @SerializedName("elenco") val elenco: String? = null ) data class Categorias( @SerializedName("categoria") val categoria: MutableList<Categoria> )
0
Kotlin
0
0
89f67c729e8cde460715e62ac5441191d37cfdae
641
MovieApp
Apache License 2.0
src/main/kotlin/no/nav/klage/dokument/domain/MellomlagretMultipartFile.kt
navikt
297,650,936
false
null
package no.nav.klage.dokument.domain import no.nav.klage.oppgave.util.getLogger import org.springframework.web.multipart.MultipartFile import java.io.* class MellomlagretMultipartFile(private val mellomlagretDokument: MellomlagretDokument) : MultipartFile { companion object { @Suppress("JAVA_CLASS_ON_COMPANION") private val logger = getLogger(javaClass.enclosingClass) } override fun getName(): String { return mellomlagretDokument.title } override fun getOriginalFilename(): String? { return mellomlagretDokument.title } override fun getContentType(): String? { return mellomlagretDokument.contentType.toString() } override fun isEmpty(): Boolean { return mellomlagretDokument.content.isEmpty() } override fun getSize(): Long { return mellomlagretDokument.content.size.toLong() } @Throws(IOException::class) override fun getBytes(): ByteArray { return mellomlagretDokument.content } @Throws(IOException::class) override fun getInputStream(): InputStream { return ByteArrayInputStream(mellomlagretDokument.content) } @Throws(IOException::class) override fun transferTo(dest: File) { FileOutputStream(dest).use { f -> f.write(mellomlagretDokument.content) } } }
3
Kotlin
1
2
168c8c4b9ed5192ac6870f88b6e82a665b29a4b9
1,337
kabal-api
MIT License
src/main/kotlin/no/nav/klage/dokument/domain/MellomlagretMultipartFile.kt
navikt
297,650,936
false
null
package no.nav.klage.dokument.domain import no.nav.klage.oppgave.util.getLogger import org.springframework.web.multipart.MultipartFile import java.io.* class MellomlagretMultipartFile(private val mellomlagretDokument: MellomlagretDokument) : MultipartFile { companion object { @Suppress("JAVA_CLASS_ON_COMPANION") private val logger = getLogger(javaClass.enclosingClass) } override fun getName(): String { return mellomlagretDokument.title } override fun getOriginalFilename(): String? { return mellomlagretDokument.title } override fun getContentType(): String? { return mellomlagretDokument.contentType.toString() } override fun isEmpty(): Boolean { return mellomlagretDokument.content.isEmpty() } override fun getSize(): Long { return mellomlagretDokument.content.size.toLong() } @Throws(IOException::class) override fun getBytes(): ByteArray { return mellomlagretDokument.content } @Throws(IOException::class) override fun getInputStream(): InputStream { return ByteArrayInputStream(mellomlagretDokument.content) } @Throws(IOException::class) override fun transferTo(dest: File) { FileOutputStream(dest).use { f -> f.write(mellomlagretDokument.content) } } }
3
Kotlin
1
2
168c8c4b9ed5192ac6870f88b6e82a665b29a4b9
1,337
kabal-api
MIT License
app/src/main/java/com/rubens/salonpremiumclient/view/adapters/AgendaAdapter.kt
rubens23
709,950,371
false
{"Kotlin": 134489}
package com.rubens.salonpremiumclient.view.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.rubens.salonpremiumclient.R import com.rubens.salonpremiumclient.data.models.Appointment import com.rubens.salonpremiumclient.databinding.ItemAgendaBinding import com.rubens.salonpremiumclient.view.AgendaItemClickListener class AgendaAdapter(private val listaAppointments: ArrayList<Appointment>, val agendaItemClickListener: AgendaItemClickListener): RecyclerView.Adapter<AgendaAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(ItemAgendaBinding.inflate(LayoutInflater.from(parent.context), parent, false)) } override fun getItemCount(): Int { return listaAppointments.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindAppointment(listaAppointments[position]) } inner class ViewHolder(val binding: ItemAgendaBinding): RecyclerView.ViewHolder(binding.root) { fun bindAppointment(app: Appointment){ binding.tvNumeroDia.text = app.day binding.tvHoraAtendimento.text = app.hour binding.tvMonthName.text = app.month binding.tvNomeServico.text = app.service binding.tvNomeAtendente.text = app.employee binding.tvDiaSemana.text = agendaItemClickListener.pegarDiaDaSemanaAbreviado(app.appointmentDayFormatted) when(app.confirmacaoAtendimento){ "aguardando confirmacao"->{binding.statusAtendimento.setBackgroundResource(R.color.light_yellow)} "negado"->{binding.statusAtendimento.setBackgroundResource(R.color.vermelho)} "confirmado"->{binding.statusAtendimento.setBackgroundResource(R.color.verde)} } binding.root.setOnClickListener { agendaItemClickListener.onAgendaItemClickListener(app) } } } }
0
Kotlin
0
0
876a7dd4bf62fd10246667aa60013e5d72e19d48
2,041
Salon-Premium-Client
Apache License 2.0
compiler/testData/diagnostics/tests/callableReference/callableReferenceAssignmentToVar.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}
// FIR_IDENTICAL // SKIP_TXT // FILE: lib.kt package lib fun foo(x: Double): Double = x // FILE: main.kt import lib.* fun foo(): Map<Int, String> = TODO() var z: (x: Double) -> Double = { it } fun bar() { z = ::foo } fun baz(x: (Double) -> Double) {}
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
262
kotlin
Apache License 2.0
src/main/kotlin/io/hsar/practice3/ProblemA.kt
HSAR
241,918,109
false
null
package io.hsar.practice3 /* https://codeforces.com/contest/1298/problem/A Input: 201 101 101 200 Output: 1 100 100 */ fun main() { val input = readLine()!!.split(" ") .map { inputSegment -> inputSegment.toInt() } val total = input.max()!! val pairwiseSums = input.minus(total) .sorted() val pairwiseDiffA = pairwiseSums[1] - pairwiseSums[0] val pairwiseDiffB = pairwiseSums[2] - pairwiseSums[1] val pairwiseDiffC = pairwiseSums[2] - pairwiseSums[0] // Sum of these pairwise differences yields 2C-2A val CminusA = (pairwiseDiffA + pairwiseDiffB + pairwiseDiffC) / 2 val CplusA = pairwiseSums[1] val valC = (CplusA + CminusA) / 2 val valA = CplusA - valC val valB = pairwiseSums[0] - valA println("${valA} ${valB} ${valC}") }
0
Kotlin
0
0
69a1187ffa6e0a61324f88572851b2147d8a1210
837
KotlinHeroes
MIT License
src/main/kotlin/io/hsar/practice3/ProblemA.kt
HSAR
241,918,109
false
null
package io.hsar.practice3 /* https://codeforces.com/contest/1298/problem/A Input: 201 101 101 200 Output: 1 100 100 */ fun main() { val input = readLine()!!.split(" ") .map { inputSegment -> inputSegment.toInt() } val total = input.max()!! val pairwiseSums = input.minus(total) .sorted() val pairwiseDiffA = pairwiseSums[1] - pairwiseSums[0] val pairwiseDiffB = pairwiseSums[2] - pairwiseSums[1] val pairwiseDiffC = pairwiseSums[2] - pairwiseSums[0] // Sum of these pairwise differences yields 2C-2A val CminusA = (pairwiseDiffA + pairwiseDiffB + pairwiseDiffC) / 2 val CplusA = pairwiseSums[1] val valC = (CplusA + CminusA) / 2 val valA = CplusA - valC val valB = pairwiseSums[0] - valA println("${valA} ${valB} ${valC}") }
0
Kotlin
0
0
69a1187ffa6e0a61324f88572851b2147d8a1210
837
KotlinHeroes
MIT License
rotadilavk/src/main/kotlin/com/github/alexxxdev/rotadilavk/rule/IRule.kt
alexxxdev
143,407,528
false
null
package com.github.alexxxdev.rotadilavk.rule interface IRule { val message: String fun check(text: String): Boolean }
0
Kotlin
0
1
c1abf166639d41f45c7e934073584421614885d1
126
RotadilavK
Apache License 2.0
libs/kotlin-reflection/src/test/kotlin/net/corda/kotlin/SplitApi.kt
corda
346,070,752
false
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.kotlin interface SplitApi { var firstApi: Any? var secondApi: Any? var thirdApi: Any? var reference: Any? }
14
Kotlin
27
69
0766222eb6284c01ba321633e12b70f1a93ca04e
144
corda-runtime-os
Apache License 2.0
library/src/main/java/com/zdog/library/render/Ellipse.kt
prostory
211,052,399
false
null
package com.zdog.library.render open class Ellipse: Shape() { var diameter = 1f var width = 0f var height = 0f var quarters = 4 init { closed = true } override fun setPath() { val x = if (width != 0f) width/2 else diameter/2 val y = if (height != 0f) height/2 else diameter/2 path( move(x = 0f, y = -y), arc( vector(x = x, y = -y), vector(x = x, y = 0f) ) ).apply { if (quarters > 1) { add(arc( vector(x = x, y = y), vector(x = 0f, y = y) )) } if (quarters > 2) { add(arc( vector(x = -x, y = y), vector(x = -x, y = 0f) )) } if (quarters > 3) { add(arc( vector(x = -x, y = -y), vector(x = 0f, y = -y) )) } } } override fun copy(): Ellipse { return copy(Ellipse()) } override fun copy(shape: Anchor): Ellipse { return (super.copy(shape) as Ellipse).also { it.diameter = diameter it.width = width it.height = height it.quarters = quarters } } }
0
Kotlin
5
27
0e0027feccb0a27b4f9926e6eabf8c59200cc54b
1,371
AndroidZdog
MIT License
wear/src/main/java/ca/joshstagg/slate/SlatePaints.kt
stagg
28,216,539
false
null
package ca.joshstagg.slate import android.content.Context import android.graphics.Paint import android.graphics.Typeface import ca.joshstagg.slate.config.Config class SlatePaints(context: Context, scaleFactor: Float = 1f) { private val scale: Float = scaleFactor * context.resources.displayMetrics.density private val textScale = scaleFactor * context.resources.displayMetrics.scaledDensity val centerRadius = 6f * scale val centerSecondRadius = 4f * scale val notificationOuterRadius = 5f * scale val notificationInnerRadius = 3f * scale val innerTickRadius = 9 * scale val largeInnerTickRadius = 21 * scale val secLength = 8 * scale val minLength = 13 * scale val hrLength = 35 * scale val secStart = -20 * scale val notificationOffset = 18 * scale val burnInShift = 3f * scale private val complicationTextSize = 14f * textScale private val complicationMainTextSize = 12f * textScale private val complicationSubTextSize = 10f * textScale val hour: Paint = Paint() val minute: Paint = Paint() val second: Paint = Paint() val center: Paint = Paint() val tick: Paint = Paint() val complicationText: Paint = Paint() val complicationMainText: Paint = Paint() val complicationSubText: Paint = Paint() val complicationEdge: Paint = Paint() val complicationFill: Paint = Paint() val complicationSecondary: Paint = Paint() val tickColor = 0x64D5D5D6 val primaryHandColor = 0xfff5f5f5.toInt() val shadowColor = 0xaa000000.toInt() val primaryComplicationColor = 0xF4FFFFFF.toInt() var accentHandColor = Config().accentColor set(value) { if (field != value) { field = value second.color = value } } var handColor = primaryHandColor set(value) { if (field != value) { field = value hour.color = value minute.color = value center.color = value } } val complicationTint: Int get() = primaryComplicationColor init { hour.color = primaryHandColor hour.strokeWidth = 6f * scale hour.isAntiAlias = true hour.strokeCap = Paint.Cap.BUTT hour.setShadowLayer(2.5f * scale, 0f, 0f, shadowColor) minute.color = primaryHandColor minute.strokeWidth = 5f * scale minute.isAntiAlias = true minute.strokeCap = Paint.Cap.BUTT minute.setShadowLayer(2f * scale, 0f, 0f, shadowColor) second.color = accentHandColor second.strokeWidth = 3f * scale second.isAntiAlias = true second.strokeCap = Paint.Cap.BUTT second.setShadowLayer(3f * scale, 0f, 0f, shadowColor) center.color = primaryHandColor center.strokeWidth = 5f * scale center.isAntiAlias = true center.strokeCap = Paint.Cap.BUTT tick.color = tickColor tick.strokeWidth = 3f * scale tick.isAntiAlias = true tick.setShadowLayer(.5f * scale, 0f, 0f, shadowColor) complicationText.color = primaryComplicationColor complicationText.textSize = complicationTextSize complicationText.typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL) complicationText.textAlign = Paint.Align.CENTER complicationText.isAntiAlias = true complicationMainText.color = primaryComplicationColor complicationMainText.textSize = complicationMainTextSize complicationMainText.typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL) complicationMainText.textAlign = Paint.Align.CENTER complicationMainText.isAntiAlias = true complicationSubText.color = primaryComplicationColor complicationSubText.textSize = complicationSubTextSize complicationSubText.typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL) complicationSubText.textAlign = Paint.Align.CENTER complicationSubText.isAntiAlias = true complicationEdge.setARGB(255, 50, 50, 50) complicationEdge.strokeCap = Paint.Cap.ROUND complicationEdge.strokeJoin = Paint.Join.ROUND complicationEdge.style = Paint.Style.STROKE complicationEdge.strokeWidth = 2f * scale complicationEdge.isAntiAlias = true complicationFill.setARGB(100, 50, 50, 50) complicationSecondary.setARGB(255, 155, 155, 155) complicationSecondary.strokeCap = Paint.Cap.ROUND complicationSecondary.strokeJoin = Paint.Join.ROUND complicationSecondary.style = Paint.Style.STROKE complicationSecondary.strokeWidth = 3f * scale complicationSecondary.isAntiAlias = true } fun setAntiAlias(antiAlias: Boolean) { hour.isAntiAlias = antiAlias minute.isAntiAlias = antiAlias second.isAntiAlias = antiAlias center.isAntiAlias = antiAlias tick.isAntiAlias = antiAlias complicationText.isAntiAlias = antiAlias complicationMainText.isAntiAlias = antiAlias complicationSubText.isAntiAlias = antiAlias complicationEdge.isAntiAlias = antiAlias complicationSecondary.isAntiAlias = antiAlias } }
1
Kotlin
1
1
b16c7ef8c5956f6e2d4c3bf4ff32fdc0e4cf1dee
5,269
slatewatchface
Apache License 2.0
src/main/kotlin/io/github/ydwk/ydwk/evm/handler/handlers/role/GuildRoleCreateHandler.kt
YDWK
527,250,343
false
null
/* * Copyright 2024 YDWK inc. * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.ydwk.ydwk.evm.handler.handlers.role import com.fasterxml.jackson.databind.JsonNode import io.github.ydwk.yde.cache.CacheIds import io.github.ydwk.ydwk.evm.event.events.role.GuildRoleCreateEvent import io.github.ydwk.ydwk.evm.handler.Handler import io.github.ydwk.ydwk.impl.YDWKImpl class GuildRoleCreateHandler(ydwk: YDWKImpl, json: JsonNode) : Handler(ydwk, json) { override suspend fun start() { val guild = ydwk.getGuildById(json.get("guild_id").asLong()) if (guild != null) { val role = ydwk.entityInstanceBuilder.buildRole(json) ydwk.cache[json.get("role").get("id").asText(), role] = CacheIds.ROLE ydwk.emitEvent(GuildRoleCreateEvent(ydwk, role)) } else { ydwk.logger.warn("Guild is null") } } }
9
null
1
2
7e479b29ddca2e0d9093ab8c5dae6892f5640d80
1,411
YDWK
Apache License 2.0
app/src/main/java/com/ten/lifecat/phone/util/http/HttpUtil.kt
daili-dl
361,082,388
false
null
package com.ten.lifecat.phone.util.http import java.io.BufferedReader import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL import okhttp3.OkHttpClient import okhttp3.Request object HttpUtil { /** * HttpURLConnection手动实现连接 */ fun sendHttpRequest(address: String, listener: HttpCallbackListener?) { Thread { var connection: HttpURLConnection? = null try { val url = URL(address) connection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" connection.connectTimeout = 8000 connection.readTimeout = 8000 connection.doInput = true connection.doOutput = true /* 获取响应输入流 */ val `in` = connection.inputStream val reader = BufferedReader(InputStreamReader(`in`)) val response = StringBuilder() while (reader.readLine() != null) { response.append(reader.readLine()) } listener?.onFinish(response.toString()) } catch (e: Exception) { listener?.onError(e) } finally { connection?.disconnect() } }.start() } /** * @description OkHttp方法 内置Callback回调对象 */ fun sendOkHttpRequest(address: String, callback: okhttp3.Callback) { val client = OkHttpClient() val request = Request.Builder() .url(address) .build() /* OkHttp开启子线程,请求结果回调到Callback中 */ client.newCall(request).enqueue(callback) } }
1
null
1
1
5baded03862426ab21ca4785469a893cac7fc844
1,705
lifecat
Apache License 2.0
processor/src/main/kotlin/com/autodsl/processor/Constants.kt
juanchosaravia
155,285,356
false
null
/* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autodsl.processor object Constants { const val LIST_TYPE_NAME = "kotlin.collections.List" const val MUTABLE_LIST_TYPE_NAME = "kotlin.collections.MutableList" const val SET_TYPE_NAME = "kotlin.collections.Set" const val MUTABLE_SET_TYPE_NAME = "kotlin.collections.MutableSet" }
4
Kotlin
13
340
5e0a2f7fad26d52e766d3a330768ebb3b1698435
895
autodsl
Apache License 2.0
lib/src/main/kotlin/com/lemonappdev/konsist/api/provider/KoTypeProvider.kt
LemonAppDev
621,181,534
false
{"Kotlin": 2941189, "Python": 25669}
package com.lemonappdev.konsist.api.provider import com.lemonappdev.konsist.api.declaration.KoTypeDeclaration import kotlin.reflect.KClass /** * An interface representing a Kotlin declaration that provides access to its type information. */ interface KoTypeProvider : KoBaseProvider { /** * Type of the declaration. */ val type: KoTypeDeclaration /** * Whether declaration has a specified type. * * @param predicate The predicate function used to determine if a declaration type satisfies a condition. * @return `true` if the declaration has the specified type, `false` otherwise. */ fun hasType(predicate: (KoTypeDeclaration) -> Boolean): Boolean /** * Whether declaration has a type of the specified Kotlin class. * * @param kClass The Kotlin class representing the type to check for. * @return `true` if the declaration has a type matching the specified KClass, `false` otherwise. */ fun hasTypeOf(kClass: KClass<*>): Boolean }
16
Kotlin
19
768
22f45504ab1c88fca8314bd86f91af7dd8a3672b
1,021
konsist
Apache License 2.0
01. Variables/01.07 (Bonus) This property must either have a type annotation, be initialized or be delegated/solution.kts
evgeny-trushin
136,894,138
false
{"Kotlin": 15292, "Shell": 3369}
//error: this property must either have a type annotation, be initialized or be delegated var c: Int c = 1 println("c equals " + c)
0
Kotlin
0
0
052845a963dccb788405386e0cef9db0f36bd110
132
Kotlin-Script_CLI_Presentation_Trial-And-Error
MIT License
app/src/main/java/com/technorapper/boiler/application/App.kt
HaneetGH
228,811,463
false
null
@file:Suppress("DEPRECATION") package com.technorapper.boiler.application import android.app.Activity import android.app.Application import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.multidex.MultiDexApplication import com.technorapper.boiler.di.applyAutoInjector import com.technorapper.boiler.data.tunnel.remote.utils.AppSocket import com.technorapper.boiler.di.component.AppComponent import com.technorapper.boiler.di.component.BindingComponent import com.technorapper.boiler.di.component.DaggerAppComponent import com.technorapper.boiler.di.component.DaggerBindingComponent import com.technorapper.boiler.di.module.AppModule import com.technorapper.boiler.di.module.BindingModule import com.github.nkzawa.socketio.client.Socket import com.squareup.picasso.Picasso import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import dagger.android.support.HasSupportFragmentInjector import javax.inject.Inject open class App : Application(), HasActivityInjector, HasSupportFragmentInjector { @Inject lateinit var appComponent: AppComponent @Inject lateinit var picasso: Picasso @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity> @Inject lateinit var dispatchingFragmentInjector: DispatchingAndroidInjector<Fragment> @Inject lateinit var socket: AppSocket override fun onCreate() { super.onCreate() INSTANCE = this initDagger() socket.connect() val bindingComponent: BindingComponent? = DaggerBindingComponent.builder() ?.bindingModule(BindingModule()) ?.picasso(picasso) ?.build() DataBindingUtil.setDefaultComponent(bindingComponent) applyAutoInjector() } open fun initDagger() { appComponent = DaggerAppComponent.builder() .application(this) .appModule(AppModule(this)) .build() appComponent.inject(this) } override fun activityInjector(): DispatchingAndroidInjector<Activity>? { return dispatchingAndroidInjector } override fun supportFragmentInjector(): AndroidInjector<Fragment>? { return dispatchingFragmentInjector } companion object { lateinit var INSTANCE: App } }
1
null
5
9
14abab83d47749ebe8ca4b57b89e096b3c8c6abb
2,391
KotlinAndroidBase
Apache License 2.0
simpleBleClient/src/main/java/com/bortxapps/simplebleclient/api/SimpleBleClientBuilder.kt
neoBortx
735,979,951
false
{"Kotlin": 155392, "Java": 572}
package com.bortxapps.simplebleclient.api import android.content.Context import com.bortxapps.simplebleclient.api.SimpleBleClientBuilder.operationTimeOutMillis import com.bortxapps.simplebleclient.api.contracts.SimpleBleClient import com.bortxapps.simplebleclient.di.BleLibraryContainer import com.bortxapps.simplebleclient.exceptions.SimpleBleClientException import com.bortxapps.simplebleclient.manager.BleManager /** * Builder for creating instances of [SimpleBleClient]. * * This builder provides a fluent interface to configure and create an instance of [SimpleBleClient], * which is the main entry point for interacting with BLE devices using the SimpleBleClient library. * * Usage involves setting up any required configurations and then calling `build(context)` to create * an instance of [SimpleBleClient] that can be used for BLE operations. * * @property operationTimeOutMillis Optional configuration to set a custom timeout for BLE operations. * If not set, a default timeout defined in the library will be used. * A SimpleBleClientException will be thrown if the timeout is exceeded. *@property Context The context to use for BLE operations. To avoid memory leaks, this should be the * application context. * * @throws SimpleBleClientException Thrown when an error occurs during the BLE operation. * Usage example: * ``` * val simpleBleClient = SimpleBleClientBuilder * .setOperationTimeOutMillis(10000) // Optional: Set custom operation timeout (in milliseconds) * .build(context) * */ public object SimpleBleClientBuilder { private var operationTimeOutMillis: Long? = null private var scanPeriodMillis: Long? = null public fun setOperationTimeOutMillis(timeout: Long): SimpleBleClientBuilder = apply { operationTimeOutMillis = timeout } public fun setScanPeriodMillis(timeout: Long): SimpleBleClientBuilder = apply { scanPeriodMillis = timeout } public fun build(context: Context): SimpleBleClient { return buildInstance(context) } private fun buildInstance(context: Context): SimpleBleClient { val container = BleLibraryContainer(context) operationTimeOutMillis?.let { container.bleConfiguration.operationTimeoutMillis = it } scanPeriodMillis?.let { container.bleConfiguration.scanPeriodMillis = it } return BleManager( container.bleManagerDeviceSearchOperations, container.bleManagerGattConnectionOperations, container.bleManagerGattSubscriptions, container.bleManagerGattReadOperations, container.bleManagerGattWriteOperations, container.bleManagerGattCallBacks, context.applicationContext ) } }
0
Kotlin
0
1
d08eee4aaaea1c44268682add3565a2749c4007e
2,811
SimpleBleClient
MIT License
data/src/main/java/com/example/data/cloud/service/SchoolService.kt
yusuf0405
484,801,816
false
null
package com.example.data.cloud.service import com.example.data.cloud.models.SchoolResponse import retrofit2.Response import retrofit2.http.GET interface SchoolService { @GET("classes/School") suspend fun getAllSchools(): Response<SchoolResponse> }
1
Kotlin
1
3
067abb34f0348b0dda1f05470a32ecbed59cfb19
260
BookLoverFinalApp
Apache License 1.1
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/medialive/CfnChannelArchiveCdnSettingsPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.medialive import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.medialive.CfnChannel /** * Settings to configure the destination of an Archive output. * * The parent of this entity is ArchiveGroupSettings. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.medialive.*; * ArchiveCdnSettingsProperty archiveCdnSettingsProperty = ArchiveCdnSettingsProperty.builder() * .archiveS3Settings(ArchiveS3SettingsProperty.builder() * .cannedAcl("cannedAcl") * .build()) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-archivecdnsettings.html) */ @CdkDslMarker public class CfnChannelArchiveCdnSettingsPropertyDsl { private val cdkBuilder: CfnChannel.ArchiveCdnSettingsProperty.Builder = CfnChannel.ArchiveCdnSettingsProperty.builder() /** @param archiveS3Settings Sets up Amazon S3 as the destination for this Archive output. */ public fun archiveS3Settings(archiveS3Settings: IResolvable) { cdkBuilder.archiveS3Settings(archiveS3Settings) } /** @param archiveS3Settings Sets up Amazon S3 as the destination for this Archive output. */ public fun archiveS3Settings(archiveS3Settings: CfnChannel.ArchiveS3SettingsProperty) { cdkBuilder.archiveS3Settings(archiveS3Settings) } public fun build(): CfnChannel.ArchiveCdnSettingsProperty = cdkBuilder.build() }
3
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,883
awscdk-dsl-kotlin
Apache License 2.0
ktor_ecommerce/src/main/kotlin/com/flowerencee/models/data/request/ForgotPasswordRequest.kt
bayuds9
575,217,673
false
{"Java": 666229, "Kotlin": 216505, "Assembly": 744}
package com.flowerencee.models.data.request data class ForgotPasswordRequest( var email: String = "", var phone: String = "" )
1
null
1
1
7b469215bdd39264f1f55f86fda4468902727c0f
136
ktor-sample
Apache License 2.0
app/src/main/java/com/daya/navigation/sample/FlowStepFragment.kt
shnoble
170,830,183
false
null
package com.daya.navigation.sample import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.Navigation import kotlinx.android.synthetic.main.fragment_flow_step_one.* class FlowStepFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val safeArgs = arguments?.let { FlowStepFragmentArgs.fromBundle(it) } ?: return null val flowStepNumber = safeArgs.flowStepNumber // Inflate the layout for this fragment return when(flowStepNumber) { 2 -> inflater.inflate(R.layout.fragment_flow_step_two, container, false) else -> inflater.inflate(R.layout.fragment_flow_step_one, container, false) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) next_button.setOnClickListener( Navigation.createNavigateOnClickListener(R.id.next_action) ) } }
0
Kotlin
0
0
5f84f9f4e8ab6c8d75d505e5fd1cd94159812a3f
1,150
AndroidNavigationSample
Apache License 2.0
complete/app/src/main/java/com/denofprogramming/mycoroutineapplication/ui/main/MainViewModel.kt
denofprogramming
406,424,799
false
{"Kotlin": 30300}
package com.denofprogramming.mycoroutineapplication.ui.main import android.graphics.Bitmap import androidx.lifecycle.* import com.denofprogramming.mycoroutineapplication.network.NetworkServiceApi import com.denofprogramming.mycoroutineapplication.repository.image.RetrofitImageRepository import com.denofprogramming.mycoroutineapplication.repository.time.DefaultClock import com.denofprogramming.mycoroutineapplication.shared.Resource import com.denofprogramming.mycoroutineapplication.shared.uilt.logMessage import kotlinx.coroutines.launch import java.lang.IndexOutOfBoundsException class MainViewModel : ViewModel() { private val _clock = DefaultClock.build() private val _imageRepository = RetrofitImageRepository.build(NetworkServiceApi.retrofitService) val image: LiveData<Resource<Bitmap>> get() = _image private val _image = MutableLiveData<Resource<Bitmap>>() val currentTimeTransformed = _clock.time.switchMap { val timeFormatted = MutableLiveData<String>() val time = _clock.timeStampToTime(it) logMessage("currentTimeTransformed time is $time") timeFormatted.value = time timeFormatted } init { startClock() } fun onButtonClicked() { logMessage("Start onButtonClicked()") viewModelScope.launch { loadImage() } } fun onCancelClicked() { _imageRepository.cancel() } private suspend fun loadImage() { logMessage("Start loadImage()") val imageResource = try { _imageRepository.fetchImage(_imageRepository.nextImageId()) } catch (e: Exception) { logMessage("loadImage() exception $e") Resource.error(e.localizedMessage ?: "No Message") } showImage(imageResource) } private fun showImage(imageResource: Resource<Bitmap>) { logMessage("Start showImage()") _image.postValue(imageResource) logMessage("End showImage()") } private fun startClock() { logMessage("Start startClock()") _clock.start() } }
0
Kotlin
0
0
cc7bb4e7b40b346be9d39312cacd77d2cf6d6cf1
2,107
kotlinCoroutinesExplainedAndroidApp21
MIT License
app/src/main/java/com/example/managerlibrary/ui/manager/AddMemberActivity.kt
nqmgaming
692,788,624
false
{"Kotlin": 173384}
package com.example.managerlibrary.ui.manager import android.content.Intent import android.os.Bundle import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.managerlibrary.R import com.example.managerlibrary.dao.MemberDAO import com.example.managerlibrary.databinding.ActivityAddMemberBinding import com.example.managerlibrary.dto.MemberDTO import com.example.managerlibrary.ui.MainActivity class AddMemberActivity : AppCompatActivity() { private lateinit var binding: ActivityAddMemberBinding private lateinit var memberDAO: MemberDAO private lateinit var memberDTO: MemberDTO override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAddMemberBinding.inflate(layoutInflater) val view = binding.root setContentView(view) setSupportActionBar(binding.toolbarAddMember) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) binding.btnCancelAddMember.setOnClickListener { finish() } binding.btnSaveAddMember.setOnClickListener { val name = binding.edtNameMember.text.toString() val birthYear = binding.edtBirthMember.text.toString() if (name.isEmpty()) { binding.edtNameMember.error = "Tên không được để trống" return@setOnClickListener } if (birthYear.isEmpty()) { binding.edtBirthMember.error = "Năm sinh không được để trống" return@setOnClickListener } //giới hạn năm sinh từ 1900 đến 2016 if (birthYear.toInt() < 1900 || birthYear.toInt() > 2016) { binding.edtBirthMember.error = "Năm sinh không hợp lệ" return@setOnClickListener } memberDAO = MemberDAO(this) memberDTO = MemberDTO(-1, name, birthYear) val result = memberDAO.insertMember(memberDTO) if (result > 0) { val builderSuccess = androidx.appcompat.app.AlertDialog.Builder(this, R.style.CustomDialog) val bindingSuccess = com.example.managerlibrary.databinding.DialogLoginSuccessBinding.inflate( layoutInflater ) builderSuccess.setView(bindingSuccess.root) val dialogSuccess = builderSuccess.create() dialogSuccess.show() dialogSuccess.setCancelable(false) bindingSuccess.txtLoginSuccess.text = "Thêm thành công thành viên!" bindingSuccess.btnLoginSuccess.setOnClickListener { dialogSuccess.dismiss() val intent = Intent(this, MainActivity::class.java) intent.putExtra("ok", "member") startActivity(intent) finish() } } else { Toast.makeText(this, "Thêm thất bại", Toast.LENGTH_SHORT).show() } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() return true } return super.onOptionsItemSelected(item) } }
0
Kotlin
0
1
1bac9423c8a0daf3f31b5268d4e8386c4cffc161
3,414
ManagerLibrary
MIT License
app/src/main/kotlin/com/thekhaeng/materialstyletemplate/adapter/item/TopicItem.kt
nontravis
87,284,931
false
{"Kotlin": 105356, "Java": 1197}
package com.thekhaeng.materialstyletemplate.adapter.item import androidx.annotation.ColorInt import com.thekhaeng.materialstyletemplate.adapter.ItemConstant.TYPE_TOPIC import com.thekhaeng.materialstyletemplate.adapter.base.BaseItem /** * Created by thekhaeng on 4/7/2017 AD. */ class TopicItem(val topic: String, @ColorInt val color: Int) : BaseItem(TYPE_TOPIC)
1
Kotlin
36
174
804e1cd36159a778a27ad4c6162b12d725c99b93
384
material-design-guideline
Apache License 2.0
evs_sdk/src/main/java/com/iflytek/cyber/evs/sdk/agent/Launcher.kt
iFLYOS-OPEN
209,758,318
false
null
package com.iflytek.cyber.evs.sdk.agent import androidx.annotation.CallSuper import com.alibaba.fastjson.JSONObject import com.iflytek.cyber.evs.sdk.RequestManager import com.iflytek.cyber.evs.sdk.model.Constant /** * 启动器模块。详细介绍见https://doc.iflyos.cn/device/evs/reference/launcher.html#%E5%90%AF%E5%8A%A8%E5%99%A8 */ abstract class Launcher { val version get() = "1.0" companion object { const val NAME_START_ACTIVITY = "${Constant.NAMESPACE_LAUNCHER}.start_activity" const val NAME_BACK = "${Constant.NAMESPACE_LAUNCHER}.back" const val NAME_START_ACTIVITY_RESULT = "${Constant.NAMESPACE_LAUNCHER}.start_activity_result" const val NAME_BACK_RESULT = "${Constant.NAMESPACE_LAUNCHER}.back_result" const val NAME_START_INTERNAL_APP = "${Constant.NAMESPACE_LAUNCHER}.start_internal_app" const val NAME_START_INTERNAL_APP_RESULT = "${Constant.NAMESPACE_LAUNCHER}.start_internal_app_result" const val PAYLOAD_PAGE = "page" const val PAYLOAD_RESULT = "result" const val PAYLOAD_FAILURE_CODE = "failure_code" const val PAYLOAD_FEEDBACK_TEXT = "feedback_text" const val KEY_SUPPORTED_APP_TYPE = "supported_app_type" const val KEY_FOREGROUND_APP_TYPE = "foreground_app_type" const val KEY_FOREGROUND_APP_ID = "foreground_app_id" const val KET_INTERNAL_APP = "internal_app" const val TYPE_TEMPLATE = "TEMPLATE" const val TYPE_SKILL = "SKILL" const val TYPE_EVALUATE = "EVALUATE" const val TYPE_H5_APP = "H5_APP" const val PAGE_HOME = "home" const val PAGE_SETTINGS = "settings" const val PAGE_CONTENTS = "contents" const val PAGE_SKILLS = "skills" const val PAGE_ALARMS = "alarms" const val PAGE_MESSAGES = "messages" const val PAGE_NEXT = "next" const val PAGE_PREVIOUS = "previous" const val RESULT_SUCCEED = "SUCCEED" const val RESULT_FAILED = "FAILED" const val FAILURE_CODE_NOT_FOUND_PAGE = "NOT_FOUND_PAGE" const val FAILURE_CODE_INTERNAL_ERROR = "INTERNAL_ERROR" const val FAILURE_CODE_NOT_FOUND_APP = "APP_NOT_FOUND" } /** * 打开跳转 Launcher 内的某个页面 * @return 是否自定义反馈结果 */ abstract fun startActivity(page: String, callback: ExecuteCallback): Boolean abstract fun back(callback: ExecuteCallback) abstract fun startInternalApp(payload: JSONObject, callback: ExecuteCallback): Boolean abstract fun getForegroundAppType(): String? abstract fun getForegroundAppId(): String? abstract fun getSupportedType(): List<String> @CallSuper open fun sendStartActivitySucceed(page: String, feedbackText: String? = null) { val payload = JSONObject() payload[PAYLOAD_RESULT] = RESULT_SUCCEED payload[PAYLOAD_PAGE] = page feedbackText?.let { payload[PAYLOAD_FEEDBACK_TEXT] = feedbackText } RequestManager.sendRequest(NAME_START_ACTIVITY_RESULT, payload) } @CallSuper open fun sendStartActivityFailed( page: String, failureCode: String?, feedbackText: String? ) { val payload = JSONObject() payload[PAYLOAD_RESULT] = RESULT_FAILED payload[PAYLOAD_PAGE] = page failureCode?.let { payload[PAYLOAD_FAILURE_CODE] = it } feedbackText?.let { payload[PAYLOAD_FEEDBACK_TEXT] = it } RequestManager.sendRequest(NAME_START_ACTIVITY_RESULT, payload) } open fun sendBackSucceed(feedbackText: String? = null) { val payload = JSONObject() payload[PAYLOAD_RESULT] = RESULT_SUCCEED feedbackText?.let { payload[PAYLOAD_FEEDBACK_TEXT] = feedbackText } RequestManager.sendRequest(NAME_BACK_RESULT, payload) } open fun sendBackFailed(feedbackText: String?) { val payload = JSONObject() payload[PAYLOAD_RESULT] = RESULT_FAILED feedbackText?.let { payload[PAYLOAD_FEEDBACK_TEXT] = it } RequestManager.sendRequest(NAME_BACK_RESULT, payload) } open fun sendStartInternalAppSucceed( internalAppId: String, type: String, feedbackText: String? = null ) { val payload = JSONObject() payload[PAYLOAD_RESULT] = RESULT_SUCCEED payload["id"] = internalAppId payload["type"] = type feedbackText?.let { payload[PAYLOAD_FEEDBACK_TEXT] = it } RequestManager.sendRequest(NAME_START_INTERNAL_APP_RESULT, payload) } open fun sendStartInternalAppFailed( internalAppId: String, type: String, feedbackText: String? = null, failureCode: String? = null ) { val payload = JSONObject() payload[PAYLOAD_RESULT] = RESULT_FAILED payload["id"] = internalAppId payload["type"] = type payload["failure_code"] = failureCode feedbackText?.let { payload[PAYLOAD_FEEDBACK_TEXT] = it } RequestManager.sendRequest(NAME_START_INTERNAL_APP_RESULT, payload) } abstract class ExecuteCallback { var result = "" var page = "" var failureCode: String? = null var feedbackText: String? = null abstract fun onSuccess(feedbackText: String? = null) abstract fun onFailed(failureCode: String?, feedbackText: String?) } }
1
C
11
21
4739e2450dcda545fb1361469a9172f82ce28c66
5,478
ShowCore-Open
Apache License 2.0