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
tests/src/androidTest/java/viacheslav/chugunov/tests/util/factory/RepositoryFactory.kt
viacheslav-chugunov
475,984,676
false
{"Kotlin": 216949}
package viacheslav.chugunov.tests.util.factory import viacheslav.chugunov.core.datasource.PreferenceDataSource import viacheslav.chugunov.core.model.Language import viacheslav.chugunov.core.model.Theme import viacheslav.chugunov.core.repository.LanguageRepository import viacheslav.chugunov.core.repository.PreferredColorsRepository import viacheslav.chugunov.core.repository.PreferredThemesRepository import viacheslav.chugunov.core.repository.ThemeRepository import viacheslav.chugunov.storage.datastore.model.DataStorePreferredColors import viacheslav.chugunov.storage.reposiotry.DefaultLanguageRepository import viacheslav.chugunov.storage.reposiotry.DefaultPreferredColorsRepository import viacheslav.chugunov.storage.reposiotry.DefaultPreferredThemesRepository import viacheslav.chugunov.storage.room.ThemeDao import viacheslav.chugunov.storage.room.ThemeDatabaseDataSource import viacheslav.chugunov.tests.util.TestThemeDao import viacheslav.chugunov.tests.util.datasource.TestDataStorePreferredColorsPreferenceDataSource import viacheslav.chugunov.tests.util.datasource.TestLanguagePreferenceDataSource import viacheslav.chugunov.theme.DefaultColorDescriptionFactory import viacheslav.chugunov.theme.DefaultRandomThemeDataSource import viacheslav.chugunov.theme.DefaultThemeRepository class RepositoryFactory { fun newLanguage( currentLanguage: Language?, defaultLanguage: Language ): LanguageRepository = newLanguage( preferences = TestLanguagePreferenceDataSource(currentLanguage), defaultLanguage = defaultLanguage ) fun newLanguage( preferences: PreferenceDataSource<Language>, defaultLanguage: Language ): LanguageRepository = DefaultLanguageRepository( preferences = preferences, defaultLanguage = defaultLanguage ) fun newPreferredColors( currentColors: DataStorePreferredColors?, defaultColors: DataStorePreferredColors ): PreferredColorsRepository = newPreferredColors( preference = TestDataStorePreferredColorsPreferenceDataSource(currentColors), defaultColors = defaultColors ) fun newPreferredColors( preference: PreferenceDataSource<DataStorePreferredColors>, defaultColors: DataStorePreferredColors ): PreferredColorsRepository = DefaultPreferredColorsRepository( preference = preference, defaultColors = defaultColors ) fun newPreferredThemes(themes: List<Theme>): PreferredThemesRepository = newPreferredThemes(TestThemeDao(themes)) fun newPreferredThemes(dao: ThemeDao): PreferredThemesRepository = DefaultPreferredThemesRepository(ThemeDatabaseDataSource(dao)) fun newTheme(): ThemeRepository = DefaultThemeRepository(DefaultRandomThemeDataSource(DefaultColorDescriptionFactory())) }
0
Kotlin
0
1
a365fd0f4d506b688329c97399208fe8566de2e2
2,830
appalet
MIT License
Pace Power Pulse/app/src/main/java/com/example/pacepowerpulse/FinishActivity.kt
CS639-Team1-FinalProject
785,913,874
false
{"Kotlin": 83539}
package com.example.pacepowerpulse import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.lifecycle.lifecycleScope import com.example.pacepowerpulse.databinding.ActivityExerciseBinding import com.example.pacepowerpulse.databinding.ActivityFinishBinding import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.* class FinishActivity : AppCompatActivity() { private var binding: ActivityFinishBinding? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityFinishBinding.inflate(layoutInflater) setContentView(binding?.root) setSupportActionBar(binding?.toolbarFinishActivity) if (supportActionBar != null) { supportActionBar?.setDisplayHomeAsUpEnabled(true) } binding?.toolbarFinishActivity?.setNavigationOnClickListener { onBackPressedDispatcher.onBackPressed() } binding?.btnFinish?.setOnClickListener { finish() } // //get the dao through the database in the application class // val dao = (application as WorkOutApp).db.historyDao() // addDateToDatabase(dao) } // START // private fun addDateToDatabase(historyDao: HistoryDao) { // // val c = Calendar.getInstance() // Calendars Current Instance // val dateTime = c.time // Current Date and Time of the system. // Log.e("Date : ", "" + dateTime) // Printed in the log. // // // val sdf = SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.getDefault()) // Date Formatter // val date = sdf.format(dateTime) // dateTime is formatted in the given format. // Log.e("Formatted Date : ", "" + date) // Formatted date is printed in the log. // // lifecycleScope.launch { // historyDao.insert(HistoryEntity(date)) // Add date function is called. // Log.e( // "Date : ", // "Added..." // ) // Printed in log which is printed if the complete execution is done. // } // } // //END //} }
2
Kotlin
0
0
42dff5a1c7fb95d437916d5623ff39204c613df2
2,155
PacePowerPulse
MIT License
app/src/main/java/com/tomer/anibadi/util/Repo.kt
tomer00
679,804,315
false
null
package com.tomer.anibadi.util import android.content.Context import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.tomer.anibadi.modal.Mother class Repo(private val con: Context) { private val prefAll by lazy { con.getSharedPreferences("mothers", Context.MODE_PRIVATE) } private val gson by lazy { Gson() } fun getALLMother(): List<Mother> { val type = object : TypeToken<Mother>() {}.type val retKi = mutableListOf<Mother>() for (entry: MutableMap.MutableEntry<String, out Any?> in prefAll.all.entries) retKi.add(gson.fromJson(entry.value.toString(), type)) return retKi } fun getMother(id: String): Mother { return gson.fromJson(prefAll.getString(id, ""), Mother::class.java) } fun saveMother(mod: Mother) { prefAll.edit() .putString(mod.ID, gson.toJson(mod)) .apply() } }
0
Kotlin
0
0
7cb77f067f776df1783772fcf9fb26583a595d21
925
Anganwadi-Helper
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/visitscheduler/model/entity/Visit.kt
ministryofjustice
409,259,375
false
{"Kotlin": 1439490, "PLpgSQL": 148899, "FreeMarker": 14114, "Dockerfile": 1541, "Shell": 238}
package uk.gov.justice.digital.hmpps.visitscheduler.model.entity import jakarta.persistence.CascadeType import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.EnumType import jakarta.persistence.Enumerated import jakarta.persistence.FetchType import jakarta.persistence.JoinColumn import jakarta.persistence.ManyToOne import jakarta.persistence.OneToMany import jakarta.persistence.OneToOne import jakarta.persistence.PostPersist import jakarta.persistence.Table import org.hibernate.annotations.CreationTimestamp import org.hibernate.annotations.NaturalId import org.hibernate.annotations.UpdateTimestamp import uk.gov.justice.digital.hmpps.visitscheduler.model.OutcomeStatus import uk.gov.justice.digital.hmpps.visitscheduler.model.VisitRestriction import uk.gov.justice.digital.hmpps.visitscheduler.model.VisitStatus import uk.gov.justice.digital.hmpps.visitscheduler.model.VisitType import uk.gov.justice.digital.hmpps.visitscheduler.model.entity.base.AbstractIdEntity import uk.gov.justice.digital.hmpps.visitscheduler.utils.QuotableEncoder import java.time.LocalDateTime @Entity @Table(name = "VISIT") class Visit( @Column(nullable = false) var prisonerId: String, @Column(name = "PRISON_ID", nullable = false) val prisonId: Long, @ManyToOne(cascade = [CascadeType.DETACH]) @JoinColumn(name = "PRISON_ID", updatable = false, insertable = false) val prison: Prison, @Column(nullable = false) val visitRoom: String, @Column(nullable = true) var sessionTemplateReference: String? = null, @Column(nullable = false) var visitStart: LocalDateTime, @Column(nullable = false) var visitEnd: LocalDateTime, @Column(nullable = false) @Enumerated(EnumType.STRING) var visitType: VisitType, @Column(nullable = false) @Enumerated(EnumType.STRING) var visitStatus: VisitStatus, @Column(nullable = true) @Enumerated(EnumType.STRING) var outcomeStatus: OutcomeStatus? = null, @Column(nullable = false) @Enumerated(EnumType.STRING) var visitRestriction: VisitRestriction, @OneToOne(fetch = FetchType.LAZY, cascade = [CascadeType.ALL], mappedBy = "visit", orphanRemoval = true) var visitContact: VisitContact? = null, @OneToMany(fetch = FetchType.LAZY, cascade = [CascadeType.ALL], mappedBy = "visit", orphanRemoval = true) var visitors: MutableList<VisitVisitor> = mutableListOf(), @OneToMany(fetch = FetchType.LAZY, cascade = [CascadeType.ALL], mappedBy = "visit", orphanRemoval = true) var support: MutableList<VisitSupport> = mutableListOf(), @OneToMany(fetch = FetchType.LAZY, cascade = [CascadeType.ALL], mappedBy = "visit", orphanRemoval = true) var visitNotes: MutableList<VisitNote> = mutableListOf(), @Transient private val _reference: String = "", ) : AbstractIdEntity() { @CreationTimestamp @Column val createTimestamp: LocalDateTime? = null @UpdateTimestamp @Column val modifyTimestamp: LocalDateTime? = null @Column var reference = _reference @Column @NaturalId(mutable = true) var applicationReference: String = "" @PostPersist fun createReference() { if (_reference.isBlank()) { reference = QuotableEncoder(minLength = 8).encode(id) } if (applicationReference.isBlank()) { applicationReference = QuotableEncoder(minLength = 8, chunkSize = 3).encode(id) } } override fun toString(): String { return "Visit(id=$id,reference='$reference')" } }
3
Kotlin
2
6
ad50f9f146566e043c3d115fece2f3fbce059c6d
3,446
visit-scheduler
MIT License
Test/Activity12.01/app/src/main/java/com/packt/android/MainActivity.kt
PacktPublishing
810,886,298
false
{"Kotlin": 1045857}
package com.packt.android import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.ClickableText import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState 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.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewmodel.compose.viewModel import androidx.room.Room import com.packt.android.api.DogService import com.packt.android.storage.filesystem.FileToUriMapper import com.packt.android.storage.filesystem.ProviderFileHandler import com.packt.android.storage.preference.DownloadPreferences import com.packt.android.storage.repository.DogMapper import com.packt.android.storage.repository.DogRepositoryImpl import com.packt.android.storage.repository.DogUi import com.packt.android.storage.repository.Result import com.packt.android.storage.room.DogDatabase import com.packt.android.ui.theme.Activity1201Theme import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() val retrofit = Retrofit.Builder() .baseUrl("https://dog.ceo/api/") .addConverterFactory(GsonConverterFactory.create()) .build() val downloadService = retrofit.create<DogService>(DogService::class.java) val database = Room.databaseBuilder(applicationContext, DogDatabase::class.java, "dog-db") .build() val dogRepository = DogRepositoryImpl( DownloadPreferences(applicationContext), ProviderFileHandler( applicationContext, FileToUriMapper() ), downloadService, database.dogDao(), DogMapper() ) setContent { Activity1201Theme { Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -> val viewModel = viewModel<DogViewModel>(factory = object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return DogViewModel(dogRepository) as T } }) Dog( dogViewModel = viewModel, modifier = Modifier .padding(innerPadding) .fillMaxSize() ) } } } } } @Composable fun Dog( dogViewModel: DogViewModel, modifier: Modifier ) { when (val result = dogViewModel.state.collectAsState().value) { is Result.Success -> { DogScreen( dogs = result.data, onNumberOfResultsClicked = { dogViewModel.saveNumberOfResult(it) }, onRowClicked = { dogViewModel.downloadDog(it) }, modifier = modifier ) } is Result.Loading -> { Loading(modifier = modifier) } is Result.Error -> { Error(modifier = modifier) } } } @Composable fun DogScreen( dogs: List<DogUi>, onNumberOfResultsClicked: (Int) -> Unit, onRowClicked: (String) -> Unit, modifier: Modifier = Modifier ) { LazyColumn(modifier = modifier) { item { var textFieldText by remember { mutableStateOf(dogs.size.toString()) } TextField(value = textFieldText, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), onValueChange = { textFieldText = it }) Button(onClick = { onNumberOfResultsClicked(textFieldText.toInt()) }) { Text(text = stringResource(id = R.string.click_me)) } } items(dogs.size) { val index = it ClickableText( text = AnnotatedString(text = dogs[it].url), modifier = Modifier.padding(16.dp) ) { onRowClicked(dogs[index].url) } } } } @Composable fun Loading(modifier: Modifier) { CircularProgressIndicator( modifier = modifier.width(64.dp) ) } @Composable fun Error(modifier: Modifier) { Text( text = "Something went wrong", modifier = modifier ) }
0
Kotlin
2
2
c06351e0dbb6280c31e551dcd76231c975e5d593
5,637
How-to-Build-Android-Apps-with-Kotlin-Third-Edition
MIT License
shared/src/commonMain/kotlin/com/presta/customer/ui/components/signAppHome/ui/SignHomeScreen.kt
morgan4080
726,765,347
false
{"Kotlin": 2170913, "Swift": 2162, "Ruby": 382, "Shell": 228}
package com.presta.customer.ui.components.signAppHome.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import com.presta.customer.ui.components.signAppHome.SignHomeComponent @Composable fun SignHomeScreen(component: SignHomeComponent) { val authState by component.authState.collectAsState() val signHomeStateState by component.signHomeState.collectAsState() val applyLongTermLoansState by component.applyLongTermLoansState.collectAsState() SignHomeContent( component = component, state = signHomeStateState, applyLongTermLoanState = applyLongTermLoansState, authState = authState, onApplyLongTermLoanEvent = component::onApplyLongTermLoanEvent, logout = component::logout, ) }
0
Kotlin
0
0
0850928853c87390a97953cfec2d21751904d3a9
840
kmp
Apache License 2.0
dsl/jpql/src/main/kotlin/com/linecorp/kotlinjdsl/dsl/jpql/expression/impl/CaseBuilder.kt
line
442,633,985
false
{"Kotlin": 1959613, "JavaScript": 5144, "Shell": 1023}
package com.linecorp.kotlinjdsl.dsl.jpql.expression.impl import com.linecorp.kotlinjdsl.querymodel.jpql.expression.Expression import com.linecorp.kotlinjdsl.querymodel.jpql.expression.Expressions import com.linecorp.kotlinjdsl.querymodel.jpql.predicate.Predicate internal data class CaseBuilder<T : Any>( private val whens: MutableMap<Predicate, Expression<T>>, private var `else`: Expression<T>? = null, private var currentPredicate: Predicate, ) { constructor( predicate: Predicate, then: Expression<T>, ) : this( mutableMapOf(predicate to then), null, predicate, ) fun `when`(predicate: Predicate): CaseBuilder<T> { currentPredicate = predicate return this } fun then(value: Expression<T>): CaseBuilder<T> { whens[currentPredicate] = value return this } fun `else`(value: Expression<T>): CaseBuilder<T> { `else` = value return this } fun build(): Expression<T> { return Expressions.caseWhen( whens = whens, `else` = `else`, ) } }
4
Kotlin
86
705
3a58ff84b1c91bbefd428634f74a94a18c9b76fd
1,127
kotlin-jdsl
Apache License 2.0
data/mediaplayer/src/main/java/com/mcgrady/xproject/data/mediaplayer/model/subsonic/bookmark/Bookmark.kt
mcgrady911
208,754,271
false
null
package com.mcgrady.xproject.data.mediaplayer.model.subsonic.bookmark import com.mcgrady.xproject.data.mediaplayer.model.subsonic.Child import java.util.Date data class Bookmark( val entry: Child, val position: Long = 0, val username: String, val comment: String, val created: Date? = null, val changed: Date? = null )
1
null
1
1
8120d889c9cc471870cfef6fe553ca1585c6f9c7
344
xskeleton
Apache License 2.0
ok-workout-be-repo-inmemory/src/test/kotlin/exercise/RepoExerciseInMemoryDeleteTest.kt
otuskotlin
377,713,426
false
null
package exercise import ru.otus.otuskotlin.workout.be.repo.inmemory.models.RepoExerciseInMemory import ru.otus.otuskotlin.workout.be.repo.test.exercise.RepoExerciseDeleteTest import ru.otus.otuskotlin.workout.backend.repo.common.exercise.IRepoExercise class RepoExerciseInMemoryDeleteTest : RepoExerciseDeleteTest() { override val repo: IRepoExercise = RepoExerciseInMemory(initObjects = initObjects) }
0
Kotlin
1
0
7f9445aacad7e524a74b3a0cab0e853e845faba7
408
ok-202105-workout-kkh
MIT License
src/test/kotlin/hm/binkley/kunits/system/mit/MITTest.kt
binkley
246,632,931
false
null
package hm.binkley.kunits.system.mit import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test internal class MITTest { @Test fun `should pretty print`() { "$MIT" shouldBe "MIT" } }
0
Kotlin
0
0
abc5e52626ee5882028a4f6db33047269a638daf
215
kunits
The Unlicense
testsuite/extra/src/test/java/io/smallrye/config/test/mapping/KotlinDefaultFunction.kt
smallrye
134,160,731
false
null
package io.smallrye.config.test.mapping import io.smallrye.config.ConfigMapping @ConfigMapping(prefix = "server") interface KotlinDefaultFunction { fun host(): String fun serverUrl(): String = "https://${host()}" }
42
Java
83
67
024e66bbe828c8e6b9188d1807c7b509c397adca
226
smallrye-config
Apache License 2.0
app/src/main/java/com/marin/fireexpense/data/model/User.kt
emarifer
307,340,374
false
null
package com.marin.fireexpense.data.model /** * Created by Enrique Marín on 01-10-2020. */ data class User( val userName: String = "", val userPhoto: String = "" )
0
Kotlin
0
0
e553ee54d9d2a98b8b2d9a65363b6025522d8dc4
174
FireExpense
MIT License
shared/src/androidMain/kotlin/app/duss/easyproject/utils/AppDispatchers.kt
Shahriyar13
721,031,988
false
{"Kotlin": 247935, "Swift": 6282, "Ruby": 2302}
package app.duss.easyproject.utils import app.duss.easyproject.utils.AppDispatchers import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers actual val appDispatchers: AppDispatchers = object: AppDispatchers { override val main: CoroutineDispatcher = Dispatchers.Main.immediate override val io: CoroutineDispatcher = Dispatchers.IO override val unconfined: CoroutineDispatcher = Dispatchers.Unconfined }
0
Kotlin
0
0
3b21efcf1c9bcdc2148884458a7c34f75020e071
444
Kara_EasyProject_CMP
Apache License 2.0
app/src/main/java/com/vonbrank/forkify/ui/addNewRecipe/AddNewRecipeActivity.kt
vonbrank
591,377,901
false
null
package com.vonbrank.forkify.ui.addNewRecipe import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import com.vonbrank.forkify.databinding.ActivityAddNewRecipeBinding class AddNewRecipeActivity : AppCompatActivity() { companion object { fun actionStart( context: Context, ) { val intent = Intent(context, AddNewRecipeActivity::class.java) context.startActivity(intent) } } lateinit var binding: ActivityAddNewRecipeBinding private set override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAddNewRecipeBinding.inflate(layoutInflater) setContentView(binding.root) supportFragmentManager.beginTransaction() .add(binding.addNewRecipeContainer.id, AddNewRecipeFragment()) .commit() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } }
0
Kotlin
0
1
c4ab8ccc559a03d7288a6c15c889c59a6e42c273
1,255
ForkifyForAndroid
Apache License 2.0
src/main/java/me/shadowalzazel/mcodyssey/tasks/enchantment_tasks/GaleWindTask.kt
ShadowAlzazel
511,383,377
false
{"Kotlin": 1003062}
package me.shadowalzazel.mcodyssey.tasks.enchantment_tasks import org.bukkit.Sound import org.bukkit.entity.LivingEntity import org.bukkit.scheduler.BukkitRunnable class GaleWindTask( private val entity: LivingEntity, private val modifier: Int) : BukkitRunnable() { override fun run() { entity.world.playSound(entity.location, Sound.ITEM_TRIDENT_RIPTIDE_2, 2.5F, 1.2F) entity.velocity = entity.eyeLocation.direction.clone().normalize().multiply(modifier * 0.5) this.cancel() } }
0
Kotlin
0
3
2329c35fdbb399e0cfb0caf735afcfdc9dad3907
522
MinecraftOdyssey
MIT License
src/main/kotlin/org/propercrew/minecord/commands/ReloadCommand.kt
Netherald
350,152,580
false
null
package org.propercrew.minecord.commands import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.events.interaction.SlashCommandEvent import net.dv8tion.jda.api.hooks.ListenerAdapter import net.kyori.adventure.text.Component import org.bukkit.Bukkit import org.bukkit.ChatColor import org.bukkit.plugin.java.JavaPlugin import org.propercrew.minecord.Minecord class ReloadCommand: ListenerAdapter() { override fun onSlashCommand(event: SlashCommandEvent) { val plugin = Minecord.instance!! if (event.channel.id != Minecord.instance?.config?.getString("channelId")) { return } if (event.name == "reload") { if (event.member!!.isOwner) { val reloadEmbed = EmbedBuilder() .setTitle("**:repeat: Reloading...**") .setDescription("Reloading minecraft server...") .setFooter(event.user.asTag, event.user.avatarUrl) event.replyEmbeds(reloadEmbed.build()).queue() Bukkit.broadcast(Component.text("${ChatColor.GREEN}Reloading...")) Bukkit.getScheduler().runTaskLater(plugin, Runnable { Bukkit.getServer().reload() }, 60L) Bukkit.broadcast(Component.text("${ChatColor.GREEN}Reload Complete!")) } else { val errorEmbed = EmbedBuilder() .setTitle("**:warning: Error!**") .setDescription("Permission denied!") .setFooter("${event.user.name}#${event.user.discriminator}", event.user.avatarUrl) event.replyEmbeds(errorEmbed.build()).queue() } } } }
0
Kotlin
2
3
83bf81cd96003dd02a6dcca9f219e23d91c45bb6
1,715
minecord
MIT License
kmp-firebase/src/commonMain/kotlin/com/tweener/firebase/firestore/model/FirestoreModel.kt
Tweener
766,294,641
false
{"Kotlin": 42020}
package com.tweener.firebase.firestore.model import kotlinx.serialization.Serializable /** * @author <NAME> * @since 09/02/2024 */ @Serializable abstract class FirestoreModel { abstract var id: String // Firestore ID }
0
Kotlin
0
9
14ce51dc9b4805a104a50b4ad35fdf6e16b9be14
229
kmp-bom
Apache License 2.0
clientprotocol/src/commonMain/generated/org/inthewaves/kotlinsignald/clientprotocol/v1/requests/DeleteServer.kt
inthewaves
398,221,861
false
null
// File is generated by ./gradlew generateSignaldClasses --- do not edit unless reformatting package org.inthewaves.kotlinsignald.clientprotocol.v1.requests import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.inthewaves.kotlinsignald.clientprotocol.v1.structures.EmptyResponse /** * This class only represents the response from signald for the request. Make a request by creating * an instance of [org.inthewaves.kotlinsignald.clientprotocol.v1.structures.RemoveServerRequest] and * then calling its `submit` function. */ @Serializable @SerialName("delete_server") internal data class DeleteServer private constructor( public override val data: EmptyResponse? = null ) : JsonMessageWrapper<EmptyResponse>()
11
Kotlin
1
2
6f48a612fc307c08e44af25f826bb627e3e4f499
758
kotlin-signald
MIT License
src/main/kotlin/org/virtuslab/pulumikotlin/scripts/GetRidOfDescriptionInSchemaScript.kt
VirtuslabRnD
531,060,226
false
{"Kotlin": 516974}
package com.virtuslab.pulumikotlin.scripts import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.options.required import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import java.io.File import java.nio.file.Path import kotlin.io.path.Path import kotlin.io.path.extension import kotlin.io.path.nameWithoutExtension fun main(args: Array<String>) { GetRidOfDescriptionInSchemaScript().main(args) } class GetRidOfDescriptionInSchemaScript : CliktCommand() { private val schemaPath: String by option().required() override fun run() { val json = Json { prettyPrint = true } val inputSchema = File(schemaPath) val filesToProcess = if (inputSchema.isDirectory) { inputSchema.listFiles()?.toList().orEmpty() } else { listOf(inputSchema) } val modifiedNameSuffix = "-no-description" val filesNotAlreadyProcessed = filesToProcess .filterNot { it.name.contains(modifiedNameSuffix) } filesNotAlreadyProcessed.forEach { file -> val jsonContents = json.parseToJsonElement( file.bufferedReader().readText(), ) val withoutDescription = json.encodeToString(deleteDescription(jsonContents)) val newPath = pathWithFileSuffix(file.path, suffix = modifiedNameSuffix) newPath.toFile().writeText(withoutDescription) } } private fun pathWithFileSuffix(path: String, suffix: String): Path { val originalPath = Path(path) val name = originalPath.nameWithoutExtension val extension = originalPath.extension return originalPath.parent.resolve("$name$suffix.$extension") } private fun deleteDescription(jsonElement: JsonElement): JsonElement { return when (jsonElement) { is JsonObject -> JsonObject( jsonElement .filterNot { (key, _) -> key == "description" } .map { (key, value) -> key to deleteDescription(value) } .toMap(), ) is JsonArray -> JsonArray(jsonElement.map { deleteDescription(it) }) else -> jsonElement } } }
65
Kotlin
3
59
cbd8b1f0741c547a82ba5a995a2be2f0be2c667b
2,539
pulumi-kotlin
Apache License 2.0
src/main/kotlin/com/dp/advancedgunnerycontrol/weaponais/tags/FighterTag.kt
DesperatePeter
361,380,141
false
null
package com.dp.advancedgunnerycontrol.weaponais.tags import com.dp.advancedgunnerycontrol.weaponais.FiringSolution import com.fs.starfarer.api.combat.CombatEntityAPI import com.fs.starfarer.api.combat.ShipAPI import com.fs.starfarer.api.combat.WeaponAPI class FighterTag(weapon: WeaponAPI) : WeaponAITagBase(weapon) { override fun isValidTarget(entity: CombatEntityAPI): Boolean { return (entity as? ShipAPI)?.isFighter == true } override fun computeTargetPriorityModifier(solution: FiringSolution): Float = 1.0f override fun shouldFire(solution: FiringSolution): Boolean = true override fun isBaseAiOverridable(): Boolean = true override fun avoidDebris(): Boolean = false }
0
Kotlin
3
9
514c3a1b9bd3f16ad6d0c602c9d9bdd9b50fb9fb
713
starsector-advanced-weapon-control
MIT License
processing-tests/common/test/kotlin/com/livefront/sealedenum/compilation/generics/GenericSealedClassTests.kt
livefront
244,991,153
false
null
package com.livefront.sealedenum.compilation.generics import com.livefront.sealedenum.testing.assertCompiles import com.livefront.sealedenum.testing.assertGeneratedFileMatches import com.livefront.sealedenum.testing.compile import com.livefront.sealedenum.testing.getSourceFile import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class GenericSealedClassTests { @Test fun `one type parameter sealed class`() { assertEquals( listOf( OneTypeParameterSealedClass.FirstObject, OneTypeParameterSealedClass.SecondObject, OneTypeParameterSealedClass.ThirdObject ), OneTypeParameterSealedClass.values ) } @Test fun `compilation for one type parameter generates correct code`() { val result = compile(getSourceFile("compilation", "generics", "GenericSealedClass.kt")) assertCompiles(result) assertGeneratedFileMatches( "OneTypeParameterSealedClass_SealedEnum.kt", oneTypeParameterSealedClassGenerated, result ) } @Test fun `two type parameter sealed class`() { assertEquals( listOf( TwoTypeParameterSealedClass.FirstObject, TwoTypeParameterSealedClass.SecondObject ), TwoTypeParameterSealedClass.values ) } @Test fun `compilation for two type parameter generates correct code`() { val result = compile(getSourceFile("compilation", "generics", "GenericSealedClass.kt")) assertCompiles(result) assertGeneratedFileMatches( "TwoTypeParameterSealedClass_SealedEnum.kt", twoTypeParameterSealedClassGenerated, result ) } @Test fun `limited type parameter sealed class`() { assertEquals( listOf( LimitedTypeParameterSealedClass.FirstObject, LimitedTypeParameterSealedClass.SecondObject ), LimitedTypeParameterSealedClass.values ) } @Test fun `compilation for limited type parameter generates correct code`() { val result = compile(getSourceFile("compilation", "generics", "GenericSealedClass.kt")) assertCompiles(result) assertGeneratedFileMatches( "LimitedTypeParameterSealedClass_SealedEnum.kt", limitedTypeParameterSealedClassGenerated, result ) } @Test fun `multiple bounds sealed class`() { assertEquals( listOf( MultipleBoundsSealedClass.FirstObject ), MultipleBoundsSealedClass.values ) } @Test fun `compilation for multiple bounds sealed class generates correct code`() { val result = compile(getSourceFile("compilation", "generics", "GenericSealedClass.kt")) assertCompiles(result) assertGeneratedFileMatches( "MultipleBoundsSealedClass_SealedEnum.kt", multipleBoundsSealedClassGenerated, result ) } }
6
null
5
87
00b8f3753c71ed7cdd82a9c5e822f9e558ffb8c1
3,147
sealed-enum
Apache License 2.0
app/src/main/java/com/example/myapplication/domain/usecase/BaseUseCase.kt
Nikhil-Bohra
392,342,333
false
null
package com.example.myapplication.domain.usecase import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.observers.DisposableSingleObserver import io.reactivex.schedulers.Schedulers abstract class BaseUseCase<T, Params> { abstract fun getUseCaseObservable(params: Params):Single<T> private val compositeDisposable = CompositeDisposable() fun execute(observer: DisposableSingleObserver<T>, params: Params){ compositeDisposable.add(getUseCaseObservable(params) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(observer)) } fun dispose(){ if(!compositeDisposable.isDisposed) compositeDisposable.dispose() } }
0
Kotlin
1
0
6c1dbe00d211ff730529811b9a5bff657c285b70
838
top-github
Apache License 2.0
core/src/main/kotlin/me/shkschneider/skeleton/ui/widget/LongPreference.kt
shkschneider
11,576,696
false
{"Gradle": 9, "Shell": 4, "Ignore List": 2, "Java Properties": 3, "Text": 1, "Batchfile": 1, "Makefile": 3, "YAML": 1, "Markdown": 1, "XML": 79, "Java": 1, "Kotlin": 171, "C": 1}
package me.shkschneider.skeleton.ui.widget import android.content.Context import android.preference.Preference import android.util.AttributeSet import android.view.View import android.widget.TextView class LongPreference : Preference { constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) override fun onBindView(view: View) { super.onBindView(view) view.findViewById<TextView>(android.R.id.summary).maxLines = 5 } }
0
Kotlin
12
25
ef82d0b963a7ec7a3210fa396a2ecc6358e42d26
517
android_Skeleton
Apache License 2.0
src/main/kotlin/hu/kszi2/boti/command/MoschtCommand.kt
kszi2
686,428,085
false
{"Kotlin": 26538, "Dockerfile": 314}
package hu.kszi2.boti.command import com.jessecorbett.diskord.api.channel.Embed import com.jessecorbett.diskord.bot.interaction.InteractionBuilder import hu.kszi2.moscht.* import hu.kszi2.moscht.rendering.SimpleDliRenderer import java.time.Clock import java.time.LocalDateTime class MoschtCommand : BotSlashCommand() { override fun initSlashCommand(interactionBuilder: InteractionBuilder) { interactionBuilder.slashCommand("moscht", "Request StatuSCH.") { val args by stringParameter("argument", "Arguments.", optional = true) callback { respond { val renderer = SimpleDliRenderer() val filter = when (args) { "w" -> { m: Machine -> m.type == MachineType.WashingMachine } "wa" -> { m: Machine -> m.type == MachineType.WashingMachine && m.status == MachineStatus(MachineStatus.MachineStatusType.Available) } "d" -> { m: Machine -> m.type == MachineType.Dryer } "da" -> { m: Machine -> m.type == MachineType.Dryer && m.status == MachineStatus(MachineStatus.MachineStatusType.Available) } else -> { _: Machine -> true } } with(renderer) { renderData(MosogepApiV1(), MosogepApiV2()) { filter(it) } content = "" embeds = mutableListOf( Embed( title = "StatuSCH :sweat_drops:", description = getData(), timestamp = LocalDateTime.now(Clock.systemUTC()).toString(), color = 808080, url = "https://mosogep.sch.bme.hu", ) ) } } } } } }
6
Kotlin
0
0
6329c8dd6da5d9edc4e050f87ec137b5b895ee90
2,060
boti
MIT License
app/src/main/java/com/github/anchernyshov/chaperon/view/ContentActivity.kt
anchernyshov
802,545,568
false
{"Kotlin": 9613}
package com.github.anchernyshov.chaperon.view import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.github.anchernyshov.chaperon.R import com.github.anchernyshov.chaperon.databinding.ActivityContentBinding class ContentActivity : AppCompatActivity() { private lateinit var binding: ActivityContentBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() binding = ActivityContentBinding.inflate(layoutInflater) setContentView(binding.root) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } binding.activityContentLogoutBtn.setOnClickListener { val sharedPreferences = getSharedPreferences("com.github.anchernyshov.chaperon", Context.MODE_PRIVATE) val editor: SharedPreferences.Editor = sharedPreferences.edit() editor.remove("PREF_AUTHENTICATION_TOKEN") editor.apply() val intent = Intent( this@ContentActivity, AuthActivity::class.java ) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) startActivity(intent) } } }
0
Kotlin
0
0
6568c85336f5319c9e36b7c3465860b2d5d3fe52
1,705
chaperon
MIT License
app/src/main/java/com/example/bagshop/model/repository/TokenInMemory.kt
esipiderman
521,835,056
false
{"Kotlin": 125585}
package com.example.bagshop.model.repository object TokenInMemory { var username: String? = null private set var token: String? = null private set fun refreshToken(username:String?, token:String?){ this.username = username this.token = token } }
0
Kotlin
0
1
39ebc489a3d038ac0bb8a6f77ce2817945e17295
297
bag_shop
MIT License
backend/ticket-broker-ktor-server/src/main/kotlin/com/github/damianreeves/ticketbroker/ktor/server/KtorServer.kt
DamianReeves
177,315,311
false
{"Scala": 43094, "Kotlin": 8205, "HTML": 3812}
package com.github.damianreeves.ticketbroker.ktor.server fun main(args: Array<String>) { println("Hello from KtorServer") }
0
Scala
1
0
64998395f8ad5ea3dd7ec9f1288b5a17bdd51ca0
128
ticket-broker
MIT License
kmath-tensors/src/commonTest/kotlin/space/kscience/kmath/tensors/core/TestDoubleAnalyticTensorAlgebra.kt
SciProgCentre
129,486,382
false
null
/* * Copyright 2018-2022 KMath contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package space.kscience.kmath.tensors.core import space.kscience.kmath.nd.ShapeND import space.kscience.kmath.operations.invoke import space.kscience.kmath.structures.asBuffer import kotlin.math.* import kotlin.test.Test import kotlin.test.assertTrue internal class TestDoubleAnalyticTensorAlgebra { val shape = ShapeND(2, 1, 3, 2) val buffer = doubleArrayOf( 27.1, 20.0, 19.84, 23.123, 3.0, 2.0, 3.23, 133.7, 25.3, 100.3, 11.0, 12.012 ) val tensor = DoubleTensor(shape, buffer.asBuffer()) fun DoubleArray.fmap(transform: (Double) -> Double): DoubleArray { return this.map(transform).toDoubleArray() } fun expectedTensor(transform: (Double) -> Double): DoubleTensor { return DoubleTensor(shape, buffer.fmap(transform).asBuffer()) } @Test fun testExp() = DoubleTensorAlgebra { assertTrue { exp(tensor) eq expectedTensor(::exp) } } @Test fun testLog() = DoubleTensorAlgebra { assertTrue { ln(tensor) eq expectedTensor(::ln) } } @Test fun testSqrt() = DoubleTensorAlgebra { assertTrue { sqrt(tensor) eq expectedTensor(::sqrt) } } @Test fun testCos() = DoubleTensorAlgebra { assertTrue { cos(tensor) eq expectedTensor(::cos) } } @Test fun testCosh() = DoubleTensorAlgebra { assertTrue { cosh(tensor) eq expectedTensor(::cosh) } } @Test fun testAcosh() = DoubleTensorAlgebra { assertTrue { acosh(tensor) eq expectedTensor(::acosh) } } @Test fun testSin() = DoubleTensorAlgebra { assertTrue { sin(tensor) eq expectedTensor(::sin) } } @Test fun testSinh() = DoubleTensorAlgebra { assertTrue { sinh(tensor) eq expectedTensor(::sinh) } } @Test fun testAsinh() = DoubleTensorAlgebra { assertTrue { asinh(tensor) eq expectedTensor(::asinh) } } @Test fun testTan() = DoubleTensorAlgebra { assertTrue { tan(tensor) eq expectedTensor(::tan) } } @Test fun testAtan() = DoubleTensorAlgebra { assertTrue { atan(tensor) eq expectedTensor(::atan) } } @Test fun testTanh() = DoubleTensorAlgebra { assertTrue { tanh(tensor) eq expectedTensor(::tanh) } } @Test fun testCeil() = DoubleTensorAlgebra { assertTrue { ceil(tensor) eq expectedTensor(::ceil) } } @Test fun testFloor() = DoubleTensorAlgebra { assertTrue { floor(tensor) eq expectedTensor(::floor) } } val shape2 = ShapeND(2, 2) val buffer2 = doubleArrayOf( 1.0, 2.0, -3.0, 4.0 ) val tensor2 = DoubleTensor(shape2, buffer2.asBuffer()) @Test fun testMin() = DoubleTensorAlgebra { assertTrue { tensor2.min() == -3.0 } assertTrue { tensor2.min(0, true) eq fromArray( ShapeND(1, 2), doubleArrayOf(-3.0, 2.0) ) } assertTrue { tensor2.min(1, false) eq fromArray( ShapeND(2), doubleArrayOf(1.0, -3.0) ) } } @Test fun testMax() = DoubleTensorAlgebra { assertTrue { tensor2.max() == 4.0 } assertTrue { tensor2.max(0, true) eq fromArray( ShapeND(1, 2), doubleArrayOf(1.0, 4.0) ) } assertTrue { tensor2.max(1, false) eq fromArray( ShapeND(2), doubleArrayOf(2.0, 4.0) ) } } @Test fun testSum() = DoubleTensorAlgebra { assertTrue { tensor2.sum() == 4.0 } assertTrue { tensor2.sum(0, true) eq fromArray( ShapeND(1, 2), doubleArrayOf(-2.0, 6.0) ) } assertTrue { tensor2.sum(1, false) eq fromArray( ShapeND(2), doubleArrayOf(3.0, 1.0) ) } } @Test fun testMean() = DoubleTensorAlgebra { assertTrue { mean(tensor2) == 1.0 } assertTrue { mean(tensor2, 0, true) eq fromArray( ShapeND(1, 2), doubleArrayOf(-1.0, 3.0) ) } assertTrue { mean(tensor2, 1, false) eq fromArray( ShapeND(2), doubleArrayOf(1.5, 0.5) ) } } }
89
null
55
645
6c1a5e62bff541cca8065e4ab4c97d02a29d685a
4,572
kmath
Apache License 2.0
src/main/kotlin/com/github/vani5h/uhh/ExampleMod.kt
vani5h
731,864,377
false
{"Kotlin": 11847, "Java": 2710}
package com.github.vani5h.uhh import com.github.vani5h.uhh.commands.CommandManager import com.github.vani5h.uhh.config.ConfigManager import com.github.vani5h.uhh.config.categories.ExampleModConfig import com.github.vani5h.uhh.features.ChatFeatures import net.minecraftforge.common.MinecraftForge import net.minecraftforge.fml.common.Loader import net.minecraftforge.fml.common.Mod import net.minecraftforge.fml.common.event.FMLInitializationEvent import net.minecraftforge.fml.common.event.FMLPreInitializationEvent @Mod(modid = ExampleMod.MOD_ID, useMetadata = true) class ExampleMod { @Mod.EventHandler fun init(event: FMLInitializationEvent) { configManager = ConfigManager() MinecraftForge.EVENT_BUS.register(configManager) } @Mod.EventHandler fun preInit(event: FMLPreInitializationEvent) { CommandManager() MinecraftForge.EVENT_BUS.register(ChatFeatures()) } companion object { lateinit var configManager: ConfigManager const val MOD_ID = "uhh" @JvmStatic val version: String get() = Loader.instance().indexedModList[MOD_ID]!!.version val config: ExampleModConfig get() = configManager.config ?: error("config is null") } }
0
Kotlin
0
0
3211cb11e5595043f66f8fb238806eec9891382d
1,266
uhh
The Unlicense
app/src/test/java/com/polendina/knounce/presentation/shared/floatingbubble/FloatingBubbleViewModelTest.kt
z0xyz
695,183,007
false
{"Kotlin": 114861}
package com.polendina.knounce.presentation.shared.floatingbubble import android.app.Application import androidx.compose.ui.text.input.TextFieldValue import com.polendina.knounce.domain.model.Word import com.polendina.knounce.utils.refine import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment //@RunWith(MockitoJUnitRunner::class) @RunWith(RobolectricTestRunner::class) class FloatingBubbleViewModelTest { private lateinit var floatingBubbleViewModel: FloatingBubbleViewModel private lateinit var application: Application private var germanWords = listOf( Word( title = "nacht", translation = "night", pronunciations = null ), Word( title = "milch", translation = "milk", pronunciations = null ), Word( title = "ich", translation = "I", pronunciations = null ), Word( title = "ich", translation = "I", pronunciations = null ), Word( title = "", translation = "I", pronunciations = null ), Word( title = " ", translation = "I", pronunciations = null ), // Following 2 are empty Word( title = "spechieren", translation = "spec", pronunciations = null ), Word( title = "@$@!#$", translation = "@$@!#$", pronunciations = null ), Word( title = "Mediterrane Pflanzen halten das locker aus.\n Aber auch die brauchen ab und an mal Wasser", translation = "Mediterranean plants can easily handle this. But they also need water from time to time", pronunciations = null ) ) @OptIn(ExperimentalCoroutinesApi::class) @Before fun setup() { val testDispatcher = UnconfinedTestDispatcher() Dispatchers.setMain(testDispatcher) // application = Mockito.mock(Application::class.java) application = RuntimeEnvironment.getApplication() floatingBubbleViewModel = FloatingBubbleViewModel(application, testDispatcher) } @Test fun translateWord() = runTest { floatingBubbleViewModel.words.clear() germanWords.forEach { floatingBubbleViewModel.words.add(Word(title = it.title)) floatingBubbleViewModel.currentWord = floatingBubbleViewModel.words.last() floatingBubbleViewModel.translateWord(word = it.title.refine()).join() } assertEquals( germanWords.map { it.translation }, floatingBubbleViewModel.words.map { it.translation } ) } @Test fun grabAudioFiles() = runTest { germanWords.map { it.title }.map { floatingBubbleViewModel.grabAudioFiles( searchTerm = it ).run { println(this?.attributes?.total) } }.let { println(it) // assertEquals( // germanWords.map { it.pronunciations.isNotEmpty() }, // it // ) } } @Test fun loadPronunciations() = runTest { germanWords.forEach { println(it.title) floatingBubbleViewModel.srcWord = TextFieldValue(it.title) floatingBubbleViewModel.loadPronunciations( searchTerm = it.title ).join() } println(floatingBubbleViewModel.words.toList()) } @Test fun searchWordTest() = runTest { germanWords.map { it.title }.forEach { floatingBubbleViewModel.searchWord(it) } assertEquals( germanWords.map { it.title }.filter { it.isNotBlank() }.distinct(), floatingBubbleViewModel.words.toList().map { it.title } ) } @OptIn(ExperimentalCoroutinesApi::class) @Test fun loadWordsFromDbTest() = runTest { germanWords.forEach { floatingBubbleViewModel.searchWord(it.title) println(floatingBubbleViewModel.currentWord.title) floatingBubbleViewModel.insertWordToDb(floatingBubbleViewModel.currentWord) } advanceUntilIdle() println(floatingBubbleViewModel.loadWordsFromDb().map { it.title }) } }
0
Kotlin
0
0
64c501b4efd350138b5a10a5730042b98aae5910
4,808
knounce
MIT License
app/src/main/java/com/ahmadshubita/moviesapp/ui/core/navigation/MainNavHost.kt
AhmadShubita
735,040,563
false
{"Kotlin": 156270}
package com.ahmadshubita.moviesapp.ui.core.navigation import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Modifier import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.rememberNavController import com.ahmadshubita.moviesapp.ui.bottombar.MoviesDestination import com.ahmadshubita.moviesapp.ui.bottombar.allItemsGraph import com.ahmadshubita.moviesapp.ui.bottombar.detailsGraph import com.ahmadshubita.moviesapp.ui.bottombar.moviesGraph import com.ahmadshubita.moviesapp.ui.bottombar.peopleGraph import com.ahmadshubita.moviesapp.ui.bottombar.tvGraph @Composable fun MainNavHost( navController: NavHostController = rememberNavController(), startDestination: String = MoviesDestination.route, modifier: Modifier = Modifier, isBottomNavVisible: MutableState<Boolean>, ) { NavHost( navController = navController, startDestination = startDestination, modifier = modifier ) { // Define the Graphs here and you can define nested graphs also. moviesGraph(navController = navController, isBottomNavVisible = isBottomNavVisible) tvGraph(navController = navController, isBottomNavVisible = isBottomNavVisible) peopleGraph(navController = navController, isBottomNavVisible = isBottomNavVisible) allItemsGraph(navController = navController, isBottomNavVisible = isBottomNavVisible) detailsGraph(navController = navController, isBottomNavVisible = isBottomNavVisible) } }
0
Kotlin
0
13
c76614da6aac5fe3705c0910714716605be7c1c9
1,619
MoviesApp
MIT License
hw6/src/main/kotlin/ru/itmo/tokenizer/Tokenizer.kt
KirillKurdyukov
538,702,916
false
null
package ru.itmo.tokenizer import ru.itmo.state.StateMachine object Tokenizer { fun createTokens(expression: String): List<Token> { val tokens: MutableList<Token> = mutableListOf() val stateMachine = StateMachine(expression) while (true) { when (val curState = stateMachine.nextState()) { StateMachine.End -> break is StateMachine.Error -> throw RuntimeException("Unexpected symbol on position ${curState.pos + 1}") else -> { tokens.add(curState.createToken()) } } } return tokens } }
0
Kotlin
1
1
7f93a94c1ec72cc033e57d44c15439f584b02814
646
software-design
MIT License
app/src/main/java/com/example/mywaycompose/di/data/DataDatabaseModule.kt
larkes-cyber
739,078,285
false
{"Kotlin": 575045}
package com.example.mywaycompose.di.data import android.content.Context import androidx.room.Room import com.example.mywaycompose.data.local.database.AppDatabase import com.example.mywaycompose.data.local.database.dao.* import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) object DataDatabaseModule { @Provides fun provideDataBase(context: Context): AppDatabase { return Room.databaseBuilder( context, AppDatabase::class.java,"myway_database" ) .fallbackToDestructiveMigration() .allowMainThreadQueries() .build() } @Provides fun provideTasksDao(database: AppDatabase): TasksDao { return database.tasksDao() } @Provides fun provideMainTasksDao(database: AppDatabase): MainTasksDao { return database.mainTasksDao() } @Provides fun provideIdeasDao(database: AppDatabase): IdeasDao { return database.ideasDao() } @Provides fun provideVisualTaskDao(database: AppDatabase): VisualTaskDao{ return database.visualTasksDao() } @Provides fun provideProductTasksDao( database: AppDatabase ):ProductTasksDao = database.productTasksDao() @Provides fun provideTaskClassDao( database: AppDatabase ):TaskClassDao = database.taskClassDao() }
0
Kotlin
0
1
81ff3952a4aa8d83269a349ff52f8afb6a1156ff
1,464
PlannerApp
Apache License 2.0
plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/base/codeInsight/PsiOnlyKotlinMainFunctionDetector.kt
ingokegel
72,937,917
true
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.codeInsight import com.intellij.util.concurrency.annotations.RequiresReadLock import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.psi.KtNamedFunction @ApiStatus.Internal object PsiOnlyKotlinMainFunctionDetector : KotlinMainFunctionDetector { @RequiresReadLock override fun isMain(function: KtNamedFunction, configuration: KotlinMainFunctionDetector.Configuration): Boolean { if (function.isLocal || function.typeParameters.isNotEmpty()) { return false } val isTopLevel = function.isTopLevel val parameterCount = function.valueParameters.size + (if (function.receiverTypeReference != null) 1 else 0) if (parameterCount == 0) { if (!isTopLevel) { return false } if (!function.languageVersionSettings.supportsFeature(LanguageFeature.ExtendedMainConvention)) { return false } } else if (parameterCount == 1) { if (configuration.checkParameterType && !isMainCheckParameter(function)) { return false } } else { return false } if ((KotlinPsiHeuristics.findJvmName(function) ?: function.name) != "main") { return false } if (!isTopLevel && configuration.checkJvmStaticAnnotation && !KotlinPsiHeuristics.hasJvmStaticAnnotation(function)) { return false } if (configuration.checkResultType) { val returnTypeReference = function.typeReference if (returnTypeReference != null && !KotlinPsiHeuristics.typeMatches(returnTypeReference, StandardClassIds.Unit)) { return false } } return true } private fun isMainCheckParameter(function: KtNamedFunction): Boolean { val receiverTypeReference = function.receiverTypeReference if (receiverTypeReference != null) { return KotlinPsiHeuristics.typeMatches(receiverTypeReference, StandardClassIds.Array, StandardClassIds.String) } val parameter = function.valueParameters.singleOrNull() ?: return false val parameterTypeReference = parameter.typeReference ?: return false return when { parameter.isVarArg -> KotlinPsiHeuristics.typeMatches(parameterTypeReference, StandardClassIds.String) else -> KotlinPsiHeuristics.typeMatches(parameterTypeReference, StandardClassIds.Array, StandardClassIds.String) } } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
2,919
intellij-community
Apache License 2.0
app/src/main/java/ru/sukharev/myrecipes/addrecipe/AddRecipeContract.kt
SukharevPavel
141,687,438
false
null
package ru.sukharev.myrecipes.addrecipe import ru.sukharev.myrecipes.base.BasePresenter import ru.sukharev.myrecipes.base.BaseView /** * Created by pasha on 13.11.17. */ interface AddRecipeContract { interface View : BaseView<Presenter> { fun onRecipeAdded() fun onRecipeAddingError() fun setRating(rating: Int) } interface Presenter : BasePresenter<View> { fun addRecipe(title: String, desc: String) fun setRating(rating: Int) } }
0
Kotlin
0
0
a9b6078bc33e5b18d137e84914d6fcebd996fd78
500
my-recipes
MIT License
src/main/kotlin/no/nav/tiltakspenger/meldekort/api/tilgang/InnloggetBrukerProvider.kt
navikt
720,213,646
false
{"Kotlin": 239497, "Shell": 1201, "Dockerfile": 515}
package no.nav.tiltakspenger.meldekort.api.tilgang import io.ktor.server.application.ApplicationCall import io.ktor.server.auth.authentication import mu.KotlinLogging import no.nav.security.token.support.v2.TokenValidationContextPrincipal import no.nav.tiltakspenger.meldekort.api.AdRolle import no.nav.tiltakspenger.meldekort.api.Configuration import java.util.* private val LOG = KotlinLogging.logger {} class InnloggetBrukerProvider( private val allAvailableRoles: List<AdRolle> = Configuration.alleAdRoller(), ) { private fun finnRolleMedUUID(uuidFraClaim: UUID) = allAvailableRoles.single { configRole -> configRole.objectId == uuidFraClaim } private fun List<UUID>.mapFromUUIDToRoleName(): List<Rolle> = this.map { LOG.debug { "Mapper rolle $it" }; it } .map { finnRolleMedUUID(it).name } private fun hentSaksbehandler(principal: TokenValidationContextPrincipal): Saksbehandler { val ident = requireNotNull(principal.getClaim("azure", "NAVident")) { "NAVident er null i token" } val roller = principal.getListClaim("azure", "groups").map { UUID.fromString(it) }.mapFromUUIDToRoleName() return Saksbehandler( navIdent = ident, roller = roller, ) } fun krevInnloggetSaksbehandler(call: ApplicationCall): Saksbehandler { val principal = call.authentication.principal<TokenValidationContextPrincipal>() ?: throw ManglendeJWTTokenException() return hentSaksbehandler(principal) } fun krevSystembruker(call: ApplicationCall) { val principal = call.authentication.principal<TokenValidationContextPrincipal>() ?: throw ManglendeJWTTokenException() if (!principal.getClaim("azure", "idtyp").equals("app")) throw IkkeSystembrukerException() } } internal fun TokenValidationContextPrincipal.getClaim(issuer: String, name: String): String? = this.context .getClaims(issuer) ?.getStringClaim(name) internal fun TokenValidationContextPrincipal.getListClaim(issuer: String, name: String): List<String> = this.context .getClaims(issuer) ?.getAsList(name) ?: emptyList()
2
Kotlin
0
0
7c2e203ceee7766185495b2adae9716a8eb50b8a
2,161
tiltakspenger-meldekort-api
MIT License
testaction/src/commonMain/kotlin/com/motorro/keeplink/testaction/data/LocalDateFields.kt
motorro
536,743,338
false
{"JavaScript": 265185, "Kotlin": 115503, "TypeScript": 5925}
/* * Copyright 2022 Nikolai Kotchetkov. * 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.motorro.keeplink.testaction.data import com.motorro.keeplink.uri.data.ComponentValue import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport import kotlin.js.JsName /** * Represents local date which has 'YYYY-MM-DD` representation in components * See platform implementation for details * @param year Full year * @param month Month: 1 - 12 * @param day Day: 1 - 31 */ @JsExport @OptIn(ExperimentalJsExport::class) data class LocalDateFields( @JsName("year") val year: Int, @JsName("month") val month: Int, @JsName("day") val day: Int ): ComponentValue { companion object { /** * Date RegEx */ private val DateReEx = "^(\\d{4})-(\\d{2})-(\\d{2})$".toRegex() /** * Parses from component value * @param componentValue Component value in a form of 'YYYY-MM-DD` */ fun parse(componentValue: String): LocalDateFields { val match = DateReEx.matchEntire(componentValue) ?: throw IllegalArgumentException("Not a valid local date") return match.groupValues.run { LocalDateFields(get(1).toInt(), get(2).toInt(), get(3).toInt()) } } } /** * Returns component representation 'YYYY-MM-DD` */ override fun toComponentValue(): String = "$year-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}" }
0
JavaScript
1
17
3e2dec51989e5966eafe8d4681e68a493549e37c
1,973
KeepLink
Apache License 2.0
frontend/android-feedme-app/app/src/main/java/com/mobilesystems/feedme/data/repository/ShoppingListRepository.kt
JaninaMattes
523,417,679
false
null
package com.mobilesystems.feedme.data.repository import com.mobilesystems.feedme.domain.model.Product interface ShoppingListRepository { suspend fun loadOldShoppingListProducts(userId: Int): List<Product>? suspend fun loadCurrentShoppingListProducts(userId: Int): List<Product>? suspend fun updateCurrentShoppingList(userId: Int, currentShoppingList: List<Product>?) suspend fun removeProductFromCurrentShoppingList(userId: Int, product: Product) suspend fun addNewProductToCurrentShoppingList(userId: Int, product: Product): Product? // new created product suspend fun addProductToCurrentShoppingList(userId: Int, product: Product)//product from oldShoppinglist suspend fun updateSingleProductOnCurrentShoppingList(userId: Int, product: Product) suspend fun updateOldShoppingList(userId: Int, oldShoppingList: List<Product>?) suspend fun removeProductFromOldShoppingList(userId: Int, product: Product) suspend fun addProductToOldShoppingList(userId: Int, product: Product) // product from currentShoppinglist suspend fun updateSingleProductOnOldShoppingList(userId: Int, product: Product) //suspend fun suggestProductsForShoppingList(userId: Int): MutableLiveData<List<Product>?> //for future features }
1
Kotlin
0
2
3913a24db0ee341b30be864882c14d91cd24f535
1,266
fudge-android-springboot
MIT License
app/src/main/java/com/handstandsam/shoppingapp/features/home/HomeActivity.kt
alishaheen
341,156,020
true
{"Kotlin": 118232}
package com.handstandsam.shoppingapp.features.home import android.content.Context import android.os.Bundle import android.widget.TextView import androidx.lifecycle.lifecycleScope import com.handstandsam.shoppingapp.LoggedInActivity import com.handstandsam.shoppingapp.R import com.handstandsam.shoppingapp.compose.CategoryListView import com.handstandsam.shoppingapp.models.Category class HomeActivity : LoggedInActivity() { // Example of `get() =` private val sessionManager get() = graph.sessionGraph.sessionManager // Example of `by lazy` private val categoryRepo by lazy { graph.networkGraph.categoryRepo } private lateinit var presenter: HomePresenter private var welcomeMessageText: TextView? = null private val categoryListView get() = findViewById<CategoryListView>(R.id.compose_frame_layout) private lateinit var homeView: HomeView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar!!.title = "Categories" setContentView(R.layout.activity_home) welcomeMessageText = findViewById(R.id.welcome_message) homeView = MyHomeView() presenter = HomePresenter( view = homeView, sessionManager = sessionManager, categoryRepo = categoryRepo, scope = lifecycleScope ) } interface HomeView { val context: Context fun showCategories(categories: List<Category>) fun setWelcomeMessage(welcomeStr: String) } inner class MyHomeView : HomeView { override val context: Context get() = this@HomeActivity override fun showCategories(categories: List<Category>) { categoryListView.categories.value = categories } override fun setWelcomeMessage(welcomeStr: String) { welcomeMessageText!!.text = welcomeStr } } override fun onResume() { super.onResume() presenter.onResume(intent) } }
0
null
0
0
f700659a1a86216369c8437f1ad1bd39154b39b4
2,027
ShoppingApp
Apache License 2.0
feature_feeds/src/main/java/com/example/instagram_clone_clean_architecture/feature/feeds/presentation/decorators/FeedViewItemDecorator.kt
kyleliao321
284,104,912
false
null
package com.example.instagram_clone_clean_architecture.feature.feeds.presentation.decorators import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView class FeedViewItemDecorator( private val space: Int ) : RecyclerView.ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { outRect.bottom = space if (parent.getChildLayoutPosition(view) == 0) { outRect.top = space } } }
0
Kotlin
1
2
365a0c94b79eccaef2d54e29465d726ef0046c0b
576
instagram-clone-clean-architecture
MIT License
src/main/kotlin/com/sourcegraph/cody/internals/InternalsStatusBarWidgetFactory.kt
sourcegraph
702,947,607
false
{"Kotlin": 690009, "Java": 152855, "TypeScript": 5588, "Shell": 4631, "Nix": 1122, "JavaScript": 436, "HTML": 294}
package com.sourcegraph.cody.internals import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.StatusBar import com.intellij.openapi.wm.StatusBarWidget import com.intellij.openapi.wm.StatusBarWidgetFactory import com.sourcegraph.config.ConfigUtil class InternalsStatusBarWidgetFactory : StatusBarWidgetFactory { override fun getId(): String = ID override fun getDisplayName(): String = "⚠\uFE0F Cody Internals" override fun isAvailable(project: Project): Boolean { return ConfigUtil.isFeatureFlagEnabled("cody.feature.internals-menu") } override fun canBeEnabledOn(statusBar: StatusBar): Boolean = true override fun createWidget(project: Project): StatusBarWidget = InternalsStatusBarWidget(project) override fun disposeWidget(widget: StatusBarWidget) { Disposer.dispose(widget) } companion object { const val ID = "cody.internalsStatusBarWidget" } }
358
Kotlin
22
67
437e3e2e53ae85edb7e445b2a0d412fbb7a54db0
952
jetbrains
Apache License 2.0
pipelines/pipeline-jet-api/src/main/java/com/orbitalhq/pipelines/jet/api/transport/PipelineSpec.kt
orbitalapi
541,496,668
false
{"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337}
package com.orbitalhq.pipelines.jet.api.transport import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonPropertyOrder import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.google.common.annotations.VisibleForTesting import com.orbitalhq.models.Provided import com.orbitalhq.models.TypedInstance import com.orbitalhq.models.json.Jackson import com.orbitalhq.schemas.Schema import com.orbitalhq.schemas.Type import com.orbitalhq.utils.Ids import lang.taxi.query.TaxiQLQueryString import org.apache.commons.csv.CSVRecord import java.io.Serializable import java.time.Instant data class PipelineSpec<I : PipelineTransportSpec, O : PipelineTransportSpec>( val name: String, @JsonDeserialize(using = PipelineTransportSpecDeserializer::class) val input: I, /** * Allows defining an optional query that is used to transform the given * Input to the Output. * * The query has a given {} clause prepended, which attaches the value * of the input. * * At present, it is invalid to define a query with it's own given{} clause, though * this may change in the future. * * If defined, then the output of this query is used as the input into the Output phase, * where it can be further transformed. * * The output can optionally define the target type as "*" to inherit the output type from this * phase. */ val transformation: TaxiQLQueryString? = null, @JsonDeserialize(using = PipelineListTransportSpecDeserializer::class) val outputs: List<O>, val id: String = Ids.id("pipeline-"), val kind: PipelineKind = PipelineKind.Pipeline ) : Serializable { @get:JsonProperty(access = JsonProperty.Access.READ_ONLY) val description = "From ${input.description} to ${outputs.size} outputs" } enum class PipelineKind { /** * A Pipeline defined using a Pipeline Spec, normally * as part of a taxi project */ Pipeline, /** * A managed stream, created by a streaming query present wihtin the schema */ Stream } /** * Defines the parameters of a transport, * not the actual transport itself */ @JsonPropertyOrder("type", "direction") interface PipelineTransportSpec : Serializable { val type: PipelineTransportType val direction: PipelineDirection /** * A human, log-friendly description of this spec */ @get:JsonIgnore val description: String @get:JsonIgnore val requiredSchemaTypes: List<String> get() = emptyList() } typealias CronExpression = String interface ScheduledPipelineTransportSpec : PipelineTransportSpec { val pollSchedule: CronExpression /** * When set to true, specifically controls the next execution time when the last execution finishes. */ val preventConcurrentExecution: Boolean } /** * Defines a transport spec which accepts messages in batches. * The pipeline will wait for "windows" of the configured millis, and * then pass messages along in a group */ interface WindowingPipelineTransportSpec : PipelineTransportSpec { val windowDurationMs: Long } data class GenericPipelineTransportSpec( override val type: PipelineTransportType, override val direction: PipelineDirection, override val requiredSchemaTypes: List<String> = emptyList() ) : PipelineTransportSpec { override val description: String = "Pipeline $direction $type" } enum class PipelineDirection(val label: String) { INPUT("in"), OUTPUT("out"); companion object { fun from(label: String): PipelineDirection { return when (label) { INPUT.label -> INPUT OUTPUT.label -> OUTPUT else -> error("Unknown label: $label") } } } } typealias PipelineTransportType = String /** Optional data that a producer may include that provides consumers with additional information that is only knowable at the time the message was emitted **/ interface SourceMessageMetadata /** Indicates that the message source can be described with a simple string. Doesn't imply that the message has exactly one message (it's valid for a message source to produce multiple messages) - only that there's a simple string-able description of the source. **/ interface MessageSourceWithGroupId : SourceMessageMetadata { val groupId: String } interface MessageContentProvider { fun asString(): String fun readAsTypedInstance(inputType: Type, schema: Schema): TypedInstance val messageTimestamp: Instant val sourceMessageMetadata: SourceMessageMetadata? } data class TypedInstanceContentProvider( @VisibleForTesting val content: TypedInstance, private val mapper: ObjectMapper = Jackson.defaultObjectMapper, override val sourceMessageMetadata: SourceMessageMetadata? = null, override val messageTimestamp: Instant = Instant.now() ) : MessageContentProvider { override fun asString(): String { return mapper.writeValueAsString(content.toRawObject()) } override fun readAsTypedInstance(inputType: Type, schema: Schema): TypedInstance { return content } } data class StringContentProvider( val content: String, override val sourceMessageMetadata: SourceMessageMetadata? = null, override val messageTimestamp: Instant = Instant.now() ) : MessageContentProvider { override fun asString(): String { return content } override fun readAsTypedInstance(inputType: Type, schema: Schema): TypedInstance { return TypedInstance.from( inputType, content, schema, source = Provided ) } } data class CsvRecordContentProvider( val content: CSVRecord, val nullValues: Set<String>, override val sourceMessageMetadata: SourceMessageMetadata? = null, override val messageTimestamp: Instant = Instant.now() ) : MessageContentProvider { override fun asString(): String { return content.joinToString() } override fun readAsTypedInstance(inputType: Type, schema: Schema): TypedInstance { return TypedInstance.from( inputType, content, schema, source = Provided, nullValues = nullValues ) } }
9
TypeScript
10
292
2be59abde0bd93578f12fc1e2ecf1f458a0212ec
6,282
orbital
Apache License 2.0
src/test/kotlin/mjs/kotest/fixtures/BehaviorSpecTest.kt
mjstrasser
445,743,305
false
null
/* Copyright 2022-2023 Michael Strasser. 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 mjs.kotest.fixtures import io.kotest.core.spec.style.BehaviorSpec import mjs.kotest.SpecReport import mjs.kotest.TestReport import mjs.kotest.errorTest import mjs.kotest.failingTest import mjs.kotest.fixtures.BehaviorSpecFixture.givenName import mjs.kotest.fixtures.BehaviorSpecFixture.thenName1 import mjs.kotest.fixtures.BehaviorSpecFixture.thenName2 import mjs.kotest.fixtures.BehaviorSpecFixture.thenName3 import mjs.kotest.fixtures.BehaviorSpecFixture.whenName1 import mjs.kotest.fixtures.BehaviorSpecFixture.whenName2 import mjs.kotest.fixtures.BehaviorSpecFixture.whenName3 import mjs.kotest.passingTest import mjs.kotest.randomName class BehaviorSpecTest : BehaviorSpec({ Given(givenName) { When(whenName1) { Then(thenName1) { passingTest() } } When(whenName2) { Then(thenName2) { failingTest() } } When(whenName3) { Then(thenName3) { errorTest() } } } }) internal object BehaviorSpecFixture { val givenName = randomName() val whenName1 = randomName() val thenName1 = randomName() val whenName2 = randomName() val thenName2 = randomName() val whenName3 = randomName() val thenName3 = randomName() val behaviorExpectedReport: SpecReport = SpecReport( "mjs.kotest.fixtures.BehaviorSpecTest", reports = mutableListOf( TestReport( "Given: $givenName", reports = mutableListOf( TestReport("When: $whenName1", reports = mutableListOf(TestReport("Then: $thenName1"))), TestReport("When: $whenName2", reports = mutableListOf(TestReport("Then: $thenName2"))), ), ), ), ) }
1
Kotlin
0
2
a8aa9c5b4635be0a26a9c10780147965d5f26dc1
2,431
kotest-html-reporter
Apache License 2.0
app/src/main/java/com/github/htdangkhoa/cleanarchitecture/data/model/AuthModel.kt
DevAtNight
236,293,673
false
{"Kotlin": 47942}
package com.github.htdangkhoa.cleanarchitecture.data.model import com.chibatching.kotpref.KotprefModel object AuthModel : KotprefModel() { var accessToken: String? by nullableStringPref() var refreshToken: String? by nullableStringPref() }
0
Kotlin
7
21
d3ea16c8924e9ec6432992bb327e2cecb4107974
251
android-clean-architecture
MIT License
arrow-libs/core/arrow-core-test/src/main/kotlin/arrow/core/test/laws/MonoidalLaws.kt
clojj
343,913,289
true
{"Kotlin": 6274993, "SCSS": 78040, "JavaScript": 77812, "HTML": 21200, "Scala": 8073, "Shell": 2474, "Ruby": 83}
package arrow.core.test.laws import arrow.Kind import arrow.KindDeprecation import arrow.core.Tuple2 import arrow.core.extensions.eq import arrow.core.extensions.tuple2.eq.eq import arrow.core.test.generators.GenK import arrow.typeclasses.Eq import arrow.typeclasses.EqK import arrow.typeclasses.Monoidal import io.kotlintest.properties.Gen import io.kotlintest.properties.forAll @Deprecated(KindDeprecation) object MonoidalLaws { fun <F> laws( MDAL: Monoidal<F>, GENK: GenK<F>, EQK: EqK<F>, BIJECTION: (Kind<F, Tuple2<Tuple2<Int, Int>, Int>>) -> (Kind<F, Tuple2<Int, Tuple2<Int, Int>>>) ): List<Law> { val GEN = GENK.genK(Gen.int()) val EQ = EQK.liftEq(Tuple2.eq(Int.eq(), Int.eq())) return SemigroupalLaws.laws( MDAL, GENK, BIJECTION, EQK ) + listOf( Law("Monoidal Laws: Left identity") { MDAL.monoidalLeftIdentity(GEN, EQ) }, Law("Monoidal Laws: Right identity") { MDAL.monoidalRightIdentity(GEN, EQ) } ) } private fun <F> Monoidal<F>.monoidalLeftIdentity(G: Gen<Kind<F, Int>>, EQ: Eq<Kind<F, Tuple2<Int, Int>>>): Unit = forAll(G) { fa: Kind<F, Int> -> identity<Int>().product(fa).equalUnderTheLaw(identity(), EQ) } private fun <F> Monoidal<F>.monoidalRightIdentity(G: Gen<Kind<F, Int>>, EQ: Eq<Kind<F, Tuple2<Int, Int>>>): Unit = forAll(G) { fa: Kind<F, Int> -> fa.product(identity<Int>()).equalUnderTheLaw(identity(), EQ) } }
0
null
0
0
5eae605bbaeb2b911f69a5bccf3fa45c42578416
1,447
arrow
Apache License 2.0
emoji/src/commonTest/kotlin/com/vanniktech/emoji/TestEmoji.kt
vanniktech
53,511,222
false
null
package com.vanniktech.emoji data class TestEmoji( override val unicode: String, override val shortcodes: List<String>, override val isDuplicate: Boolean, override val variants: List<TestEmoji> = emptyList(), private var parent: TestEmoji? = null, ) : Emoji { constructor( codePoints: IntArray, shortcodes: List<String>, isDuplicate: Boolean, variants: List<TestEmoji> = emptyList(), ) : this(String(codePoints, 0, codePoints.size), shortcodes, isDuplicate, variants) override val base by lazy(LazyThreadSafetyMode.NONE) { var result = this while (result.parent != null) { result = result.parent!! } result } init { @Suppress("LeakingThis") for (variant in variants) { variant.parent = this } } }
20
null
292
1,501
2047a86272ecdaa3eaf54e83d889b5c091edaa50
778
Emoji
Apache License 2.0
uuid-serialization/src/commonMain/kotlin/pw/binom/uuid/serialization/UUIDSerializersModule.kt
caffeine-mgn
647,490,801
false
{"Kotlin": 14064}
package pw.binom.uuid.serialization import kotlinx.serialization.modules.SerializersModule import pw.binom.uuid.UUID object UUIDSerializersModule { val BINARY = SerializersModule { contextual(UUID::class, UUIDLongSerializer) } val TEXT = SerializersModule { contextual(UUID::class, UUIDStringSerializer) } }
0
Kotlin
0
0
f05f0858f7b9d641abc6bf0545d77594cc2e0fe4
343
kuuid
Apache License 2.0
app/src/main/java/com/GamesFinder_GiantBomb/exam/GameDetailActivity.kt
hugo-HDSF
638,490,229
false
null
package com.GamesFinder_GiantBomb.exam import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.ImageView import android.widget.TextView import androidx.core.text.HtmlCompat import com.bumptech.glide.Glide import com.GamesFinder_GiantBomb.exam.R import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Callback import retrofit2.Response import org.json.JSONObject import kotlin.math.log class GameDetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_game_detail) // Récupérer le jeu à partir de l'intent val game = intent.getParcelableExtra<Game>("game") // Trouver les vues et les remplir avec les données du jeu val gameImage = findViewById<ImageView>(R.id.game_image) val gameName = findViewById<TextView>(R.id.game_name) val gameReleaseDate = findViewById<TextView>(R.id.game_release_date) val gameDescription = findViewById<TextView>(R.id.game_description) val gameComments = findViewById<TextView>(R.id.game_comments) // Charger l'image avec Glide Glide.with(this) .load(game?.image?.medium_url) .into(gameImage) // Remplir les autres vues avec les données du jeu gameName.text = game?.name gameReleaseDate.text = game?.original_release_date ?: "Date de sortie inconnue" gameDescription.text = game?.description?.replace(Regex("<.*?>"), "") ?: "Description non disponible" val gameId = game?.id Log.e("GameDetailActivity", "Game ID: $gameId") if (gameId != null) { fetchGameComments(gameId) } } private fun fetchGameComments(gameId: Int) { val apiClient = ApiClient.create() val call = apiClient.getGameComments( apiKey = "90f011305c53c1ec3340214868ba42eaf9ce6fe8", format = "json", fieldList = "score,reviewer,deck,description", gameId = gameId ) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { if (response.isSuccessful) { response.body()?.let { responseBody -> val jsonString = responseBody.string() val jsonObject = JSONObject(jsonString) val results = jsonObject.getJSONArray("results") val stringBuilder = StringBuilder() for (i in 0 until results.length()) { val comment = results.getJSONObject(i) val score = comment.getDouble("score") val reviewer = comment.getString("reviewer") val deck = comment.getString("deck") val description = comment.getString("description") stringBuilder.append("Reviewer: $reviewer\n") stringBuilder.append("Score: $score\n") stringBuilder.append("Deck: $deck\n") val plainTextDescription = HtmlCompat.fromHtml(description, HtmlCompat.FROM_HTML_MODE_LEGACY).toString() stringBuilder.append("Description: $plainTextDescription\n\n") stringBuilder.append("====================================\n\n") } val gameCommentsTextView = findViewById<TextView>(R.id.game_comments) gameCommentsTextView.text = stringBuilder.toString() } } else { Log.e("GameDetailActivity", "Failed to fetch game comments: ${response.errorBody()?.string()}") } } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { Log.e("GameDetailActivity", "Failed to fetch game comments", t) } }) } }
0
Kotlin
0
1
7daf5f74cc3224047a60fc6237ff4f9d0f5df1cf
4,166
GamesFinder_android
MIT License
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/scepter/MassFortifyAugment.kt
fzzyhmstrs
461,338,617
false
null
package me.fzzyhmstrs.amethyst_imbuement.scepter import me.fzzyhmstrs.amethyst_core.modifier_util.AugmentConsumer import me.fzzyhmstrs.amethyst_core.modifier_util.AugmentEffect import me.fzzyhmstrs.amethyst_core.scepter_util.LoreTier import me.fzzyhmstrs.amethyst_core.scepter_util.SpellType import me.fzzyhmstrs.amethyst_core.scepter_util.augments.AugmentDatapoint import me.fzzyhmstrs.amethyst_core.scepter_util.augments.MiscAugment import me.fzzyhmstrs.fzzy_core.trinket_util.EffectQueue import net.minecraft.entity.Entity import net.minecraft.entity.EquipmentSlot import net.minecraft.entity.LivingEntity import net.minecraft.entity.effect.StatusEffects import net.minecraft.entity.mob.Monster import net.minecraft.entity.passive.PassiveEntity import net.minecraft.item.Items import net.minecraft.sound.SoundEvent import net.minecraft.sound.SoundEvents import net.minecraft.world.World import kotlin.math.max class MassFortifyAugment(tier: Int, maxLvl: Int, vararg slot: EquipmentSlot): MiscAugment(tier,maxLvl, *slot){ override val baseEffect: AugmentEffect get() = super.baseEffect.withDuration(700,100,0) .withAmplifier(-1,1,0) .withRange(9.0,1.0,0.0) override fun effect( world: World, user: LivingEntity, entityList: MutableList<Entity>, level: Int, effect: AugmentEffect ): Boolean { var successes = 0 if (entityList.isEmpty()){ successes++ EffectQueue.addStatusToQueue(user,StatusEffects.RESISTANCE, effect.duration(level), max(effect.amplifier((level-1)/4+3),3)) EffectQueue.addStatusToQueue(user,StatusEffects.STRENGTH, (effect.duration(level) * 1.25).toInt(), effect.amplifier((level-1)/4)) effect.accept(user, AugmentConsumer.Type.BENEFICIAL) } else { entityList.add(user) for (entity3 in entityList) { if (entity3 !is Monster && entity3 !is PassiveEntity && entity3 is LivingEntity) { successes++ EffectQueue.addStatusToQueue(entity3, StatusEffects.RESISTANCE, effect.duration(level), max(effect.amplifier((level-1)/4+2),3)) EffectQueue.addStatusToQueue(entity3, StatusEffects.STRENGTH, effect.duration(level), effect.amplifier((level-1)/4)) effect.accept(entity3,AugmentConsumer.Type.BENEFICIAL) } } } return successes > 0 } override fun augmentStat(imbueLevel: Int): AugmentDatapoint { return AugmentDatapoint(SpellType.GRACE,1200,60,16,imbueLevel,LoreTier.HIGH_TIER, Items.GOLDEN_APPLE) } override fun soundEvent(): SoundEvent { return SoundEvents.BLOCK_BEACON_ACTIVATE } }
9
Kotlin
5
3
5cfab8c66335546b660875a114df1e5f051808c2
2,757
ai
MIT License
data/src/main/java/com/itechevo/data/model/CharacterData.kt
itechevo
291,954,814
false
null
package com.itechevo.data.model data class CharacterData( val char_id: Int, val name: String, val birthday: String, val occupation: List<String>, val img: String, val status: String, val nickname: String, val appearance: List<Int>, val portrayed: String, val category: String, val better_call_saul_appearance: List<String> )
0
Kotlin
0
0
1be398f1dadbde36c1686e75592098659831a0e3
369
breaking-bad
MIT License
testing-lib/src/main/kotlin/app/cash/quiver/arb/Arbitrary.kt
cashapp
610,098,851
false
{"Kotlin": 95569, "Shell": 1366, "CSS": 209}
package app.cash.quiver.arb import app.cash.quiver.Outcome import app.cash.quiver.toOutcome import arrow.core.Ior import arrow.core.leftIor import arrow.core.rightIor import io.kotest.property.Arb import io.kotest.property.arbitrary.bind import io.kotest.property.arbitrary.choice import io.kotest.property.arbitrary.map import io.kotest.property.arrow.core.either import io.kotest.property.arrow.core.option fun <E, A> Arb.Companion.outcome(error: Arb<E>, value: Arb<A>): Arb<Outcome<E, A>> = Arb.either(error, Arb.option(value)).map { it.toOutcome() } fun <E, A> Arb.Companion.ior(error: Arb<E>, value: Arb<A>): Arb<Ior<E, A>> = Arb.choice( error.map { it.leftIor() }, value.map { it.rightIor() }, Arb.bind(error, value) { e, a -> Ior.Both(e, a) } )
7
Kotlin
6
96
337b1c78510046b8c7f5e6e1820cf8844f122d2e
773
quiver
Apache License 2.0
compiler/visualizer/testData/rawBuilder/expressions/qualifierWithTypeArguments.kt
JetBrains
3,432,266
false
null
fun test() { // class Array<T>: java/io/Serializable, Cloneable // │ Array<String>::class }
155
null
5608
45,423
2db8f31966862388df4eba2702b2f92487e1d401
98
kotlin
Apache License 2.0
wci-core/src/main/kotlin/com/luggsoft/wci/core/commands/standard/SelectNotificationsQueryCommandResult.kt
dan-lugg
724,463,915
false
{"Kotlin": 85996, "TypeScript": 64763, "Java": 6199, "JavaScript": 1433, "SCSS": 444, "HTML": 364, "Markdown": 361, "Gherkin": 344}
package com.luggsoft.wci.core.commands.standard import com.luggsoft.wci.core.commands.query.QueryCommandResult import com.luggsoft.wci.core.notifications.Notification data class SelectNotificationsQueryCommandResult( val notifications: List<Notification<*>>, ) : QueryCommandResult
1
Kotlin
0
1
76c3cd23a0cebe41a667c45e5c3952a8d3098fae
288
luggsoft-wci
MIT License
projects/core/src/main/kotlin/site/siredvin/peripheralworks/common/setup/Blocks.kt
SirEdvin
489,471,520
false
null
package site.siredvin.peripheralworks.common.setup import net.minecraft.world.item.Item import net.minecraft.world.level.block.Block import site.siredvin.peripheralium.common.blocks.GenericBlockEntityBlock import site.siredvin.peripheralium.common.items.PeripheralBlockItem import site.siredvin.peripheralium.util.BlockUtil import site.siredvin.peripheralworks.common.block.* import site.siredvin.peripheralworks.common.configuration.PeripheralWorksConfig import site.siredvin.peripheralworks.common.item.FlexibleRealityAnchorItem import site.siredvin.peripheralworks.common.item.FlexibleStatueItem import site.siredvin.peripheralworks.utils.TooltipCollection import site.siredvin.peripheralworks.xplat.PeripheralWorksPlatform object Blocks { val PERIPHERAL_CASING = PeripheralWorksPlatform.registerBlock( "peripheral_casing", { Block(BlockUtil.defaultProperties()) }, ) val UNIVERSAL_SCANNER = PeripheralWorksPlatform.registerBlock( "universal_scanner", { GenericBlockEntityBlock({ BlockEntityTypes.UNIVERSAL_SCANNER.get() }, true) }, { PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enableUniversalScanner, alwaysShow = false, TooltipCollection::isDisabled, TooltipCollection::universalScanningRadius, ) }, ) val ULTIMATE_SENSOR = PeripheralWorksPlatform.registerBlock( "ultimate_sensor", { GenericBlockEntityBlock({ BlockEntityTypes.ULTIMATE_SENSOR.get() }, true) }, { PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enableUltimateSensor, alwaysShow = true, TooltipCollection::isDisabled, ) }, ) val ITEM_PEDESTAL = PeripheralWorksPlatform.registerBlock( "item_pedestal", ::ItemPedestal, ) { PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enableItemPedestal, alwaysShow = true, TooltipCollection::isDisabled, ) } val MAP_PEDESTAL = PeripheralWorksPlatform.registerBlock( "map_pedestal", ::MapPedestal, ) { PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enableMapPedestal, alwaysShow = true, TooltipCollection::isDisabled, ) } val DISPLAY_PEDESTAL = PeripheralWorksPlatform.registerBlock( "display_pedestal", ::DisplayPedestal, ) { PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enableDisplayPedestal, alwaysShow = true, TooltipCollection::isDisabled, ) } val REMOTE_OBSERVER = PeripheralWorksPlatform.registerBlock( "remote_observer", { GenericBlockEntityBlock({ BlockEntityTypes.REMOTE_OBSERVER.get() }, true, belongToTickingEntity = true) }, { PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enableRemoteObserver, alwaysShow = false, TooltipCollection::isDisabled, TooltipCollection::remoteObserverTooptips, ) }, ) val PERIPHERAL_PROXY = PeripheralWorksPlatform.registerBlock( "peripheral_proxy", ::PeripheralProxy, ) { PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enablePeripheralProxy, alwaysShow = true, TooltipCollection::isDisabled, TooltipCollection::peripheralProxyTooptips, ) } val FLEXIBLE_REALITY_ANCHOR = PeripheralWorksPlatform.registerBlock( "flexible_reality_anchor", ::FlexibleRealityAnchor, ) { FlexibleRealityAnchorItem(it) } val REALITY_FORGER = PeripheralWorksPlatform.registerBlock( "reality_forger", { GenericBlockEntityBlock({ BlockEntityTypes.REALITY_FORGER.get() }, isRotatable = true, belongToTickingEntity = false) }, ) { PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enableRealityForger, alwaysShow = true, TooltipCollection::isDisabled, TooltipCollection::realityForgerTooptips, ) } val RECIPE_REGISTRY = PeripheralWorksPlatform.registerBlock( "recipe_registry", { GenericBlockEntityBlock({ BlockEntityTypes.RECIPE_REGISTRY.get() }, isRotatable = true, belongToTickingEntity = false) }, ) { PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enableRecipeRegistry, alwaysShow = true, TooltipCollection::isDisabled, ) } val INFORMATIVE_REGISTRY = PeripheralWorksPlatform.registerBlock( "informative_registry", { GenericBlockEntityBlock({ BlockEntityTypes.INFORMATIVE_REGISTRY.get() }, isRotatable = true, belongToTickingEntity = false) }, ) { PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enableInformativeRegistry, alwaysShow = true, TooltipCollection::isDisabled, ) } val FLEXIBLE_STATUE = PeripheralWorksPlatform.registerBlock( "flexible_statue", ::FlexibleStatue, ) { FlexibleStatueItem(it) } val STATUE_WORKBENCH = PeripheralWorksPlatform.registerBlock( "statue_workbench", { StatueWorkbench() }, ) { // TODO: adapt PeripheralBlockItem( it, Item.Properties(), PeripheralWorksConfig::enableRealityForger, alwaysShow = true, TooltipCollection::isDisabled, ) } fun doSomething() {} }
3
Kotlin
2
6
4261ad04499375f16704c8df3f3faeb0e314ac54
6,054
UnlimitedPeripheralWorks
MIT License
app/src/main/java/com/example/amchojagdalpur/ui/HomeScreen.kt
Indresh10
655,254,428
false
null
package com.example.amchojagdalpur.ui import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.TravelExplore import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.amchojagdalpur.R import com.example.amchojagdalpur.model.CatRepo import com.example.amchojagdalpur.model.Category import com.example.amchojagdalpur.ui.theme.AmchoJagdalpurTheme @Composable fun HomeScreen( gridSize: Int, onClick: (Category) -> Unit, modifier: Modifier = Modifier ) { Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) { Image( painter = painterResource(id = R.drawable.app_logo), contentDescription = "logo", modifier = Modifier.size(128.dp) ) Text( text = stringResource(id = R.string.welcome_message), style = MaterialTheme.typography.displayLarge, textAlign = TextAlign.Center ) CategoryCardList( gridSize = gridSize, categoryList = CatRepo.categories, onClick = onClick, modifier = Modifier .padding(16.dp) .fillMaxHeight() ) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun CategoryCardList( gridSize: Int, categoryList: List<Category>, onClick: (Category) -> Unit, modifier: Modifier = Modifier ) { LazyVerticalGrid( columns = GridCells.Fixed(gridSize), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), modifier = modifier ) { items(categoryList) { CategoryCard( category = it, onClick = { onClick(it) }, modifier = Modifier.wrapContentWidth(Alignment.CenterHorizontally) ) } } } @ExperimentalMaterial3Api @Composable fun CategoryCard( category: Category, onClick: () -> Unit, modifier: Modifier = Modifier ) { Card(elevation = CardDefaults.cardElevation(4.dp), onClick = onClick, modifier = modifier) { Column( horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(id = category.image), contentDescription = stringResource( id = category.name ), modifier = Modifier.fillMaxWidth().height(128.dp), contentScale = ContentScale.Crop ) Text( text = stringResource(id = category.name), modifier = Modifier.padding(8.dp), style = MaterialTheme.typography.titleMedium ) CategoryCount(count = category.count, modifier = Modifier.padding(4.dp)) } } } @Composable fun CategoryCount(count: Int, modifier: Modifier = Modifier) { Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) { Icon( imageVector = Icons.Rounded.TravelExplore, contentDescription = stringResource(id = R.string.explore) ) Text( text = stringResource(id = R.string.places, count), modifier = Modifier.padding(horizontal = 4.dp), style = MaterialTheme.typography.labelMedium ) } } @Preview(showBackground = true) @Composable fun HomeScreenPreview() { AmchoJagdalpurTheme { HomeScreen(2, {}) } }
0
Kotlin
0
0
b8ef179afcee919a15016b93fa6cecd19c0d4ec4
4,777
AmchoJagdalpur
MIT License
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceGuardClauseWithFunctionCall/require/hasElse3.kt
ingokegel
72,937,917
false
null
// WITH_STDLIB fun test(flag: Boolean, i: Int) { <caret>if (!flag) { throw IllegalArgumentException() } else if (i == 0) { println(0) } else { println(1) println(2) } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
216
intellij-community
Apache License 2.0
app/src/main/java/com/example/employeemanagement/UI/ManageEmployees.kt
MateuszChylinski
620,533,647
false
null
package com.example.employeemanagement.UI import android.annotation.SuppressLint import android.content.ContentValues.TAG import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.employeemanagement.Adapter.EmployeeAdapter import com.example.employeemanagement.Database.DatabaseState import com.example.employeemanagement.Model.EmployeeModel import com.example.employeemanagement.ViewModel.EmployeeViewModel import com.example.employeemanagement.databinding.FragmentManageEmployeesBinding import kotlinx.coroutines.launch import javax.inject.Inject class ManageEmployees : Fragment() { private var _binding: FragmentManageEmployeesBinding? = null private val mBinding get() = _binding!! private val mViewModel: EmployeeViewModel by activityViewModels() @Inject lateinit var mAdapter: EmployeeAdapter private var employeeData: MutableList<EmployeeModel> = mutableListOf() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentManageEmployeesBinding.inflate(inflater, container, false) val view = mBinding.root mBinding.manageRv.layoutManager = LinearLayoutManager(this.requireContext()) mAdapter = EmployeeAdapter { employeeModel -> mViewModel.employeeIdFlow.value = employeeModel.id findNavController().navigate(ManageEmployeesDirections.goToUpdateEmployee()) } viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.CREATED) { mViewModel.allEmployees.collect { employee -> when (employee) { is DatabaseState.Success -> { employeeData.clear() employee.data?.forEach { employeeData.add(it) } mAdapter.employees = employeeData mBinding.manageRv.adapter = mAdapter mAdapter.notifyDataSetChanged() } is DatabaseState.Error -> { Log.i( TAG, "onCreateView: Error occurred in ManageEmployees fragment while trying to retrieve data from the ViewModel" ) } } } } } ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT){ override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val id: Int = mAdapter.employees[viewHolder.absoluteAdapterPosition].id mViewModel.deleteEmployee(id) mAdapter.notifyDataSetChanged() } }).attachToRecyclerView(mBinding.manageRv) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mBinding.manageAddEmployee.setOnClickListener { findNavController().navigate(ManageEmployeesDirections.goToAddEmployee()) } mBinding.manageDeleteAll.setOnClickListener { mViewModel.deleteAllEmployees() } } }
0
Kotlin
0
0
fb2275ce10deaef32be4d12ec919f2bf9facc267
4,120
EmployeeManagement
Apache License 2.0
sample/src/main/java/com/arc/fast/view/sample/MainActivity.kt
Arcns
594,679,017
false
null
package com.arc.fast.view.sample import android.os.Bundle import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import com.arc.fast.flowlayout.sample.R import com.arc.fast.flowlayout.sample.databinding.ActivityMainBinding import com.arc.fast.flowlayout.sample.databinding.LayoutTagBinding import com.arc.fast.view.FastFlowAdapter import com.arc.fast.view.sample.extension.applyFullScreen import com.arc.fast.view.sample.extension.setLightSystemBar class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) applyFullScreen() setLightSystemBar(true) binding = DataBindingUtil.setContentView(this, R.layout.activity_main) val data = arrayListOf<String>() for (i in 0..30) { data.add("标签 $i") } binding.flow1.adapter = FastFlowAdapter( layoutRes = R.layout.layout_tag, data = data, convert = { layout, item, position -> val tvTag = layout.findViewById<TextView>(R.id.tv_tag) tvTag.text = item }, onItemClick = { layout, item, position -> Toast.makeText(this@MainActivity, item, Toast.LENGTH_SHORT).show() } ) binding.flow2.adapter = FastFlowAdapter( data = data, onCreateItem = { layoutInflater, parent, item, position -> return@FastFlowAdapter LayoutTagBinding.inflate(layoutInflater, null, false).apply { tvTag.text = item }.root }, onItemClick = { layout, item, position -> Toast.makeText(this@MainActivity, item, Toast.LENGTH_SHORT).show() }, onCreateExpand = { layoutInflater, parent -> return@FastFlowAdapter LayoutTagBinding.inflate(layoutInflater, null, false).apply { tvTag.setBackgroundColor(resources.getColor(android.R.color.holo_blue_light)) tvTag.text = "展开" }.root }, onExpand = { expand, isExpand -> (expand as? TextView)?.text = if (isExpand) "收缩" else "展开" false } ) } }
0
Kotlin
0
2
f73742a26e9006372466ec0b91ae867b34638296
2,413
fast-flow-layout
Mulan Permissive Software License, Version 2
simulator/src/main/kotlin/io/plasmasimulator/plasma/verticles/PlasmaParticipant.kt
georgiayloff
156,192,928
false
null
package io.plasmasimulator.plasma.verticles import io.plasmasimulator.plasma.models.* import io.plasmasimulator.plasma.services.MainChainConnector import io.plasmasimulator.utils.HashUtils import io.vertx.core.Future import io.vertx.core.json.Json import io.vertx.core.json.JsonObject import org.slf4j.LoggerFactory import io.plasmasimulator.conf.Address open class PlasmaParticipant: MainChainConnector() { var chain: PlasmaChain = PlasmaChain(chainAddress = "", plasmaBlockInterval = 10) var plasmaPool: UTXOPool = UTXOPool() val rootChainService = this val address: String = PlasmaParticipant.addressNum++.toString()//UUID.randomUUID().toString() var balance: Int = 0 var myUTXOs = mutableListOf<UTXO>() var spentUTXOs = mutableListOf<UTXO>() var pendingUTXOs = myUTXOs.toMutableList() private companion object { private val LOG = LoggerFactory.getLogger(PlasmaParticipant::class.java) private var addressNum = 0 } override fun start(startFuture: Future<Void>?) { super.start(startFuture) // deploying rootChainVerticle LOG.info("Initialize PlasmaVerticle $address") val chainAddress: String = config().getString("chainAddress") val plasmaBlockInterval = config().getInteger("plasmaBlockInterval") chain = PlasmaChain(chainAddress = chainAddress, plasmaBlockInterval = plasmaBlockInterval) if(config().containsKey("parentPlasmaAddress")) { chain.parentChainAddress = config().getString("parentPlasmaAddress") } if(chain.parentChainAddress != null) { // I have a parent plasma chain, so I am expecting to see some blocks vertx.eventBus().consumer<Any>(chain.chainAddress) { msg -> val parentBlock: PlasmaBlock = Json.decodeValue(msg.body().toString(), PlasmaBlock::class.java) chain.addParentBlock(parentBlock) if(this is Operator) { vertx.eventBus().send(Address.PARENT_BLOCK_RECEIVED.name, JsonObject().put("chainAddress", chainAddress)) } } } } fun removeUTXOsForBlock(block: PlasmaBlock) { for(tx in block.transactions) { for(input in tx.inputs) { val utxoToRemove = UTXO(input.blockNum, input.txIndex, input.outputIndex) if(myUTXOs.contains(utxoToRemove)) { myUTXOs.remove(utxoToRemove) } plasmaPool.removeUTXO(utxoToRemove) } } } fun createUTXOsForBlock(block: PlasmaBlock) { for((txIndex, tx) in block.transactions.withIndex()) { for((outputIndex, output) in tx.outputs.withIndex()) { val newUTXO = UTXO(block.number, txIndex, outputIndex) if(address == output.address && !myUTXOs.contains(newUTXO)){ myUTXOs.add(newUTXO) } plasmaPool.addUTXO(newUTXO, output) } } } override fun stop(stopFuture: Future<Void>?) { super.stop(stopFuture) } }
0
Kotlin
1
0
76505a93d606794af418deb77b7a92122e9f9f94
2,867
plasmasimulator
MIT License
Rich Editor Lib/src/main/java/com/easyapps/richeditorlib/styles/StyleFontSize.kt
easy-apps-2018
334,709,458
false
null
package com.easyapps.richeditorlib.styles import android.text.Editable import com.easyapps.richeditorlib.abstracts.DynamicStyle import com.easyapps.richeditorlib.interfaces.FontSizeListener import com.easyapps.richeditorlib.spans.SpanFontSize import com.easyapps.richeditorlib.widgets.RichEditText import com.easyapps.richeditorlib.windows.SizeSlider import com.google.android.material.button.MaterialButton class StyleFontSize(private val item: MaterialButton, private val editText: RichEditText) : DynamicStyle<SpanFontSize>(), FontSizeListener { private var size = 18 private var sizeSlider: SizeSlider? = null init { editText.fontSizeListener = this item.setOnClickListener { sizeSlider = SizeSlider(item, this, size.toFloat()) } } override fun changeSpanInsideStyle(editable: Editable, start: Int, end: Int, e: SpanFontSize) { super.changeSpanInsideStyle(editable, start, end, e) if (e.size != size) applyNewStyle(editable, start, end, size) } override fun newSpan(style: Int): SpanFontSize = SpanFontSize(style) override fun newSpan(): SpanFontSize = SpanFontSize(size) override fun styleChangedHook(style: Int) { size = style } override fun getStyleButton(): MaterialButton = item override fun setChecked(isChecked: Boolean) { } override fun getIsChecked(): Boolean = true override fun onFontSizeChanged(size: Float, from: String?) { this.size = size.toInt() if (from == null) { item.isChecked = false editText.requestFocus() sizeSlider?.dismiss() } val start = editText.selectionStart val end = editText.selectionEnd if (end > start) applyNewStyle(editText.editableText, start, end, this.size) } }
1
null
3
9
7f1c189dda1154f83364daa84acece73f6cd412f
1,847
Rich-Editor-Lib
Apache License 2.0
src/main/kotlin/clz/attributes/CodeAttribute.kt
changchengfeng
686,996,848
false
{"Kotlin": 133094}
package clz.attributes import clz.* import clz.constantpool.CpInfo import clz.methods.Opcodes import clz.methods.OpcodesBodyType import okio.ByteString.Companion.toByteString import okio.BufferedSource import java.lang.StringBuilder class CodeAttribute(val max_stack: u2, val max_locals: u2,constant_pools: Array<CpInfo?>) : AttributeInfo(AttributeType.Code,constant_pools) { lateinit var codes: u1Array lateinit var exceptionTables: Array<ExceptionTable?> lateinit var attributes: Array<AttributeInfo?> class ExceptionTable(val start_pc: u2, val end_pc: u2, val handler_pc: u2, val catch_type: u2) { override fun toString(): String { return "ExceptionTable(start_pc=$start_pc, end_pc=$end_pc, handler_pc=$handler_pc, catch_type=$catch_type)" } } companion object : ReadAttributeAdapter { override fun read(source: BufferedSource,constant_pools: Array<CpInfo?>): AttributeInfo { val max_stack = source.readShort() val max_locals = source.readShort() val codeAttribute = CodeAttribute(max_stack, max_locals,constant_pools) val code_length = source.readInt() codeAttribute.codes = u1Array(code_length) for (it in 0 until code_length) { codeAttribute.codes[it] = source.readByte() } val exception_table_length = source.readShort() codeAttribute.exceptionTables = arrayOfNulls(exception_table_length.toInt()) for (it in 0 until exception_table_length) { val start_pc = source.readShort() val end_pc = source.readShort() val handler_pc = source.readShort() val catch_type = source.readShort() codeAttribute.exceptionTables[it] = ExceptionTable( start_pc, end_pc, handler_pc, catch_type ) } val attributesCount = source.readShort() codeAttribute.attributes = readAttributeInfo( attributesCount, constant_pools, source ) return codeAttribute } } override fun toString(): String { return """ CodeAttribute{ max_stack = $max_stack max_locals = $max_locals codes = ${"\n"}${codesToStr()} exceptionTables =${"\n"}${arrayToStr(exceptionTables, "exceptionTables")} attributes = ${"\n"}${arrayToStr(attributes, "attributes")} } """ } fun codesToStr(): String { val stringBuffer = StringBuilder() var it = 0 var current = 0 while (it < codes.size) { current = it stringBuffer.append(" code[${it}] = ${codes[it].toUByte()} ") val Opcode = Opcodes.valueOf(codes[it].toUByte()) stringBuffer.append(Opcode) it++ if (Opcode.type.size > 0) { for (index in 0 until Opcode.type.size) { when (Opcode.type[index]) { Opcodes.Type.VALUE_1 -> { if (Opcode == Opcodes.newarray) { stringBuffer.append(" args[#$index] = ${OpcodesBodyType.valueOf(codes[it].toUByte())}") } else { stringBuffer.append(" args[#$index] = ${codes[it]}") } it++ } Opcodes.Type.VALUE_2 -> { val toInt = byteArrayOf(codes[it], codes[it + 1]).toByteString().toInt() stringBuffer.append(" args[#$index] = ${toInt}") it += 2 } Opcodes.Type.VALUE_4 -> { val toInt = byteArrayOf(codes[it], codes[it + 1], codes[it + 2], codes[it + 3]).toByteString() .toInt() stringBuffer.append(" args[#$index] = ${toInt}") it += 4 } Opcodes.Type.CONSTANT_POOLS_1 -> { stringBuffer.append(" args[#$index] = ${constant_pools[codes[it].toInt()]}") it++ } Opcodes.Type.CONSTANT_POOLS_2 -> { val toInt = byteArrayOf(codes[it], codes[it + 1]).toByteString().toInt() stringBuffer.append(" args[#$index] = ${constant_pools[toInt]}") it += 2 } Opcodes.Type.TABLES_WITCH -> { val pad = (it % 4).let { if (it == 0) 0 else 4 - it } it += pad val offset_default = codes.readInt(it) // offset_default 是当前指令的偏移量 it += 4 val lowValue = codes.readInt(it) it += 4 val highValue = codes.readInt(it) it += 4 stringBuffer.append(" pad $pad offset_default $offset_default lowValue $lowValue highValue $highValue \n\n") for (vi in lowValue..highValue) { val offfsets = codes.readInt(it) stringBuffer.append(" jump[$vi] = offfsets ${offfsets} jumpto = ${current + offfsets} \n") it += 4 } } Opcodes.Type.LOOKUP_SWITCH -> { val pad = (it % 4).let { if (it == 0) 0 else 4 - it } it += pad val offset_default = codes.readInt(it) // offset_default 是当前指令的偏移量 it += 4 val npairs = codes.readInt(it) it += 4 stringBuffer.append(" pad $pad offset_default $offset_default npairs $npairs \n\n") for (vi in 0 until npairs) { stringBuffer.append(" jump[$vi] = val ${codes.readInt(it)}") it += 4 val offfsets = codes.readInt(it) stringBuffer.append(" offsets ${offfsets} jumpto = ${current + offfsets} \n") it += 4 } } Opcodes.Type.WIDE -> { val toUByte = codes[it].toUByte() if (toUByte == Opcodes.iinc.value) { stringBuffer.append( " args[#$index] = ${Opcodes.iinc} : index = ${ byteArrayOf( codes[it + 1], codes[it + 2] ).toByteString().toInt() } const = ${byteArrayOf(codes[it + 3], codes[it + 4]).toByteString().toInt()}" ) it += 5 } else { stringBuffer.append( " args[#$index] = ${Opcodes.valueOf(toUByte)} : index = ${ byteArrayOf( codes[it + 1], codes[it + 2] ).toByteString().toInt() }}" ) it += 3 } } } } } stringBuffer.append("\n") } return stringBuffer.toString() } }
0
Kotlin
0
0
3d0dae56f8ce2c10428ad25e4f685052f33d3d68
8,295
ClassParser
Apache License 2.0
src/main/kotlin/no/nav/klage/oppgave/domain/klage/Klagebehandling.kt
navikt
297,650,936
false
null
package no.nav.klage.oppgave.domain.klage import no.nav.klage.kodeverk.* import no.nav.klage.kodeverk.hjemmel.Hjemmel import no.nav.klage.kodeverk.hjemmel.HjemmelConverter import no.nav.klage.oppgave.domain.klage.Klagebehandling.Status.* import org.hibernate.annotations.BatchSize import org.hibernate.annotations.Fetch import org.hibernate.annotations.FetchMode import java.time.LocalDate import java.time.LocalDateTime import java.util.* import javax.persistence.* const val KLAGEENHET_PREFIX = "42" @Entity @Table(name = "klagebehandling", schema = "klage") class Klagebehandling( @Id val id: UUID = UUID.randomUUID(), @Embedded var klager: Klager, @Embedded var sakenGjelder: SakenGjelder, @Column(name = "ytelse_id") @Convert(converter = YtelseConverter::class) val ytelse: Ytelse, @Column(name = "type_id") @Convert(converter = TypeConverter::class) var type: Type, @Column(name = "kilde_referanse") val kildeReferanse: String, @Column(name = "dvh_referanse") val dvhReferanse: String? = null, @Column(name = "sak_fagsystem") @Convert(converter = FagsystemConverter::class) val sakFagsystem: Fagsystem? = null, @Column(name = "sak_fagsak_id") val sakFagsakId: String? = null, //Umulig å vite innsendt-dato. @Column(name = "dato_innsendt") val innsendt: LocalDate? = null, //Brukes ikke i anke @Column(name = "dato_mottatt_foersteinstans") val mottattFoersteinstans: LocalDate, //Mulig at identen ikke brukes. Sjekk om dette kan droppes. @Column(name = "avsender_saksbehandlerident_foersteinstans") val avsenderSaksbehandleridentFoersteinstans: String? = null, //Vises i GUI. @Column(name = "avsender_enhet_foersteinstans") val avsenderEnhetFoersteinstans: String, //Settes automatisk i klage, må kunne justeres i anke. Bør også representeres i delbehandling. Må gjøres entydig i anke, hører antageligvis ikke hjemme i felles klasse. @Column(name = "dato_mottatt_klageinstans") val mottattKlageinstans: LocalDateTime, //Teknisk avsluttet, når alle prosesser er gjennomførte. Bør muligens heller utledes av status på delbehandlinger. @Column(name = "dato_behandling_avsluttet") var avsluttet: LocalDateTime? = null, //Bør være i delbehandling @Column(name = "dato_behandling_avsluttet_av_saksbehandler") var avsluttetAvSaksbehandler: LocalDateTime? = null, //TODO: Trenger denne være nullable? Den blir da alltid satt i createKlagebehandlingFromMottak? //Litt usikkert om dette hører mest hjemme her eller på delbehandling. @Column(name = "frist") var frist: LocalDate? = null, //Hører hjemme på delbehandling @Embedded @AttributeOverrides( value = [ AttributeOverride(name = "saksbehandlerident", column = Column(name = "medunderskriverident")), AttributeOverride(name = "tidspunkt", column = Column(name = "dato_sendt_medunderskriver")) ] ) var medunderskriver: MedunderskriverTildeling? = null, //Hører hjemme på delbehandling @Column(name = "medunderskriverflyt_id") @Convert(converter = MedunderskriverflytConverter::class) var medunderskriverFlyt: MedunderskriverFlyt = MedunderskriverFlyt.IKKE_SENDT, //Hører hjemme på delbehandling, men her er det mer usikkerhet enn for medunderskriver. Litt om pragmatikken, bør se hva som er enklest å få til. @Embedded @AttributeOverrides( value = [ AttributeOverride(name = "saksbehandlerident", column = Column(name = "tildelt_saksbehandlerident")), AttributeOverride(name = "enhet", column = Column(name = "tildelt_enhet")), AttributeOverride(name = "tidspunkt", column = Column(name = "dato_behandling_tildelt")) ] ) var tildeling: Tildeling? = null, //Hører hjemme på delbehandling, men her er det mer usikkerhet enn for medunderskriver @OneToMany(cascade = [CascadeType.ALL], orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "klagebehandling_id", referencedColumnName = "id", nullable = false) @Fetch(FetchMode.SELECT) @BatchSize(size = 100) val tildelingHistorikk: MutableSet<TildelingHistorikk> = mutableSetOf(), //Hører hjemme på delbehandling @OneToMany(cascade = [CascadeType.ALL], orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "klagebehandling_id", referencedColumnName = "id", nullable = false) @Fetch(FetchMode.SELECT) @BatchSize(size = 100) val medunderskriverHistorikk: MutableSet<MedunderskriverHistorikk> = mutableSetOf(), //Hovedbehandling @Column(name = "mottak_id") val mottakId: UUID, //Skal være en kvalitetsvurdering per hovedbehandling, derfor er dette riktig sted. @Column(name = "kaka_kvalitetsvurdering_id", nullable = true) var kakaKvalitetsvurderingId: UUID? = null, //Dette er søkehjemler, input fra førsteinstans. For anker bør vel dette være samme detaljnivået som i registreringshjemler? Blir det da ulike typer for klage og anke? Må ta diskusjonen videre. @ElementCollection(targetClass = Hjemmel::class, fetch = FetchType.EAGER) @CollectionTable( name = "klagebehandling_hjemmel", schema = "klage", joinColumns = [JoinColumn(name = "klagebehandling_id", referencedColumnName = "id", nullable = false)] ) @Convert(converter = HjemmelConverter::class) @Column(name = "id") val hjemler: MutableSet<Hjemmel> = mutableSetOf(), //Her går vi mot en løsning der en behandling har flere delbehandlinger, som nok er bedre begrep enn vedtak. //Trenger en markering av hvilken delbehandling som er den gjeldende. @OneToOne(cascade = [CascadeType.ALL], orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "vedtak_id", referencedColumnName = "id") val vedtak: Vedtak, //Liste med dokumenter fra Joark. De dokumentene saksbehandler krysser av for havner her. Bør være i delbehandling. Kopierer fra forrige når ny delbehandling opprettes. @OneToMany(cascade = [CascadeType.ALL], orphanRemoval = true, fetch = FetchType.EAGER) @JoinColumn(name = "klagebehandling_id", referencedColumnName = "id", nullable = false) @Fetch(FetchMode.SELECT) @BatchSize(size = 100) val saksdokumenter: MutableSet<Saksdokument> = mutableSetOf(), @Column(name = "created") val created: LocalDateTime = LocalDateTime.now(), @Column(name = "modified") var modified: LocalDateTime = LocalDateTime.now(), //Kommer fra innsending @Column(name = "kildesystem") @Convert(converter = FagsystemConverter::class) val kildesystem: Fagsystem, //Kommer fra innsending @Column(name = "kommentar_fra_foersteinstans") val kommentarFraFoersteinstans: String? = null ) { override fun toString(): String { return "Behandling(id=$id, " + "modified=$modified, " + "created=$created)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Klagebehandling if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } /** * Brukes til ES og statistikk per nå */ fun getStatus(): Status { return when { avsluttet != null -> FULLFOERT avsluttetAvSaksbehandler != null -> AVSLUTTET_AV_SAKSBEHANDLER medunderskriverFlyt == MedunderskriverFlyt.OVERSENDT_TIL_MEDUNDERSKRIVER -> SENDT_TIL_MEDUNDERSKRIVER medunderskriverFlyt == MedunderskriverFlyt.RETURNERT_TIL_SAKSBEHANDLER -> RETURNERT_TIL_SAKSBEHANDLER medunderskriver?.saksbehandlerident != null -> MEDUNDERSKRIVER_VALGT tildeling?.saksbehandlerident != null -> TILDELT tildeling?.saksbehandlerident == null -> IKKE_TILDELT else -> UKJENT } } enum class Status { IKKE_TILDELT, TILDELT, MEDUNDERSKRIVER_VALGT, SENDT_TIL_MEDUNDERSKRIVER, RETURNERT_TIL_SAKSBEHANDLER, AVSLUTTET_AV_SAKSBEHANDLER, FULLFOERT, UKJENT } }
2
Kotlin
1
1
7255f8d9a5b0c23e4a22b5bd736d3b656790dfb7
8,181
kabal-api
MIT License
compiler/testData/diagnostics/tests/scopes/visibility3.kt
kenny9221
43,412,013
true
{"Java": 15618171, "Kotlin": 10536867, "JavaScript": 176060, "Protocol Buffer": 41362, "HTML": 25327, "Lex": 17278, "ANTLR": 9689, "CSS": 9358, "Groovy": 5199, "Shell": 4638, "Batchfile": 3703, "IDL": 3251}
// !DIAGNOSTICS: -UNUSED_VARIABLE //FILE:file1.kt package a private open class A { fun bar() {} } private var x: Int = 10 private fun foo() {} private fun bar() { val y = x x = 20 } fun makeA() = A() private object PO {} //FILE:file2.kt package a fun test() { val y = makeA() y.<!ACCESS_TO_PRIVATE_TOP_LEVEL_FROM_ANOTHER_FILE!>bar<!>() <!ACCESS_TO_PRIVATE_TOP_LEVEL_FROM_ANOTHER_FILE!>foo<!>() val u : <!ACCESS_TO_PRIVATE_TOP_LEVEL_FROM_ANOTHER_FILE!>A<!> = <!ACCESS_TO_PRIVATE_TOP_LEVEL_FROM_ANOTHER_FILE!>A<!>() val z = <!ACCESS_TO_PRIVATE_TOP_LEVEL_FROM_ANOTHER_FILE!>x<!> <!ACCESS_TO_PRIVATE_TOP_LEVEL_FROM_ANOTHER_FILE!>x<!> = 30 val po = <!ACCESS_TO_PRIVATE_TOP_LEVEL_FROM_ANOTHER_FILE!>PO<!> } class B : <!ACCESS_TO_PRIVATE_TOP_LEVEL_FROM_ANOTHER_FILE, ACCESS_TO_PRIVATE_TOP_LEVEL_FROM_ANOTHER_FILE!>A<!>() {} class Q { class W { fun foo() { val y = makeA() //assure that 'makeA' is visible } } }
0
Java
0
0
a55f9feacbf3e85ea064cc2aee6ecfd5e699918d
993
kotlin
Apache License 2.0
app/src/main/java/bruhcollective/itaysonlab/cobalt/ui/components/CobaltNavigationBar.kt
iTaysonLab
529,265,880
false
{"Kotlin": 451014}
package bruhcollective.itaysonlab.cobalt.ui.components
1
Kotlin
5
97
78a9d963893e0b675cb0e3b1a2b6b936c0be3d19
56
jetisteam
Apache License 2.0
data/src/main/kotlin/team/duckie/app/android/data/ranking/model/RankingOrderType.kt
duckie-team
503,869,663
false
{"Kotlin": 1819917}
/* * Designed and developed by Duckie Team, 2022 * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE */ package team.duckie.app.android.data.ranking.model enum class RankingOrderType(val text: String) { AnswerRate("answer_rate"), SolvedCount("solve_count"), ; }
32
Kotlin
1
8
5dbd5b7a42c621931d05a96e66431f67a3a50762
351
duckie-android
MIT License
compiler/tests-spec/testData/diagnostics/notLinked/contracts/declarations/contractBuilder/common/neg/7.fir.kt
JetBrains
3,432,266
false
null
// !DIAGNOSTICS: -UNUSED_VARIABLE -UNUSED_PARAMETER -UNREACHABLE_CODE -UNUSED_EXPRESSION // !OPT_IN: kotlin.contracts.ExperimentalContracts import kotlin.contracts.* // TESTCASE NUMBER: 1 fun <T> T?.case_1() { fun <K> K?.case_1_1(): Boolean { <!CONTRACT_NOT_ALLOWED!>contract<!> { <!ERROR_IN_CONTRACT_DESCRIPTION!>returns(true) implies (this@case_1 != null)<!> } return this@case_1 != null } }
154
Kotlin
5563
44,965
e6633d3d9214402fcf3585ae8c24213a4761cc8b
420
kotlin
Apache License 2.0
app/src/main/java/com/example/neocafe/model/UserProfile.kt
rybakova-auca-2021
726,707,145
false
{"Kotlin": 267266}
package com.example.neocafe.model data class UserProfile( val first_name: String, val birth_date: String, val email: String, val phone: String ) data class UserProfileUpdate( val birth_date: String, val email: String, val first_name: String, val phone: String ) data class Bonus( val user: Int, val amount: String, val qr_code: String )
0
Kotlin
0
0
ca4221ce008ed1ce521e7dae6d51cdf4880d1be3
384
NeoCafe_Neobook
MIT License
prova01/Ex04_Baralho.kt
InvicTheBrazilian
765,941,849
false
{"Kotlin": 16320}
//Crie uma classe Carta que represente uma carta de baralho com atributos como naipe e valor. //Crie uma classe Baralhoque represente um baralho de cartas completo. //Implemente métodos para embaralhar o baralho, distribuir cartas. //Entregue 5 cartas para um Jogador que vai verificar se as cartas possuem combinações vencedoras, //como: //Par: Duas cartas com mesmo valor //Exemplo: A♠️ + A♥️ //Trinca: Três cartas com mesmo valor //Exemplo: A♠️ + A♥️ + A♦️ //Full House: Três cartas com mesmo valor mais outras duas com mesmo valor //Exemplo: A♠️ + A♥️ + A♦️+ 5♣️ + 5♥️ //Flush: Todas cartas com mesmo naipe //Exemplo: A♦️+ 3♦️+ 6♦️ + Q♦️ + 10♦️ //Equipe: <NAME> // Classe baralho class Baralho { private val cartas = mutableListOf<Carta> // Array de valores das cartas private val valores = listOf("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K") // Inicializando o baralho com as cartas init Baralho { for (naipe in Naipe.values()) { for (valor in valores) { cartas.add(Carta(valor, naipe)) } } } // Embaralhar o baralho fun embaralhar() { cartas.shuffle() } // Distribuir cartas para o jogador fun distribuirCartas(): List<Card> { return cartas.subList(0, 5).also { cartas.removeAll(it) } } } // Função par fun temPar(cartas: List<Card>): Boolean { val valores = cartas.map { it.valor } return valores.size != valores.toSet().size } // Função trinca fun temTrinca(cartas: List<Card>): Boolean { val agrupadoPorValor = cartas.groupBy { it.valor } return agrupadoPorValor.any { it.value.size == 3 } } // Função full house fun temFullHouse(cartas: List<Card>): Boolean { val agrupadoPorValor = cartas.groupBy { it.valor } return agrupadoPorValor.any { it.value.size == 3 } && agrupadoPorValor.any { it.value.size == 2 } } // Função flush fun temFlush(cartas: List<Card>): Boolean { val naipe = cartas.first().naipe return cartas.all { it.naipe == naipe } }
0
Kotlin
0
1
a3e1784ac67c63f3a6771af7b79bbc8276e39ae8
1,988
progamacao-mobile
MIT License
src/main/kotlin/br/com/schumaker/webflux/WebfluxApplication.kt
HudsonSchumaker
409,304,528
false
null
package br.com.schumaker.webflux import br.com.schumaker.webflux.model.ToDo import br.com.schumaker.webflux.model.TodoRepository import org.springframework.boot.CommandLineRunner import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.context.annotation.Bean /** * * @author hudson.schumaker */ @SpringBootApplication class WebfluxApplication { @Bean fun run(repository: TodoRepository) = CommandLineRunner { repository.save( ToDo("Create an app") ).subscribe() repository.save( ToDo("Test an app") ).subscribe() } } fun main(args: Array<String>) { runApplication<WebfluxApplication>(*args) }
0
Kotlin
0
0
d7b556dfc6679483ab03183dcebb54c618668b1d
705
SpringBoot-WebFlux
MIT License
z2-material/src/jsMain/kotlin/hu/simplexion/z2/browser/util/label.kt
spxbhuhb
661,566,882
false
null
package hu.simplexion.z2.browser.util import hu.simplexion.z2.commons.i18n.BasicLocalizedText import hu.simplexion.z2.commons.i18n.LocalizedText import hu.simplexion.z2.commons.i18n.LocalizedTextStore import hu.simplexion.z2.commons.i18n.textStoreRegistry import hu.simplexion.z2.commons.util.UUID import hu.simplexion.z2.schematic.runtime.schema.SchemaField /** * Text store for fields that does not have a translation. */ object fieldNameFallbacks : LocalizedTextStore(UUID.nil()) fun SchemaField<*>.label() : LocalizedText { for (store in textStoreRegistry) { val localized = store.map[name] if (localized != null) return localized } return fieldNameFallbacks.map.getOrPut(name) { BasicLocalizedText(name, name.toCamelCaseWords(), fieldNameFallbacks) } } fun String.toCamelCaseWords() : String { val out = mutableListOf<Char>() for (char in toCharArray()) { when { out.isEmpty() -> out += char.uppercaseChar() char.isUpperCase() -> { out += ' ' out += char } else -> out += char } } return out.toCharArray().concatToString() }
1
Kotlin
0
0
3095730de5f4499e3f3b5a75ad560994c22cfc2d
1,188
z2-material
Apache License 2.0
buildSrc/src/main/kotlin/extensions.kt
Ikbeniyare
121,585,812
true
{"Kotlin": 60202, "Java": 6021}
import org.gradle.api.artifacts.dsl.DependencyHandler const val bintrayUser = "hendraanggrian" const val bintrayGroup = "com.hendraanggrian" const val bintrayArtifact = "socialview" const val bintrayPublish = "0.17" const val bintrayDesc = "Android TextView and EditText with hashtag, mention, and hyperlink support" const val bintrayWeb = "https://github.com/hendraanggrian/socialview" const val minSdk = 14 const val targetSdk = 27 const val buildTools = "27.0.1" const val kotlinVersion = "1.1.61" const val kotaVersion = "0.21" const val supportVersion = "27.0.1" const val picassoUtilsVersion = "0.3" const val junitVersion = "4.12" const val runnerVersion = "1.0.1" const val espressoVersion = "3.0.1" fun DependencyHandler.support(module: String, version: String, vararg suffixes: String) = "${StringBuilder("com.android.support").apply { suffixes.forEach { append(".$it") } }}:$module:$version" fun DependencyHandler.hendraanggrian(module: String, version: String) = "com.hendraanggrian:$module:$version" fun DependencyHandler.junit(version: String) = "junit:junit:$version"
0
Kotlin
0
0
7d829066851274102f137b6cd5324d676f8d5273
1,087
socialview
Apache License 2.0
domain/src/main/java/pe/fernan/domain/images/GetBreedImagesUseCase.kt
FernanApps
703,755,259
false
{"Kotlin": 116913}
package pe.fernan.domain.images import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import javax.inject.Inject class GetBreedImagesUseCase @Inject constructor( private val imagesRepository: ImagesRepository ) { operator fun invoke(breedKey: String): Flow<List<AnimalImage>> { return imagesRepository.getImagesByBreed(breedKey).distinctUntilChanged() } }
0
Kotlin
0
0
4a65d349ee9d2c5ef2bc815a28c843cbd2b632d0
412
AnimalBreeds
MIT License
features-onboarding/src/main/kotlin/com/mindstix/onboarding/di/LoginModule.kt
VidurrajeD
875,204,652
false
{"Kotlin": 305394}
/** * Copyright (c) 2023 Mindstix Software Labs * All rights reserved. */ package com.mindstix.onboarding.di import android.content.Context import com.mindstix.onboarding.repository.SkinAnalysisRepository import com.mindstix.onboarding.usecases.LoginUseCase import com.mindstix.onboarding.usecases.LoginUseCaseImpl import com.mindstix.onboarding.usecases.SkinAnalysisUseCase import com.mindstix.onboarding.usecases.SkinAnalysisUseCaseImpl import com.mindstix.onboarding.utils.SharedPreferenceManager import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) class LoginModule { @Provides fun provideLoginRepo(loginUseCaseImpl: LoginUseCaseImpl): LoginUseCase = loginUseCaseImpl @Provides fun provideSkinAnalyseUseCase(skinAnalysisUseCaseImpl: SkinAnalysisUseCaseImpl): SkinAnalysisUseCase = skinAnalysisUseCaseImpl @Provides fun provideSharedPreferenceManager(@ApplicationContext context: Context): SharedPreferenceManager { return SharedPreferenceManager(context) } }
0
Kotlin
0
0
4a0abd439a45710aacb4db2acbfb40229baba191
1,180
tech_ninja_glowai
MIT License
uast/uast-common/src/org/jetbrains/uast/baseElements/UResolvable.kt
ingokegel
284,920,751
false
null
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast import com.intellij.psi.PsiElement import com.intellij.psi.ResolveResult import org.jetbrains.annotations.ApiStatus interface UResolvable { /** * Resolve the reference. * Note that the reference is *always* resolved to an unwrapped [PsiElement], never to a [UElement]. * * @return the resolved element, or null if the reference couldn't be resolved. */ fun resolve(): PsiElement? } interface UMultiResolvable { /** * Returns multiple elements where the reference could be resolved. * It could happen if there is an ambiguity in code: it is incomplete or resolve target cannot be statically determined * * @see [com.intellij.psi.PsiPolyVariantReference] as a similar entity for plain PSI */ fun multiResolve(): Iterable<ResolveResult> } fun UResolvable.resolveToUElement(): UElement? = resolve().toUElement()
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
1,478
intellij-community
Apache License 2.0
connekted-cli/src/main/kotlin/io/github/cfraser/connekted/cli/command/GetCommand.kt
c-fraser
420,198,834
false
null
/* Copyright 2021 c-fraser 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.cfraser.connekted.cli.command import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.multiple import com.github.ajalt.clikt.parameters.arguments.unique import com.github.ajalt.mordant.rendering.BorderStyle import com.github.ajalt.mordant.rendering.TextAlign import com.github.ajalt.mordant.rendering.TextColors import com.github.ajalt.mordant.rendering.TextStyles import com.github.ajalt.mordant.table.Borders import com.github.ajalt.mordant.table.Table import com.github.ajalt.mordant.table.table import com.github.ajalt.mordant.terminal.Terminal import io.fabric8.kubernetes.client.KubernetesClient import io.github.cfraser.connekted.cli.client.V0ApiServerClient import io.github.cfraser.connekted.common.Configs import io.github.cfraser.connekted.common.MessagingApplicationData import io.github.cfraser.connekted.common.MessagingComponentData import java.net.ServerSocket import java.net.URI import javax.inject.Singleton import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.runBlocking import mu.KotlinLogging import org.eclipse.microprofile.rest.client.RestClientBuilder private val logger = KotlinLogging.logger {} /** * [GetCommand] is a [CliktCommand] to get data for messaging application(s) running on a Kubernetes * cluster. * * @property kubernetesClient the [KubernetesClient] to use to get messaging application data * @property restClientBuilder the [RestClientBuilder] to use to build [V0ApiServerClient] * @property terminal the [Terminal] to use to display output */ @Singleton internal class GetCommand( private val kubernetesClient: KubernetesClient, private val terminal: Terminal, private val restClientBuilder: Lazy<RestClientBuilder> ) : CliktCommand(name = "get", help = "Get messaging application(s) running in Kubernetes") { private val names: Set<String> by argument(help = "(optional) - the names of the messaging application(s) to get") .multiple() .unique() override fun run() { val messagingApplicationData = kubernetesClient .services() .withName(Configs.operatorName) .portForward(Configs.appPort, ServerSocket(0).use { it.localPort }) .use { localPortForward -> val v0ApiServerClient = restClientBuilder .value .baseUri(URI("http://localhost:${localPortForward.localPort}")) .build(V0ApiServerClient::class.java) names.takeUnless { it.isEmpty() }?.run { runBlocking(Dispatchers.IO) { map { name -> async { runCatching { v0ApiServerClient.getMessagingApplication(name) } .onFailure { logger.error(it) { "Failed to get messaging application data for $name" } } .getOrNull() } } .awaitAll() .mapNotNull { it } .toSet() } } ?: v0ApiServerClient.getMessagingApplications() } if (names.isNotEmpty() && names.size != messagingApplicationData.size) { val missing = names - messagingApplicationData.map { it.name } terminal.warning("Failed to get messaging application data for ${missing.joinToString()}") } if (messagingApplicationData.isNotEmpty()) terminal.println(messagingApplicationData.asTable()) } companion object { /** Initialize a [Table] to display the [Collection] of [MessagingApplicationData]. */ private fun Set<MessagingApplicationData>.asTable() = table { borderStyle = BorderStyle.ASCII_DOUBLE_SECTION_SEPARATOR header { align = TextAlign.CENTER style(TextColors.green, bold = true, italic = true) row("Messaging application", "Messaging component(s)") } column(0) { style = TextColors.brightBlue + TextStyles.italic } body { forEach { messagingApplicationData -> row( messagingApplicationData.name, messagingApplicationData.messagingComponents?.asTable()) } } } /** Initialize a [Table] to display the [List] of [MessagingComponentData]. */ private fun List<MessagingComponentData>.asTable() = table { align = TextAlign.LEFT borderStyle = BorderStyle.ASCII body { forEachIndexed { i, messagingComponentData -> row( table { align = TextAlign.LEFT borderStyle = BorderStyle.BLANK body { row("Name:", messagingComponentData.name) row("Type:", messagingComponentData.type) if (messagingComponentData.type == MessagingComponentData.Type.SENDER || messagingComponentData.type == MessagingComponentData.Type.SENDING_RECEIVER) { row("Sends to:", messagingComponentData.messagingData?.sendTo) row("Messages sent:", messagingComponentData.messagingData?.sent) row("Send errors:", messagingComponentData.messagingData?.sendErrors) } if (messagingComponentData.type == MessagingComponentData.Type.RECEIVER || messagingComponentData.type == MessagingComponentData.Type.SENDING_RECEIVER) { row("Messages received:", messagingComponentData.messagingData?.received) row("Receive errors:", messagingComponentData.messagingData?.receiveErrors) } } }) { borders = if (i == 0) Borders.NONE else Borders.TOP } } } } } }
0
Kotlin
0
2
17affcb232a20ea4f8489d915ab915dd724333e1
6,639
connekted
Apache License 2.0
jambo/src/main/java/com/tabasumu/jambo/data/JamboLogRepository.kt
tabasumu
501,671,460
false
{"Kotlin": 49204, "Java": 489}
package com.tabasumu.jambo.data import androidx.paging.Pager import androidx.paging.PagingConfig import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class JamboLogRepository(private val db: JamboLocalDB) { private val jamboLogDao: JamboLogDao by lazy { db.jamboDao() } suspend fun saveLogs(vararg jamboLog: JamboLog) { withContext(Dispatchers.IO) { jamboLogDao.insert(*jamboLog) } } suspend fun clearLogs() { withContext(Dispatchers.IO) { jamboLogDao.deleteAll() } } fun getLogs(tag: LogType = LogType.ALL, message: String = "") = Pager( config = PagingConfig(pageSize = 20, enablePlaceholders = false), pagingSourceFactory = { when (tag) { LogType.ALL -> jamboLogDao.searchJamboLogs(message = message) else -> jamboLogDao.filterJamboLogWithTagAndMsg(tag = tag.name, message = message) } } ).flow }
5
Kotlin
4
13
235dce28f7046eeac508fe1c4c3182004ef4cb99
1,005
jambo
Apache License 2.0
presentation/src/main/java/com/example/stats/model/GameIdModel.kt
minjun8946
390,971,021
false
null
package com.example.stats.model import com.example.domain.entity.GameId data class GameIdModel( val gameId : Int, val perPage : Int ) fun GameIdModel.toEntity() = GameId( gameId = gameId, perPage = perPage )
0
Kotlin
0
1
48824d846acd272e6af65423f739ed6ea29a4f34
243
Stats
MIT License
embrace-test-fakes/src/main/kotlin/io/embrace/android/embracesdk/fixtures/SessionTestFixtures.kt
embrace-io
704,537,857
false
{"Kotlin": 2807710, "C": 190147, "Java": 175321, "C++": 13140, "CMake": 4261}
package io.embrace.android.embracesdk.fixtures import io.embrace.android.embracesdk.fakes.fakeSessionEnvelope import io.embrace.android.embracesdk.getStartTime import io.embrace.android.embracesdk.internal.payload.Envelope import io.embrace.android.embracesdk.internal.payload.SessionPayload public val testSessionEnvelope: Envelope<SessionPayload> = fakeSessionEnvelope( sessionId = "80DCEC19B24B434599B04C237970B785", startMs = 1681972471807L ) public val testSessionEnvelopeOneMinuteLater: Envelope<SessionPayload> = fakeSessionEnvelope( startMs = testSessionEnvelope.getStartTime() + 60000L ) public val testSessionEnvelope2: Envelope<SessionPayload> = fakeSessionEnvelope( sessionId = "03FC033631F346C48AF6E3D5B56F6AA3", startMs = testSessionEnvelopeOneMinuteLater.getStartTime() + 300000L )
19
Kotlin
8
133
c3d8b882d91f7200c812d8ffa2dee5b820263c0d
821
embrace-android-sdk
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Italic.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold 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 me.localx.icons.rounded.Icons public val Icons.Bold.Italic: ImageVector get() { if (_italic != null) { return _italic!! } _italic = Builder(name = "Italic", defaultWidth = 512.0.dp, defaultHeight = 512.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(21.0f, 0.0f) horizontalLineTo(6.0f) arcTo(1.5f, 1.5f, 0.0f, false, false, 6.0f, 3.0f) horizontalLineToRelative(5.713f) lineTo(9.259f, 21.0f) horizontalLineTo(3.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, 0.0f, 3.0f) horizontalLineTo(18.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, 0.0f, -3.0f) horizontalLineTo(12.287f) lineTo(14.741f, 3.0f) horizontalLineTo(21.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, 0.0f, -3.0f) close() } } .build() return _italic!! } private var _italic: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
1,865
icons
MIT License
MultiModuleApp2/module4/src/main/java/com/github/yamamotoj/module4/package77/Foo07749.kt
yamamotoj
163,851,411
false
{"Text": 1, "Ignore List": 30, "Markdown": 1, "Gradle": 34, "Java Properties": 11, "Shell": 6, "Batchfile": 6, "Proguard": 22, "Kotlin": 36021, "XML": 93, "INI": 1, "Java": 32, "Python": 2}
package com.github.yamamotoj.module4.package77 class Foo07749 { fun method0() { Foo07748().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
347
android_multi_module_experiment
Apache License 2.0
src/main/kotlin/io/rozoom/next/versioning/version/VersionDetails.kt
rozoom-dev
832,741,381
false
{"Kotlin": 18155}
package io.rozoom.next.versioning.version data class VersionDetails( val lastVersion: SemanticVersion, val counter: VersionCounter, val branchName: String?, val isSnapshot: Boolean, val sha: String, val uncommitted: Boolean, ) { val currentVersion: SemanticVersion = counter.increment(lastVersion) }
0
Kotlin
0
0
9abb8113aea0cbba4b127715ee632ced13dd7aa5
329
next-version
Apache License 2.0
app/src/main/java/com/example/android/navigation/ui/main/MainActivity.kt
anthowe
264,048,959
false
null
/* * Copyright 2018, 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 * * 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.example.android.navigation.ui.main import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.android.navigation.R import com.example.android.navigation.common.onPageChange import com.example.android.navigation.ui.main.pager.MainPagerAdapter import com.example.android.navigation.ui.welcome.WelcomeActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { companion object { fun getLaunchIntent(from: Context) = Intent(from, MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initUi() } private fun initUi() { val adapter = MainPagerAdapter(supportFragmentManager) adapter.setPages(listOf(WelcomeActivity())) mainPager.adapter = adapter mainPager.offscreenPageLimit = 3 bottomNavigation.setOnNavigationItemSelectedListener { switchNavigationTab(it.order) true } mainPager.onPageChange { position -> val item = bottomNavigation.menu.getItem(position) bottomNavigation.selectedItemId = item.itemId } // addJoke.onClick { startActivity(Intent(this, AddJokeActivity::class.java)) } } private fun switchNavigationTab(position: Int) = mainPager.setCurrentItem(position, true) } // TODO (01) Create the new TitleFragment // Select File->New->Fragment->Fragment (Blank) // TODO (02) Clean up the new TitleFragment // In our new TitleFragment // TODO (03) Use DataBindingUtil.inflate to inflate and return the titleFragment in onCreateView // In our new TitleFragment // R.layout.fragment_title
0
Kotlin
0
0
a7c0a31cd6fa09df9e1ff9e8272a1b809aec89d6
2,592
AndroidTriviaFragment_toCell
Apache License 2.0
src/main/kotlin/br/com/zup/contas/Conta.kt
DigoB
346,384,198
true
{"Kotlin": 31918}
package br.com.zup.contas import javax.persistence.* @Entity class Conta( @Column(nullable = false) var agencia: String?, @Column(nullable = false) var numero: String?, @field:ManyToOne(cascade = [CascadeType.PERSIST, CascadeType.MERGE]) var instituicao: Instituicao?, @field:ManyToOne(cascade = [CascadeType.PERSIST, CascadeType.MERGE]) var titular: Titular?, // @field:Enumerated(EnumType.STRING) var tipo: String ) { @Column(nullable = false) @Id @GeneratedValue var id: Long? = null }
0
Kotlin
0
0
d2bed312f4d718db9ea0d586ffbc26005d14cdcd
549
orange-talents-01-template-pix-keymanager-grpc
Apache License 2.0
src/main/kotlin/br/com/zup/contas/Conta.kt
DigoB
346,384,198
true
{"Kotlin": 31918}
package br.com.zup.contas import javax.persistence.* @Entity class Conta( @Column(nullable = false) var agencia: String?, @Column(nullable = false) var numero: String?, @field:ManyToOne(cascade = [CascadeType.PERSIST, CascadeType.MERGE]) var instituicao: Instituicao?, @field:ManyToOne(cascade = [CascadeType.PERSIST, CascadeType.MERGE]) var titular: Titular?, // @field:Enumerated(EnumType.STRING) var tipo: String ) { @Column(nullable = false) @Id @GeneratedValue var id: Long? = null }
0
Kotlin
0
0
d2bed312f4d718db9ea0d586ffbc26005d14cdcd
549
orange-talents-01-template-pix-keymanager-grpc
Apache License 2.0
src/main/kotlin/no/nav/fia/arbeidsgiver/sporreundersokelse/api/dto/IdentifiserbartSpørsmålDto.kt
navikt
644,356,194
false
{"Kotlin": 196555, "Dockerfile": 214}
package no.nav.fia.arbeidsgiver.sporreundersokelse.api.dto import kotlinx.serialization.Serializable @Serializable data class IdentifiserbartSpørsmålDto( val temaId: Int, val spørsmålId: String, )
0
Kotlin
0
0
7cbc469c0fe892d304938a0011e5fd46e0aa9ff9
207
fia-arbeidsgiver
MIT License
platform/diff-impl/src/com/intellij/diff/editor/DiffEditorTabTitleProvider.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.diff.editor import com.intellij.diff.editor.DiffEditorTabFilesManager.Companion.isDiffOpenedInNewWindow import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.impl.EditorTabTitleProvider import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.Nls class DiffEditorTabTitleProvider : EditorTabTitleProvider, DumbAware { override fun getEditorTabTitle(project: Project, file: VirtualFile): @NlsContexts.TabTitle String? { val title = getTitle(project, file) return if (isDiffOpenedInNewWindow(file)) title else title?.shorten() } override fun getEditorTabTooltipText(project: Project, file: VirtualFile): @NlsContexts.Tooltip String? { return getTitle(project, file) } private fun getTitle(project: Project, file: VirtualFile): @Nls String? { if (file !is ChainDiffVirtualFile) return null return FileEditorManager.getInstance(project) .getSelectedEditor(file) ?.let { it as? DiffRequestProcessorEditor } ?.processor?.activeRequest?.title } private fun String.shorten(maxLength: Int = 30): @Nls String { if (length < maxLength) return this val index = indexOf('(') if (index in 1 until maxLength) return substring(0, index) return StringUtil.shortenTextWithEllipsis(this, maxLength, 0) } }
186
null
4323
13,182
26261477d6e3d430c5fa50c42b80ea8cfee45525
1,692
intellij-community
Apache License 2.0
app/src/main/java/com/peng/repo/DataStorePrefsRepository.kt
abdulwahabhassan
516,570,722
false
{"Kotlin": 146808}
package com.peng.repo import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.* import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import timber.log.Timber import java.io.IOException import javax.inject.Inject // Repository to manage all user preferences / configurations class DataStorePrefsRepository @Inject constructor(private val dataStore: DataStore<Preferences>) { // an observable flow of user preferences in datastore that can be collected in view models val appConfigPreferencesFlow: Flow<AppConfigPreferences> = dataStore.data.catch { exception -> // dataStore.data throws an IOException when an error is encountered when reading data if (exception is IOException) { Timber.d(exception, "Error reading preferences.") emit(emptyPreferences()) } else { throw exception } }.map { preferences -> mapUserPreferences(preferences) } // obtain the first element emitted from data store by the flow suspend fun fetchInitialPreferences() = mapUserPreferences(dataStore.data.first().toPreferences()) // map preferences from data store to AppConfigPreferences data class when retrieving all user // preferences in data store private fun mapUserPreferences(preferences: Preferences): AppConfigPreferences { return AppConfigPreferences( gridColumns = preferences[PreferencesKeys.GRID] ?: 2, selectedPaymentCardNumber = preferences[PreferencesKeys.SELECTED_PAYMENT_CARD] ?: "", userEmail = preferences[PreferencesKeys.USER_EMAIL] ?: "<EMAIL>", filterByPriceLowRange = preferences[PreferencesKeys.FILTER_BY_PRICE_LOW_RANGE] ?: 0, filterByPriceHighRange = preferences[PreferencesKeys.FILTER_BY_PRICE_HIGH_RANGE] ?: 0, filterByRating = preferences[PreferencesKeys.FILTER_BY_RATING] ?: 0f, ) } suspend fun updateGridPref(columns: Int) { dataStore.edit { mutablePreferences -> mutablePreferences[PreferencesKeys.GRID] = columns } } suspend fun updateSelectedPaymentCard(cardNumber: String) { dataStore.edit { mutablePreferences -> mutablePreferences[PreferencesKeys.SELECTED_PAYMENT_CARD] = cardNumber } } suspend fun updateUserEmail(email: String) { dataStore.edit { mutablePreferences -> mutablePreferences[PreferencesKeys.USER_EMAIL] = email } } suspend fun updateProductsFilter(priceLowRange: Int, priceHighRange: Int, rating: Float) { dataStore.edit { mutablePreferences -> mutablePreferences[PreferencesKeys.FILTER_BY_PRICE_LOW_RANGE] = priceLowRange mutablePreferences[PreferencesKeys.FILTER_BY_PRICE_HIGH_RANGE] = priceHighRange mutablePreferences[PreferencesKeys.FILTER_BY_RATING] = rating } } // data class to hold all configurable fields in app settings screen and in-app configurable actions // that represent a user's preferences data class AppConfigPreferences( val gridColumns: Int = 2, val selectedPaymentCardNumber: String = "", val userEmail: String = "", val filterByPriceLowRange: Int = 0, val filterByPriceHighRange: Int = 0, val filterByRating: Float = 0f, ) // object to hold preference keys used to retrieve and update user preferences private object PreferencesKeys { val GRID = intPreferencesKey("grid") val SELECTED_PAYMENT_CARD = stringPreferencesKey("preferred_payment_card") val USER_EMAIL = stringPreferencesKey("user_email") val FILTER_BY_PRICE_LOW_RANGE = intPreferencesKey("filter_by_price_low_range") val FILTER_BY_PRICE_HIGH_RANGE = intPreferencesKey("filter_by_price_high_range") val FILTER_BY_RATING = floatPreferencesKey("filter_by_rating") } }
0
Kotlin
0
1
a03b09a604dab4bcf20794096f9b35c8b26ca583
4,014
peng
Apache License 2.0
app/src/main/java/com/immortalweeds/pedometer/model/gps/Route.kt
Weedlly
523,343,757
false
{"Kotlin": 65187}
package com.immortalweeds.pedometer.model.gps data class Route( val country_crossed: Boolean, val distance: Double, val duration: Double, val geometry: Geometry, val legs: List<Leg>, val weight: Double, val weight_name: String )
0
Kotlin
0
7
411c6fcf45a7a9aa34214148264297b345211ed7
257
Pedometer
Apache License 2.0
product/server/intake/src/main/kotlin/io/codekvast/intake/agent/service/impl/AgentStateManager.kt
crispab
19,436,066
false
null
/* * Copyright (c) 2015-2022 Hallin Information Technology AB * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.codekvast.intake.agent.service.impl import io.codekvast.common.customer.CustomerData /** * Manages agent state, making sure not too many agents are enabled at the same time. * * @author <EMAIL> */ interface AgentStateManager { /** * Checks whether a certain agent may proceed with uploading publications. */ fun updateAgentState( customerData: CustomerData, jvmUuid: String, appName: String, environment: String ): Boolean }
8
null
4
42
9d751523dbd3354872c55637b4a6c50cd1f5ef87
1,618
codekvast
MIT License
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/configuration/ui/PackageSearchGeneralConfigurable.kt
ingokegel
72,937,917
true
null
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jetbrains.packagesearch.intellij.plugin.configuration.ui import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.project.Project import com.intellij.ui.TitledSeparator import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.ui.FormBuilder import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration import com.jetbrains.packagesearch.intellij.plugin.extensibility.AnalyticsAwareConfigurableContributorDriver import com.jetbrains.packagesearch.intellij.plugin.extensibility.ConfigurableContributor import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import java.awt.event.ItemEvent.SELECTED import javax.swing.JComponent import javax.swing.JPanel class PackageSearchGeneralConfigurable(project: Project) : SearchableConfigurable { private val extensions = ConfigurableContributor.extensionsForProject(project) .sortedBy { it.javaClass.simpleName } .map { it.createDriver() } private val isAnyContributorModified: Boolean get() = extensions.any { it.isModified() } private var isAutoAddRepositoriesModified: Boolean = false private val builder = FormBuilder.createFormBuilder() private val configuration = PackageSearchGeneralConfiguration.getInstance(project) private val autoAddRepositoriesCheckBox = PackageSearchUI.checkBox( PackageSearchBundle.message("packagesearch.configuration.automatically.add.repositories") ) { isSelected = configuration.autoAddMissingRepositories addItemListener { val newIsSelected = it.stateChange == SELECTED isAutoAddRepositoriesModified = newIsSelected != configuration.autoAddMissingRepositories } } override fun getId(): String = ID override fun getDisplayName(): String = PackageSearchBundle.message("packagesearch.configuration.title") override fun createComponent(): JComponent? { // Extensions extensions.forEach { it.contributeUserInterface(builder) } // General options builder.addComponent( TitledSeparator(PackageSearchBundle.message("packagesearch.configuration.general")), 0 ) // Reset defaults builder.addComponent(autoAddRepositoriesCheckBox) builder.addComponent( LinkLabel<Any>( PackageSearchBundle.message("packagesearch.configuration.restore.defaults"), null ) { _, _ -> restoreDefaults() } ) builder.addComponentFillVertically(JPanel(), 0) return builder.panel } override fun isModified() = isAutoAddRepositoriesModified || isAnyContributorModified override fun reset() { for (contributor in extensions) { contributor.reset() } autoAddRepositoriesCheckBox.isSelected = configuration.autoAddMissingRepositories isAutoAddRepositoriesModified = false } private fun restoreDefaults() { for (contributor in extensions) { contributor.restoreDefaults() } val defaultAutoAddRepositories = true isAutoAddRepositoriesModified = autoAddRepositoriesCheckBox.isSelected == defaultAutoAddRepositories autoAddRepositoriesCheckBox.isSelected = defaultAutoAddRepositories PackageSearchEventsLogger.logPreferencesRestoreDefaults() } override fun apply() { val analyticsFields = mutableSetOf<EventPair<*>>() for (contributor in extensions) { contributor.apply() if (contributor is AnalyticsAwareConfigurableContributorDriver) { analyticsFields.addAll(contributor.provideApplyEventAnalyticsData()) } } configuration.autoAddMissingRepositories = autoAddRepositoriesCheckBox.isSelected analyticsFields += PackageSearchEventsLogger.preferencesAutoAddRepositoriesField.with(configuration.autoAddMissingRepositories) PackageSearchEventsLogger.logPreferencesChanged(*analyticsFields.toTypedArray()) isAutoAddRepositoriesModified = false } companion object { const val ID = "preferences.packagesearch.PackageSearchGeneralConfigurable" } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
5,276
intellij-community
Apache License 2.0
TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/PostDetailActivity.kt
petropavel13
32,879,018
false
{"Kotlin": 93035, "Java": 40276}
package com.github.petropavel13.twophoto import android.content.Intent import android.database.sqlite.SQLiteException import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast import com.etsy.android.grid.StaggeredGridView import com.github.petropavel13.twophoto.adapters.EntriesAdapter import com.github.petropavel13.twophoto.db.DatabaseOpenHelper import com.github.petropavel13.twophoto.events.PostDeletedEvent import com.github.petropavel13.twophoto.events.PostSavedEvent import com.github.petropavel13.twophoto.extensions.* import com.github.petropavel13.twophoto.model.PostDetail import com.github.petropavel13.twophoto.sources.DataSource import com.github.petropavel13.twophoto.sources.ORMLitePostsDataSource import com.github.petropavel13.twophoto.sources.PostsDataSource import com.github.petropavel13.twophoto.sources.SpicePostsDataSource import com.github.petropavel13.twophoto.views.AuthorItemView import com.github.petropavel13.twophoto.views.RetryView import com.ns.developer.tagview.entity.Tag import com.ns.developer.tagview.widget.TagCloudLinkView import com.octo.android.robospice.Jackson2GoogleHttpClientSpiceService import com.octo.android.robospice.SpiceManager import kotlin.properties.Delegates public class PostDetailActivity : AppCompatActivity(), DataSource.ResponseListener<PostDetail> { companion object { val POST_ID_KEY ="post_id" val FETCH_FROM_DB_KEY = "fetch_from_db" } private var postId = 0 private var post: PostDetail by Delegates.notNull() private var spiceManager: SpiceManager? = null private var dataSource: PostsDataSource by Delegates.notNull() private var toolbar: Toolbar? = null private var titleTextView: TextView? = null private var descriptionTextView: TextView? = null private var entriesGridView: StaggeredGridView? = null private var loadingProgressBar: ProgressBar? = null private var retryView: RetryView? = null private var authorItemView: AuthorItemView? = null private var tagCloudView: TagCloudLinkView? = null private var headerView: View? = null private var footerView: View? = null private var menuItemSave: MenuItem? = null private var menuItemRemove: MenuItem? = null override fun onCreate(savedInstanceState: Bundle?) { super<AppCompatActivity>.onCreate(savedInstanceState) setContentView(R.layout.activity_post_detail) with(findViewById(R.id.post_detail_toolbar) as Toolbar) { toolbar = this // inflateMenu(R.menu.menu_post_entries) // for some reason "standalone" toolbar menu doesn't work // so fallback to actionbar flavor setSupportActionBar(this) } getSupportActionBar().setDisplayHomeAsUpEnabled(true) with(findViewById(R.id.post_detail_loading_progress_bar) as ProgressBar) { loadingProgressBar = this setVisibility(View.VISIBLE) } titleTextView = findViewById(R.id.post_detail_title_text_view) as? TextView descriptionTextView = findViewById(R.id.post_detail_description_text_view) as? TextView val ctx = this with(getIntent()) { postId = getIntExtra(POST_ID_KEY, postId) dataSource = if (getBooleanExtra(FETCH_FROM_DB_KEY, false)) { ORMLitePostsDataSource(DatabaseOpenHelper(ctx)) } else { with(SpiceManager(Jackson2GoogleHttpClientSpiceService::class.java)) { spiceManager = this SpicePostsDataSource(this) } } } with(findViewById(R.id.post_detail_entries_grid_view) as StaggeredGridView) { entriesGridView = this with(getLayoutInflater().inflate(R.layout.post_detail_header_layout, null)) { headerView = this titleTextView = findViewById(R.id.post_detail_title_text_view) as? TextView descriptionTextView = findViewById(R.id.post_detail_description_text_view) as? TextView } with(getLayoutInflater().inflate(R.layout.post_detail_footer_layout, null)) { footerView = this authorItemView = findViewById(R.id.post_detail_footer_author_item_view) as? AuthorItemView authorItemView?.setOnClickListener { with(Intent(ctx, AuthorDetailActivity::class.java)) { putExtra(AuthorDetailActivity.AUTHOR_KEY, authorItemView!!.author) startActivity(this) } } tagCloudView = findViewById(R.id.post_detail_tag_cloud_view) as? TagCloudLinkView } setOnItemClickListener { adapterView, view, i, l -> with(adapterView.getRealAdapter<EntriesAdapter>()) { val postEntriesIntent = Intent(ctx, PostEntriesActivity::class.java) postEntriesIntent.putParcelableArrayListExtra(PostEntriesActivity.POST_ENTRIES_KEY, this?.entries?.toArrayList()) postEntriesIntent.putExtra(PostEntriesActivity.SELECTED_ENTRY_INDEX, i - 1) postEntriesIntent.putExtra(POST_ID_KEY, postId) startActivity(postEntriesIntent) } } setVisibility(View.INVISIBLE) } with(findViewById(R.id.post_detail_retry_view) as RetryView) { retryView = this onRetryListener = object: View.OnClickListener{ override fun onClick(view: View) { retryView?.setVisibility(View.INVISIBLE) loadingProgressBar?.setVisibility(View.VISIBLE) dataSource.requestDetail(this@PostDetailActivity, postId) } } setVisibility(View.INVISIBLE) } dataSource.requestDetail(this, postId) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { getMenuInflater().inflate(R.menu.menu_post_detail, menu) menuItemSave = menu?.findItem(R.id.menu_post_detail_action_save_post) menuItemRemove = menu?.findItem(R.id.menu_post_detail_action_remove_post) return super<AppCompatActivity>.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if(item?.getItemId() == android.R.id.home) { finish() return super<AppCompatActivity>.onOptionsItemSelected(item) } val ctx = this when(item?.getItemId()) { R.id.menu_post_detail_action_save_post -> { with(DatabaseOpenHelper(ctx)) { try { post.savePostImages(ctx) post.createInDatabase(this) menuItemRemove?.setVisible(true) menuItemSave?.setVisible(false) eventsBus.post(PostSavedEvent(post)) Toast.makeText(ctx, "Successful saved post", Toast.LENGTH_LONG) } catch(e: SQLiteException) { Toast.makeText(ctx, "Failed to save post", Toast.LENGTH_LONG) } finally { close() } } } R.id.menu_post_detail_action_remove_post -> { with(DatabaseOpenHelper(ctx)) { try { post.deletePostImages(ctx) post.deleteFromDatabase(this) menuItemRemove?.setVisible(false) menuItemSave?.setVisible(true) eventsBus.post(PostDeletedEvent(post)) Toast.makeText(ctx, "Post was successfully removed", Toast.LENGTH_LONG) finish() } catch(e: SQLiteException) { Toast.makeText(ctx, "Failed to remove post", Toast.LENGTH_LONG) } finally { close() } } } } return super<AppCompatActivity>.onOptionsItemSelected(item) } override fun onResponse(result: PostDetail?) { post = result ?: PostDetail() titleTextView?.setText(post.title) descriptionTextView?.setText(post.description) authorItemView?.author = post.author post.tags.map { it.title }.forEachIndexed { i, s -> tagCloudView?.add(Tag(i, s)) } tagCloudView?.drawTags() entriesGridView?.addHeaderView(headerView) entriesGridView?.addFooterView(footerView) entriesGridView?.setAdapter(EntriesAdapter(this, post.entries)) loadingProgressBar?.setVisibility(View.INVISIBLE) entriesGridView?.setVisibility(View.VISIBLE) if(dataSource is ORMLitePostsDataSource) { menuItemRemove?.setVisible(true) menuItemSave?.setVisible(false) } else { // set default menuItemRemove?.setVisible(false) menuItemSave?.setVisible(true) // and then check existence in db with(ORMLitePostsDataSource(DatabaseOpenHelper(this))) { requestDetail(object: DataSource.ResponseListener<PostDetail>{ override fun onResponse(result: PostDetail?) { val exists = result != null menuItemRemove?.setVisible(exists) menuItemSave?.setVisible(!exists) } override fun onError(exception: Exception) { // } }, post.id) } } } override fun onError(exception: Exception) { loadingProgressBar?.setVisibility(View.INVISIBLE) retryView?.setVisibility(View.VISIBLE) } override fun onStart() { super<AppCompatActivity>.onStart() spiceManager?.start(this) } override fun onStop() { super<AppCompatActivity>.onStop() spiceManager?.shouldStop() entriesGridView?.getRealAdapter<EntriesAdapter>()?.unloadItemsImages() } override fun onRestart() { super<AppCompatActivity>.onRestart() entriesGridView?.getRealAdapter<EntriesAdapter>()?.loadItemsImages() } }
1
Kotlin
1
1
3159d5fdd06e3ec5642c2a3f07b87d0e9ff53985
10,619
2photo-android
MIT License
shared/src/test/java/com/google/samples/apps/iosched/shared/domain/sessions/LoadTagsByCategoryUseCaseTest.kt
kingstenbanh
156,424,020
false
{"Gradle": 6, "Java Properties": 2, "Markdown": 2, "Shell": 4, "Text": 17, "Ignore List": 5, "Batchfile": 1, "XML": 101, "Kotlin": 174, "Proguard": 4, "JSON": 7, "INI": 2, "HAProxy": 1, "Java": 28}
/* * Copyright 2018 Google LLC * * 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.google.samples.apps.iosched.shared.domain.sessions import com.google.samples.apps.iosched.shared.data.tag.TagDataSource import com.google.samples.apps.iosched.shared.data.tag.TagRepository import com.google.samples.apps.iosched.shared.model.Tag import com.google.samples.apps.iosched.shared.model.TestData.advancedTag import com.google.samples.apps.iosched.shared.model.TestData.androidTag import com.google.samples.apps.iosched.shared.model.TestData.beginnerTag import com.google.samples.apps.iosched.shared.model.TestData.codelabsTag import com.google.samples.apps.iosched.shared.model.TestData.intermediateTag import com.google.samples.apps.iosched.shared.model.TestData.sessionsTag import com.google.samples.apps.iosched.shared.model.TestData.tagsList import com.google.samples.apps.iosched.shared.model.TestData.webTag import com.google.samples.apps.iosched.shared.result.Result import org.junit.Assert.assertEquals import org.junit.Test /** * Unit tests for [LoadTagsByCategoryUseCase] */ class LoadTagsByCategoryUseCaseTest { @Test fun returnsOrderedTags() { val useCase = LoadTagsByCategoryUseCase(TagRepository(TestSessionDataSource)) val tags = useCase.executeNow(Unit) as Result.Success<List<Tag>> // Expected values to assert val expected = listOf( // category = LEVEL beginnerTag, intermediateTag, advancedTag, // category = TRACK androidTag, webTag, // category = TYPE sessionsTag, codelabsTag ) assertEquals(expected, tags.data) } object TestSessionDataSource : TagDataSource { override fun getTags(): List<Tag> { return tagsList } } }
1
null
1
1
f3647a65ef817cf4ae378304c083386cce4ec398
2,360
iosched
Apache License 2.0
plugins/gradle/java/testSources/importing/GradleCreateProjectTestCase.kt
present1001
201,411,886
false
null
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.org.jetbrains.plugins.gradle.importing import com.intellij.ide.impl.NewProjectUtil import com.intellij.ide.projectWizard.NewProjectWizard import com.intellij.ide.projectWizard.ProjectSettingsStep import com.intellij.ide.projectWizard.ProjectTypeStep import com.intellij.ide.util.newProjectWizard.AbstractProjectWizard import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.roots.ui.configuration.DefaultModulesProvider import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.roots.ui.configuration.actions.NewModuleAction import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ui.UIUtil import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase import org.jetbrains.plugins.gradle.service.project.wizard.GradleModuleWizardStep import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleConstants import org.junit.runners.Parameterized abstract class GradleCreateProjectTestCase : GradleImportingTestCase() { data class ProjectInfo(val root: VirtualFile, val modules: List<ModuleInfo>) { constructor(root: VirtualFile, vararg modules: ModuleInfo) : this(root, modules.toList()) } data class ModuleInfo(val name: String, val root: VirtualFile, val modulesPerSourceSet: List<String>) { constructor(name: String, root: VirtualFile, vararg modulesPerSourceSet: String) : this(name, root, modulesPerSourceSet.toList()) } fun assertProjectStructure(project: Project, projectInfo: ProjectInfo) { val modules = projectInfo.modules.map { it.name } val sourceSetModules = projectInfo.modules.flatMap { it.modulesPerSourceSet } assertModules(project, *(modules + sourceSetModules).toTypedArray()) } fun deleteProject(projectInfo: ProjectInfo) { invokeAndWaitIfNeeded { runWriteAction { for (module in projectInfo.modules) { val root = module.root if (root.exists()) { root.delete(null) } } } } } fun Project.use(save: Boolean = false, action: (Project) -> Unit) { val project = this@use try { action(project) } finally { invokeAndWaitIfNeeded { val projectManager = ProjectManagerEx.getInstanceEx() if (save) { projectManager.closeAndDispose(project) } else { projectManager.forceCloseProject(project, true) } } } } fun generateProjectInfo(id: String): ProjectInfo { val name = "${System.currentTimeMillis()}-$id" val projectDir = createProjectSubDir("$name-project") val projectModuleDir = createProjectSubDir("$name-project/module") val externalModuleDir = createProjectSubDir("$name-module") return ProjectInfo(projectDir, ModuleInfo("$name-project", projectDir, "$name-project.main", "$name-project.test"), ModuleInfo("$name-project.module", projectModuleDir, "$name-project.module.main", "$name-project.module.test"), ModuleInfo("$name-project.$name-module", externalModuleDir, "$name-project.$name-module.main", "$name-project.$name-module.test") ) } protected fun assertDefaultProjectSettings(project: Project) { val externalProjectPath = project.basePath!! val settings = ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID) as GradleSettings val projectSettings = settings.getLinkedProjectSettings(externalProjectPath)!! assertEquals(projectSettings.externalProjectPath, externalProjectPath) assertEquals(projectSettings.isUseAutoImport, false) assertEquals(projectSettings.isUseQualifiedModuleNames, true) assertEquals(settings.storeProjectFilesExternally, true) } fun createProject(projectInfo: ProjectInfo): Project { val projectDirectory = projectInfo.root val project = createProject(projectDirectory.path) { configureProjectWizardStep(projectDirectory, it) } for (module in projectInfo.modules) { val moduleDirectory = module.root if (moduleDirectory.path == projectDirectory.path) continue createModule(moduleDirectory.path, project) { configureModuleWizardStep(moduleDirectory, project, it) } } return project } private fun createProject(directory: String, configure: (ModuleWizardStep) -> Unit): Project { val project = invokeAndWaitIfNeeded { val wizard = createWizard(null, directory) wizard.runWizard(configure) NewProjectUtil.createFromWizard(wizard, null) } waitForImportCompletion() return project } private fun createModule(directory: String, project: Project, configure: (ModuleWizardStep) -> Unit) { invokeAndWaitIfNeeded { val wizard = createWizard(project, directory) wizard.runWizard(configure) NewModuleAction().createModuleFromWizard(project, null, wizard) } waitForImportCompletion() } private fun createWizard(project: Project?, directory: String): AbstractProjectWizard { val modulesProvider = project?.let { DefaultModulesProvider(it) } ?: ModulesProvider.EMPTY_MODULES_PROVIDER return NewProjectWizard(project, modulesProvider, directory).also { UIUtil.dispatchAllInvocationEvents() } } private fun AbstractProjectWizard.runWizard(configure: ModuleWizardStep.() -> Unit) { while (true) { val currentStep = currentStepObject currentStep.configure() if (isLast) break doNextAction() if (currentStep === currentStepObject) { throw RuntimeException("$currentStep is not validated") } } doFinishAction() } private fun waitForImportCompletion() { invokeAndWaitIfNeeded { UIUtil.dispatchAllInvocationEvents() } } private fun configureProjectWizardStep(directory: VirtualFile, step: ModuleWizardStep) { when (step) { is ProjectTypeStep -> { step.setSelectedTemplate("Gradle", null) } is GradleModuleWizardStep -> { step.setGroupId("org.example") step.setArtifactId(directory.name) } is ProjectSettingsStep -> { step.setNameValue(directory.name) step.setPath(directory.path) } } } private fun configureModuleWizardStep(directory: VirtualFile, project: Project, step: ModuleWizardStep) { when (step) { is ProjectTypeStep -> { step.setSelectedTemplate("Gradle", null) } is GradleModuleWizardStep -> { val projectPath = project.basePath!! val projectData = ExternalSystemApiUtil.findProjectData(project, GradleConstants.SYSTEM_ID, projectPath)!! step.setParentProject(projectData.data) step.setArtifactId(directory.name) } is ProjectSettingsStep -> { step.setNameValue(directory.name) step.setPath(directory.path) } } } companion object { /** * It's sufficient to run the test against one gradle version */ @Parameterized.Parameters(name = "with Gradle-{0}") @JvmStatic fun tests(): Collection<Array<out String>> = arrayListOf(arrayOf(BASE_GRADLE_VERSION)) } }
1
null
1
1
a79249276cf6b68a6376d1f12964572283301a01
7,665
intellij-community
Apache License 2.0
app/src/main/java/com/nibmz7gmail/sgprayertimemusollah/ui/widgets/WidgetPrayerTimesSmall.kt
nurilyas7
161,193,982
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "Proguard": 2, "Java": 3, "XML": 62, "JSON": 1, "Kotlin": 58}
package com.nibmz7gmail.sgprayertimemusollah.ui.widgets import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Context import android.util.Log import android.widget.RemoteViews import com.nibmz7gmail.sgprayertimemusollah.R import com.nibmz7gmail.sgprayertimemusollah.core.model.CalendarData import com.nibmz7gmail.sgprayertimemusollah.core.result.Result import com.nibmz7gmail.sgprayertimemusollah.core.util.PrayerTimesUtils import com.nibmz7gmail.sgprayertimemusollah.core.util.getFontBitmap import dagger.android.AndroidInjection import timber.log.Timber /** * Created by USER on 19/12/2017. */ class WidgetPrayerTimesSmall : BaseWidget() { override fun injectWidget(baseWidget: BaseWidget, context: Context) { AndroidInjection.inject(this, context) } override fun getWidgetClass(): Class<out BaseWidget> { return this.javaClass } override fun updateWidget(context: Context, result: Result<CalendarData>?) { updateSmallWidget(context, result) } companion object { fun update(context: Context, result: Result<CalendarData>?) { updateSmallWidget(context, result) } } } private fun updateSmallWidget( context: Context, result: Result<CalendarData>? ) { val views = RemoteViews(context.packageName, R.layout.widget_prayer_times_small) val appWidgetManager = AppWidgetManager.getInstance(context.applicationContext) val thisWidget = ComponentName(context.applicationContext, WidgetPrayerTimesSmall::class.java) val appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget) if (appWidgetIds != null && appWidgetIds.isNotEmpty()){ createPrayerWidget( context, views, result, WidgetPrayerTimesSmall::class.java, showPrayerTimes ) } else return for (appWidgetId in appWidgetIds) { appWidgetManager.updateAppWidget(appWidgetId, views) } } private val showPrayerTimes = { context: Context, views: RemoteViews, result: Result.Success<CalendarData> -> views.removeAllViews(R.id.prayer_list) for (i in 0..4) { val prayerTimesView = RemoteViews(context.packageName, R.layout.viewstub_prayertimes_small ) context.apply { prayerTimesView.setImageViewBitmap( R.id.prayerType, getFontBitmap(17f, white, QS_MEDIUM, PrayerTimesUtils.TIME_OF_DAY[i])) prayerTimesView.setImageViewBitmap( R.id.prayerTime, getFontBitmap(19f, white, QS_LIGHT, result.data.prayerTimes[i])) prayerTimesView.setImageViewResource(R.id.timeIcon, TIME_ICONS[i]) } views.addView(R.id.prayer_list, prayerTimesView) } }
0
Kotlin
1
4
75a6c490bdeb90ee9c86b9726ed52a6e97fbae2c
2,828
sgprayertimes
Apache License 2.0
services/backend-api/src/main/kotlin/paw/my_mess/db_service/business/bussines_models/get/BusinessAvatarLink.kt
enaki
339,822,445
false
null
package paw.my_mess.db_service.business.bussines_models.get data class BusinessAvatarLink( val avatarLink: String )
1
Kotlin
1
2
cbe739534883dafea815dc313fc571fa3d6dc37e
120
MyMess
MIT License
app/src/main/java/com/allever/videoeditordemo/TimeLineViewLayout.kt
devallever
160,824,408
false
null
package com.allever.videoeditordemo import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.os.Build import android.os.Handler import android.os.Message import android.support.annotation.RequiresApi import android.util.AttributeSet import android.util.Log import android.view.* import android.widget.LinearLayout import android.widget.Toast //import org.greenrobot.eventbus.EventBus class TimeLineViewLayout : LinearLayout, TimeLineView.MovingCallback, TimeLineView.OnOptinListener/*, View.OnDragListener*/ , DragHelper.DragListener , View.OnLongClickListener{ override fun onDragStarted() { Log.d(TAG, "onDragStarted()") } override fun onDragEnded() { Log.d(TAG, "onDragEnded()") } @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super( context, attrs, defStyleAttr ) { initView() } companion object { private val TAG = TimeLineViewLayout::class.java.simpleName private const val MESSAGE_SCROLL_TO_SCREEN_MID_FROM_RIGHT = 0x01 private const val MESSAGE_AUTO_SCROLL_TO_RIGHT = 0x02 private const val MESSAGE_AUTO_SCROLL_TO_LEFT = 0x03 private const val MESSAGE_SCROLL_TO_SCREEN_LEFT = 0x04 private const val MESSAGE_SCROLL_TO_SCREEN_RIGHT = 0x05 private const val MESSAGE_SCROLL_TO_SCREEN_MID_FROM_LEFT = 0x06 private const val FRAME_COUNT = 30 } private var mSelectedTimeLineView: TimeLineView? = null private var mHalfScreenWidth = 0 private var mScreenWidth = 0 private var mCallback: Callback? = null private var mCount = 0 private val mHandler = @SuppressLint("HandlerLeak") object : Handler() { override fun handleMessage(msg: Message) { when(msg.what){ MESSAGE_SCROLL_TO_SCREEN_MID_FROM_RIGHT -> { mCount++ if (mCount <= FRAME_COUNT){ val frequency = msg.arg1 val message = Message() message.what = MESSAGE_SCROLL_TO_SCREEN_MID_FROM_RIGHT message.arg1 = frequency modifyMarginStart(-frequency) sendMessageDelayed(message, 6) }else{ mCount = 0 } } MESSAGE_AUTO_SCROLL_TO_RIGHT -> { //修改控件内容器宽度 val contentContainer = mSelectedTimeLineView?.mContentContainer ?: return val containerWidth = contentContainer.width val lp = contentContainer.layoutParams lp?.width = containerWidth val width = lp?.width!! + 10 if (width > mSelectedTimeLineView?.mIvStartMaxTranslationX?:0){ return } lp.width = width contentContainer.layoutParams = lp val parent = parent as? ViewGroup val parentLp = parent?.layoutParams as? MarginLayoutParams val martinRight = parentLp?.rightMargin ?: 0 if (martinRight < mHalfScreenWidth){ modifyMarginEnd(10 ) } sendEmptyMessageDelayed(MESSAGE_AUTO_SCROLL_TO_RIGHT, 10) } MESSAGE_AUTO_SCROLL_TO_LEFT -> { //修改控件内容器宽度 val contentContainer = mSelectedTimeLineView?.mContentContainer ?: return val containerWidth = contentContainer.width val lp = contentContainer.layoutParams lp?.width = containerWidth val width = lp?.width!! + 10 if (width > mSelectedTimeLineView?.mIvEndMaxTranslationX?:0){ return } lp.width = width contentContainer.layoutParams = lp modifyMarginStart(-10 ) sendEmptyMessageDelayed(MESSAGE_AUTO_SCROLL_TO_LEFT, 10) } MESSAGE_SCROLL_TO_SCREEN_LEFT -> { val current = msg.arg1 val total = msg.arg2 if (current <= total){ modifyMarginStart(10) val message = Message() message.arg1 = current + 10 message.arg2 = total message.what = MESSAGE_SCROLL_TO_SCREEN_LEFT sendMessageDelayed(message, 10) }else{ modifyMarginStart( total - current) removeMessages(MESSAGE_SCROLL_TO_SCREEN_LEFT) } } MESSAGE_SCROLL_TO_SCREEN_RIGHT -> { val current = msg.arg1 val total = msg.arg2 if (current <= total){ modifyMarginEnd(10) val message = Message() message.arg1 = current + 10 message.arg2 = total message.what = MESSAGE_SCROLL_TO_SCREEN_RIGHT sendMessageDelayed(message, 10) }else{ modifyMarginEnd(total - current) removeMessages(MESSAGE_SCROLL_TO_SCREEN_RIGHT) } } MESSAGE_SCROLL_TO_SCREEN_MID_FROM_LEFT -> { val current = msg.arg1 val total = msg.arg2 Log.d(TAG, "message current = $current") Log.d(TAG, "message total = $total") if (current <= total){ modifyMarginEnd(-10) val message = Message() message.arg1 = current + 10 message.arg2 = total message.what = MESSAGE_SCROLL_TO_SCREEN_MID_FROM_LEFT sendMessageDelayed(message, 10) }else{ modifyMarginEnd(total - current) removeMessages(MESSAGE_SCROLL_TO_SCREEN_MID_FROM_LEFT) } } } } } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super( context, attrs, defStyleAttr, defStyleRes ) { initView() } private fun initView() { mScreenWidth = DeviceUtil.getScreenWidthPx(context) mHalfScreenWidth = mScreenWidth / 2 // setOnDragListener(this) // DragHelper.setupDragSort(this) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) } override fun onTouchEvent(event: MotionEvent?): Boolean { val result = super.onTouchEvent(event) Log.d(TAG, "onTouchEvent() return $result") return result } fun setCallback(callback: Callback?){ mCallback = callback } fun addTimeLineView(timeLineView: TimeLineView?, heightDp: Float){ timeLineView?: return val lp = LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, DeviceUtil.dip2px(context, heightDp)) lp.gravity = Gravity.CENTER_VERTICAL MyDragHelper.setupDragSort(timeLineView) // MyDragHelper.setLongClick(timeLineView, mCallback) timeLineView.setMovingCallback(this) timeLineView.setOptionListener(this) addView(timeLineView, lp) } override fun onLongClick(view: View?): Boolean { val parent = parent as? ViewGroup val index = parent?.indexOfChild(view) Log.d(TAG, "index = $index") mCallback?.onItemLongClick(index) return true } override fun onStartMoving(timeLineView: TimeLineView, offsetX: Int, isMoveToLeft: Boolean) { mSelectedTimeLineView = timeLineView modifyMarginStart(offsetX) } override fun onEndMoving(timeLineView: TimeLineView, offsetX: Int, isMoveToLeft: Boolean) { mSelectedTimeLineView = timeLineView modifyMarginEnd(offsetX) } override fun onStartMoveToLeft(timeLineView: TimeLineView) { mSelectedTimeLineView = timeLineView } override fun onStartMoveToRight(timeLineView: TimeLineView) { mSelectedTimeLineView = timeLineView } override fun onEndMoveToLeft(timeLineView: TimeLineView) { mSelectedTimeLineView = timeLineView } override fun onEndMoveToRight(timeLineView: TimeLineView) { mSelectedTimeLineView = timeLineView } override fun onStartMoveToScreenLeft(timeLineView: TimeLineView) { mSelectedTimeLineView = timeLineView if (mHandler.hasMessages(MESSAGE_AUTO_SCROLL_TO_RIGHT)) { mHandler.removeMessages(MESSAGE_AUTO_SCROLL_TO_RIGHT) } mHandler.sendEmptyMessageDelayed(MESSAGE_AUTO_SCROLL_TO_RIGHT, 10) } override fun onEndMoveToScreenRight(timeLineView: TimeLineView) { mSelectedTimeLineView = timeLineView if (mHandler.hasMessages(MESSAGE_AUTO_SCROLL_TO_LEFT)) { mHandler.removeMessages(MESSAGE_AUTO_SCROLL_TO_LEFT) } mHandler.sendEmptyMessageDelayed(MESSAGE_AUTO_SCROLL_TO_LEFT, 10) } override fun onStartUp(timeLineView: TimeLineView, isLeftTranslation: Boolean) { mSelectedTimeLineView = timeLineView if (mHandler.hasMessages(MESSAGE_AUTO_SCROLL_TO_RIGHT)) { mHandler.removeMessages(MESSAGE_AUTO_SCROLL_TO_RIGHT) } val lp = layoutParams as? MarginLayoutParams val marginLeft = lp?.leftMargin ?:0 if (!isLeftTranslation){ //右移 if (marginLeft > mHalfScreenWidth){ //动画滚动到中间 Log.d(TAG, "action up 动画滚动到中间") val msg = Message() msg.what = MESSAGE_SCROLL_TO_SCREEN_MID_FROM_RIGHT val frequency = (marginLeft - mHalfScreenWidth) / FRAME_COUNT msg.arg1 = frequency.toInt() mHandler.sendMessageDelayed(msg, 30) // val timeLineViewEvent = TimeLineViewEvent() // EventBus.getDefault().post(timeLineViewEvent) }else{ Log.d(TAG, "action up 不需要滚动") } } Log.d(TAG, "marginLeft = $marginLeft") if (marginLeft < 0){ val msg = Message() msg.arg1 = 0 msg.arg2 = (0 - marginLeft) msg.what = MESSAGE_SCROLL_TO_SCREEN_LEFT mHandler.sendMessageDelayed(msg, 10) // val timeLineViewEvent = TimeLineViewEvent() // EventBus.getDefault().post(timeLineViewEvent) } } override fun onEndUp(timeLineView: TimeLineView, isLeftTranslation: Boolean) { mSelectedTimeLineView = timeLineView if (mHandler.hasMessages(MESSAGE_AUTO_SCROLL_TO_LEFT)) { mHandler.removeMessages(MESSAGE_AUTO_SCROLL_TO_LEFT) } val lp = layoutParams as? MarginLayoutParams val marginRight = lp?.rightMargin ?: 0 if (marginRight < 0){ Log.d(TAG, "action up 滚动到最右") val msg = Message() msg.arg1 = 0 msg.arg2 = (0 - marginRight) msg.what = MESSAGE_SCROLL_TO_SCREEN_RIGHT mHandler.sendMessageDelayed(msg, 10) }else{ Log.d(TAG, "action up 不滚动") } if (marginRight > mHalfScreenWidth){ val msg = Message() msg.arg1 = 0 msg.arg2 = (marginRight - mHalfScreenWidth) msg.what = MESSAGE_SCROLL_TO_SCREEN_MID_FROM_LEFT mHandler.sendMessageDelayed(msg, 10) } } override fun onClick(timeLineView: TimeLineView) { } override fun onLongClick(timeLineView: TimeLineView) { //drag timeLineView.startDrag(null, View.DragShadowBuilder(timeLineView), null, 0) } // private var mIsInDragDestination = false // override fun onDrag(v: View?, dragEvent: DragEvent?): Boolean { // val action = dragEvent?.action // when (action) { // DragEvent.ACTION_DRAG_STARTED -> { // Toast.makeText(context, "开始拖动\n x = " + dragEvent?.x + "\ny = " + dragEvent?.y, Toast.LENGTH_LONG).show() // mIsInDragDestination = false // } // DragEvent.ACTION_DRAG_ENTERED -> { // Toast.makeText(context, "进入目标区域", Toast.LENGTH_LONG).show() // mIsInDragDestination = true // } // // DragEvent.ACTION_DRAG_EXITED -> { // Toast.makeText(context, "离开", Toast.LENGTH_LONG).show() // mIsInDragDestination = false // } // // DragEvent.ACTION_DROP -> { // Toast.makeText(context, "放手\n x = " + dragEvent.getX() + "\ny = " + dragEvent.getY(), Toast.LENGTH_LONG).show() // val dragView = dragEvent.localState as? View // if (v !== dragView) { // swapViewGroupChildren(this, v, dragView) // } // } // // DragEvent.ACTION_DRAG_LOCATION -> { // } // } // return true // } private fun modifyMarginStart(marginStartOffsetX:Int){ val lp = layoutParams as? MarginLayoutParams ?: return var marginStart = 0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){ //修改控件位置 marginStart = (lp.marginStart + marginStartOffsetX) Log.d(TAG, "marginStartOffsetX = $marginStartOffsetX") lp.marginStart = marginStart }else{ marginStart = (lp.leftMargin + marginStartOffsetX) lp.leftMargin = marginStart } Log.d(TAG, "marginStart = $marginStart") layoutParams = lp } private fun modifyMarginEnd(marginEndOffsetX:Int){ val lp = layoutParams as? MarginLayoutParams ?: return var marginEnd = 0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){ //修改控件位置 marginEnd = (lp.marginEnd + marginEndOffsetX) Log.d(TAG, "marginEndOffsetX = $marginEndOffsetX") lp.marginEnd = marginEnd }else{ marginEnd = (lp.rightMargin + marginEndOffsetX) lp.rightMargin = marginEnd } Log.d(TAG, "marginStart = $marginEnd") layoutParams = lp } public interface Callback{ fun onItemLongClick(index: Int?) } }
1
null
1
1
d40e11b026eb6cd20f65e36496275d4a1c2dad3f
15,019
VideoEditorDemo
Apache License 2.0
gto-support-picasso/src/main/java/org/ccci/gto/android/common/picasso/widget/TextViewDrawableStartTarget.kt
CruGlobal
30,609,844
false
{"Gradle Kotlin DSL": 70, "Java Properties": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Proguard": 16, "EditorConfig": 1, "Text": 1, "Markdown": 1, "INI": 16, "Kotlin": 523, "Java": 74, "XML": 22, "TOML": 1, "Prolog": 1, "YAML": 4, "JSON": 1}
package org.ccci.gto.android.common.picasso.widget import android.graphics.drawable.Drawable import android.widget.TextView import org.ccci.gto.android.common.picasso.BaseViewTarget import org.ccci.gto.android.common.picasso.R class TextViewDrawableStartTarget(view: TextView) : BaseViewTarget<TextView>(view) { init { view.setTag(R.id.picasso_textViewDrawableStartTarget, this) } companion object { fun of(view: TextView) = view.getTag(R.id.picasso_textViewDrawableStartTarget) as? TextViewDrawableStartTarget ?: TextViewDrawableStartTarget(view) } public override fun updateDrawable(drawable: Drawable?) { val current = view.compoundDrawablesRelative drawable?.apply { setBounds(0, 0, intrinsicWidth, intrinsicHeight) } view.setCompoundDrawablesRelative(drawable, current[1], current[2], current[3]) } }
12
Kotlin
2
9
7506718d83c532edbdf84921338a26d86422bec6
886
android-gto-support
MIT License
compiler/testData/codegen/box/when/noElseNoMatch.kt
JakeWharton
99,388,807
false
null
fun box(): String { val x = 3 when (x) { 1 -> {} 2 -> {} } return "OK" }
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
104
kotlin
Apache License 2.0
src/main/kotlin/dp/deleteAndEarn/SolutionKt.kt
eleven-max
441,597,605
false
{"Java": 104251, "Kotlin": 41506}
package dp.deleteAndEarn import com.evan.dynamicprogramming.Common.CommonUtil //https://leetcode-cn.com/problems/delete-and-earn/ class SolutionKt { fun deleteAndEarn(nums: IntArray): Int { val array = IntArray(10001) { 0 } for (i in nums) { array[i] += i } return rob(array) } private fun rob(nums: IntArray): Int { val dp = IntArray(nums.size){0} dp[0] = nums[0] dp[1] = Math.max(nums[0], nums[1]) for (i in 2 until nums.size){ dp[i] = Math.max(dp[i-1], nums[i]+dp[i-2]) } return dp[dp.size-1] } }
1
null
1
1
2e9b234b052896c6b8be07044d2b0c6812133e66
623
Learn_Algorithm
Apache License 2.0
clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/model/CatalogsFeedCredentials.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * Pinterest REST API * Pinterest's REST API * * The version of the OpenAPI document: 5.12.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.server.api.model import com.google.gson.annotations.SerializedName import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude /** * This field is **OPTIONAL**. Use this if your feed file requires username and password. * @param password The required password for downloading a feed. * @param username The required username for downloading a feed. */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) data class CatalogsFeedCredentials ( /* The required password for downloading a feed. */ @SerializedName("password") private val _password: kotlin.String?, /* The required username for downloading a feed. */ @SerializedName("username") private val _username: kotlin.String? ) { val password get() = _password ?: throw IllegalArgumentException("password is required") val username get() = _username ?: throw IllegalArgumentException("username is required") }
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
1,344
pinterest-sdk
MIT License