path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/boomapps/steemapp/repository/preferences/SharedRepository.kt
BoomApps-LLC
137,521,625
false
{"Java": 1692011, "Kotlin": 375994, "JavaScript": 10808, "CSS": 1000, "HTML": 422}
/* * Copyright 2018, BoomApps LLC. * All rights reserved. */ package com.boomapps.steemapp.repository.preferences import com.boomapps.steemapp.repository.UserData import com.boomapps.steemapp.repository.Balance import com.boomapps.steemapp.repository.StoryInstance import com.boomapps.steemapp.repository.currency.CoinmarketcapCurrency import com.boomapps.steemapp.repository.entity.VoteState import com.boomapps.steemapp.repository.entity.profile.UserExtended /** * Created by vgrechikha on 21.03.2018. */ interface SharedRepository { fun saveUserData(userData: UserData) fun updateUserData(userData: UserData) fun updatePostingKey(newKey: String?) fun loadUserData(): UserData fun isUserLogged(): Boolean fun saveBalanceData(balance: Balance?) fun loadBalance(recalculate: Boolean): Balance fun saveStoryData(storyInstance: StoryInstance) fun loadStoryData(): StoryInstance fun saveLastTimePosting(currentTimeMillis: Long) fun loadLastTimePosting(): Long fun isFirstLaunch(): Boolean fun setFirstLaunchState(isFirst: Boolean) fun saveSteemCurrency(currency: CoinmarketcapCurrency) fun saveSBDCurrency(currency: CoinmarketcapCurrency) fun saveUserExtendedData(data: UserExtended) fun saveTotalVestingData(data: Array<Double>) fun clearAllData() fun saveSuccessfulPostingNumber(num: Int) fun loadSuccessfulPostingNumber(): Int fun saveVotingState(state: VoteState) fun loadVotingState(): VoteState }
6
Java
3
3
f8ff7b430b221dc12ebb1e411b881d23f6db1c75
1,517
SteemApp-Android
MIT License
jhip60video/kotlin-app/src/main/kotlin/com/mycompany/myapp/service/MailService.kt
PacktPublishing
181,413,961
false
{"Java": 3871739, "TypeScript": 2996626, "HTML": 1354807, "Kotlin": 550842, "JavaScript": 184900, "SCSS": 82425, "CSS": 38350, "Shell": 5421, "Dockerfile": 1026}
package com.mycompany.myapp.service import com.mycompany.myapp.domain.User import io.github.jhipster.config.JHipsterProperties import java.nio.charset.StandardCharsets import java.util.Locale import org.slf4j.LoggerFactory import org.springframework.context.MessageSource import org.springframework.mail.javamail.JavaMailSender import org.springframework.mail.javamail.MimeMessageHelper import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Service import org.thymeleaf.context.Context import org.thymeleaf.spring5.SpringTemplateEngine /** * Service for sending emails. * * We use the [Async] annotation to send emails asynchronously. */ @Service class MailService( private val jHipsterProperties: JHipsterProperties, private val javaMailSender: JavaMailSender, private val messageSource: MessageSource, private val templateEngine: SpringTemplateEngine ) { private val log = LoggerFactory.getLogger(MailService::class.java) @Async fun sendEmail(to: String, subject: String, content: String, isMultipart: Boolean, isHtml: Boolean) { log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content) // Prepare message using a Spring helper log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content) // Prepare message using a Spring helper val mimeMessage = javaMailSender.createMimeMessage() try { val message = MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name()) message.setTo(to) message.setFrom(jHipsterProperties.mail.from) message.setSubject(subject) message.setText(content, isHtml) javaMailSender.send(mimeMessage) log.debug("Sent email to User '{}'", to) } catch (e: Exception) { if (log.isDebugEnabled) { log.warn("Email could not be sent to user '{}'", to, e) } else { log.warn("Email could not be sent to user '{}': {}", to, e.message) } } } @Async fun sendEmailFromTemplate(user: User, templateName: String, titleKey: String) { val locale = Locale.forLanguageTag(user.langKey) val context = Context(locale) context.setVariable(USER, user) context.setVariable(BASE_URL, jHipsterProperties.mail.baseUrl) val content = templateEngine.process(templateName, context) val subject = messageSource.getMessage(titleKey, null, locale) sendEmail(user.email!!, subject, content, isMultipart = false, isHtml = true) } @Async fun sendActivationEmail(user: User) { log.debug("Sending activation email to '{}'", user.email) sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title") } @Async fun sendCreationEmail(user: User) { log.debug("Sending creation email to '{}'", user.email) sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title") } @Async fun sendPasswordResetMail(user: User) { log.debug("Sending password reset email to '{}'", user.email) sendEmailFromTemplate(user, "mail/passwordResetEmail", "email.reset.title") } companion object { private const val USER = "user" private const val BASE_URL = "baseUrl" } }
57
Java
4
2
29988104aef5240a44686aa51f64e8390c58aabb
3,539
Hands-On-JHipster-Powerful-Web-Apps-in-Spring-Boot-and-Angular
MIT License
Main/src/main/java/com/redelf/commons/security/encryption/Encryption.kt
red-elf
731,934,432
false
{"Kotlin": 540978, "Java": 41189, "Shell": 3417}
package com.redelf.commons.security.encryption import java.security.GeneralSecurityException interface Encryption<IN, OUT> { @Throws(GeneralSecurityException::class) fun encrypt(data: IN): OUT @Throws(GeneralSecurityException::class) fun decrypt(source: OUT): IN }
0
Kotlin
1
0
7996ea1b0a323f17dc87a4b55a5481a0254be85e
284
Android-Toolkit
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/ui/reader/setting/ReadingModeType.kt
emodatt08
347,666,326
true
{"Kotlin": 1710636}
package eu.kanade.tachiyomi.ui.reader.setting import androidx.annotation.StringRes import eu.kanade.tachiyomi.R import kotlin.math.max enum class ReadingModeType(val prefValue: Int, @StringRes val stringRes: Int) { DEFAULT(0, R.string.default_viewer), LEFT_TO_RIGHT(1, R.string.left_to_right_viewer), RIGHT_TO_LEFT(2, R.string.right_to_left_viewer), VERTICAL(3, R.string.vertical_viewer), WEBTOON(4, R.string.webtoon_viewer), CONTINUOUS_VERTICAL(5, R.string.vertical_plus_viewer), ; companion object { fun fromPreference(preference: Int): ReadingModeType = values().find { it.prefValue == preference } ?: DEFAULT fun getNextReadingMode(preference: Int): ReadingModeType { // There's only 6 options (0 to 5) val newReadingMode = max(0, (preference + 1) % 6) return fromPreference(newReadingMode) } } }
0
null
0
0
94f5117941c368ee5cb300af0d89b39b5427b8ad
901
tachiyomi
Apache License 2.0
app/src/main/java/com/plusmobileapps/sample/workflow/root/RootWorkflow.kt
plusmobileapps
526,144,527
false
{"Kotlin": 26647}
package com.plusmobileapps.sample.workflow.root import com.plusmobileapps.sample.workflow.characters.CharactersWorkflow import com.plusmobileapps.sample.workflow.episodes.EpisodesWorkFlow import com.plusmobileapps.sample.workflow.root.RootWorkflow.State import com.squareup.workflow1.Snapshot import com.squareup.workflow1.StatefulWorkflow import com.squareup.workflow1.action import com.squareup.workflow1.renderChild import com.squareup.workflow1.ui.Screen import com.squareup.workflow1.ui.navigation.BackStackScreen import com.squareup.workflow1.ui.navigation.toBackStackScreen import javax.inject.Inject class RootWorkflow @Inject constructor( private val episodesWorkflow: EpisodesWorkFlow, private val charactersWorkflow: CharactersWorkflow ) : StatefulWorkflow<Unit, State, Nothing, BackStackScreen<*>>() { sealed class State { object Episodes : State() object Characters : State() } override fun initialState(props: Unit, snapshot: Snapshot?): State = State.Characters override fun render( renderProps: Unit, renderState: State, context: RenderContext ): BackStackScreen<*> { val backstackScreens = mutableListOf<Screen>() backstackScreens += context.renderChild( charactersWorkflow, handler = this::onCharactersOutput ) when (renderState) { State.Characters -> {/* always added to stack */ } State.Episodes -> { backstackScreens += context.renderChild(episodesWorkflow, handler = this::onEpisodesOutput) } } return backstackScreens.toBackStackScreen() } override fun snapshotState(state: State): Snapshot? = null private fun onEpisodesOutput(output: EpisodesWorkFlow.Output) = action { state = when (output) { is EpisodesWorkFlow.Output.OpenEpisodeDetail -> TODO() EpisodesWorkFlow.Output.GoBackToCharacter -> State.Characters } } private fun onCharactersOutput(output: CharactersWorkflow.Output) = action { state = when (output) { is CharactersWorkflow.Output.OpenCharacterDetail -> TODO() CharactersWorkflow.Output.OpenEpisodes -> State.Episodes } } }
2
Kotlin
0
0
fadf79224b21ce9c9c7a6e86e8d14f69554425de
2,268
workflow-anvil-sample
MIT License
kafka-reference-impl/color-chooser/src/main/kotlin/ColorPref.kt
Terkwood
191,042,808
false
null
enum class ColorPref { Black, White, Any } fun isAny(c : ColorPref): Boolean = c == ColorPref.Any
83
Rust
7
66
ec01dc3dae54e1e248d540d442caa1731f2822e4
110
BUGOUT
MIT License
app/src/main/java/com/gitfit/android/data/local/db/dao/ActivityDao.kt
adikosa
222,304,790
false
null
package com.gitfit.android.data.local.db.dao import androidx.lifecycle.LiveData import androidx.room.* import com.gitfit.android.data.local.db.entity.Activity @Dao interface ActivityDao { @Query("SELECT * FROM activities where id=:id") suspend fun getById(id: Long): Activity @Query("SELECT * FROM activities") suspend fun getAll(): List<Activity> @Query("SELECT * FROM activities where type = :activityType") suspend fun getAllByActivityType(activityType: String): List<Activity> @Query("SELECT * FROM activities") fun getLiveData(): LiveData<List<Activity>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(activity: Activity) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertList(activities: List<Activity>) @Delete suspend fun delete(activity: Activity) @Query("DELETE FROM activities") suspend fun deleteAll() }
0
Kotlin
0
1
6b39b182ae53cc5abeebee2043874004bb06a577
929
GitFit-Android
Apache License 2.0
core/ui/src/test/kotlin/com/merxury/blocker/core/ui/RuleMatchedAppItemScreenshotTests.kt
lihenggui
115,417,337
false
{"Kotlin": 2019772, "Java": 24192, "Shell": 10296, "AIDL": 771}
/* * Copyright 2023 Blocker * * 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.merxury.blocker.core.ui import androidx.activity.ComponentActivity import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onRoot import com.github.takahirom.roborazzi.captureRoboImage import com.google.accompanist.testharness.TestHarness import com.merxury.blocker.core.designsystem.theme.BlockerTheme import com.merxury.blocker.core.model.ComponentType.ACTIVITY import com.merxury.blocker.core.model.ComponentType.PROVIDER import com.merxury.blocker.core.model.data.AppItem import com.merxury.blocker.core.model.data.ComponentItem import com.merxury.blocker.core.testing.util.DefaultRoborazziOptions import com.merxury.blocker.core.testing.util.captureMultiTheme import com.merxury.blocker.core.ui.rule.MatchedAppItemHeader import com.merxury.blocker.core.ui.rule.RuleMatchedApp import dagger.hilt.android.testing.HiltTestApplication import org.junit.Rule import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.annotation.GraphicsMode import org.robolectric.annotation.LooperMode import kotlin.test.Test @RunWith(RobolectricTestRunner::class) @GraphicsMode(GraphicsMode.Mode.NATIVE) @Config(application = HiltTestApplication::class, sdk = [33], qualifiers = "480dpi") @LooperMode(LooperMode.Mode.PAUSED) class RuleMatchedAppItemScreenshotTests { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun ruleMatchedAppItem_multipleThemes() { composeTestRule.captureMultiTheme("RuleMatchedAppItem") { Surface { RuleMatchedAppItemExample() } } } @Test fun ruleMatchedAppItem_longName_multipleThemes() { composeTestRule.captureMultiTheme("RuleMatchedAppItem", "RuleMatchedAppItemLongName") { Surface { RuleMatchedAppItemExample(isLongName = true) } } } @Test fun ruleMatchedAppItem_hugeFont() { composeTestRule.setContent { CompositionLocalProvider( LocalInspectionMode provides true, ) { TestHarness(fontScale = 2f) { BlockerTheme { RuleMatchedAppItemExample() } } } } composeTestRule.onRoot() .captureRoboImage( "src/test/screenshots/RuleMatchedAppItem" + "/RuleMatchedAppItem_fontScale2.png", roborazziOptions = DefaultRoborazziOptions, ) } @Composable private fun RuleMatchedAppItemExample(isLongName: Boolean = false) { val label = if (isLongName) { "This is a very long long long long long long name " } else { "Blocker" } val componentList = remember { mutableStateListOf( ComponentItem( packageName = "com.merxury.example", name = "com.merxury.example.MainActivity", simpleName = "MainActivity", pmBlocked = true, type = ACTIVITY, ), ComponentItem( packageName = "com.merxury.example", name = "com.merxury.example.provider", simpleName = "example", type = PROVIDER, pmBlocked = false, ), ) } val ruleMatchedApp = RuleMatchedApp( app = AppItem( packageName = "com.merxury.example", label = label, packageInfo = null, ), componentList = componentList, ) MatchedAppItemHeader( ruleMatchedApp = ruleMatchedApp, expanded = isLongName, ) } }
29
Kotlin
50
789
82316a8276bd4c3999e54e0831b98be4998b944c
4,808
blocker
Apache License 2.0
app/src/main/java/com/example/compose_clean_base/data/remote/service/RegisterService.kt
samyoney
783,208,332
false
{"Kotlin": 136569}
package com.example.compose_clean_base.data.remote.service import com.example.compose_clean_base.data.model.remote.request.RegisterRequest import com.example.compose_clean_base.data.model.remote.response.RegisterResponse import retrofit2.http.Body import retrofit2.http.POST interface RegisterService { @POST("register") suspend fun fetch(@Body param: RegisterRequest): RegisterResponse }
0
Kotlin
0
7
38ebae18cd04f7533f151885746f8b90cef0099a
398
compose_clean_base
MIT License
game/core/src/com/lyeeedar/Components/PositionComponentExtensions.kt
Lyeeedar
257,323,195
false
null
package com.lyeeedar.Components import com.lyeeedar.AI.Tasks.TaskWait import com.lyeeedar.Direction import com.lyeeedar.Game.Tile import com.lyeeedar.Renderables.Animation.MoveAnimation import com.lyeeedar.Renderables.SkeletonRenderable import com.lyeeedar.SpaceSlot import com.lyeeedar.Systems.AbstractTile import com.lyeeedar.Systems.World import com.lyeeedar.Util.Point var PositionComponent.tile: Tile? get() = position as? Tile set(value) { if (value != null) position = value } fun PositionComponent.isOnTile(point: Point): Boolean { val tile = this.tile ?: return false for (x in 0 until size) { for (y in 0 until size) { val t = tile.world.grid.tryGet(tile, x, y, null) ?: continue if (t == point) return true } } return false } fun PositionComponent.getEdgeTiles(dir: Direction): com.badlogic.gdx.utils.Array<Tile> { val tile = position as? Tile ?: throw Exception("Position must be a tile!") var xstep = 0 var ystep = 0 var sx = 0 var sy = 0 if ( dir == Direction.NORTH ) { sx = 0 sy = size - 1 xstep = 1 ystep = 0 } else if ( dir == Direction.SOUTH ) { sx = 0 sy = 0 xstep = 1 ystep = 0 } else if ( dir == Direction.EAST ) { sx = size - 1 sy = 0 xstep = 0 ystep = 1 } else if ( dir == Direction.WEST ) { sx = 0 sy = 0 xstep = 0 ystep = 1 } val tiles = com.badlogic.gdx.utils.Array<Tile>(1) for (i in 0 until size) { val t = tile.world.grid.tryGet(tile, sx + xstep * i, sy + ystep * i, null) as? Tile ?: continue tiles.add(t) } return tiles } fun PositionComponent.isValidTile(t: AbstractTile, entity: Entity, checkCanSwap: Boolean = false): Boolean { for (x in 0 until size) { for (y in 0 until size) { val tile = t.world.grid.tryGet(t, x, y, null) if (tile == null || tile.wall != null || tile.contents.get(SpaceSlot.WALL) != null) { return false } else { val other = tile.contents[slot]?.get() if (other != null) { if (checkCanSwap) { if (canSwap && other.isAllies(entity)) { } else { return other == entity } } else { return other == entity } } } } } return true } fun PositionComponent.removeFromTile(entity: Entity) { if (tile == null) return for (x in 0 until size) { for (y in 0 until size) { val tile = tile!!.world.grid.tryGet(tile!!, x, y, null) ?: continue if (tile.contents[slot]?.get() == entity) tile.contents.remove(slot) } } } fun PositionComponent.addToTile(entity: Entity) { val ref = entity.getRef() val t = tile!! for (x in 0 until size) { for (y in 0 until size) { val tile = t.world.grid.tryGet(t, x, y, null) ?: continue if (tile.contents[slot]?.get() != null && tile.contents[slot]?.get() != entity) { throw RuntimeException("Tile wasnt empty! Currently contains " + tile.contents[slot]!!.entity.toString()) } tile.contents[slot] = ref } } } fun Entity.addToTile(tile: Tile, slot: SpaceSlot? = null) { val pos = addOrGet(ComponentType.Position) as PositionComponent pos.position = tile if (slot != null) pos.slot = slot pos.addToTile(this) } fun PositionComponent.doMove(t: AbstractTile, entity: Entity) { removeFromTile(entity) position = t addToTile(entity) } fun PositionComponent.moveInDirection(direction: Direction, e: Entity, world: World<*>): Boolean { val prev = world.grid.tryGet(this.position, null) ?: return false val next = world.grid.tryGet(prev, direction, null) ?: return false if (this.isValidTile(next, e)) { this.doMove(next, e) e.renderable()?.renderable?.animation = MoveAnimation.obtain().set(next, prev, 0.4f) var renderable = e.renderable()?.renderable if (renderable is SkeletonRenderable) { renderable.gotoStateForDuration("Walk", 0.45f, "Idle") } return true } else if (this.canSwap) { val contents = next.contents[this.slot]?.get() if (contents != null && e.isAllies(contents) && e.activeAbility() == null && e.combo()?.currentStep == null) { val opos = contents.position()!! if (opos.moveable && !opos.moveLocked) { val task = contents.task() if (task != null) { task.tasks.clear() task.tasks.add(TaskWait.obtain()) } opos.removeFromTile(contents) this.doMove(next, e) e.renderable()?.renderable?.animation = MoveAnimation.obtain().set(next, prev, 0.4f) var renderable = e.renderable()?.renderable if (renderable is SkeletonRenderable) { renderable.gotoStateForDuration("Walk", 0.45f, "Idle") } opos.doMove(prev, contents) contents.renderable()?.renderable?.animation = MoveAnimation.obtain().set(prev, next, 0.4f) renderable = contents.renderable()?.renderable if (renderable is SkeletonRenderable) { renderable.gotoStateForDuration("Walk", 0.45f, "Idle") } return true } } } return false }
0
Kotlin
0
0
5068af2489fa6ff52a99016bceafca5690864754
4,905
PortalClosers
Apache License 2.0
analysis/analysis-api/testData/components/dataFlowInfoProvider/exitPointSnapshot/variables/incrementPrefix.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
fun test() { var x = 0 <expr>++x</expr> consume(x) } fun consume(n: Int) {}
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
88
kotlin
Apache License 2.0
supermarket/src/main/kotlin/model/discount/Discount.kt
santukis
558,526,758
false
null
package model.discount import model.product.Product class Discount( val product: Product, val description: String, val discountAmount: Double)
0
Kotlin
0
1
396e0f071d9a425600667df7a6b1fe47123cee55
157
refactoringKatas
Apache License 2.0
app/src/main/java/io/github/muhrifqii/reactivelibrarysample/rxbinding/SimpleTextChangesKotlinActivity.kt
muhrifqii
78,018,181
false
null
/* * MIT License * * Copyright (c) 2017 <NAME> * * 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.github.muhrifqii.reactivelibrarysample.rxbinding import android.os.Bundle import android.support.design.widget.TextInputLayout import android.support.v7.app.AppCompatActivity import android.widget.EditText import android.widget.TextView import com.jakewharton.rxbinding.widget.text import com.jakewharton.rxbinding.widget.textChanges import io.github.muhrifqii.reactivelibrarysample.R import rx.functions.Func1 import rx.subscriptions.CompositeSubscription import java.util.Locale /** * Created on : 11/01/17 * Author : muhrifqii * Name : <NAME> * Github : https://github.com/muhrifqii * LinkedIn : https://linkedin.com/in/muhrifqii */ class SimpleTextChangesKotlinActivity : AppCompatActivity() { private val MESSAGE_MAX_LENGTH = 100 private val subs = CompositeSubscription() private lateinit var etMsg: EditText private lateinit var tilMsg: TextInputLayout private lateinit var tvMsg: TextView private lateinit var tvStar: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_simple_text_changes) etMsg = findViewById(R.id.et_message) as EditText tilMsg = findViewById(R.id.til_message) as TextInputLayout tvMsg = findViewById(R.id.tv_message) as TextView tvStar = findViewById(R.id.tv_star) as TextView tilMsg.isCounterEnabled = true tilMsg.counterMaxLength = MESSAGE_MAX_LENGTH } override fun onStart() { super.onStart() val obsMsg = etMsg.textChanges().filter({ text -> text.length < MESSAGE_MAX_LENGTH }) val subMsg = obsMsg.subscribe(tvMsg.text()) val subTotalStarMsg = obsMsg.map { it.split(" ") } .map { countStars(it) } .map { "Total Stars: %d".format(Locale.US, it) } .subscribe(tvStar.text()) subs.addAll(subMsg, subTotalStarMsg) } override fun onStop() { super.onStop() subs.clear() } override fun onDestroy() { super.onDestroy() } private fun countStars(source: List<String>): Int { var total = 0 for (word in source) { total = if (word.equals("star", ignoreCase = true) or word.equals("stars", ignoreCase = true)) total + 1 else total } return total } }
2
null
1
1
f77d0e223ed0f677dae1d9cc60b839539eb6825f
3,380
ReactiveLibrarySample
MIT License
presentation/ui/src/main/java/com/cupcake/ui/jobs/JobsFragment.kt
The-Cupcake-team
646,926,125
false
null
package com.cupcake.ui.jobs import android.os.Bundle import android.view.View import androidx.lifecycle.lifecycleScope import com.cupcake.ui.R import com.cupcake.ui.base.BaseFragment import com.cupcake.ui.databinding.FragmentJobsBinding import com.cupcake.ui.jobs.adapter.JobsAdapter import com.cupcake.viewmodels.jobs.JobsViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch class JobsFragment : BaseFragment<FragmentJobsBinding, JobsViewModel>( R.layout.fragment_jobs, JobsViewModel::class.java ) { override val LOG_TAG: String = this::class.java.name private lateinit var jobsAdapter: JobsAdapter override fun onViewCreated(view: View, savedInstanceState: Bundle?) { // setUpAdapter() } // private fun setUpAdapter() { // jobsAdapter = JobsAdapter(emptyList(), viewModel) // loadJobsToAdapter() //// binding?.jobsRecycler?.adapter = jobsAdapter // } // // private fun loadJobsToAdapter() { // lifecycleScope.launch(Dispatchers.Main) { // viewModel.jobsUIState.collect { // val recommendedJobs = async { JobsItem.Recommended(it.recommendedJobs) } // val topSalaryJobs = async { JobsItem.TopSalary(it.topSalaryJobs) } // val onLocationJobs = async { JobsItem.LocationJobs(it.inLocationJobs) } // val jobs = mutableListOf( // recommendedJobs.await(), // topSalaryJobs.await(), // onLocationJobs.await() // ) // jobsAdapter.setJobsItems(jobs) // } // } // } }
5
Kotlin
0
0
f215bc977d9f5288d2a4cd8d4a625371a964b2f7
1,670
Jobs-finder
MIT License
shared/src/commonMain/kotlin/markdown/compose/elements/MarkdownImage.kt
vinceglb
628,619,356
false
{"Kotlin": 206592, "Swift": 954, "Shell": 228}
package markdown.compose.elements import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import markdown.utils.findChildOfTypeRecursive import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.ast.getTextInNode import ui.components.ImageUrl @Composable internal fun MarkdownImage(content: String, node: ASTNode) { val link = node.findChildOfTypeRecursive(MarkdownElementTypes.LINK_DESTINATION)?.getTextInNode(content)?.toString() ?: return ImageUrl( url = link, contentDescription = "Markdown Image", // TODO contentScale = ContentScale.FillWidth, modifier = Modifier.fillMaxWidth() ) }
2
Kotlin
2
93
7240671bdd5e6b74ff247f7443f3e996e995f634
822
ComposeAI
Apache License 2.0
src/main/kotlin/com/simpleservice/constant/ResultCode.kt
mrgamza
637,117,330
false
null
package com.simpleservice.constant enum class ResultCode(val code: String, val message: String) { SUCCESS("0000", "Success"), DB_ERROR("1000", "Fail DB Error"), KNOWN_ERROR("9000", "Server known error") }
0
Kotlin
0
0
a7dabba15bec455c9d029146b120be6c1d1fb070
218
simple-service
MIT License
core/core/src/commonMain/kotlin/zakadabar/core/resource/LocalizedStringDelegate.kt
spxbhuhb
290,390,793
false
{"Kotlin": 2348240, "HTML": 2835, "JavaScript": 1021, "Dockerfile": 269, "Shell": 253}
/* * Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package zakadabar.core.resource import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty class LocalizedStringDelegate<T>( val key : String ) : ReadOnlyProperty<T,String> { override fun getValue(thisRef: T, property: KProperty<*>): String { return localizedStrings[key] } }
12
Kotlin
3
24
61ac92ff04eb53bff5b9a9b2649bd4866f469942
436
zakadabar-stack
Apache License 2.0
TDD_QuickSetup/ui/DetailsFragment.kt
cavigna
428,074,755
false
{"Kotlin": 21896}
package com.example.myapplication.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.activityViewModels import com.example.myapplication.databinding.FragmentDetailsBinding class DetailsFragment : Fragment() { private val viewModel by activityViewModels<MainViewModel>() private lateinit var binding: FragmentDetailsBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentDetailsBinding.inflate(layoutInflater, container, false) return binding.root } }
0
Kotlin
0
1
b544e2bdf4157f3e2593db195821e0dd3f10d929
729
Android_101
MIT License
waffle/preview/src/main/kotlin/me/donedone/waffle/preview/WaffleSampleBaseActivity.kt
TodayDoneDone
592,624,926
false
null
/* * Designed and developed by DoneDone Team 2023. * * Licensed under the MIT. * Please see full license: https://github.com/TodayDoneDone/donedone-android/blob/main/LICENSE */ package me.donedone.waffle.preview import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import me.donedone.waffle.preview.annotations.WaffleSample open class WaffleSampleBaseActivity : AppCompatActivity() { private companion object { const val MENU_INFO = "menu_info" } private var infoMenuItem: MenuItem? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) javaClass.getAnnotation(WaffleSample::class.java)?.let { waffleSample -> title = waffleSample.displayName } supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onCreateOptionsMenu(menu: Menu): Boolean { infoMenuItem = menu.add(MENU_INFO) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() return true } if (item == infoMenuItem) { Toast.makeText(this, this::class.java.simpleName, Toast.LENGTH_SHORT).show() return true } return super.onOptionsItemSelected(item) } }
6
Kotlin
0
5
56d725c1a17bb212475d0dcb7bfb44732de0ea65
1,372
donedone-android
MIT License
sdk-base/src/main/java/com/mapbox/maps/extension/observable/eventdata/SourceDataLoadedEventData.kt
UWDIEYN-NETWORK-DIGITAL-CENTER
376,704,698
true
{"Kotlin": 2736510, "Java": 88200, "Shell": 22160, "Python": 18705, "C++": 10129, "Makefile": 4787, "JavaScript": 4344, "CMake": 1201, "EJS": 1194}
package com.mapbox.maps.extension.observable.eventdata import com.google.gson.annotations.SerializedName import com.mapbox.maps.extension.observable.model.SourceDataType import com.mapbox.maps.extension.observable.model.TileID /** * The data class for source-data-loaded event data in Observer */ data class SourceDataLoadedEventData( /** * Representing timestamp taken at the time of an event creation, in microseconds, since the epoch. */ @SerializedName("begin") val begin: Long, /** * For an interval events, an optional `end` property will be present that represents timestamp taken at the time * of an event completion. */ @SerializedName("end") val end: Long?, /** * The 'id' property defines the source id. */ @SerializedName("id") val id: String, /** * The 'type' property defines if source's metadata (e.g., TileJSON) or tile has been loaded. */ @SerializedName("type") val type: SourceDataType, /** * The 'loaded' property will be set to 'true' if all source's data required for Map's visible viewport, are loaded. */ @SerializedName("loaded") val loaded: Boolean?, /** * The 'tile-id' property defines the tile id if the 'type' field equals 'tile'. */ @SerializedName("tile-id") val tileID: TileID? )
1
Kotlin
0
0
de2e75df0bb81f615accfc628d4374b23632b493
1,282
mapbox-maps-android
Apache License 2.0
partiql-cli/src/main/kotlin/org/partiql/cli/shell/Shell.kt
partiql
186,474,394
false
{"Kotlin": 6061510, "HTML": 103438, "ANTLR": 34092, "Inno Setup": 3838, "Java": 1949, "Shell": 748}
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at: * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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.partiql.cli.shell import com.google.common.base.CharMatcher import com.google.common.util.concurrent.Uninterruptibles import org.fusesource.jansi.AnsiConsole import org.jline.reader.EndOfFileException import org.jline.reader.History import org.jline.reader.LineReader import org.jline.reader.LineReaderBuilder import org.jline.reader.UserInterruptException import org.jline.reader.impl.completer.AggregateCompleter import org.jline.terminal.Terminal import org.jline.terminal.TerminalBuilder import org.jline.utils.AttributedString import org.jline.utils.AttributedStringBuilder import org.jline.utils.AttributedStyle import org.jline.utils.InfoCmp import org.joda.time.Duration import org.partiql.cli.format.ExplainFormatter import org.partiql.cli.pipeline.AbstractPipeline import org.partiql.lang.SqlException import org.partiql.lang.eval.Bindings import org.partiql.lang.eval.EvaluationException import org.partiql.lang.eval.EvaluationSession import org.partiql.lang.eval.ExprValue import org.partiql.lang.eval.PartiQLResult import org.partiql.lang.eval.delegate import org.partiql.lang.eval.namedValue import org.partiql.lang.graph.ExternalGraphException import org.partiql.lang.graph.ExternalGraphReader import org.partiql.lang.syntax.PartiQLParserBuilder import org.partiql.lang.util.ConfigurableExprValueFormatter import java.io.Closeable import java.io.File import java.io.OutputStream import java.io.PrintStream import java.nio.file.Path import java.nio.file.Paths import java.util.Locale import java.util.Properties import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.BlockingQueue import java.util.concurrent.CountDownLatch import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import javax.annotation.concurrent.GuardedBy private const val PROMPT_1 = "PartiQL> " private const val PROMPT_2 = " | " internal const val BAR_1 = "===' " internal const val BAR_2 = "--- " private const val WELCOME_MSG = "Welcome to the PartiQL shell!" private const val DEBUG_MSG = """ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ██████╗ ███████╗██████╗ ██╗ ██╗ ██████╗ ██╔══██╗██╔════╝██╔══██╗██║ ██║██╔════╝ ██║ ██║█████╗ ██████╔╝██║ ██║██║ ███╗ ██║ ██║██╔══╝ ██╔══██╗██║ ██║██║ ██║ ██████╔╝███████╗██████╔╝╚██████╔╝╚██████╔╝ ╚═════╝ ╚══════╝╚═════╝ ╚═════╝ ╚═════╝ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ """ private const val HELP = """ !list_commands Prints this message !help Prints this message !add_to_global_env Adds to the global environment key/value pairs of the supplied struct !global_env Displays the current global environment !add_graph Adds to the global environment a name and a graph supplied as Ion !add_graph_from_file Adds to the global environment a name and a graph from an Ion file !history Prints command history !exit Exits the shell !clear Clears the screen """ private val SUCCESS: AttributedStyle = AttributedStyle.DEFAULT.foreground(AttributedStyle.GREEN) private val ERROR: AttributedStyle = AttributedStyle.DEFAULT.foreground(AttributedStyle.RED) private val INFO: AttributedStyle = AttributedStyle.DEFAULT private val WARN: AttributedStyle = AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW) private val EXIT_DELAY: Duration = Duration(3000) /** * Initial work to replace the REPL with JLine3. I have attempted to keep this similar to Repl.kt, but have some * opinions on ways to clean this up in later PRs. */ val exiting = AtomicBoolean(false) val doneCompiling = AtomicBoolean(false) val donePrinting = AtomicBoolean(false) internal class Shell( output: OutputStream, private val compiler: AbstractPipeline, initialGlobal: Bindings<ExprValue>, private val config: ShellConfiguration = ShellConfiguration() ) { private val homeDir: Path = Paths.get(System.getProperty("user.home")) private val globals = ShellGlobalBinding().add(initialGlobal) private var previousResult = ExprValue.nullValue private val out = PrintStream(output) private val currentUser = System.getProperty("user.name") private val inputs: BlockingQueue<RunnablePipeline.Input> = ArrayBlockingQueue(1) private val results: BlockingQueue<PartiQLResult> = ArrayBlockingQueue(1) private var pipelineService: ExecutorService = Executors.newFixedThreadPool(1) private val values: BlockingQueue<ExprValue> = ArrayBlockingQueue(1) private var printingService: ExecutorService = Executors.newFixedThreadPool(1) fun start() { val interrupter = ThreadInterrupter() val exited = CountDownLatch(1) pipelineService.submit(RunnablePipeline(inputs, results, compiler, doneCompiling)) printingService.submit(RunnableWriter(out, ConfigurableExprValueFormatter.pretty, values, donePrinting)) Runtime .getRuntime() .addShutdownHook( Thread { exiting.set(true) interrupter.interrupt() Uninterruptibles.awaitUninterruptibly(exited, EXIT_DELAY.millis, TimeUnit.MILLISECONDS) } ) try { AnsiConsole.systemInstall() run(exiting) } catch (ex: java.lang.Exception) { ex.printStackTrace() } finally { exited.countDown() interrupter.close() AnsiConsole.systemUninstall() } } private val signalHandler = Terminal.SignalHandler { sig -> if (sig == Terminal.Signal.INT) { exiting.set(true) } } private fun run(exiting: AtomicBoolean) = TerminalBuilder.builder() .name("PartiQL") .nativeSignals(true) .signalHandler(signalHandler) .build().use { terminal -> val highlighter = when { this.config.isMonochrome -> null else -> ShellHighlighter() } val completer = AggregateCompleter(CompleterDefault()) val reader = LineReaderBuilder.builder() .terminal(terminal) .parser(ShellParser) .completer(completer) .option(LineReader.Option.GROUP_PERSIST, true) .option(LineReader.Option.AUTO_LIST, true) .option(LineReader.Option.CASE_INSENSITIVE, true) .variable(LineReader.LIST_MAX, 10) .highlighter(highlighter) .expander(ShellExpander) .variable(LineReader.HISTORY_FILE, homeDir.resolve(".partiql/.history")) .variable(LineReader.SECONDARY_PROMPT_PATTERN, PROMPT_2) .build() out.info(WELCOME_MSG) out.info("Typing mode: ${compiler.options.typingMode.name}") out.info("Using version: ${retrievePartiQLVersionAndHash()}") if (compiler is AbstractPipeline.PipelineDebug) { out.println("\n\n") out.success(DEBUG_MSG) out.println("\n\n") } while (!exiting.get()) { val line: String = try { reader.readLine(PROMPT_1) } catch (ex: UserInterruptException) { if (ex.partialLine.isNotEmpty()) { reader.history.add(ex.partialLine) } continue } catch (ex: EndOfFileException) { out.info("^D") return } // Pretty print AST if (line.endsWith("\n!!")) { printAST(line.removeSuffix("!!")) continue } if (line.isBlank()) { out.success("OK!") continue } // Handle commands val command = when (val end: Int = CharMatcher.`is`(';').or(CharMatcher.whitespace()).indexIn(line)) { -1 -> "" else -> line.substring(0, end) }.lowercase(Locale.ENGLISH).trim() when (command) { "!exit" -> return "!add_to_global_env" -> { // Consider PicoCLI + Jline, but it doesn't easily place nice with commands + raw SQL // https://github.com/partiql/partiql-lang-kotlin/issues/63 val arg = requireInput(line, command) ?: continue executeAndPrint { val locals = refreshBindings() val result = evaluatePartiQL( arg, locals, exiting ) as PartiQLResult.Value globals.add(result.value.bindings) result } continue } "!add_graph" -> { val input = requireInput(line, command) ?: continue val (name, graphStr) = requireTokenAndMore(input, command) ?: continue bringGraph(name, graphStr) continue } "!add_graph_from_file" -> { val input = requireInput(line, command) ?: continue val (name, filename) = requireTokenAndMore(input, command) ?: continue val graphStr = readTextFile(filename) ?: continue bringGraph(name, graphStr) continue } "!global_env" -> { executeAndPrint { AbstractPipeline.convertExprValue(globals.asExprValue()) } continue } "!clear" -> { terminal.puts(InfoCmp.Capability.clear_screen) terminal.flush() continue } "!history" -> { for (entry in reader.history) { out.println(entry.pretty()) } continue } "!list_commands", "!help" -> { out.info(HELP) continue } } // Execute PartiQL executeAndPrint { val locals = refreshBindings() evaluatePartiQL(line, locals, exiting) } } out.println("Thanks for using PartiQL!") } /** After a command [detectedCommand] has been detected to start the user input, * analyze the entire [wholeLine] user input again, expecting to find more input after the command. * Returns the extra input or null if none present. */ private fun requireInput(wholeLine: String, detectedCommand: String): String? { val input = wholeLine.trim().removePrefix(detectedCommand).trim() if (input.isEmpty() || input.isBlank()) { out.error("Command $detectedCommand requires input.") return null } return input } private fun requireTokenAndMore(input: String, detectedCommand: String): Pair<String, String>? { val trimmed = input.trim() val n = trimmed.indexOf(' ') if (n == -1) { out.error("Command $detectedCommand, after token $trimmed, requires more input.") return null } val token = trimmed.substring(0, n) val rest = trimmed.substring(n).trim() return Pair(token, rest) } private fun readTextFile(filename: String): String? = try { val file = File(filename) file.readText() } catch (ex: Exception) { out.error("Could not read text from file '$filename'${ex.message?.let { ":\n$it" } ?: "."}") null } /** Prepare bindings to use for the next evaluation. */ private fun refreshBindings(): Bindings<ExprValue> { return Bindings.buildLazyBindings<ExprValue> { addBinding("_") { previousResult } }.delegate(globals.bindings) } /** Evaluate a textual PartiQL query [textPartiQL] in the context of given [bindings]. */ private fun evaluatePartiQL( textPartiQL: String, bindings: Bindings<ExprValue>, exiting: AtomicBoolean ): PartiQLResult { doneCompiling.set(false) inputs.put( RunnablePipeline.Input( textPartiQL, EvaluationSession.build { globals(bindings) user(currentUser) } ) ) return catchCancellation( doneCompiling, exiting, pipelineService, PartiQLResult.Value(value = ExprValue.newString("Compilation cancelled.")) ) { pipelineService = Executors.newFixedThreadPool(1) pipelineService.submit(RunnablePipeline(inputs, results, compiler, doneCompiling)) } ?: results.poll(5, TimeUnit.SECONDS)!! } private fun bringGraph(name: String, graphIonText: String) { try { val graph = ExprValue.newGraph(ExternalGraphReader.read(graphIonText)) val namedGraph = graph.namedValue(ExprValue.newString(name)) globals.add(Bindings.ofMap(mapOf(name to namedGraph))) out.info("""Bound identifier "$name" to a graph. """) } catch (ex: ExternalGraphException) { out.error(ex.message) } } private fun executeAndPrint(func: () -> PartiQLResult) { val result: PartiQLResult? = try { func.invoke() } catch (ex: SqlException) { out.error(ex.generateMessage()) out.error(ex.message) null // signals that there was an error } catch (ex: NotImplementedError) { out.error(ex.message ?: "kotlin.NotImplementedError was raised") null // signals that there was an error } printPartiQLResult(result) } private fun printPartiQLResult(result: PartiQLResult?) { when (result) { null -> { out.error("ERROR!") } is PartiQLResult.Value -> { try { donePrinting.set(false) values.put(result.value) catchCancellation(donePrinting, exiting, printingService, 1) { printingService = Executors.newFixedThreadPool(1) printingService.submit( RunnableWriter( out, ConfigurableExprValueFormatter.pretty, values, donePrinting ) ) } } catch (ex: EvaluationException) { // should not need to do this here; see https://github.com/partiql/partiql-lang-kotlin/issues/1002 out.error(ex.generateMessage()) out.error(ex.message) return } out.success("OK!") } is PartiQLResult.Explain.Domain -> { val explain = ExplainFormatter.format(result) out.println(explain) out.success("OK!") } is PartiQLResult.Insert, is PartiQLResult.Replace, is PartiQLResult.Delete -> { out.warn("Insert/Replace/Delete are not yet supported") } } out.flush() } /** * If nothing was caught and execution finished: return null * If something was caught: resets service and returns defaultReturn */ private fun <T> catchCancellation( doneExecuting: AtomicBoolean, cancellationFlag: AtomicBoolean, service: ExecutorService, defaultReturn: T, resetService: () -> Unit ): T? { while (!doneExecuting.get()) { if (exiting.get()) { service.shutdown() service.shutdownNow() when (service.awaitTermination(2, TimeUnit.SECONDS)) { true -> { cancellationFlag.set(false) doneExecuting.set(false) resetService() return defaultReturn } false -> throw Exception("Printing service couldn't terminate") } } } return null } private fun retrievePartiQLVersionAndHash(): String { val properties = Properties() properties.load(this.javaClass.getResourceAsStream("/partiql.properties")) return "${properties.getProperty("version")}-${properties.getProperty("commit")}" } private fun printAST(query: String) { if (query.isNotBlank()) { val parser = PartiQLParserBuilder.standard().build() val ast = try { parser.parseAstStatement(query) } catch (ex: SqlException) { out.error(ex.generateMessage()) out.error(ex.message) out.error("ERROR!") out.flush() return } val explain = PartiQLResult.Explain.Domain(value = ast, format = null) val output = ExplainFormatter.format(explain) out.println(output) out.success("OK!") out.flush() } } /** * A configuration class representing any configurations specified by the user * @param isMonochrome specifies the removal of syntax highlighting */ class ShellConfiguration(val isMonochrome: Boolean = false) } /** * Pretty print a History.Entry with a gutter for the entry index */ private fun History.Entry.pretty(): String { val entry = StringBuilder() for (line in this.line().lines()) { entry.append('\t').append(line).append('\n') } return AttributedStringBuilder() .style(AttributedStyle.DEFAULT.foreground(AttributedStyle.CYAN)) .append(java.lang.String.format("%5d", this.index() + 1)) .style(AttributedStyle.DEFAULT) .append(entry.trimEnd()) .toAnsi() } private fun ansi(string: String, style: AttributedStyle) = AttributedString(string, style).toAnsi() private fun PrintStream.success(string: String) = this.println(ansi(string, SUCCESS)) private fun PrintStream.error(string: String) = this.println(ansi(string, ERROR)) internal fun PrintStream.info(string: String) = this.println(ansi(string, INFO)) private fun PrintStream.warn(string: String) = this.println(ansi(string, WARN)) private class ThreadInterrupter : Closeable { private val thread = Thread.currentThread() @GuardedBy("this") private var processing = true @Synchronized fun interrupt() { if (processing) { thread.interrupt() } } @Synchronized override fun close() { processing = false Thread.interrupted() } }
278
Kotlin
60
527
7e3625f8f240a557d15633a6b578b5772b55ed8b
20,240
partiql-lang-kotlin
Apache License 2.0
mbingresskit/src/test/java/com/daimler/mbingresskit/implementation/network/api/UserApiTest.kt
Daimler
199,815,262
false
null
package com.daimler.mbingresskit.implementation.network.api import com.daimler.mbingresskit.common.UnitPreferences import com.daimler.mbingresskit.implementation.network.model.biometric.UserBiometricActivationStateRequest import com.daimler.mbingresskit.implementation.network.model.pin.ChangePinRequest import com.daimler.mbingresskit.implementation.network.model.pin.LoginUserRequest import com.daimler.mbingresskit.implementation.network.model.pin.SetPinRequest import com.daimler.mbingresskit.implementation.network.model.profilefields.FieldOwnerTypeResponse import com.daimler.mbingresskit.implementation.network.model.profilefields.ProfileDataFieldRelationshipTypeResponse import com.daimler.mbingresskit.implementation.network.model.profilefields.ProfileFieldUsageResponse import com.daimler.mbingresskit.implementation.network.model.user.ApiAccountIdentifier import com.daimler.mbingresskit.implementation.network.model.user.create.CreateUserRequest import com.daimler.mbingresskit.implementation.network.model.user.fetch.UserPinStatusResponse import com.daimler.mbingresskit.implementation.network.model.user.update.UpdateUserRequest import com.daimler.testutils.coroutines.TestCoroutineExtension import io.mockk.mockk import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.assertj.core.api.SoftAssertions import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.net.HttpURLConnection @ExperimentalCoroutinesApi @ExtendWith(SoftAssertionsExtension::class, TestCoroutineExtension::class) class UserApiTest { private lateinit var mockServer: MockWebServer private lateinit var userApi: UserApi @BeforeEach fun setUp() { mockServer = MockWebServer() userApi = Retrofit.Builder() .client(OkHttpClient.Builder().build()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(mockServer.url("/")) .build() .create(UserApi::class.java) } @AfterEach fun tearDown() { mockServer.shutdown() } @Test fun `send pin call with valid data`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK, LOGIN_JSON_FILE)) runBlocking { val loginUserResponse = userApi.sendTan( body = LoginUserRequest("<EMAIL>", COUNTRY_CODE, "de-DE", "nonce") ).body() assertEquals(true, loginUserResponse?.isEmail) assertEquals("johnneumann", loginUserResponse?.userName) } } @ParameterizedTest @ValueSource( ints = [ HttpURLConnection.HTTP_BAD_REQUEST, HttpURLConnection.HTTP_INTERNAL_ERROR, HttpURLConnection.HTTP_BAD_GATEWAY, HttpURLConnection.HTTP_UNAUTHORIZED, HttpURLConnection.HTTP_NOT_FOUND ] ) fun `send pin call with different http response`(responseCode: Int) { mockServer.enqueue(createMockResponse(responseCode)) runBlocking { val loginUserResponse = userApi.sendTan( body = LoginUserRequest("thisisnotanemail", "asdf", "asdf-ASDF", "nonce") ).body() assertEquals(null, loginUserResponse) } } @Test fun `fetch user data`(softly: SoftAssertions) { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK, USER_JSON_FILE)) runBlocking { val userTokenResponse = userApi.fetchUserData( jwtToken = JWT_TOKEN, ).body() softly.assertThat(userTokenResponse).isNotNull softly.assertThat(userTokenResponse?.ciamId).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.firstName).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.lastName1).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.lastName2).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.birthday).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.email).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.mobilePhone).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.landlinePhone).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.accountCountryCode).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.preferredLanguageCode).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.createdAt).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.updatedAt).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.title).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.salutationCode).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.taxNumber).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.accountVerified).isEqualTo(true) softly.assertThat(userTokenResponse?.isEmailVerified).isEqualTo(true) softly.assertThat(userTokenResponse?.isMobileVerified).isEqualTo(true) // Address softly.assertThat(userTokenResponse?.address).isNotNull softly.assertThat(userTokenResponse?.address?.countryCode).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.state).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.province).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.street).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.houseNumber).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.zipCode).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.city).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.streetType).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.houseName).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.floorNumber).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.doorNumber).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.addressLine1).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.addressLine2).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.addressLine3).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(userTokenResponse?.address?.postOfficeBox).isEqualTo(JSON_FIELD_VALUE) // UserPinStatus assertEquals(UserPinStatusResponse.SET, userTokenResponse?.userPinStatus) // UserCommunicationPreference softly.assertThat(userTokenResponse?.communicationPreference).isNotNull softly.assertThat(userTokenResponse?.communicationPreference?.contactByPhone) .isEqualTo(true) softly.assertThat(userTokenResponse?.communicationPreference?.contactByLetter) .isEqualTo(true) softly.assertThat(userTokenResponse?.communicationPreference?.contactByMail) .isEqualTo(true) softly.assertThat(userTokenResponse?.communicationPreference?.contactBySms) .isEqualTo(true) // UserUnitPreferences softly.assertThat(userTokenResponse?.unitPreferences).isNotNull softly.assertThat(userTokenResponse?.unitPreferences?.clockHours) .isEqualTo(UnitPreferences.ClockHoursUnits.TYPE_24H) softly.assertThat(userTokenResponse?.unitPreferences?.speedDistance) .isEqualTo(UnitPreferences.SpeedDistanceUnits.KILOMETERS) softly.assertThat(userTokenResponse?.unitPreferences?.consumptionCo) .isEqualTo(UnitPreferences.ConsumptionCoUnits.LITERS_PER_100_KILOMETERS) softly.assertThat(userTokenResponse?.unitPreferences?.consumptionEv) .isEqualTo(UnitPreferences.ConsumptionEvUnits.KILOWATT_HOURS_PER_100_KILOMETERS) softly.assertThat(userTokenResponse?.unitPreferences?.consumptionGas) .isEqualTo(UnitPreferences.ConsumptionGasUnits.KILOGRAM_PER_100_KILOMETERS) softly.assertThat(userTokenResponse?.unitPreferences?.tirePressure) .isEqualTo(UnitPreferences.TirePressureUnits.KILOPASCAL) softly.assertThat(userTokenResponse?.unitPreferences?.temperature) .isEqualTo(UnitPreferences.TemperatureUnits.CELSIUS) // ApiAccountIdentifier softly.assertThat(userTokenResponse?.accountIdentifier) .isEqualTo(ApiAccountIdentifier.EMAIL) } } @ParameterizedTest @ValueSource( ints = [ HttpURLConnection.HTTP_BAD_REQUEST, HttpURLConnection.HTTP_INTERNAL_ERROR, HttpURLConnection.HTTP_BAD_GATEWAY, HttpURLConnection.HTTP_UNAUTHORIZED, HttpURLConnection.HTTP_NOT_FOUND ] ) fun `fetch user data with different http response`(responseCode: Int) { mockServer.enqueue(createMockResponse(responseCode)) runBlocking { val userTokenResponse = userApi.fetchUserData( jwtToken = JWT_TOKEN, ).body() assertEquals(null, userTokenResponse) } } @Test fun `create user data`(softly: SoftAssertions) { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK, CREATE_USER_JSON_FILE)) val createUserRequest = mockk<CreateUserRequest>() runBlocking { val createUserResponse = userApi.createUser( locale = HEADER_LOCALE, body = createUserRequest ).body() softly.assertThat(createUserResponse?.email).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(createUserResponse?.firstName).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(createUserResponse?.lastName).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(createUserResponse?.username).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(createUserResponse?.userId).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(createUserResponse?.phone).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(createUserResponse?.countryCode).isEqualTo(JSON_FIELD_VALUE) softly.assertThat(createUserResponse?.communicationPreference).isEqualTo(null) } } @ParameterizedTest @ValueSource( ints = [ HttpURLConnection.HTTP_BAD_REQUEST, HttpURLConnection.HTTP_INTERNAL_ERROR, HttpURLConnection.HTTP_BAD_GATEWAY, HttpURLConnection.HTTP_UNAUTHORIZED, HttpURLConnection.HTTP_NOT_FOUND ] ) fun `create user data with different http response`(responseCode: Int) { mockServer.enqueue(createMockResponse(responseCode)) val createUserRequest = mockk<CreateUserRequest>() runBlocking { val createUserResponse = userApi.createUser( locale = HEADER_LOCALE, body = createUserRequest ).body() assertEquals(null, createUserResponse) } } @Test fun `update user data`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK, UPDATE_USER_JSON_FILE)) val updateUserRequest = mockk<UpdateUserRequest>() runBlocking { val userTokenResponse = userApi.updateUser( jwtToken = JWT_TOKEN, countryCode = COUNTRY_CODE, body = updateUserRequest ).body() assertEquals(TIMESTAMP_EXAMPLE, userTokenResponse?.updatedAt) } } @ParameterizedTest @ValueSource( ints = [ HttpURLConnection.HTTP_BAD_REQUEST, HttpURLConnection.HTTP_INTERNAL_ERROR, HttpURLConnection.HTTP_BAD_GATEWAY, HttpURLConnection.HTTP_UNAUTHORIZED, HttpURLConnection.HTTP_NOT_FOUND ] ) fun `update user data with different http response`(responseCode: Int) { mockServer.enqueue(createMockResponse(responseCode)) val updateUserRequest = mockk<UpdateUserRequest>() runBlocking { val userTokenResponse = userApi.updateUser( jwtToken = JWT_TOKEN, countryCode = COUNTRY_CODE, body = updateUserRequest ).body() assertEquals(null, userTokenResponse) } } @Test fun `delete user data`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK)) runBlocking { val responseBody = userApi.deleteUser( jwtToken = JWT_TOKEN, countryCode = COUNTRY_CODE ).body() assertNotNull(responseBody) } } @Test fun `fetch profile picture bytes 200`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK)) runBlocking { val responseBody = userApi.fetchProfilePictureIfModified( jwtToken = JWT_TOKEN, eTag = null ).body() assertNotNull(responseBody) } } @Test fun `fetch profile picture bytes 304`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_NOT_MODIFIED)) runBlocking { val responseBody = userApi.fetchProfilePictureIfModified( jwtToken = JWT_TOKEN, eTag = "" ).body() assertNull(responseBody) } } @Test fun `update profile picture`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK)) runBlocking { val responseBody = userApi.updateProfilePicture( jwtToken = JWT_TOKEN, image = ByteArray(1234).toRequestBody(MEDIA_TYPE.toMediaTypeOrNull(), 0) ).body() assertNotNull(responseBody) } } @Test fun `fetch countries`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK, COUNTRIES_JSON_FILE)) runBlocking { val responseBody = userApi.fetchCountries( locale = HEADER_LOCALE ).body() assertNotNull(responseBody) val countryResponse = responseBody?.first() assertEquals(JSON_FIELD_VALUE, countryResponse?.countryCode) assertEquals(JSON_FIELD_VALUE, countryResponse?.countryName) assertEquals(null, countryResponse?.instance) assertEquals(JSON_FIELD_VALUE, countryResponse?.legalRegion) assertEquals(true, countryResponse?.connectCountry) assertEquals(true, countryResponse?.natconCountry) assertEquals(JSON_FIELD_VALUE, countryResponse?.locales?.first()?.localeCode) } } @Test fun `set pin`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK)) val setPinRequest = mockk<SetPinRequest>() runBlocking { val responseBody = userApi.setPin( jwtToken = JWT_TOKEN, pinRequest = setPinRequest ).body() assertNotNull(responseBody) } } @Test fun `change pin`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK)) val changePinRequest = mockk<ChangePinRequest>() runBlocking { val responseBody = userApi.changePin( jwtToken = JWT_TOKEN, pinRequest = changePinRequest ).body() assertNotNull(responseBody) } } @Test fun `delete pin`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK)) runBlocking { val responseBody = userApi.deletePin( jwtToken = JWT_TOKEN, currentPin = "12345" ).body() assertNotNull(responseBody) } } @Test fun `send biometric activation`() { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK)) val userBiometricActivationStateRequest = mockk<UserBiometricActivationStateRequest>() runBlocking { val sendBiometricActivationResponse = userApi.sendBiometricActivation( jwtToken = JWT_TOKEN, countryCode = COUNTRY_CODE, body = userBiometricActivationStateRequest ).body() assertNotNull(sendBiometricActivationResponse) } } @Test fun `fetch profile fields`(softly: SoftAssertions) { mockServer.enqueue(createMockResponse(HttpURLConnection.HTTP_OK, PROFILE_JSON_FILE)) runBlocking { val profileFieldsDataResponse = userApi.fetchProfileFields( headerLocale = HEADER_LOCALE, countryCode = COUNTRY_CODE ).body() val customerDataFieldResponse = profileFieldsDataResponse?.customerDataFields?.first() softly.assertThat(customerDataFieldResponse).isNotNull softly.assertThat(customerDataFieldResponse?.sequenceOrder).isEqualTo(0) softly.assertThat(customerDataFieldResponse?.fieldUsageResponse) .isEqualTo(ProfileFieldUsageResponse.INVISIBLE) val fieldValidation = customerDataFieldResponse?.fieldValidation softly.assertThat(fieldValidation?.minLength).isEqualTo(0) softly.assertThat(fieldValidation?.maxLength).isEqualTo(0) softly.assertThat(fieldValidation?.regularExpression).isEqualTo(JSON_FIELD_VALUE) val selectableValues = customerDataFieldResponse?.selectableValues softly.assertThat(selectableValues?.matchSelectableValueByKey).isEqualTo(true) softly.assertThat(selectableValues?.defaultSelectableValueKey) .isEqualTo(JSON_FIELD_VALUE) softly.assertThat(selectableValues?.selectableValues?.first()?.key) .isEqualTo(JSON_FIELD_VALUE) softly.assertThat(selectableValues?.selectableValues?.first()?.description) .isEqualTo(JSON_FIELD_VALUE) val groupDependencyResponse = profileFieldsDataResponse?.groupDependencies?.first() softly.assertThat(groupDependencyResponse?.fieldType) .isEqualTo(ProfileDataFieldRelationshipTypeResponse.GROUP) val fieldDependencyResponse = profileFieldsDataResponse?.fieldDependencies?.first() softly.assertThat(fieldDependencyResponse?.fieldOwnerType) .isEqualTo(FieldOwnerTypeResponse.ACCOUNT) softly.assertThat(fieldDependencyResponse?.fieldType) .isEqualTo(ProfileDataFieldRelationshipTypeResponse.GROUP) } } private fun createMockResponse(responseCode: Int, jsonFilePath: String? = null) = MockResponse().apply { setResponseCode(responseCode) jsonFilePath?.let { val resource = UserApiTest::class.java.getResource(it) val readText = resource?.readText() readText?.let { text -> setBody(text) } } } companion object { private const val JSON_FIELD_VALUE = "string" private const val JWT_TOKEN = "MyJwtToken" private const val HEADER_LOCALE = "de" private const val COUNTRY_CODE = "DE" private const val TIMESTAMP_EXAMPLE = "2020-03-18T15:31:33.148Z" private const val MEDIA_TYPE = "image/jpeg" // JSON Files private const val LOGIN_JSON_FILE = "/login_200.json" private const val USER_JSON_FILE = "/get_user_200.json" private const val CREATE_USER_JSON_FILE = "/post_user_200.json" private const val UPDATE_USER_JSON_FILE = "/put_user_200.json" private const val COUNTRIES_JSON_FILE = "/get_countries_200.json" private const val PROFILE_JSON_FILE = "/get_profile_fields_200.json" } }
1
null
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
20,826
MBSDK-Mobile-Android
MIT License
UIViewLess/src/main/java/com/angcyo/uiview/less/ContainerActivity.kt
zhilangtaosha
223,696,624
true
{"Gradle": 15, "Markdown": 1, "Text": 1, "Ignore List": 4, "Proguard": 3, "XML": 468, "Java": 514, "Kotlin": 184, "JSON": 4, "Java Properties": 2}
package com.angcyo.uiview.less import android.content.Intent import android.content.pm.ActivityInfo import com.angcyo.uiview.less.base.activity.BasePermissionActivity import com.angcyo.uiview.less.kotlin.handleTargetFragment /** * 容器Activity, 用来当做Fragment的载体 * Email:[email protected] * @author angcyo * @date 2019/10/24 * Copyright (c) 2019 ShenZhen O&M Cloud Co., Ltd. All rights reserved. */ open class ContainerActivity : BasePermissionActivity() { override fun toMain() { } override fun handleIntent(intent: Intent?) { handleTargetFragment(intent, mActivityInfo?.launchMode ?: ActivityInfo.LAUNCH_MULTIPLE) } }
0
null
2
0
8a09b91edaa4a21a43b356f67d3e063e72df3a19
646
UIKit
MIT License
TeamCode/src/main/kotlin/org/firstinspires/ftc/teamcode/opModes/auto/SampleAuto.kt
ftc13100
662,761,834
false
{"Java": 41907, "Kotlin": 3287}
package org.firstinspires.ftc.teamcode.opModes.auto class SampleAuto { }
1
null
1
1
556988cf21d8cee870bd9a46dfa78b66c9ef7bfc
73
Programming-Practice-2023
BSD 3-Clause Clear License
Acornote_Kotlin/app/src/main/java/tonnysunm/com/acornote/ui/drawer/DrawerFragment.kt
tonnylitao
77,864,942
false
{"Swift": 154786, "Kotlin": 99077, "JavaScript": 564, "Ruby": 559}
package tonnysunm.com.acornote.ui.drawer import android.content.Context import android.graphics.Rect import android.os.Bundle import android.util.AttributeSet import android.view.* import android.widget.TextView import androidx.core.view.forEach import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import com.google.android.material.navigation.NavigationView import tonnysunm.com.acornote.R import tonnysunm.com.acornote.databinding.FragmentDrawerBinding import tonnysunm.com.acornote.model.NoteFilter import tonnysunm.com.acornote.ui.HomeSharedViewModel class DrawerFragment : Fragment() { private val mViewModel by viewModels<DrawerViewModel>() private val homeSharedModel by activityViewModels<HomeSharedViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val fragment = this val binding = FragmentDrawerBinding.inflate(inflater, container, false).apply { lifecycleOwner = fragment viewModel = fragment.mViewModel } mViewModel.allNotesCountLiveData.observe(viewLifecycleOwner, Observer { val item = binding.navView.menu.findItem(R.id.nav_all) val textView = item.actionView.findViewById<TextView>(R.id.notes_count) textView.text = it.toString() }) mViewModel.starCountLiveData.observe(viewLifecycleOwner, Observer { val item = binding.navView.menu.findItem(R.id.nav_star) val textView = item.actionView.findViewById<TextView>(R.id.notes_count) textView.text = it.toString() }) mViewModel.data.observe(viewLifecycleOwner, Observer { val itemIds = mutableListOf<Int>() binding.navView.menu.forEach { item -> if (item.groupId == R.id.menu_group_labels && item.itemId != R.id.menu_group_labels_title ) { itemIds.add(item.itemId) } } itemIds.forEach { id -> binding.navView.menu.removeItem(id) } // it.forEachIndexed { index, labelWrapper -> val itemId = labelWrapper.label.id.toInt() val item = binding.navView.menu.add( R.id.menu_group_labels, itemId, index, labelWrapper.label.title // + "_" + labelWrapper.label.id + "_" + labelWrapper.noteCount ).setActionView(R.layout.drawer_item) .setCheckable(true) homeSharedModel.noteFilterLiveData.value?.let { filter -> item.isChecked = item.isChecked(filter) } val textView = item.actionView.findViewById<TextView>(R.id.notes_count) textView.text = labelWrapper.noteCount.toString() } binding.navView.invalidate() }) val navView = binding.navView homeSharedModel.noteFilterLiveData.observe(viewLifecycleOwner, Observer { val drawer = activity?.findViewById(R.id.drawer_layout) as? DrawerLayout if (drawer?.isOpen == true) { drawer.closeDrawers() } updateMenuChecked(it) }) navView.setNavigationItemSelectedListener { item -> homeSharedModel.setFilter(item.noteFilter) true } return binding.root } private fun updateMenuChecked(filter: NoteFilter) { val menu = (view as? NavigationView)?.menu menu?.forEach { menuItem -> menuItem.isChecked = menuItem.isChecked(filter) } } } private val MenuItem.noteFilter: NoteFilter get() = when (itemId) { R.id.nav_all -> NoteFilter.All R.id.nav_star -> NoteFilter.Star else -> NoteFilter.ByLabel(itemId, title.toString()) } private fun MenuItem.isChecked(filter: NoteFilter) = when (itemId) { R.id.nav_all -> filter == NoteFilter.All R.id.nav_star -> filter == NoteFilter.Star else -> itemId == filter.labelId } class AllowChildInterceptTouchEventDrawerLayout(context: Context, attrs: AttributeSet) : DrawerLayout(context, attrs) { override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { val drawer = findViewById(R.id.fragment_drawer) as? View val scroll = drawer?.findViewById(R.id.color_tag_fragment) as? View if (scroll != null) { val rect = Rect() scroll.getHitRect(rect) if (ev.y > rect.top) { return false } } return super.onInterceptTouchEvent(ev) } }
0
Swift
5
6
b859c81debc8dbbae398c1b288829410ae725911
4,900
Acornote
Apache License 2.0
app/src/main/java/com/vincenzopavano/discounttracker/data/remote/DiscountApi.kt
VincenzoPavano
146,538,603
false
null
package com.vincenzopavano.discounttracker.data.remote import com.vincenzopavano.discounttracker.data.model.DiscountListResponse import io.reactivex.Single import retrofit2.http.GET interface DiscountApi { @GET("discount") fun getDiscountList() : Single<DiscountListResponse> }
0
Kotlin
0
0
df91d499b95dab7956d9b54279e469b55f66328c
288
DiscountTracker-Kotlin
The Unlicense
utbot-go/src/main/kotlin/org/utbot/go/gocodeanalyzer/AnalysisTargets.kt
UnitTestBot
480,810,501
false
null
package org.utbot.go.gocodeanalyzer internal data class AnalysisTarget(val absoluteFilePath: String, val targetFunctionsNames: List<String>) internal data class AnalysisTargets(val targets: List<AnalysisTarget>)
346
Kotlin
26
79
5151b1bee58f24b95d05be394b0ef2dda20381c6
213
UTBotJava
Apache License 2.0
plugin/src/test/kotlin/com/jraska/module/graph/assertion/ConfigurationAvoidanceTest.kt
jraska
227,907,412
false
{"Kotlin": 65591}
package com.jraska.module.graph.assertion import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.GradleRunner import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File class ConfigurationAvoidanceTest { @get:Rule val testProjectDir: TemporaryFolder = TemporaryFolder() @Before fun setup() { testProjectDir.newFile("build.gradle").writeText( """ plugins { id 'com.jraska.module.graph.assertion' } moduleGraphAssert { maxHeight = 3 allowed = [':app -> .*', ':feature-\\S* -> :lib\\S*', '.* -> :core', ':feature-one -> :feature-exclusion-test', ':feature-one -> :feature-one:nested'] restricted = [':feature-[a-z]* -X> :feature-[a-z]*'] } ext.moduleNameAssertAlias = "Alias" """ ) } @Test fun tasksAreUpToDate() { runGradleAssertModuleGraph(testProjectDir.root) val secondRunResult = runGradleAssertModuleGraph(testProjectDir.root) val findAll = Regex("UP-TO-DATE").findAll(secondRunResult.output) assert(findAll.count() == 4) } } fun runGradleAssertModuleGraph(dir: File, vararg arguments: String = arrayOf("--configuration-cache", "assertModuleGraph")): BuildResult { return GradleRunner.create() .withProjectDir(dir) .withPluginClasspath() .withArguments(arguments.asList()) .build() }
3
Kotlin
22
522
03a3d40cae4c8625f3f80f0286214f3dd4fd4a78
1,466
modules-graph-assert
Apache License 2.0
app/src/main/java/com/fidibo/scrollviewpager/adapter/ListItemAdapter.kt
secondstriker
398,748,745
false
null
package com.fidibo.scrollviewpager.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.DiffUtil import com.fidibo.scrollviewpager.AppCoroutineDispatchers import com.fidibo.scrollviewpager.Model import com.fidibo.scrollviewpager.R import com.fidibo.scrollviewpager.databinding.ListItemBinding import android.view.ViewTreeObserver.OnGlobalLayoutListener import android.widget.Toast import androidx.core.view.marginEnd import androidx.core.view.marginStart import androidx.databinding.ViewDataBinding import com.fidibo.scrollviewpager.Constants.FADE_THRESHOLD import com.fidibo.scrollviewpager.Constants.SKIP_THRESHOLD import com.fidibo.scrollviewpager.Constants.FIRST_SCROLL import kotlin.math.PI import kotlin.math.abs import kotlin.math.cos /** * A RecyclerView adapter for [Item List] class. */ class ListItemAdapter( appCoroutineDispatchers: AppCoroutineDispatchers, private val itemClickCallback: ((Model) -> Unit)? = null ) : DataBoundListAdapter<Model, ViewDataBinding>( appCoroutineDispatchers = appCoroutineDispatchers, diffCallback = object : DiffUtil.ItemCallback<Model>() { override fun areItemsTheSame(oldItem: Model, newItem: Model): Boolean { return oldItem.integer == newItem.integer } override fun areContentsTheSame(oldItem: Model, newItem: Model): Boolean { return oldItem.integer == newItem.integer } } ) { var itemWidth: Int = 0 var finalPosition = 0 var currentPosition: Int = 0 private var delta = 0 private var alpha: Float = 1F private var startToFadeIndex: Int = 0 private var startToFadeOutIndex: Int = 0 fun setPosition(currentPosition: Int, finalPosition: Int){ this.currentPosition = currentPosition this.finalPosition = finalPosition this.delta = finalPosition - currentPosition startToFadeIndex = getStartToFadeIndex() startToFadeOutIndex = getStartToFadeOutIndex() } override fun createBinding(parent: ViewGroup, viewType: Int): ViewDataBinding { println("viewHolder: start create binding ...") val binding = DataBindingUtil.inflate<ViewDataBinding>( LayoutInflater.from(parent.context), R.layout.list_item, parent, false ) binding.root.setOnClickListener { _ -> (binding as ListItemBinding).item.let { if (it != null) itemClickCallback?.invoke(it) } } if(itemWidth == 0) binding.root.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener { override fun onGlobalLayout() { binding.root.viewTreeObserver.removeOnGlobalLayoutListener(this) itemWidth = binding.root.width + (binding.root.marginStart + binding.root.marginEnd) / 2 } }) println("viewHolder: end of creating binding") return binding } override fun getItemViewType(position: Int): Int { if(delta > SKIP_THRESHOLD && position < finalPosition && position > currentPosition) { if (position < currentPosition + FIRST_SCROLL){ alpha = 1F return 0 } else if (position < finalPosition && position > finalPosition - FIRST_SCROLL){ alpha = 1F return 0 } alpha = getAlpha(position) return 0 } if(delta < -SKIP_THRESHOLD && position > finalPosition && position < currentPosition) { if (position > currentPosition - FIRST_SCROLL){ alpha = 1F return 0 } else if (position > finalPosition && position < finalPosition + FIRST_SCROLL){ alpha = 1F return 0 } alpha = getAlpha(position) return 0 } alpha = 1F return 0 } private fun getStartToFadeIndex(): Int { if(delta > 0 && delta > SKIP_THRESHOLD && (finalPosition - currentPosition) > (FIRST_SCROLL + FADE_THRESHOLD) * 2) return currentPosition + FIRST_SCROLL + FADE_THRESHOLD if(delta < 0 && delta < -SKIP_THRESHOLD && (finalPosition - currentPosition) < -(FIRST_SCROLL + FADE_THRESHOLD) * 2) return -(currentPosition - FIRST_SCROLL - FADE_THRESHOLD) else return 0 } private fun getStartToFadeOutIndex(): Int { if(delta > 0 && delta > SKIP_THRESHOLD && (finalPosition - currentPosition) > (FIRST_SCROLL + FADE_THRESHOLD) * 2) return finalPosition - FIRST_SCROLL - FADE_THRESHOLD if(delta < 0 && delta < -SKIP_THRESHOLD && (finalPosition - currentPosition) < -(FIRST_SCROLL + FADE_THRESHOLD) * 2) return -(finalPosition + FIRST_SCROLL + FADE_THRESHOLD) else return 0 } private fun getAlpha(position: Int): Float{ //for no need to skip if(startToFadeIndex == 0 || startToFadeOutIndex == 0) return 1F //for scrolling forward if(startToFadeIndex > 0 && startToFadeOutIndex > 0){ if(position <= (startToFadeIndex + FADE_THRESHOLD) && position >= startToFadeIndex) return abs(cos((position - startToFadeIndex) / (FADE_THRESHOLD).toFloat() * PI.toFloat() / 2)) if(position > (startToFadeIndex + FADE_THRESHOLD) && position < startToFadeOutIndex - FADE_THRESHOLD){ return 0F } if(position >= (startToFadeOutIndex - FADE_THRESHOLD) && position < startToFadeOutIndex) return abs(cos((position - startToFadeOutIndex + 2 * FADE_THRESHOLD) / (FADE_THRESHOLD).toFloat() * PI.toFloat() / 2)) if(position >= startToFadeOutIndex) return 1F } //for scrolling backward if(startToFadeIndex < 0 && startToFadeOutIndex < 0){ if(position >= (-startToFadeIndex - FADE_THRESHOLD) && position <= -startToFadeIndex) return abs(cos((-position - startToFadeIndex) / (FADE_THRESHOLD).toFloat() * PI.toFloat() / 2)) if(position < (-startToFadeIndex - FADE_THRESHOLD) && position > -startToFadeOutIndex + FADE_THRESHOLD){ return 0F } if(position <= (-startToFadeOutIndex + FADE_THRESHOLD) && position > -startToFadeOutIndex) return abs(cos((-position -startToFadeOutIndex + 2 * FADE_THRESHOLD) / (FADE_THRESHOLD).toFloat() * PI.toFloat() / 2)) if(position <= -startToFadeOutIndex) return 1F } return 1F } override fun bind(binding: ViewDataBinding, item: Model) { (binding as ListItemBinding).item = item (binding as ListItemBinding).alphaForItems = alpha (binding as ListItemBinding).alphaForSkipped = 1 - alpha } }
0
Kotlin
0
0
0ffd88e43a7dfb11f4987c43aadcb76c3febc8e6
7,071
viewPagerFragmentStatePager
Apache License 2.0
src/main/kotlin/com/de/c0dr/mailservice/adapter/primary/MailRequestController.kt
c0dr
261,247,793
false
null
package com.de.c0dr.mailservice.adapter.primary; import com.de.c0dr.mailservice.MailApplicationService import com.de.c0dr.mailservice.adapter.secondary.sending.MailSendingAdapter import com.de.c0dr.mailservice.adapter.secondary.transpiling.MJMLTranspiler import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController @RestController class MailRequestController(private val mailApplicationService: MailApplicationService, private val mailSendingAdapter: MailSendingAdapter, private val mailTranspilingAdapter: MJMLTranspiler) { @PostMapping("/send") fun greeting(@RequestBody mailRequest: MailRequest) { val formattedTemplate = mailApplicationService.generateTemplate(mailRequest.templateName, mailRequest.variables) val htmlTemplate = mailTranspilingAdapter.transpile(formattedTemplate) mailSendingAdapter.sendMail(mailRequest.recipient, mailRequest.subject, htmlTemplate) } }
2
Kotlin
0
0
5404dff670c5611311f47e1fd7143515d6c3e9c8
1,034
mailService
MIT License
net.akehurst.language.editor/agl-editor-ace/src/jsMain/kotlin/AglTokenizerAce.kt
dhakehurst
252,659,008
false
null
/** * Copyright (C) 2020 Dr. <NAME> (http://dr.david.h.akehurst.net) * * 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 net.akehurst.language.editor.ace import net.akehurst.language.api.sppt.SPPTLeaf import net.akehurst.language.editor.common.AglComponents import net.akehurst.language.editor.common.AglStyleHandler import net.akehurst.language.editor.common.AglTokenizer class AglBackgroundTokenizer( tok: ace.Tokenizer, ed: ace.Editor ) : ace.BackgroundTokenizer(tok, ed) { } class AglLineStateAce( val lineNumber: Int, val leftOverText: String ) : ace.LineState { } class AglTokenAce( styles: Array<String>, override val value: String, override val line: Int, column: Int ) : ace.Token { override val type = styles.joinToString(".") override var start = column } class AglLineTokensAce( override val state: ace.LineState, override val tokens: Array<ace.Token> ) : ace.LineTokens {} class AglTokenizerAce( val agl: AglComponents, val aglStyleHandler: AglStyleHandler ) : ace.Tokenizer { val aglTokenizer = AglTokenizer(agl) // --- ace.Ace.Tokenizer --- override fun getLineTokens(line: String, pState: ace.LineState?, row: Int): ace.LineTokens { val sppt = this.agl.sppt val state = if (null == pState) AglLineStateAce(0, "") else pState as AglLineStateAce return if (null == sppt) { this.getLineTokensByScan(line, state, row) } else { this.getLineTokensByParse(line, state, row) } } fun getLineTokensByScan(line: String, state: AglLineStateAce, row: Int): ace.LineTokens { TODO() } fun getLineTokensByParse(line: String, state: AglLineStateAce, row: Int): ace.LineTokens { TODO() } }
2
Kotlin
0
3
4545320435da906da859f2b583bb7ca0281c6482
2,339
net.akehurst.language.editor
Apache License 2.0
demo/multiplatform/common/src/linuxMain/kotlin/dev/teogor/multiplatform/common/ClipboardSaver.linux.kt
teogor
713,830,828
false
{"Kotlin": 244579}
package dev.teogor.multiplatform.common actual class ClipboardSaver { actual fun saveToClipboard(text: String) { } }
0
Kotlin
0
18
3a74ca27cba5ad6ec0de4a96638e846e9340e89d
122
winds
Apache License 2.0
core/designsystem/src/main/java/com/conf/mad/todo/designsystem/preview/DevicePreview.kt
MobileAppDeveloperConference
709,286,274
false
{"Kotlin": 122200}
/* * MIT License * Copyright 2023 MADConference * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.conf.mad.todo.designsystem.preview import androidx.compose.ui.tooling.preview.Preview @Preview( name = "Galaxy S23 Ultra", showBackground = true, device = "spec:width=360dp,height=772dp,dpi=411" ) @Preview( name = "Galaxy S23", showBackground = true, device = "spec:width=360dp,height=800dp,dpi=500" ) annotation class DevicePreview
3
Kotlin
3
35
cf84977e2606104632a7d5965ce186a9f9ad8b92
1,500
android
MIT License
csstype-kotlin/src/jsMain/kotlin/web/cssom/ScrollMarginInlineStart.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.cssom typealias ScrollMarginInlineStart = LengthProperty
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
115
types-kotlin
Apache License 2.0
Cockpit/PiServer/src/main/kotlin/nyc/spookyrobotics/piserver/GraphPaperStateManager.kt
jsjrobotics
761,934,416
false
{"Kotlin": 35196}
package nyc.spookyrobotics.piserver class GraphPaperStateManager { fun updateState(textPayload: String?) { currentState = textPayload } fun reset() { currentState = DEFAULT_STATE } var currentState: String? = DEFAULT_STATE private set companion object { private val DEFAULT_STATE = "{\"channelId\":\"ChillQueens\",\"gameState\":{\"cell1\":0,\"cell2\":0,\"cell3\":0,\"cell4\":1,\"cell5\":0,\"cell6\":0,\"currentPlayerTurn\":0}}" } }
0
Kotlin
0
0
f355d83a0bdcefbbb3c6c1e0800ef11340f0c17c
496
InternetVan
MIT License
src/main/kotlin/br/com/colman/kaucasus/Clustering.kt
LeoColman
364,760,768
true
{"Kotlin": 110184}
package br.com.colman.kaucasus import org.apache.commons.math3.ml.clustering.* fun Collection<Pair<Double, Double>>.kMeansCluster(k: Int, maxIterations: Int) = kMeansCluster(k, maxIterations, { it.first }, { it.second }) fun Sequence<Pair<Double, Double>>.kMeansCluster(k: Int, maxIterations: Int) = toList().kMeansCluster(k, maxIterations, { it.first }, { it.second }) inline fun <T> Collection<T>.kMeansCluster( k: Int, maxIterations: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double ) = asSequence().map { ClusterInput(it, doubleArrayOf(xSelector(it), ySelector(it))) } .toList() .let { KMeansPlusPlusClusterer<ClusterInput<T>>(k, maxIterations) .cluster(it) .map { Centroid((it.center).point.let { DoublePoint(it[0], it[1]) }, it.points.map { it.item }) } } inline fun <T> Sequence<T>.kMeansCluster( k: Int, maxIterations: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double ) = toList().kMeansCluster(k, maxIterations, xSelector, ySelector) inline fun <T> Collection<T>.fuzzyKMeansCluster( k: Int, fuzziness: Double, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double ) = asSequence().map { ClusterInput(it, doubleArrayOf(xSelector(it), ySelector(it))) } .toList() .let { FuzzyKMeansClusterer<ClusterInput<T>>(k, fuzziness) .cluster(it) .map { Centroid((it.center).point.let { DoublePoint(it[0], it[1]) }, it.points.map { it.item }) } } inline fun <T> Sequence<T>.fuzzyKMeansCluster( k: Int, fuzziness: Double, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double ) = toList().fuzzyKMeansCluster(k, fuzziness, xSelector, ySelector) fun Collection<Pair<Double, Double>>.multiKMeansCluster(k: Int, maxIterations: Int, trialCount: Int) = multiKMeansCluster(k, maxIterations, trialCount, { it.first }, { it.second }) fun Sequence<Pair<Double, Double>>.multiKMeansCluster(k: Int, maxIterations: Int, trialCount: Int) = toList().multiKMeansCluster(k, maxIterations, trialCount, { it.first }, { it.second }) inline fun <T> Sequence<T>.multiKMeansCluster( k: Int, maxIterations: Int, trialCount: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double ) = toList().multiKMeansCluster(k, maxIterations, trialCount, xSelector, ySelector) inline fun <T> Collection<T>.multiKMeansCluster( k: Int, maxIterations: Int, trialCount: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double ) = asSequence().map { ClusterInput(it, doubleArrayOf(xSelector(it), ySelector(it))) } .toList() .let { list -> KMeansPlusPlusClusterer<ClusterInput<T>>(k, maxIterations) .let { MultiKMeansPlusPlusClusterer<ClusterInput<T>>(it, trialCount) .cluster(list) .map { Centroid(DoublePoint(-1.0, -1.0), it.points.map { it.item }) } } } inline fun <T> Collection<T>.dbScanCluster( maximumRadius: Double, minPoints: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double ) = asSequence().map { ClusterInput(it, doubleArrayOf(xSelector(it), ySelector(it))) } .toList() .let { DBSCANClusterer<ClusterInput<T>>(maximumRadius, minPoints) .cluster(it) .map { Centroid(DoublePoint(-1.0, -1.0), it.points.map { it.item }) } } inline fun <T> Sequence<T>.dbScanCluster( maximumRadius: Double, minPoints: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double ) = toList().dbScanCluster(maximumRadius, minPoints, xSelector, ySelector) class ClusterInput<out T>(val item: T, val location: DoubleArray) : Clusterable { override fun getPoint() = location } data class DoublePoint(val x: Double, val y: Double) data class Centroid<out T>(val center: DoublePoint, val points: List<T>)
3
Kotlin
0
3
08187a786cf34002e2c65022d39e44250db5e253
4,714
Kaucasus
Apache License 2.0
app/src/main/java/de/stefanoberdoerfer/bierumvier/data/network/model/Beer.kt
stefanoberdoerfer
603,884,076
false
null
package de.stefanoberdoerfer.bierumvier.data.network.model import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Beer( @Json(name = "id") val id: Long, @Json(name = "name") val name: String? = null, @Json(name = "tagline") val tagline: String? = null, @Json(name = "first_brewed") val firstBrewed: String? = null, @Json(name = "description") val description: String? = null, @Json(name = "image_url") val imageUrl: String? = null, @Json(name = "abv") val abv: Double? = null, @Json(name = "ibu") val ibu: Double? = null, @Json(name = "target_fg") val targetFg: Double? = null, @Json(name = "target_og") val targetOg: Double? = null, @Json(name = "ebc") val ebc: Double? = null, @Json(name = "srm") val srm: Double? = null, @Json(name = "ph") val ph: Double? = null, @Json(name = "attenuation_level") val attenuationLevel: Double? = null, @Json(name = "volume") val volume: Amount? = Amount(), @Json(name = "boil_volume") val boilVolume: Amount? = Amount(), @Json(name = "ingredients") val ingredients: Ingredients? = Ingredients(), @Json(name = "food_pairing") val foodPairing: List<String> = listOf(), @Json(name = "brewers_tips") val brewersTips: String? = null, @Json(name = "contributed_by") val contributedBy: String? = null ) @JsonClass(generateAdapter = true) data class Ingredients( @Json(name = "malt") var malt: List<Ingredient> = listOf(), @Json(name = "hops") var hops: List<Ingredient> = listOf(), @Json(name = "yeast") var yeast: String? = null ) @JsonClass(generateAdapter = true) data class Ingredient( @Json(name = "name") var name: String? = null, @Json(name = "amount") var amount: Amount? = Amount(), @Json(name = "add") var add: String? = null, @Json(name = "attribute") var attribute: String? = null ) @JsonClass(generateAdapter = true) data class Amount( @Json(name = "value") var value: Double? = null, @Json(name = "unit") var unit: String? = null )
0
Kotlin
0
0
572ca2b76726b19f434afd2774c2680e6a769381
2,054
BierUmVier-AndroidSample
Apache License 2.0
collapse-toolbar/app/src/main/java/com/hariofspades/collapsetoolbar/util/CollapsibleToolbar.kt
Hariofspades
147,617,936
false
null
package com.hariofspades.collapsetoolbar.util import android.content.Context import android.support.constraint.motion.MotionLayout import android.support.design.widget.AppBarLayout import android.util.AttributeSet class CollapsibleToolbar @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : MotionLayout(context, attrs, defStyleAttr), AppBarLayout.OnOffsetChangedListener { override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) { progress = -verticalOffset / appBarLayout?.totalScrollRange?.toFloat()!! } override fun onAttachedToWindow() { super.onAttachedToWindow() (parent as? AppBarLayout)?.addOnOffsetChangedListener(this) } }
2
Kotlin
19
203
e53e13a12caf597166002756316c3a605f5402a7
756
MotionLayoutExperiments
MIT License
src/main/kotlin/xyz/mcxross/cohesive/sui/view/Explorer.kt
mcxross
643,096,409
false
null
package xyz.mcxross.cohesive.sui.view import androidx.compose.foundation.VerticalScrollbar import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollbarAdapter import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.Card import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import xyz.mcxross.cohesive.sui.pxToDp @Composable internal fun BackLayer( isOpen: Boolean, ) { var isContentVisible by remember { mutableStateOf(isOpen) } var rotationState by remember { mutableStateOf(0f) } LaunchedEffect(isOpen) { isContentVisible = isOpen rotationState = if (isOpen) 180f else 0f } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.background(MaterialTheme.colors.background).padding(16.dp)) { Text(text = "Explorer", style = MaterialTheme.typography.subtitle1) Spacer(modifier = Modifier.weight(1f)) Icon( imageVector = Icons.Default.Close, contentDescription = "Toggle Button", tint = Color.Black, modifier = Modifier.rotate(rotationState).alpha(if (isOpen) 1f else 0.5f)) } } @Composable internal fun FrontLayer() { Surface( elevation = 5.dp, modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(topStart = 15.dp, topEnd = 15.dp))) { Box(Modifier.padding(start = 12.dp, top = 2.dp, end = 12.dp).fillMaxSize()) { val stateVertical = rememberScrollState(0) Box( modifier = Modifier.padding(start = 30.dp, end = 30.dp) .fillMaxSize() .verticalScroll(stateVertical)) { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Surface( modifier = Modifier.fillMaxWidth().height(400.dp), shape = RoundedCornerShape(8.dp), contentColor = MaterialTheme.colors.onSurface, elevation = 5.dp) { Column(modifier = Modifier.fillMaxWidth()) { Box(modifier = Modifier.padding(5.dp).fillMaxWidth()) { Text( text = "Network Summary", fontSize = 18.sp, fontWeight = FontWeight.Medium) } Divider( modifier = Modifier.fillMaxWidth(), color = MaterialTheme.colors.primary, thickness = 1.dp) } } BoxWithConstraints(modifier = Modifier.fillMaxWidth()) { var maxWidth by remember { mutableStateOf(maxWidth.value) } Row( modifier = Modifier.fillMaxWidth().onSizeChanged { maxWidth = it.width.toFloat() }, horizontalArrangement = Arrangement.spacedBy(16.dp)) { Card( modifier = Modifier.size( (maxWidth.toInt().pxToDp() - 16.dp) * 0.25f, 300.dp)) {} Card( modifier = Modifier.size( (maxWidth.toInt().pxToDp() - 16.dp) * 0.5f, 300.dp)) {} Card( modifier = Modifier.size( (maxWidth.toInt().pxToDp() - 16.dp) * 0.25f, 300.dp)) {} } } Column(modifier = Modifier.fillMaxWidth()) { Box(modifier = Modifier.padding(5.dp).fillMaxWidth()) { Text( text = "Transaction Blocks", fontSize = 18.sp, fontWeight = FontWeight.Medium) } Divider( modifier = Modifier.fillMaxWidth(), color = MaterialTheme.colors.background, thickness = 1.dp) Box(modifier = Modifier) { Column(Modifier) { repeat(100) { Text(it.toString()) } } } } } } VerticalScrollbar( modifier = Modifier.padding(end = 3.dp).align(Alignment.CenterEnd).fillMaxHeight(), adapter = rememberScrollbarAdapter(stateVertical)) } } } @Composable internal fun PseudoBackdrop( isOpen: Boolean = false, ) { Column(Modifier.fillMaxSize()) { BackLayer(isOpen) FrontLayer() } } @Composable fun Explorer() { PseudoBackdrop() }
0
Kotlin
0
0
179abe05fdc2f9f2676b3cfb32fbd0c82f686806
6,590
sui-cohesive
Apache License 2.0
weiV/src/main/java/cn/flutterfirst/weiv/wrappers/constraintlayout/CLVisibility.kt
hackware1993
493,227,143
false
{"Kotlin": 128669, "Java": 7893}
package cn.flutterfirst.weiv.wrappers.constraintlayout enum class CLVisibility { visible, invisible, gone }
5
Kotlin
8
75
17867a038c0002e5f80ab40b4ebc6c7e8e440572
120
weiV
MIT License
weiV/src/main/java/cn/flutterfirst/weiv/wrappers/constraintlayout/CLVisibility.kt
hackware1993
493,227,143
false
{"Kotlin": 128669, "Java": 7893}
package cn.flutterfirst.weiv.wrappers.constraintlayout enum class CLVisibility { visible, invisible, gone }
5
Kotlin
8
75
17867a038c0002e5f80ab40b4ebc6c7e8e440572
120
weiV
MIT License
app/src/main/java/com/saint/utillib/gloading/EmptyFrag.kt
saint-li
217,494,681
false
{"Java": 780282, "Kotlin": 30101}
package com.saint.utillib.gloading import android.os.Bundle import com.saint.util.base.BaseFrag import com.saint.util.util.toast.AppToast import com.saint.utillib.R import com.saint.widget.GLoading class EmptyFrag : BaseFrag() { private var holder: GLoading.Holder? = null override fun setLayout(): Int { return R.layout.frag_gloading_empty } override fun initData(savedInstanceState: Bundle?) { holder = GLoading.getDefault().wrap(rootView).withRetry { AppToast.tShort("重试点击-----") } holder!!.showLoading() rootView.postDelayed({ holder!!.showEmpty() }, 1000) } }
0
Java
0
0
9d43bc8e261ed0046c6f949499f62c5d267ec844
659
util
Apache License 2.0
src/main/kotlin/kim/bifrost/rain/orm/api/IDao.kt
ColdRain-Moro
446,545,699
false
{"Kotlin": 13694}
package kim.bifrost.rain.orm.api import taboolib.module.database.Host import taboolib.module.database.SQL import taboolib.module.database.Table import javax.sql.DataSource /** * kim.bifrost.rain.orm.api.IDao * RainORM * * @author 寒雨 * @since 2022/1/11 2:14 **/ interface IDao<T> { /** * Data source */ val dataSource: DataSource /** * SQL Table */ val table: Table<Host<SQL>, SQL> }
0
Kotlin
0
5
455a71e5bb496a8af0ebc9368993da496915331a
427
RainORM
Creative Commons Zero v1.0 Universal
answering_machine/src/main/kotlin/Command.kt
mikbot
601,587,024
false
{"Kotlin": 197467}
package dev.schlaubi.mikbot.util_plugins.answering_machine import com.kotlindiscord.kord.extensions.checks.guildFor import com.kotlindiscord.kord.extensions.commands.Arguments import com.kotlindiscord.kord.extensions.commands.converters.impl.defaultingBoolean import com.kotlindiscord.kord.extensions.commands.converters.impl.string import com.kotlindiscord.kord.extensions.components.components import com.kotlindiscord.kord.extensions.components.ephemeralButton import com.kotlindiscord.kord.extensions.components.forms.ModalForm import com.kotlindiscord.kord.extensions.extensions.Extension import com.kotlindiscord.kord.extensions.extensions.ephemeralSlashCommand import com.kotlindiscord.kord.extensions.types.respond import com.kotlindiscord.kord.extensions.utils.suggestStringMap import dev.kord.common.entity.ButtonStyle import dev.kord.common.entity.Permission import dev.kord.core.behavior.interaction.response.edit import dev.schlaubi.mikbot.plugin.api.util.discordError import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList import org.bson.types.ObjectId import org.litote.kmongo.eq import java.util.regex.PatternSyntaxException class AddAnsweringMachineArgs : Arguments() { val pattern by string { name = "pattern" description = "commands.add_answering_machine.arguments.pattern.description" } val replacement by string { name = "replacement" description = "commands.add_answering_machine.arguments.replacement.description" } val delete by defaultingBoolean { name = "delete" description = "commands.add_answering_machine.arguments.delete.description" defaultValue = false } val ignoreCase by defaultingBoolean { name = "ignore-case" description = "commands.add_answering_machine.arguments.ignore_case.description" defaultValue = true } } class TestInputModal : ModalForm() { override var title: String = "Test your input" val testInput = lineText { label = "Test Message" } } class DeleteAnsweringMachineArgs : Arguments() { val machine by string { name = "pattern" description = "commands.delete_answering_machine.arguments.machine.description" autoComplete { event -> val answers = AnsweringMachineDatabase.regexes .find(AnswerRegex::guildId eq guildFor(event)?.id) .toFlow() .take(25) .map { "${it.regex} -> ${it.replacement}" to it.id.toString() } .toList() .toMap() suggestStringMap(answers) } } } suspend fun Extension.addAnsweringMachine() = ephemeralSlashCommand(::AddAnsweringMachineArgs, ::TestInputModal) { name = "add-answering-machine" description = "commands.add_answering_machine.description" requirePermission(Permission.ManageGuild) requireBotPermissions(Permission.ManageMessages) allowInDms = false action { input -> val response = interactionResponse val regex = try { if (arguments.ignoreCase) { arguments.pattern.toRegex(RegexOption.IGNORE_CASE) } else { arguments.pattern.toRegex() } } catch (e: PatternSyntaxException) { discordError(e.message!!) } val replacement = input!!.testInput.value!!.replace(regex, arguments.replacement) respond { content = translate("commands.add_answering_machine.confirmation.received", arrayOf(replacement)) components { ephemeralButton { bundle = "answering_machine" style = ButtonStyle.Success label = translate("commands.add_answering_machine.confirmation.confirm") action { val entity = AnswerRegex( guildId = guild!!.id, regex = regex, replacement = arguments.replacement, delete = arguments.delete ) AnsweringMachineDatabase.regexes.save(entity) response.edit { content = translate("commands.add_answering_machine.created") components = mutableListOf() } } } ephemeralButton { bundle = "answering_machine" style = ButtonStyle.Danger label = translate("commands.add_answering_machine.confirmation.decline") action { response.edit { content = translate("commands.add_answering_machine.declined") components = mutableListOf() } } } } } } } suspend fun Extension.deleteAnsweringMachine() = ephemeralSlashCommand(::DeleteAnsweringMachineArgs) { name = "delete-answering-machine" description = "commands.delete_answering_machine.description" allowInDms = false requirePermission(Permission.ManageGuild) action { AnsweringMachineDatabase.regexes.deleteOneById(ObjectId(arguments.machine)) respond { content = translate("commands.delete_answering_machine.success") } } }
0
Kotlin
0
0
f9095e7da1310fe4703af33aa7dd9e3ffa3cf345
5,526
utils
MIT License
shared/src/commonMain/kotlin/penta/BoardState.kt
jmfayard
238,160,990
true
{"Kotlin": 320266, "HTML": 763, "JavaScript": 170, "Shell": 170}
package penta import PentaBoard import actions.Action import com.soywiz.klogger.Logger import penta.logic.Field import penta.logic.Field.Goal import penta.logic.Piece import penta.network.GameEvent import penta.util.exhaustive import penta.util.requireMove data class BoardState private constructor( val players: List<PlayerState> = listOf(), val currentPlayer: PlayerState = PlayerState("_", "triangle"), val gameType: GameType = GameType.TWO, val scoringColors: Map<String, Array<PentaColor>> = mapOf(), val figures: List<Piece> = listOf(), val positions: Map<String, Field?> = mapOf(), val history: List<PentaMove> = listOf(), val gameStarted: Boolean = false, val turn: Int = 0, val forceMoveNextPlayer: Boolean = false, val winner: String? = null, val selectedPlayerPiece: Piece.Player? = null, val selectedBlackPiece: Piece.BlackBlocker? = null, val selectedGrayPiece: Piece.GrayBlocker? = null, /** * true when no gray pieces are in the middle and one from the board has to be be selected */ val selectingGrayPiece: Boolean = false, val illegalMove: PentaMove.IllegalMove? = null ) { object RemoveIllegalMove enum class GameType { TWO, THREE, FOUR, TWO_VS_TO } companion object { private val logger = Logger("BoardState") fun create(): BoardState { logger.info { "created new BoardState" } return WithMutableState( BoardState() ).apply { val blacks = (0 until 5).map { i -> Piece.BlackBlocker( "b$i", PentaColor.values()[i], PentaBoard.j[i] ).also { it.position = it.originalPosition } } val greys = (0 until 5).map { i -> Piece.GrayBlocker( "g$i", PentaColor.values()[i] ).also { it.position = null } } nextState = nextState.copy( figures = listOf(*blacks.toTypedArray(), *greys.toTypedArray()) ) }.nextState } data class WithMutableState(var nextState: BoardState) { val originalState = nextState var Piece.position: Field? get() = nextState.positions[id] set(value) { logger.debug { "move $id to ${value?.id}" } nextState = nextState.copy(positions = nextState.positions + (id to value)) } } fun reduceFunc(state: BoardState, action: Any): BoardState { logger.info { "action: ${action::class}" } return when (action) { is org.reduxkotlin.ActionTypes.INIT -> { logger.info { "received INIT" } state } is org.reduxkotlin.ActionTypes.REPLACE -> { logger.info { "received REPLACE" } state } is Action<*> -> { reduceFunc(state, action.action) } is GameEvent -> { reduceFunc(state, action.asMove(state)) } is PentaMove -> { WithMutableState(state).processMove(action) } is RemoveIllegalMove -> { state.copy( illegalMove = null ) } else -> { error("$action is of unhandled type") } } } fun WithMutableState.handleIllegalMove(illegalMove: PentaMove.IllegalMove) { nextState = originalState.copy( illegalMove = illegalMove ) } fun WithMutableState.processMove(move: PentaMove, undo: Boolean = false): BoardState { try { logger.info { "turn: ${nextState.turn}" } logger.info { "currentPlayer: ${nextState.currentPlayer}" } logger.info { "processing $move" } when (move) { is PentaMove.MovePlayer -> { if (!undo) { with(originalState) { requireMove(gameStarted) { PentaMove.IllegalMove( "game is not started yet", move ) } requireMove(move.playerPiece.playerId == currentPlayer.id) { PentaMove.IllegalMove( "move is not from currentPlayer: ${currentPlayer.id}", move ) } requireMove(canMove(move.from, move.to)) { PentaMove.IllegalMove( "no path between ${move.from.id} and ${move.to.id}", move ) } } val piecesOnTarget = nextState.positions .filterValues { it == move.to }.keys .mapNotNull { id -> nextState.figures.find { it.id == id } } if (piecesOnTarget.size > 1) { handleIllegalMove( PentaMove.IllegalMove( "multiple pieces on target field ${move.to.id}", move ) ) return nextState } val pieceOnTarget = piecesOnTarget.firstOrNull() if (pieceOnTarget != null) { when (pieceOnTarget) { is Piece.GrayBlocker -> { logger.info { "taking ${pieceOnTarget.id} off the board" } pieceOnTarget.position = null // updatePiecesAtPos(null) } is Piece.BlackBlocker -> { nextState = nextState.copy( selectedBlackPiece = pieceOnTarget ) pieceOnTarget.position = null // TODO: set corner field // updatePiecesAtPos(null) logger.info { "holding ${pieceOnTarget.id} for repositioning" } } else -> { requireMove(false) { PentaMove.IllegalMove( "cannot click on piece type: ${pieceOnTarget::class.simpleName}", move ) } } } // TODO: can unset when pieces float on pointer // pieceOnTarget.position = null } else { // no piece on target field } move.playerPiece.position = move.to //TODO: set in figurePositions postProcess(move) // updatePiecesAtPos(move.from) // updatePiecesAtPos(move.to) // // updateBoard() logger.info { "append history" } with(nextState) { nextState = nextState.copy(history = history + move) } } else { if (nextState.selectingGrayPiece == true) { nextState = nextState.copy( selectingGrayPiece = false ) } if (nextState.selectedBlackPiece != null) { nextState.selectedBlackPiece!!.position = move.to nextState = nextState.copy( selectedBlackPiece = null ) } if (nextState.selectedGrayPiece != null) { // move back to center / off-board nextState.selectedGrayPiece!!.position = null nextState = nextState.copy( selectedGrayPiece = null ) } move.playerPiece.position = move.from nextState = nextState.copy( selectedPlayerPiece = move.playerPiece, history = nextState.history.dropLast(1), turn = nextState.turn - 1 ) } } is PentaMove.ForcedPlayerMove -> { if (!undo) { with(originalState) { requireMove(gameStarted) { PentaMove.IllegalMove( "game is not started yet", move ) } requireMove(move.playerPiece.playerId == currentPlayer.id) { PentaMove.IllegalMove( "move is not from currentPlayer: ${currentPlayer.id}", move ) } } val sourceField = move.from if (sourceField is Goal && move.playerPiece.pentaColor == sourceField.pentaColor) { postProcess(move) } else { requireMove(false) { PentaMove.IllegalMove( "Forced player move cannot happen", move ) } } with(nextState) { nextState = nextState.copy(history = history + move) } } else { if (nextState.selectingGrayPiece == true) { nextState = nextState.copy( selectingGrayPiece = false ) } if (nextState.selectedBlackPiece != null) { nextState.selectedBlackPiece!!.position = move.to nextState = nextState.copy( selectedBlackPiece = null ) } if (nextState.selectedGrayPiece != null) { // move back to center / off-board nextState.selectedGrayPiece!!.position = null nextState = nextState.copy( selectedGrayPiece = null ) } move.playerPiece.position = move.from nextState = nextState.copy( selectedPlayerPiece = move.playerPiece, history = nextState.history.dropLast(1), turn = nextState.turn - 1 ) } } is PentaMove.SwapOwnPiece -> { if (!undo) { with(originalState) { requireMove(gameStarted) { PentaMove.IllegalMove( "game is not started yet", move ) } requireMove(canMove(move.from, move.to)) { PentaMove.IllegalMove( "no path between ${move.from.id} and ${move.to.id}", move ) } requireMove(move.playerPiece.playerId == currentPlayer.id) { PentaMove.IllegalMove( "move is not from currentPlayer: ${currentPlayer.id}", move ) } requireMove(move.playerPiece.position == move.from) { PentaMove.IllegalMove( "piece ${move.playerPiece.id} is not on expected position ${move.from.id}", move ) } requireMove(move.otherPlayerPiece.playerId == currentPlayer.id) { PentaMove.IllegalMove( "piece ${move.otherPlayerPiece.id} is not from another player", move ) } requireMove(move.otherPlayerPiece.position == move.to) { PentaMove.IllegalMove( "piece ${move.otherPlayerPiece.id} is not on expected position ${move.to.id}", move ) } } move.playerPiece.position = move.to move.otherPlayerPiece.position = move.from // updatePiecesAtPos(move.to) // updatePiecesAtPos(move.from) postProcess(move) with(nextState) { nextState = nextState.copy(history = history + move) } } else { move.playerPiece.position = move.from move.otherPlayerPiece.position = move.to nextState = nextState.copy( selectedPlayerPiece = move.playerPiece, history = nextState.history.dropLast(1), turn = nextState.turn - 1 ) } } is PentaMove.SwapHostilePieces -> { if (!undo) { with(originalState) { requireMove(gameStarted) { PentaMove.IllegalMove( "game is not started yet", move ) } requireMove(canMove(move.from, move.to)) { PentaMove.IllegalMove( "no path between ${move.from.id} and ${move.to.id}", move ) } requireMove(move.playerPiece.playerId == currentPlayer.id) { PentaMove.IllegalMove( "move is not from currentPlayer: ${currentPlayer.id}", move ) } requireMove(move.playerPiece.position == move.from) { PentaMove.IllegalMove( "piece ${move.playerPiece.id} is not on expected position ${move.from.id}", move ) } requireMove(move.otherPlayerPiece.playerId != currentPlayer.id) { PentaMove.IllegalMove( "piece ${move.otherPlayerPiece.id} is from another player", move ) } requireMove(move.otherPlayerPiece.position == move.to) { PentaMove.IllegalMove( "piece ${move.otherPlayerPiece.id} is not on expected position ${move.to.id}", move ) } val lastMove = history.findLast { it is PentaMove.Move && it.playerPiece.playerId == move.playerPiece.playerId } requireMove(lastMove != move) { PentaMove.IllegalMove( "repeating move ${move.asNotation()} is illegal", move ) } } move.playerPiece.position = move.to move.otherPlayerPiece.position = move.from // updatePiecesAtPos(move.to) // updatePiecesAtPos(move.from) // TODO postProcess(move) with(nextState) { nextState = nextState.copy(history = history + move) } } else { move.playerPiece.position = move.from move.otherPlayerPiece.position = move.to nextState = nextState.copy( selectedPlayerPiece = move.playerPiece ) nextState = nextState.copy( history = nextState.history.dropLast(1), turn = nextState.turn - 1 ) } } is PentaMove.CooperativeSwap -> { TODO("implement cooperative swap") postProcess(move) } is PentaMove.SetBlack -> { if (!undo) { with(originalState) { if (positions.values.any { it == move.to }) { PentaMove.IllegalMove( "target position not empty: ${move.to.id}", move ) } requireMove(move.piece.position == null || move.piece.position == move.from) { PentaMove.IllegalMove( "illegal source position of ${move.piece.position?.id}", move ) } move.piece.position = move.to val lastMove = history.findLast { it !is PentaMove.SetGrey } if (lastMove !is PentaMove.CanSetBlack) { PentaMove.IllegalMove( "last move was not the expected move type: ${lastMove!!::class.simpleName} instead of ${PentaMove.CanSetBlack::class.simpleName}", move ) } } with(nextState) { nextState = nextState.copy( history = history + move, selectedBlackPiece = null ) } // updatePiecesAtPos(move.to) // updatePiecesAtPos(move.from) } else { move.piece.position = null nextState = nextState.copy( selectedBlackPiece = move.piece, history = nextState.history.dropLast(1), turn = nextState.turn - 1 ) } } is PentaMove.SetGrey -> { if (!undo) { with(originalState) { if (positions.values.any { it == move.to }) { handleIllegalMove( PentaMove.IllegalMove( "target position not empty: ${move.to.id}", move ) ) return nextState } requireMove(move.piece.position == move.from) { PentaMove.IllegalMove( "source and target position are the same: ${move.from?.id}", move ) } logger.debug { "selected: $selectedGrayPiece" } if (selectingGrayPiece) { requireMove(selectingGrayPiece && move.from != null) { PentaMove.IllegalMove( "source is null", move ) } } else { requireMove(selectedGrayPiece == move.piece) { PentaMove.IllegalMove( "piece ${move.piece .id} is not the same as selected gray piece: ${selectedGrayPiece?.id}", move ) } } move.piece.position = move.to val lastMove = history.findLast { it !is PentaMove.SetBlack } requireMove(lastMove is PentaMove.CanSetGrey) { PentaMove.IllegalMove( "last move was not the expected move type: ${lastMove!!::class.simpleName} instead of ${PentaMove.CanSetGrey::class.simpleName}", move ) } } with(nextState) { nextState = nextState.copy( history = history + move, selectedGrayPiece = null ) } // updatePiecesAtPos(move.to) // updatePiecesAtPos(move.from) } else { move.piece.position = null nextState = nextState.copy( selectedGrayPiece = move.piece, history = nextState.history.dropLast(1), turn = nextState.turn - 1 ) } } is PentaMove.SelectGrey -> { if (!undo) { // TODO: add checks if (move.grayPiece != null) { nextState = nextState.copy( selectedGrayPiece = move.grayPiece, selectingGrayPiece = false ) move.grayPiece.position = null } else { with(originalState) { requireMove(selectedGrayPiece != null) { PentaMove.IllegalMove( "cannot deselect, since no grey piece is selected", move ) } } nextState = nextState.copy( selectedGrayPiece = null ) } with(nextState) { nextState = nextState.copy( history = history + move ) } } else { if (move.grayPiece != null) { move.grayPiece!!.position = move.from } else { TODO("UNDO deselecting gray pieces") } nextState = nextState.copy( selectingGrayPiece = true, selectedGrayPiece = null, // turn = nextState.turn- 1, history = nextState.history.dropLast(1) ) } } is PentaMove.SelectPlayerPiece -> { if (!undo) { with(originalState) { if (move.playerPiece != null) { requireMove(currentPlayer.id == move.playerPiece.playerId) { PentaMove.IllegalMove( "selected piece ${move.playerPiece} is not owned by current player ${currentPlayer.id}", move ) } } else { requireMove(selectedPlayerPiece != null) { PentaMove.IllegalMove( "cannot deselect because there is no piece selected", move ) } } } logger.info { "last before: ${nextState.history.size} ${nextState.history.lastOrNull()}" } nextState = nextState.copy( history = nextState.history + move, selectedPlayerPiece = move.playerPiece ) logger.info { "last after: ${nextState.history.size} ${nextState.history.lastOrNull()}" } } else { nextState = nextState.copy( selectedPlayerPiece = move.before, // turn = nextState.turn- 1, history = nextState.history.dropLast(1) ) } } is PentaMove.PlayerJoin -> { with(originalState) { requireMove(!gameStarted) { PentaMove.IllegalMove( "game is already started", move ) } requireMove(players.none { it.id == move.player.id }) { PentaMove.IllegalMove( "player already joined", move ) } } with(nextState) { nextState = nextState.copy( players = players + move.player ) } val playerPieces = (0 until nextState.players.size).flatMap { p -> (0 until 5).map { i -> Piece.Player( "p$p$i", nextState.players[p].id, nextState.players[p].figureId, PentaColor.values()[i] ).also { it.position = PentaBoard.c[i] } } } // val removedPositions = originalState.positions.entries - nextState.positions.entries // val addedPositions = nextState.positions.entries - originalState.positions.entries // val changed = originalState.positions.entries.map { // it.key to "${it.value?.id} -> ${nextState.positions[it.key]?.id}" // }.toMap() // logger.info { "removed pos" } // removedPositions.forEach { // logger.warn { "- pos ${it.key} : ${it.value?.id}" } // } // logger.info { "added pos" } // addedPositions.forEach { // logger.warn { "+ pos ${it.key} : ${it.value?.id}" } // } // logger.info { "changed pos" } // changed.forEach { // logger.warn { "~ pos ${it.key} : ${it.value}" } // } with(nextState) { nextState = nextState.copy( figures = listOf<Piece>( // keep all black and grey blockers *figures.filterIsInstance<Piece.BlackBlocker>().toTypedArray(), *figures.filterIsInstance<Piece.GrayBlocker>().toTypedArray(), *playerPieces.toTypedArray() ) ) } // resetPlayers() // updateAllPieces() with(nextState) { nextState = nextState.copy(history = history + move) } } is PentaMove.InitGame -> { with(originalState) { requireMove(!gameStarted) { PentaMove.IllegalMove( "game is already started", move ) } requireMove(players.isNotEmpty()) { PentaMove.IllegalMove( "there is no players", move ) } } // TODO: setup UI for players related stuff here // remove old player pieces positions // figures.filterIsInstance<Piece.Player>().forEach { // positions.remove(it.id) // } // figures.filterIsInstance<Piece.BlackBlocker>().forEach { // it.position = it.originalPosition // } // figures.filterIsInstance<Piece.GrayBlocker>().forEach { // it.position = null // } with(nextState) { nextState = nextState.copy( gameStarted = true, turn = 0, history = history + move, currentPlayer = players.first() ) } // updateAllPieces() logger.info { "after init: " + nextState.figures.joinToString { it.id } } } // TODO: is this a Move ? is PentaMove.Win -> { // TODO handle win // TODO: set game to not running with(nextState) { nextState = nextState.copy( history = history + move ) } } is PentaMove.IllegalMove -> { logger.error { "illegal move: $move" } handleIllegalMove(move) } is PentaMove.Undo -> { move.moves.forEach { reverseNotation -> logger.info { "reverseNotation $reverseNotation" } val toReverseMove = reverseNotation.asMove(nextState) requireMove(nextState.history.last() == toReverseMove) { PentaMove.IllegalMove("cannot undo move $toReverseMove", move) } nextState = processMove(toReverseMove, true) } } }.exhaustive if (undo || move is PentaMove.Undo) { // early return, skip rest logger.info { "finished undoing $move" } return nextState } checkWin() with(nextState) { if (selectedBlackPiece == null && selectedGrayPiece == null && !selectingGrayPiece && move !is PentaMove.InitGame && move !is PentaMove.PlayerJoin && move !is PentaMove.Win && move !is PentaMove.SelectPlayerPiece && move !is PentaMove.SelectGrey && winner == null && !undo ) { logger.info { "incrementing turn after ${move.asNotation()}" } nextState = nextState.copy( currentPlayer = players[(turn + 1) % players.count()], turn = turn + 1 ) } } // if(forceMoveNextPlayer) { forceMovePlayerPiece(nextState.currentPlayer) // } // updateBoard() } catch (e: IllegalMoveException) { handleIllegalMove(e.move) } catch (e: Exception) { logger.error { e } } return nextState } /** * check if the moved piece is on a exit point */ fun WithMutableState.postProcess(move: PentaMove.Move) { nextState = nextState.copy(selectedPlayerPiece = null) val targetField = move.to logger.debug { "playerColor = ${move.playerPiece.pentaColor}" } logger.debug { if (targetField is Goal) { "pentaColor = ${targetField.pentaColor}" } else { "not a JointField" } } if (targetField is Goal && targetField.pentaColor == move.playerPiece.pentaColor) { // take piece off the board move.playerPiece.position = null val colors = nextState.figures .filterIsInstance<Piece.Player>() .filter { it.playerId == move.playerPiece.playerId } .filter { it.position == null } .map { it.pentaColor } .toTypedArray() val selectedGrayPiece = nextState.positions.filterValues { it == null } .keys.map { id -> nextState.figures.find { it.id == id } } .filterIsInstance<Piece.GrayBlocker>() .firstOrNull() nextState = nextState.copy( scoringColors = nextState.scoringColors + (move.playerPiece.playerId to colors), // set gamestate to `MOVE_GREY` selectedGrayPiece = selectedGrayPiece, selectingGrayPiece = selectedGrayPiece == null ) if (selectedGrayPiece == null) { logger.info { "selected gray piece: ${selectedGrayPiece?.id}" } } // TODO: update GUI somehow ? // updatePiecesAtPos(null) } } fun WithMutableState.forceMovePlayerPiece(player: PlayerState) { with(nextState) { if (selectingGrayPiece || selectingGrayPiece) return val playerPieces = figures.filterIsInstance<Piece.Player>().filter { it.playerId == player.id } for (playerPiece in playerPieces) { val field = playerPiece.position as? Goal ?: continue if (field.pentaColor != playerPiece.pentaColor) continue // TODO: use extra move type to signal forced move ? // TODO: trigger next action processMove( PentaMove.ForcedPlayerMove( playerPiece = playerPiece, from = field, to = field ) ) } } } fun WithMutableState.checkWin() = with(nextState) { // check win after last players turn if (winner != null || turn % players.size != players.size - 1) return if (selectingGrayPiece || selectedGrayPiece != null || selectedBlackPiece != null) return val winners = players.filter { player -> val playerPieces = figures.filterIsInstance<Piece.Player>().filter { it.playerId == player.id } val offBoardPieces = playerPieces.filter { it.position == null } offBoardPieces.size >= 3 } if (winners.isNotEmpty()) { nextState = nextState.copy( winner = winners.joinToString(", ") { it.id } ) processMove(PentaMove.Win(winners.map { it.id })) } } } fun canMove(start: Field, end: Field): Boolean { val backtrack = mutableSetOf<Field>() val next = mutableSetOf<Field>(start) while (next.isNotEmpty()) { val toIterate = next.toList() next.clear() toIterate.map { nextField -> logger.debug { "checking: ${nextField.id}" } nextField.connected.forEach { connectedField -> if (connectedField == end) return true if (connectedField in backtrack) return@forEach val free = positions.filterValues { field -> field == connectedField }.isEmpty() if (!free) return@forEach if (connectedField !in backtrack) { backtrack += connectedField next += connectedField } } } } return false } }
0
Kotlin
0
0
05acffed453348022b7ae603ccd8a0b7cedf844d
43,148
pentagame
MIT License
galleryImagePicker/src/main/java/com/samuelunknown/galleryImagePicker/presentation/ui/screen/gallery/fragment/GalleryFragmentVmFactory.kt
Samuel-Unknown
409,861,199
false
{"Kotlin": 78145}
package com.samuelunknown.galleryImagePicker.presentation.ui.screen.gallery.fragment import androidx.lifecycle.SavedStateHandle import com.samuelunknown.galleryImagePicker.domain.useCase.getImagesUseCase.GetImagesUseCase import com.samuelunknown.galleryImagePicker.domain.model.GalleryConfigurationDto import com.samuelunknown.galleryImagePicker.domain.useCase.getFoldersUseCase.GetFoldersUseCase import com.samuelunknown.galleryImagePicker.presentation.ui.SavedStateVmAssistedFactory internal class GalleryFragmentVmFactory( private val configurationDto: GalleryConfigurationDto, private val getImagesUseCase: GetImagesUseCase, private val getFoldersUseCase: GetFoldersUseCase ) : SavedStateVmAssistedFactory<GalleryFragmentVm> { override fun create(handle: SavedStateHandle): GalleryFragmentVm = GalleryFragmentVm( configurationDto = configurationDto, getImagesUseCase = getImagesUseCase, getFoldersUseCase = getFoldersUseCase ) }
0
Kotlin
2
8
e9a179911b811df77055ff0a4bdbaaf70db7e75f
1,002
Gallery-Image-Picker
Apache License 2.0
app/src/test/java/com/ms/catlife/feature_note/domain/use_case/ValidateCatUseCaseTest.kt
morganesoula
446,932,843
false
null
package com.ms.catlife.feature_note.domain.use_case import org.junit.Assert.assertTrue import org.junit.Test internal class ValidateCatUseCaseTest { private val validateCatUseCase = ValidateCatUseCase() @Test fun `test with 0, error`() { val result = validateCatUseCase.execute(0) assertTrue(!result.successful) } @Test fun `test with correct data, success`() { val result = validateCatUseCase.execute(2) assertTrue(result.successful) } }
0
Kotlin
0
2
80eb98072fd3326ae13503b2dc150a20f6574742
502
catlife
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/clipboard/ClipboardItem.kt
karakum-team
393,199,102
false
null
// Automatically generated - do not modify! package web.clipboard import js.core.ReadonlyArray import js.core.ReadonlyRecord import web.buffer.Blob import kotlin.js.Promise /** * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ClipboardItem) */ external class ClipboardItem( items: ReadonlyRecord<String, Any /* String | Blob | PromiseLike<String | Blob> */>, options: ClipboardItemOptions = definedExternally, ) { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ClipboardItem/types) */ val types: ReadonlyArray<String> /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ClipboardItem/getType) */ fun getType(type: String): Promise<Blob> }
0
Kotlin
6
23
3861ecb114ba6e0e8cef6e9885b1e4bc11c1cbcd
749
types-kotlin
Apache License 2.0
subprojects/client-paket/src/main/kotlin/com/handtruth/mc/mcsman/client/event/UnknownEvent.kt
handtruth
417,843,728
false
null
package com.handtruth.mc.mcsman.client.event class UnknownEvent { }
0
Kotlin
0
0
58b2d4bd0413522dbf1cbabc1c8bab78e1b1edfe
68
mcsman
Apache License 2.0
amazon/dynamodb/client/src/main/kotlin/org/http4k/connect/amazon/dynamodb/model/ReturnConsumedCapacity.kt
http4k
295,641,058
false
{"Kotlin": 1624429, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675}
package org.http4k.connect.amazon.dynamodb.model import se.ansman.kotshi.JsonSerializable @JsonSerializable enum class ReturnConsumedCapacity { INDEXES, TOTAL, NONE }
7
Kotlin
17
37
94e71e6bba87d9c79ac29f7ba23bdacd0fdf354c
173
http4k-connect
Apache License 2.0
app/src/main/java/io/pulque/blindhorse/choices/WrongOptionConfig.kt
pulcata
225,655,040
false
null
package io.pulque.blindhorse.choices import io.pulque.blindfold.R import io.pulque.fastchoicebutton.configurations.ChoiceConfiguration /* * @author savirdev on 2019-12-02 */ private const val WRONG_OPTION_CONFIG = "WRONG_OPTION_CONFIG" class WrongOptionConfig : ChoiceConfiguration(){ override fun getColorButton() = R.color.colorAccent override fun getDrawable(): Int = R.drawable.ic_close_black_24dp override fun getTag() = WRONG_OPTION_CONFIG override fun getSound(): Int? = R.raw.wrong }
0
Kotlin
0
0
8030b37cd3f24804e6c81b641055ee4d09d0fcee
517
blindhorse
Apache License 2.0
libraries/model/src/main/java/de/schnettler/scrobbler/model/remote/AlbumResponse.kt
nschnettler
260,203,355
false
{"Kotlin": 440825}
package de.schnettler.scrobbler.model.remote interface AlbumResponse { val name: String val url: String val artist: String val images: List<ImageResponse> }
10
Kotlin
5
57
523d0b739901b971fd41e09258dcab6dcb1c8e58
173
Compose-Scrobbler
Apache License 2.0
redwood-treehouse-host/src/commonTest/kotlin/app/cash/redwood/treehouse/FakeDispatchers.kt
cashapp
305,409,146
false
{"Kotlin": 1935697, "Swift": 13352, "Java": 1583, "Objective-C": 1499, "Shell": 253, "HTML": 235, "C": 43}
/* * Copyright (C) 2023 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 app.cash.redwood.treehouse import kotlinx.coroutines.CoroutineDispatcher class FakeDispatchers( override val ui: CoroutineDispatcher, override val zipline: CoroutineDispatcher, ) : TreehouseDispatchers { override fun checkUi() { } override fun checkZipline() { } override fun close() { } }
125
Kotlin
65
1,516
b3028ae96c84b66fa377c2c1b668908227bd774a
920
redwood
Apache License 2.0
src/functionalTest/kotlin/kotlinx/validation/api/testDsl.kt
Him188
331,521,181
true
{"Kotlin": 74466, "Java": 245}
/* * Copyright 2016-2020 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ package kotlinx.validation.api import org.gradle.testkit.runner.* import java.io.* internal fun BaseKotlinGradleTest.test(fn: BaseKotlinScope.() -> Unit): GradleRunner { val baseKotlinScope = BaseKotlinScope() fn(baseKotlinScope) baseKotlinScope.files.forEach { scope -> val fileWriteTo = testProjectDir.root.resolve(scope.filePath) .apply { parentFile.mkdirs() createNewFile() } scope.files.forEach { val fileContent = readFileList(it) fileWriteTo.appendText("\n" + fileContent) } } return GradleRunner.create() // .withProjectDir(testProjectDir.root) .withPluginClasspath() .withArguments(baseKotlinScope.runner.arguments) // disabled because of: https://github.com/gradle/gradle/issues/6862 // .withDebug(baseKotlinScope.runner.debug) } internal fun BaseKotlinScope.file(fileName: String, fn: AppendableScope.() -> Unit) { val appendableScope = AppendableScope(fileName) fn(appendableScope) files.add(appendableScope) } /** * same as [file], but appends "src/main/java" before given `classFileName` */ internal fun BaseKotlinScope.kotlin(classFileName: String, fn: AppendableScope.() -> Unit) { require(classFileName.endsWith(".kt")) { "ClassFileName must end with '.kt'" } val fileName = "src/main/java/$classFileName" file(fileName, fn) } /** * Shortcut for creating a `build.gradle.kts` by using [file] */ internal fun BaseKotlinScope.buildGradleKts(fn: AppendableScope.() -> Unit) { val fileName = "build.gradle.kts" file(fileName, fn) } internal fun BaseKotlinScope.runner(fn: Runner.() -> Unit) { val runner = Runner() fn(runner) this.runner = runner } internal fun AppendableScope.resolve(fileName: String) { this.files.add(fileName) } internal class BaseKotlinScope { var files: MutableList<AppendableScope> = mutableListOf() var runner: Runner = Runner() } internal class AppendableScope(val filePath: String) { val files: MutableList<String> = mutableListOf() } internal class Runner { val arguments: MutableList<String> = mutableListOf() } internal fun readFileList(fileName: String): String { val resource = BaseKotlinGradleTest::class.java.classLoader.getResource(fileName) ?: throw IllegalStateException("Could not find resource '$fileName'") return File(resource.toURI()).readText() }
0
null
0
0
5c7a3ca0a55ada518610b43742057ff21afdf291
2,629
binary-compatibility-validator
Apache License 2.0
build-systems/src/commonMain/kotlin/org/jetbrains/packagesearch/maven/HttpClientMavenPomProvider.kt
JetBrains
498,634,410
false
{"Kotlin": 154308}
package org.jetbrains.packagesearch.maven import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.call.body import io.ktor.client.plugins.HttpRequestRetry import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.get import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.Url import io.ktor.serialization.kotlinx.KotlinxSerializationConverter import io.ktor.utils.io.core.Closeable import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import nl.adaptivity.xmlutil.serialization.XML public class HttpClientMavenPomProvider( public val mirrors: List<MavenUrlBuilder>, public val httpClient: HttpClient, public val xml: XML = PomResolver.defaultXml(), ) : MavenPomProvider, Closeable by httpClient { @Deprecated("Use mirrors instead", ReplaceWith("mirrors")) public val repositories: List<MavenUrlBuilder> get() = mirrors public companion object { public fun defaultHttpClient( xml: XML = PomResolver.defaultXml(), configure: HttpClientConfig<*>.() -> Unit = {}, ): HttpClient = HttpClient { install(ContentNegotiation) { val converter = KotlinxSerializationConverter(xml) register(ContentType.Application.Xml, converter) register(ContentType.Text.Xml, converter) } install(HttpRequestRetry) { retryOnExceptionOrServerErrors(10) constantDelay(100, 50, false) } configure() } } override suspend fun getPom( groupId: String, artifactId: String, version: String, ): ProjectObjectModel = getPomFromMultipleRepositories(groupId, artifactId, version).first() override suspend fun getPomFromMultipleRepositories( groupId: String, artifactId: String, version: String, ): Flow<ProjectObjectModel> = mirrors.asFlow().map { it.getPom(groupId, artifactId, version) } override suspend fun getPomByUrl(url: Url): ProjectObjectModel = httpClient.get(url).bodyAsPom(xml) private suspend fun MavenUrlBuilder.getPom( groupId: String, artifactId: String, version: String, ): ProjectObjectModel = getPomByUrl(buildPomUrl(groupId, artifactId, version)) private suspend fun HttpResponse.bodyAsPom(xml: XML) = runCatching { body<ProjectObjectModel>() }.getOrNull() ?: xml.decodeFromString(POM_XML_NAMESPACE, bodyAsText()) }
0
Kotlin
4
5
62fe96f6d76ae6416ee1d4ad049ad13bb8a92179
2,812
package-search-api-models
Apache License 2.0
app/src/main/java/com/tommunyiri/dvtweatherapp/data/sources/local/database/dao/WeatherDao.kt
TomMunyiri
745,177,252
false
{"Kotlin": 217339}
package com.tommunyiri.dvtweatherapp.data.sources.local.database.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.tommunyiri.dvtweatherapp.data.sources.local.database.entity.DBFavoriteLocation import com.tommunyiri.dvtweatherapp.data.sources.local.database.entity.DBWeather import com.tommunyiri.dvtweatherapp.data.sources.local.database.entity.DBWeatherForecast /** * Created by <NAME> on 18/01/2024. * Company: Eclectics International Ltd * Email: <EMAIL> */ @Dao interface WeatherDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertWeather(vararg dbWeather: DBWeather) @Query("SELECT * FROM weather_table ORDER BY unique_id DESC LIMIT 1") suspend fun getWeather(): DBWeather @Query("SELECT * FROM weather_table ORDER BY unique_id DESC") suspend fun getAllWeather(): List<DBWeather> @Query("DELETE FROM weather_table") suspend fun deleteAllWeather() @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertForecastWeather(vararg dbWeatherForecast: DBWeatherForecast) @Query("SELECT * FROM weather_forecast ORDER BY id") suspend fun getAllWeatherForecast(): List<DBWeatherForecast> @Query("DELETE FROM weather_forecast") suspend fun deleteAllWeatherForecast() @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertFavoriteCity(vararg city: DBFavoriteLocation): List<Long> @Query("SELECT * FROM favorite_locations_table ORDER BY name ASC") suspend fun getAllFavoriteLocations(): List<DBFavoriteLocation> @Query("DELETE FROM favorite_locations_table WHERE name=:name") suspend fun deleteFavoriteLocation(name: String): Int }
0
Kotlin
0
0
9d4bcb1d4e1a3e47ad4ae9424e8c57a6a100acc3
1,749
DVTWeatherApp
The Unlicense
src/main/kotlin/dk/cachet/carp/webservices/common/extensions/StringExtensions.kt
cph-cachet
674,650,033
false
{"Kotlin": 671387, "TypeScript": 106849, "HTML": 14228, "Shell": 4202, "CSS": 1656, "Dockerfile": 1264, "JavaScript": 706}
package dk.cachet.carp.webservices.common.extensions import java.util.* fun String.toSnakeCase(): String = this.replace( Regex( "([a-z])([A-Z]+)" ), "$1_$2" ) .replace( Regex( "([A-Z])([A-Z][a-z])" ), "$1_$2" ) .lowercase(Locale.getDefault())
16
Kotlin
1
3
15a2c8788738fae973d2bb0dd14aadd0524fe8ea
265
carp-webservices-spring
MIT License
app/src/main/java/com/example/mylotteryapp/screens/listScreen/ListScreen.kt
petyo-petkov
766,056,034
false
{"Kotlin": 90720}
package com.example.mylotteryapp.screens.listScreen import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FabPosition import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import com.example.mylotteryapp.screens.ListBoletos import com.example.mylotteryapp.screens.TopBar import com.example.mylotteryapp.viewModels.RealmViewModel import com.example.mylotteryapp.viewModels.ScannerViewModel import com.ramcosta.composedestinations.annotation.Destination import com.ramcosta.composedestinations.annotation.RootGraph import com.ramcosta.composedestinations.navigation.DestinationsNavigator @OptIn(ExperimentalMaterial3Api::class) @Destination<RootGraph> @Composable fun BoletosListScreen( navigator: DestinationsNavigator, realmViewModel: RealmViewModel, scannerViewModel: ScannerViewModel ) { val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() val boletos = realmViewModel.boletos Scaffold( modifier = Modifier .fillMaxSize() .nestedScroll(scrollBehavior.nestedScrollConnection) , topBar = { TopBar( boletos = boletos, scrollBehavior, realmViewModel ) }, floatingActionButton = { ListScreenFAB( realmViewModel = realmViewModel, scannerViewModel = scannerViewModel, navigator = navigator ) }, floatingActionButtonPosition = FabPosition.Center, containerColor = MaterialTheme.colorScheme.background ) { ListBoletos( realmViewModel = realmViewModel, paddingValues = it, boletos = boletos ) } }
0
Kotlin
0
0
699c38f06cd775b0c82fceb9b4ee25c33469b468
2,022
MyLotteryApp
MIT License
src/main/kotlin/net/schowek/nextclouddlna/nextcloud/db/MimetypeRepository.kt
thanek
702,137,946
false
{"Kotlin": 57868, "Groovy": 32175, "Shell": 692, "Dockerfile": 137}
package net.schowek.nextclouddlna.nextcloud.db import jakarta.persistence.Entity import jakarta.persistence.Id import jakarta.persistence.Table import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface MimetypeRepository : JpaRepository<Mimetype, Int> @Entity @Table(name = "oc_mimetypes") data class Mimetype( @Id val id: Int, val mimetype: String )
1
Kotlin
0
3
2a33a897221a0ad163a76d89d64640ad964c7c72
442
nextcloud-dlna
MIT License
core/src/com/coronadefense/receiver/messages/MoneyUpdateMessage.kt
swa-group1
346,617,304
false
{"Kotlin": 102514}
package com.coronadefense.receiver.messages data class MoneyUpdateMessage( val newValue: Int, ): IMessage
7
Kotlin
0
1
c93845de7e2ed4b4d95070547721ef93e0357a6e
111
corona-defense-client
MIT License
client-android/app/src/test/java/stasis/test/client_android/security/SecretsSpec.kt
sndnv
153,169,374
false
{"Scala": 2983542, "Kotlin": 1568224, "Dart": 784931, "Python": 344197, "Shell": 67975, "CMake": 8759, "C++": 4051, "HTML": 2666, "Dockerfile": 1948, "Ruby": 1330, "C": 691, "Swift": 607, "JavaScript": 516}
package stasis.test.client_android.security import android.content.SharedPreferences import io.mockk.every import io.mockk.mockk import io.mockk.verify import kotlinx.coroutines.runBlocking import okio.ByteString.Companion.toByteString import org.hamcrest.CoreMatchers.anyOf import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import stasis.client_android.persistence.config.ConfigRepository import stasis.client_android.security.Secrets import java.util.Base64 import java.util.UUID @RunWith(RobolectricTestRunner::class) @Config(sdk = [Config.OLDEST_SDK]) class SecretsSpec { @Test fun generateRawDeviceSecrets() { val expectedSecretSize = 42 val generatedSecret = Secrets.generateRawDeviceSecret(secretSize = expectedSecretSize) assertThat(generatedSecret.size, equalTo(expectedSecretSize)) } @Test fun createDeviceSecrets() { val preferences = initPreferences() val editor = mockk<SharedPreferences.Editor>(relaxUnitFun = true) every { preferences.edit() } returns editor every { editor.putString( ConfigRepository.Companion.Keys.Secrets.EncryptedDeviceSecret, any() ) } returns editor every { editor.commit() } returns true runBlocking { val result = Secrets.createDeviceSecret( user = UUID.randomUUID(), userSalt = "test-salt", userPassword = "<PASSWORD>".toCharArray(), device = UUID.randomUUID(), preferences = preferences ) assertThat(result.isSuccess, equalTo(true)) verify(exactly = 1) { editor.commit() } } } @Test fun loadDeviceSecrets() { val preferences = initPreferences() val user = UUID.randomUUID() val userSalt = "test-salt" val userPassword = "<PASSWORD>".toCharArray() val device = UUID.randomUUID() runBlocking { val result = Secrets.loadDeviceSecret( user = user, userSalt = userSalt, userPassword = <PASSWORD>, device = device, preferences = preferences ) // loading of all config is expected to be successful but actual // device secret decryption should fail because there's no valid // encrypted secret in the mock preferences val e = result.failed().get() assertThat( e.message, anyOf( containsString("Output buffer invalid"), containsString("BAD_DECRYPT"), equalTo("Input too short - need tag") ) ) } } @Test fun storeDeviceSecrets() { val preferences = initPreferences() val editor = mockk<SharedPreferences.Editor>(relaxUnitFun = true) every { preferences.edit() } returns editor every { editor.putString( ConfigRepository.Companion.Keys.Secrets.EncryptedDeviceSecret, any() ) } returns editor every { editor.commit() } returns true val user = UUID.randomUUID() val userSalt = "test-salt" val userPassword = "<PASSWORD>".toCharArray() val device = UUID.randomUUID() runBlocking { val result = Secrets.storeDeviceSecret( user = user, userSalt = userSalt, userPassword = <PASSWORD>, device = device, secret = "other-secret".toByteArray().toByteString(), preferences = preferences ) assertThat(result.isSuccess, equalTo(true)) verify(exactly = 1) { editor.commit() } } } @Test fun loadUserAuthenticationPasswords() { val preferences = initPreferences() val user = UUID.randomUUID() val userSalt = "test-salt" val userPassword = "<PASSWORD>".toCharArray() val result = Secrets.loadUserAuthenticationPassword( user = user, userSalt = userSalt, userPassword = <PASSWORD>, preferences = preferences ) assertThat(result.user, equalTo(user)) assertThat(result.extract().isNotBlank(), equalTo(true)) } @Test fun initDeviceSecrets() { val preferences = initPreferences() val user = UUID.randomUUID() val device = UUID.randomUUID() val secret = "test-secret".toByteArray().toByteString() val result = Secrets.initDeviceSecret( user = user, device = device, secret = secret, preferences = preferences ) assertThat(result.user, equalTo(user)) assertThat(result.device, equalTo(device)) assertThat(result.secret, equalTo(secret)) } private fun initPreferences(): SharedPreferences { val preferences = mockk<SharedPreferences>() every { preferences.getString( ConfigRepository.Companion.Keys.Secrets.EncryptedDeviceSecret, null ) } returns Base64.getUrlEncoder().withoutPadding() .encodeToString("invalid-secret".toByteArray()) every { preferences.getInt( ConfigRepository.Companion.Keys.Secrets.DerivationEncryptionSecretSize, any() ) } returns 16 every { preferences.getInt( ConfigRepository.Companion.Keys.Secrets.DerivationEncryptionIterations, any() ) } returns 100000 every { preferences.getString( ConfigRepository.Companion.Keys.Secrets.DerivationEncryptionSaltPrefix, any() ) } returns "test-encryption-prefix" every { preferences.getBoolean( ConfigRepository.Companion.Keys.Secrets.DerivationAuthenticationEnabled, any() ) } returns true every { preferences.getInt( ConfigRepository.Companion.Keys.Secrets.DerivationAuthenticationSecretSize, any() ) } returns 32 every { preferences.getInt( ConfigRepository.Companion.Keys.Secrets.DerivationAuthenticationIterations, any() ) } returns 200000 every { preferences.getString( ConfigRepository.Companion.Keys.Secrets.DerivationAuthenticationSaltPrefix, any() ) } returns "test-authentication-prefix" every { preferences.getInt(ConfigRepository.Companion.Keys.Secrets.EncryptionFileKeySize, any()) } returns 16 every { preferences.getInt( ConfigRepository.Companion.Keys.Secrets.EncryptionMetadataKeySize, any() ) } returns 16 every { preferences.getInt( ConfigRepository.Companion.Keys.Secrets.EncryptionDeviceSecretKeySize, any() ) } returns 16 return preferences } }
1
Scala
3
23
1cf502a358825f36dcae6c096fbaf9dc5147649f
7,594
stasis
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem19/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 577604}
package com.hj.leetcode.kotlin.problem19 import com.hj.leetcode.kotlin.common.model.ListNode /** * LeetCode page: [19. Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the number of nodes in head; */ fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? { val totalNodes = head.size() val removePositionFromStart = totalNodes - n + 1 val isRemovingHead = removePositionFromStart == 1 if (isRemovingHead) return head?.next val nodeBefore = head.getNthNode(removePositionFromStart - 1) nodeBefore?.next = nodeBefore?.next?.next return head } private fun ListNode?.size(): Int { var count = 0 var currNode = this while (currNode != null) { count++ currNode = currNode.next } return count } private fun ListNode?.getNthNode(n: Int): ListNode? { var position = 1 var node = this while (position < n && node != null) { position++ node = node.next } return node } }
1
Kotlin
0
1
92ef539b049a047ed3ce1b282be2c79c6f84ffee
1,217
hj-leetcode-kotlin
Apache License 2.0
app/src/main/java/com/azaless/cheerball/util/InjectorUtils.kt
annchar
136,462,003
false
{"Kotlin": 44639}
package com.azaless.cheerball.util import android.content.Context import com.azaless.cheerball.data.CheerBallDataRepository import com.azaless.cheerball.view.ui.teams.TeamsViewModelFactory import com.azaless.cheerball.view.ui.groupsball.GroupsBallViewModelFactory import com.azaless.cheerball.view.ui.teamdetail.TeamDetailViewModelFactory object InjectorUtils { fun provideTeamViewModelFactory( context: Context, teamId: Int, teamName: String): TeamDetailViewModelFactory { return TeamDetailViewModelFactory(CheerBallDataRepository.getInstance(),teamId, teamName) } fun provideTeamsViewModelFactory( context: Context, eventId: Int): TeamsViewModelFactory { return TeamsViewModelFactory(CheerBallDataRepository.getInstance(),eventId) } fun provideGroupsBallViewModelFactory( context: Context, eventId: Int): GroupsBallViewModelFactory { return GroupsBallViewModelFactory(CheerBallDataRepository.getInstance(),eventId) } }
0
Kotlin
1
2
7565e88051a1a9357ebbf3c7129f5e3f95228aea
955
CheerBall
The Unlicense
ahp-base/src/main/kotlin/pl/poznan/put/ahp/ahp-base.kt
Azbesciak
140,010,837
false
{"Kotlin": 93061, "R": 67629, "Shell": 24899, "Groovy": 24559}
package pl.poznan.put.ahp import pl.poznan.put.xmcda.WarnException import pl.poznan.put.xmcda.XmcdaFile val criteriaV2files = arrayOf( XmcdaFile("criteria"), XmcdaFile("criteria_comparisons", tag = "criteriaComparisons") ) val criteriaV3files = arrayOf( XmcdaFile("criteria"), XmcdaFile("criteria_comparisons", tag = "criteriaMatrix") ) typealias CrytId = String fun AhpResult.validityErrorMessage() = "Found invalid nodes (cr should be below ${Category.VALIDITY_THRESHOLD}): ${invalidNode.joinToString(", ") { "${it.name} - ${it.cr}" }}}" fun AhpResult.compute() = if (invalidNode.isNotEmpty()) throw WarnException(validityErrorMessage(), ranking) else ranking
0
Kotlin
2
1
96c182d7e37b41207dc2da6eac9f9b82bd62d6d7
748
DecisionDeck
MIT License
src/main/kotlin/com/turbohesap/exceptions/GlobalExceptionHandler.kt
mcihad
764,637,754
false
{"Kotlin": 30439}
package com.turbohesap.exceptions import com.turbohesap.dtos.ErrorResponseDto import org.springframework.http.HttpStatus import org.springframework.web.ErrorResponse import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestControllerAdvice @RestControllerAdvice class GlobalExceptionHandler { @ExceptionHandler(RecordAlreadyExistsException::class) @ResponseStatus(HttpStatus.BAD_REQUEST) fun handleRecordAlreadyExistsException(ex: RecordAlreadyExistsException): ErrorResponseDto { return ErrorResponseDto( message = ex.message!!, data = null ) } @ExceptionHandler(ValidationException::class) @ResponseStatus(HttpStatus.BAD_REQUEST) fun handleValidationException(ex: ValidationException): ErrorResponseDto { return ErrorResponseDto( message = ex.message!!, data = ex.data ) } @ExceptionHandler(RecordNotFoundException::class) @ResponseStatus(HttpStatus.NOT_FOUND) fun handleRecordNotFoundException(ex: RecordNotFoundException): ErrorResponseDto { return ErrorResponseDto( message = ex.message!!, data = null ) } }
0
Kotlin
0
0
2f3f4ae994edac632596fcfbad70d9011382c4fd
1,305
springboot-kotlin-jwt
MIT License
sdk/src/main/java/io/stipop/view/pickerview/StickerPickerPopupView.kt
stipop-development
372,351,610
false
{"Kotlin": 309491}
package io.stipop.view.pickerview import android.app.Activity import android.widget.PopupWindow import io.stipop.Config import io.stipop.Stipop import io.stipop.StipopKeyboardHeightProvider import io.stipop.databinding.ViewPickerBinding import io.stipop.view.pickerview.listener.VisibleStateListener internal class StickerPickerPopupView( private val activity: Activity ) : PopupWindow() { private var binding: ViewPickerBinding = ViewPickerBinding.inflate(activity.layoutInflater) var wantShowing: Boolean = false var lastKeyboardHeight: Int = 0 init { if (Config.isPickerViewPopupWindow()) { Stipop.stickerPickerViewClass = StickerPickerViewClass( PickerViewType.ON_KEYBOARD, this, null, activity, binding ) getStickerPickerKeyboardViewHeight() } } internal fun setDelegate(visibleDelegate: VisibleStateListener) { Stipop.stickerPickerViewClass?.setDelegate(visibleDelegate) } internal fun show(y: Int) { Stipop.stickerPickerViewClass?.show(y) } private fun getStickerPickerKeyboardViewHeight() { try { StipopKeyboardHeightProvider(activity).init().setHeightListener(object : StipopKeyboardHeightProvider.StipopKeyboardHeightListener { override fun onHeightChanged(fromTopToVisibleFramePx: Int, keyboardHeight: Int) { val fixedKeyboardHeight = if (keyboardHeight >= 0) { keyboardHeight } else { 0 } if (lastKeyboardHeight != fixedKeyboardHeight) { Stipop.keyboardHeightDelegate?.onHeightChanged(keyboardHeight) lastKeyboardHeight = fixedKeyboardHeight } } }) } catch (exception: Exception) { Stipop.trackError(exception) } } }
2
Kotlin
5
19
6b78b4354e3b3cfbc51db685196d56197d57a653
2,021
stipop-android-sdk
MIT License
src/main/kotlin/com/github/dreamylost/LeetcodeGradlePlugin.kt
jxnu-liguobin
348,630,254
false
null
/* Licensed under Apache-2.0 @梦境迷离 */ package com.github.dreamylost import com.github.dreamylost.task.LeetcodeGradleTask import org.gradle.api.Plugin import org.gradle.api.Project open class LeetcodeGradlePlugin : Plugin<Project> { override fun apply(project: Project) { val tasks = project.tasks val extensions = project.extensions tasks.create("leetcodeCodegen", LeetcodeGradleTask::class.java) extensions.create("leetcodeExtension", LeetcodePluginExtension::class.java) } } open class LeetcodePluginExtension { var templateSourceCode: String? = null var templateName: String? = null var customData: Map<String, Any> = mapOf() var deleteExistsFolder: Boolean = false }
0
Kotlin
0
0
19e47a96ca3c98eccdd7b3f245a465ce845b23d8
730
leetcode-helper
Apache License 2.0
plugins/python/src/test/kotlin/io/paddle/testExecutor/AbstractTestContainerTest.kt
JetBrains-Research
377,213,824
false
null
package io.paddle.testExecutor import io.paddle.execution.local.LocalCommandExecutor import io.paddle.terminal.Terminal import io.paddle.testExecutor.AbstractTestContainerTest.Companion.paddleHome import io.paddle.testExecutor.AbstractTestContainerTest.Companion.resources import io.paddle.utils.config.PaddleAppRuntime import io.paddle.utils.config.PaddleApplicationSettings import io.paddle.utils.deepResolve import org.junit.jupiter.api.* import org.junit.jupiter.api.extension.RegisterExtension import org.koin.dsl.module import org.koin.test.KoinTest import org.koin.test.junit5.KoinTestExtension import org.testcontainers.containers.BindMode import org.testcontainers.containers.GenericContainer import org.testcontainers.containers.output.OutputFrame import org.testcontainers.containers.output.ToStringConsumer import org.testcontainers.images.builder.ImageFromDockerfile import org.testcontainers.junit.jupiter.Container import org.testcontainers.junit.jupiter.Testcontainers import java.io.File import java.nio.file.Path import java.time.Duration /** * An abstract test, that executes in a docker container * * To use just inherit your test class from this class. It mounts resources folder * and creates a local paddle home directory, that is not associated with your PADDLE_HOME. * * **NB**: the paddle home directory is not clearing between test, but the project folders (.venv, project's .paddle) are. * @param containerName Docker's container name:version, that will be pulled locally(?) or from Docker Hub * @property resources A test resources folder * @property paddleHome A local paddle home folder, that is used * @property container Currently running container abstraction, that set to run until test completes, * set user with your user permissions and mounted [resources] and [paddleHome] with your host's paths, so in code you can use your local paths * @property console Every test refreshing console, that holds stdout and stderr * @property terminal Every test refreshing terminal, that used in [LocalCommandExecutor.execute] * @property executor Every test refreshing executor, that run command in the docker container * @property logConsumer Container's log consumer */ @Testcontainers open class AbstractTestContainerTest(containerName: String) : KoinTest { private class PaddleResourcesHomeProvider : PaddleApplicationSettings.PaddleHomeProvider { override fun getPath(): Path { return paddleHome.absoluteFile.toPath() } } init { if (!paddleHome.exists()) { paddleHome.mkdirs() } } @Container protected var container: GenericContainer<*> = GenericContainer(ImageFromDockerfile() .withDockerfileFromBuilder { val cmdExecutor = LocalCommandExecutor() val output = mutableListOf<String>() cmdExecutor.execute("id", args = listOf("-u"), workingDir = resources, terminal = Terminal.MOCK, systemOut = { output.add(it) } ) val USER_ID = output[0].trim() output.clear() cmdExecutor.execute("id", args = listOf("-g"), workingDir = resources, terminal = Terminal.MOCK, systemOut = { output.add(it) } ) val GROUP_ID = output[0].trim() it .from(containerName) .run("addgroup --gid $GROUP_ID user") .run("adduser --disabled-password --gecos '' --uid $USER_ID --gid $GROUP_ID user") .user("user") }) .withCommand("tail -f /dev/null") // a stub command to keep container alive .withFileSystemBind(resources.absolutePath, resources.absolutePath, BindMode.READ_WRITE) .withFileSystemBind(paddleHome.absolutePath, paddleHome.absolutePath, BindMode.READ_WRITE) .withStartupTimeout(Duration.ofHours(1)) protected lateinit var executor: TestContainerExecutor protected lateinit var console: TestConsole protected lateinit var terminal: Terminal protected lateinit var logConsumer: ToStringConsumer /** * Initialize test environment */ @BeforeEach fun executorInit() { executor = TestContainerExecutor(container) console = TestConsole() terminal = Terminal(console) logConsumer = ToStringConsumer() container.followOutput(logConsumer, OutputFrame.OutputType.STDOUT) assert(container.isRunning) // FIXME: this make TestContainer fail without error and with empty log // paddleHome.listFiles()?.forEach { // it.deleteRecursively() // } } @JvmField @RegisterExtension val koinTestExtension = KoinTestExtension.create { modules(module { single<PaddleApplicationSettings.PaddleHomeProvider> { PaddleResourcesHomeProvider() } }) } companion object { @JvmStatic protected val resources: File = File("src").deepResolve("test", "resources") @JvmStatic protected val paddleHome: File = resources.resolve(".paddle") /** * Cleanup .paddleHome after all tests */ @JvmStatic @AfterAll fun deletePaddleHome() { paddleHome.deleteRecursively() } @JvmStatic @BeforeAll fun assertTestMode() { assert(PaddleAppRuntime.isTests) } } }
13
Kotlin
6
20
42a26a7f5815961d564f71e3606252fab7a87f82
5,631
paddle
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem502/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619847}
package com.hj.leetcode.kotlin.problem502 import java.util.* /** * LeetCode page: [502. IPO](https://leetcode.com/problems/ipo/); */ class Solution { /* Complexity: * Time O(NLogN) and Space O(N) where N is the size of capital/profits; */ fun findMaximizedCapital(k: Int, w: Int, profits: IntArray, capital: IntArray): Int { // Use the index of capital/profits as project's id val idSortedByCapital = capital.indices.sortedBy { capital[it] } var maxCapital = w var nextIdIndex = 0 val availableProfitMaxPq = PriorityQueue<Int>(reverseOrder()) repeat(k) { while ( nextIdIndex < idSortedByCapital.size && capital[idSortedByCapital[nextIdIndex]] <= maxCapital ) { val id = idSortedByCapital[nextIdIndex] val profit = profits[id] availableProfitMaxPq.offer(profit) nextIdIndex++ } val maxAvailableProfit = availableProfitMaxPq.poll() ?: 0 val noAvailableProfitOrIsZeroProfit = maxAvailableProfit == 0 if (noAvailableProfitOrIsZeroProfit) return maxCapital maxCapital += maxAvailableProfit } return maxCapital } }
1
Kotlin
0
1
e7eddc93823a158f611ee2a79df5397d1c305a26
1,280
hj-leetcode-kotlin
Apache License 2.0
leetcode/src/linkedlist/Q82.kt
zhangweizhe
387,808,774
false
null
package linkedlist fun main() { // 82. 删除排序链表中的重复元素 II // https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/ val createList = LinkedListUtil.createList(intArrayOf(1, 2, 3, 3, 3, 4, 4, 5, 5)) LinkedListUtil.printLinkedList(deleteDuplicates(createList)) } private fun deleteDuplicates(head: ListNode?): ListNode? { var dummyHead = ListNode(0) dummyHead.next = head var cur:ListNode? = dummyHead while (cur?.next != null && cur.next?.next != null) { if (cur.next?.`val` == cur.next?.next?.`val`) { val tmp = cur.next?.`val` while (tmp == cur.next?.`val`) { cur.next = cur.next?.next } }else { cur = cur.next } } return dummyHead.next }
0
Kotlin
0
0
86d3414a84cc43054f13f6be9b1b3e66c184a246
784
kotlin-study
MIT License
app/src/main/java/com/example/noteapp/NoteApp.kt
nguyencse
611,364,219
false
null
package com.example.noteapp import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class NoteApp : Application() {}
0
Kotlin
0
0
85d467406fe889fe2edb0bbab882a18ab0710906
151
NoteApp
Apache License 2.0
app/src/main/java/com/bluethunder/tar2/ui/BaseFragment.kt
eslamfaisal
512,166,864
false
null
package com.bluethunder.tar2.ui import android.view.View import androidx.fragment.app.Fragment open class BaseFragment : Fragment() { var hasInitializedRootView = false }
0
Kotlin
0
18
1ca46a9b534bd23c61ebf6f143bf9b5379223e53
179
emergency-services
Apache License 2.0
replay/src/main/kotlin/ys/phoebos/redis/replay/client/Connector.kt
phoebosys
162,104,139
false
null
/* * Copyright Phoebosys * * 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 ys.phoebos.redis.replay.client import redis.clients.jedis.util.IOUtils import ys.phoebos.redis.protocol.Reply import ys.phoebos.redis.protocol.ReplyInputStream import ys.phoebos.redis.replay.DEFAULT_TIMEOUT import java.io.* import java.net.InetSocketAddress import java.net.Socket import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLParameters import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory class Connector(private val addr: InetSocketAddress, private val ssl: Boolean = false, private var sslSocketFactory: SSLSocketFactory? = null, private var sslParameters: SSLParameters? = null, private var hostnameVerifier: HostnameVerifier? = null ) : Closeable { private var socket: Socket? = null private var outputStream: OutputStream? = null private var replyInputStream: ReplyInputStream? = null //private var rowReader: BufferedReader? = null private val connectionTimeout = DEFAULT_TIMEOUT private val soTimeout = DEFAULT_TIMEOUT private var isBroken = false private val CRLF = "\r\n".toByteArray() fun send(cmd: ByteArray) { try { connect() outputStream!!.write(cmd) outputStream!!.write(CRLF) outputStream!!.flush() } catch (ex: IOException) { isBroken = true throw ex } } fun send(cmd: String) { send(cmd.toByteArray()) } fun sendRow(cmd: String) { send(cmd) } fun receive(): Reply { try { connect() return replyInputStream!!.readReply() } catch (ex: IOException) { isBroken = true throw ex } } fun receiveRow(): String { return String(receive().toProtocol()) } fun connect() { if (!isConnected()) { try { socket = Socket() socket!!.reuseAddress = true socket!!.keepAlive = true socket!!.tcpNoDelay = true socket!!.setSoLinger(true, 0) socket!!.connect(addr, connectionTimeout) // socket!!.soTimeout = soTimeout if (ssl) { if (null == sslSocketFactory) { sslSocketFactory = SSLSocketFactory.getDefault() as SSLSocketFactory } socket = sslSocketFactory!!.createSocket(socket, addr.hostName, addr.port, true) if (null != sslParameters) { (socket as SSLSocket).sslParameters = sslParameters } if (null != hostnameVerifier && !hostnameVerifier!!.verify(addr.hostName, (socket as SSLSocket).session)) { throw IOException("The connection to ${addr.hostName} failed ssl/tls hostname verification.") } } outputStream = socket!!.getOutputStream() replyInputStream = ReplyInputStream(socket!!.getInputStream()) // rowReader = BufferedReader(InputStreamReader(socket!!.getInputStream())) } catch (ex: IOException) { isBroken = true throw IOException("Failed connecting to host ${addr.hostName}:${addr.port}", ex) } } } fun isConnected(): Boolean { return socket != null && socket!!.isBound && !socket!!.isClosed && socket!!.isConnected && !socket!!.isInputShutdown && !socket!!.isOutputShutdown } fun disconnect() { if (isConnected()) { try { outputStream!!.flush() socket!!.close() } catch (ex: IOException) { isBroken = true throw IOException(ex) } finally { IOUtils.closeQuietly(socket) } } } protected fun flush() { try { outputStream!!.flush() } catch (ex: IOException) { isBroken = true throw ex } } override fun close() { disconnect() } }
0
Kotlin
0
0
66a7768df9043e1edc1432e0c875c03ee9f433e7
4,784
redis-remoteback
Apache License 2.0
src/main/kotlin/br/com/zupacademy/gabrielamartins/model/enums/TipoChave.kt
gabrielamartinszup
409,667,340
true
{"Kotlin": 82274}
package br.com.zupacademy.gabrielamartins.model.enums import org.hibernate.validator.internal.constraintvalidators.hv.br.CPFValidator enum class TipoChave { CPF { override fun valida(chave: String?): Boolean { if (chave.isNullOrBlank()) { return false } if (!chave.matches("[0-9]+".toRegex())) { return false } CPFValidator().run { initialize(null) return isValid(chave, null) } } }, TELEFONE { override fun valida(chave: String?): Boolean { if (chave.isNullOrBlank()) { return false } return chave.matches("^\\+[1-9][0-9]\\d{1,14}\$".toRegex()) } }, EMAIL { override fun valida(chave: String?): Boolean { if (chave.isNullOrBlank()) { return false } return chave.matches("^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}\$".toRegex()) } }, ALEATORIA { override fun valida(chave: String?) = chave.isNullOrBlank() // não deve se preenchida }; abstract fun valida(chave: String?): Boolean }
0
Kotlin
0
0
1b007c351604cbf3a576fb0ed22d2e3751f333cb
1,216
orange-talents-07-template-pix-keymanager-grpc
Apache License 2.0
07_CURSO_controle_de_fluxo_e_colecoes_em_kotlin/11_set_collection.kt
marlonprado04
731,388,009
false
{"Kotlin": 36737}
// Cria variável imutável como um Conjunto mutável val openIssues: MutableSet<String> = mutableSetOf("uniqueDescr1", "uniqueDescr2", "uniqueDescr3") // 1 // Adiciona elemento no conjunto mutável fun addIssue(uniqueDesc: String): Boolean { return openIssues.add(uniqueDesc) // 2 } // Verifica o log na hora de adicionar um elemento no conjunto fun getStatusLog(isAdded: Boolean): String { return if (isAdded) "registered correctly." else "marked as duplicate and rejected." // 3 } fun main() { val aNewIssue: String = "uniqueDescr4" val anIssueAlreadyIn: String = "uniqueDescr2" // Imprime o resultado da tentativa de adicionar um elemento novo println("Issue $aNewIssue ${getStatusLog(addIssue(aNewIssue))}") // Imprime o resultado da tentativa de adicionar um elemento duplicado println("Issue $anIssueAlreadyIn ${getStatusLog(addIssue(anIssueAlreadyIn))}") // 5 }
0
Kotlin
0
0
fa21c044879eb98845eabfd1237da50818ff8c19
1,103
BOOTCAMP_backend_com_kotlin
MIT License
app/src/main/java/com/volcaniccoder/spotty/library/LibraryFragment.kt
volsahin
144,414,847
false
null
package com.volcaniccoder.spotty.library import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.os.Bundle import android.support.constraint.ConstraintLayout import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import com.volcaniccoder.spotty.R import com.volcaniccoder.spotty.base.hide import com.volcaniccoder.spotty.helper.commonmusiclist.CommonMusicListAdapter import com.volcaniccoder.spotty.main.MainActivity import dagger.android.support.AndroidSupportInjection import kotlinx.android.synthetic.main.fragment_library.* import javax.inject.Inject class LibraryFragment : Fragment(), LibraryTopCategoriesAdapter.OnClickListener { @Inject lateinit var viewModelFactory: LibraryViewModelFactory private lateinit var viewModel: LibraryViewModel private lateinit var topListAdapter : LibraryTopCategoriesAdapter private lateinit var bottomListAdapter : CommonMusicListAdapter override fun onAttach(context: Context?) { super.onAttach(context) AndroidSupportInjection.inject(this) viewModel = ViewModelProviders.of(this, viewModelFactory).get(LibraryViewModel::class.java) topListAdapter = LibraryTopCategoriesAdapter(this) bottomListAdapter = CommonMusicListAdapter() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_library, container, false) viewModel.topCategoriesLiveData.observe(this, Observer { topListAdapter.submitList(it) }) viewModel.bottomListLiveData.observe(this, Observer { bottomListAdapter.submitList(it) }) viewModel.middleHeaderLiveData.observe(this, Observer { val midTitleView = view.findViewById<ConstraintLayout>(R.id.library_mid_title) midTitleView.findViewById<TextView>(R.id.title_top).text = it?.title midTitleView.findViewById<TextView>(R.id.title_bottom).hide() }) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) library_top_list.adapter = topListAdapter library_top_list.isNestedScrollingEnabled = false library_bottom_list.adapter = bottomListAdapter library_bottom_list.isNestedScrollingEnabled = false } override fun onItemClicked(view: View, item: SingleRowItem) { // Just a dummy check for item if (item.title == getString(R.string.songs)) (activity as MainActivity).navigator.navigateToPlaylist(activity as FragmentActivity) else Toast.makeText(context,"Not ready. Click 'Songs'",Toast.LENGTH_SHORT).show() } }
0
Kotlin
9
33
7c204702b0a5eb54d1bb022a0610baa6b4613dd4
2,974
spotty-clone-app
Apache License 2.0
src/main/kotlin/guild/software/husky/messageinabottle/MessageInABottleApplication.kt
HuskyGrimoire
361,942,197
false
null
package guild.software.husky.messageinabottle import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication open class MessageInABottleApplication fun main(args: Array<String>) { runApplication<MessageInABottleApplication>(*args) }
0
null
0
0
a91f62a74dd7eaa8ff0b038561357567137625d3
315
messageInABottle
Apache License 2.0
src/main/kotlin/uno/rebellious/minetrello/TileEntityBoardSign.kt
RebelliousUno
153,525,272
false
null
package uno.rebellious.minetrello import net.minecraft.tileentity.TileEntitySign import net.minecraft.util.text.TextComponentString class TileEntityBoardSign : TileEntitySign() { fun updateText(s: String) { signText[0] = TextComponentString(s) } }
3
Kotlin
0
0
750a135a247be427b59dd2070f480a33c8b51ff1
267
MineTrello
MIT License
src/main/kotlin/jp/takeda/springathena/dao/SomeDao.kt
takedasan
186,819,762
false
null
package jp.takeda.springathena.dao import jp.takeda.springathena.entity.Person import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.jdbc.core.JdbcTemplate import org.springframework.stereotype.Component import java.time.LocalDate @Component class SomeDao( @Qualifier("jdbcTemplate") private val jdbcTemplate: JdbcTemplate, @Value("\${athena.database}") private val database: String ) { fun selectSomeByDate(date: LocalDate): List<Person> { val sql = """ SELECT name, age FROM $database.some WHERE some.year = '${date.year}' AND some.month = '${date.monthValue.toString().padStart(2, '0')}' AND some.day = '${date.dayOfMonth.toString().padStart(2, '0')}' ; """.trimIndent() return jdbcTemplate.query(sql) { resultSet, _ -> Person( name = resultSet.getString("name"), age = resultSet.getInt("age") ) } } }
0
Kotlin
0
0
1d8450c22125312d984865beb64ddb5b6dee0ba4
1,163
spring-athena
MIT License
src/main/kotlin/jp/takeda/springathena/dao/SomeDao.kt
takedasan
186,819,762
false
null
package jp.takeda.springathena.dao import jp.takeda.springathena.entity.Person import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.jdbc.core.JdbcTemplate import org.springframework.stereotype.Component import java.time.LocalDate @Component class SomeDao( @Qualifier("jdbcTemplate") private val jdbcTemplate: JdbcTemplate, @Value("\${athena.database}") private val database: String ) { fun selectSomeByDate(date: LocalDate): List<Person> { val sql = """ SELECT name, age FROM $database.some WHERE some.year = '${date.year}' AND some.month = '${date.monthValue.toString().padStart(2, '0')}' AND some.day = '${date.dayOfMonth.toString().padStart(2, '0')}' ; """.trimIndent() return jdbcTemplate.query(sql) { resultSet, _ -> Person( name = resultSet.getString("name"), age = resultSet.getInt("age") ) } } }
0
Kotlin
0
0
1d8450c22125312d984865beb64ddb5b6dee0ba4
1,163
spring-athena
MIT License
util/time-flow/src/main/kotlin/org/a_cyb/sayitalarm/util/time_flow/TimeFlow.kt
a-cyborg
751,578,623
false
{"Kotlin": 713068}
/* * Copyright (c) 2024 <NAME> / All rights reserved. * * Use of this source code is governed by Apache v2.0 */ package org.a_cyb.sayitalarm.presentation.viewmodel.time_flow import java.time.LocalTime import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import org.a_cyb.sayitalarm.entity.Hour import org.a_cyb.sayitalarm.entity.Minute object TimeFlow : TimeFlowContract { override val currentTimeFlow: Flow<Pair<Hour, Minute>> = flow { while (true) { emit(getCurrentTime()) delay(FIVE_SEC_IN_MILLIS) } } private fun getCurrentTime(): Pair<Hour, Minute> { val now = LocalTime.now() return Pair(Hour(now.hour), Minute(now.minute)) } private const val FIVE_SEC_IN_MILLIS = 5000L }
0
Kotlin
0
0
f20079c06adf86e8297ab8322887c875715e6cd1
817
SayItAlarm
Apache License 2.0
database/src/commonMain/kotlin/kosh/database/KVStore.kt
niallkh
855,100,709
false
{"Kotlin": 1920679, "Swift": 25684}
package kosh.database import app.cash.sqldelight.coroutines.asFlow import kosh.data.sources.KVStore import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import okio.ByteString class DefaultKVStore( private val queries: KVQueries, ) : KVStore { override fun get(key: ByteString): Flow<ByteString?> = flow { emitAll(queries.get(key).asFlow().map { it.executeAsOneOrNull() }) }.flowOn(Dispatchers.Default) override suspend fun update( key: ByteString, update: (ByteString?) -> ByteString?, ): ByteString? = withContext(Dispatchers.Default) { queries.transactionWithResult { val previous = queries.get(key).executeAsOneOrNull() val updated = update(previous) if (updated != null) { queries.insert(key, updated) } else { queries.delete(key) } updated } } }
0
Kotlin
0
3
1581392a0bdf9f075941125373b8d1bed937ab43
1,134
kosh
MIT License
library/src/test/kotlin/ru/kontur/kinfra/kfixture/data/objects/random1/Pot.kt
skbkontur
212,616,062
false
null
package ru.kontur.kinfra.kfixture.data.objects.random1 data class Pot( val above: String, val activity: String, val actually: Int, val agree: Int, val alphabet: Boolean, val answer: Double, val anyway: Boolean, val area: String, val arm: Boolean, val army: Boolean, val ask: Ask, val ate: Boolean, val badly: Boolean, val bag: Boolean, val band: Boolean, val bean: String, val beauty: Double, val belong: Int, val bet: Int, val blue: Int, val breathe: String, val brief: String, val broken: Boolean, val brown: Double, val building: Double, val but: String, val came: Int, val camp: Boolean, val cap: Int, val carry: Int, val cast: String, val castle: String, val cat: Boolean, val caught: String, val chosen: Boolean, val citizen: String, val column: Int, val construction: String, val cool: Boolean, val copy: Boolean, val cost: Double, val country: String, val couple: Boolean, val courage: Boolean, val course: Int, val damage: Boolean, val dance: Boolean, val dangerous: Int, val dead: String, val depend: Int, val die: String, val difference: String, val different: String, val distant: Boolean, val done: String, val doubt: Double, val drew: Int, val due: String, val energy: String, val everyone: Int, val everywhere: Boolean, val far: String, val farmer: Boolean, val fast: Boolean, val fellow: Double, val figure: String, val film: String, val fur: Double, val further: Boolean, val gently: Boolean, val giant: Double, val glad: Boolean, val golden: String, val grew: String, val grown: Boolean, val hall: String, val herd: Double, val himself: Double, val hot: String, val immediately: Boolean, val improve: String, val job: Boolean, val judge: String, val know: Int, val laugh: String, val leave: Boolean, val listen: String, val living: Boolean, val locate: String, val longer: Boolean, val love: String, val luck: String, val meant: Boolean, val measure: Boolean, val member: String, val method: Int, val military: String, val moment: Int, val most: Boolean, val must: Boolean, val native: String, val naturally: Boolean, val nearer: Boolean, val needle: Boolean, val newspaper: Boolean, val night: Boolean, val nothing: String, val ocean: Boolean, val oil: Boolean, val old: Double, val older: Double, val once: Double, val operation: Double, val oxygen: Boolean, val pack: Double, val pick: Boolean, val pictured: Int, val piece: String, val planned: Boolean, val police: Double, val president: Boolean, val press: Double, val pretty: String, val purpose: String, val quickly: Int, val race: Int, val recall: Boolean, val related: Boolean, val rice: Boolean, val right: Int, val rising: Boolean, val rod: Boolean, val route: Boolean, val satellites: Double, val scared: Int, val see: Int, val service: String, val silence: String, val skill: Boolean, val skin: Boolean, val sky: Int, val sleep: String, val slept: Int, val slipped: String, val smaller: Int, val society: Int, val somebody: Double, val son: Double, val southern: String, val spent: String, val spider: Boolean, val spread: Int, val stand: String, val step: Boolean, val storm: String, val stranger: Double, val string: Double, val struggle: Boolean, val studying: String, val successful: Boolean, val such: Double, val suit: Boolean, val supply: Int, val tank: Boolean, val team: Boolean, val terrible: Boolean, val them: Boolean, val thirty: String, val thrown: Boolean, val tightly: Boolean, val took: String, val trail: Double, val train: String, val turn: Boolean, val under: Boolean, val usually: String, val vegetable: Boolean, val verb: String, val visitor: String, val vowel: Boolean, val warn: String, val was: Boolean, val wash: Double, val weight: Double, val went: String, val whispered: String, val wolf: Boolean, val wool: Boolean, val world: Boolean )
7
Kotlin
1
1
e1845e8c9737c66b63cfa49925ad3bb9c589fbd1
4,505
KFixture
MIT License
src/main/kotlin/io/foxcapades/lib/cli/builder/arg/ShortArgument.kt
Foxcapades
850,780,005
false
{"Kotlin": 253956}
package io.foxcapades.lib.cli.builder.arg /** * Argument type for containing [Short] values. * * @since 1.0.0 */ interface ShortArgument : ScalarArgument<Short>
8
Kotlin
0
0
457d895219666963b70ac10df70092a7b778ebea
166
lib-kt-cli-builder
MIT License
app/src/main/java/com/karimi/seller/model/CategoryProduct.kt
karimi96
520,105,490
false
null
package com.karimi.seller.model import androidx.annotation.NonNull import androidx.room.Entity import androidx.room.Ignore import androidx.room.PrimaryKey @Entity class CategoryProduct { @NonNull @PrimaryKey(autoGenerate = true) var id_table :Int? = null var id_product :Int? = null var id_category :Int? = null constructor() @Ignore constructor(id_product: Int?, id_category: Int?) { this.id_product = id_product this.id_category = id_category } }
0
Kotlin
0
0
dde24d07b705b893e799a24c97ef15e340312251
506
Seller
MIT License
project/common/src/main/kotlin/ink/ptms/adyeshach/core/entity/type/AdyPolarBear.kt
TabooLib
284,936,010
false
{"Kotlin": 1050024, "Java": 35966}
package ink.ptms.adyeshach.core.entity.type /** * @author sky * @date 2020/8/4 23:15 */ interface AdyPolarBear : AdyEntityAgeable { fun isStanding(): Boolean { return getMetadata("isStanding") } fun setStanding(value: Boolean) { setMetadata("isStanding", value) } }
13
Kotlin
86
98
ac7098b62db19308c9f14182e33181c079b9e561
303
adyeshach
MIT License
tooling/src/commonMain/kotlin/dev/datlag/tooling/ExtendCollection.kt
DatL4g
739,165,922
false
{"Kotlin": 535226}
package dev.datlag.tooling import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.ImmutableSet import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList import kotlinx.collections.immutable.toImmutableSet import kotlin.math.max import kotlin.math.min import kotlin.collections.contains as defaultContains /** * Combine any [Iterable] of the same type to one [MutableList]. * * @return a [MutableList] of all provided items in iterables. */ fun <T> mutableListFrom(vararg list: Iterable<T>): MutableList<T> { return mutableListOf<T>().apply { list.forEach(::addAll) } } /** * Combine any [Iterable] of the same type to one [List]. * * @return a [List] of all provided items in iterables. */ fun <T> listFrom(vararg list: Iterable<T>): List<T> = mutableListFrom(*list) /** * Combine any [Iterable] of the same type to one [MutableSet]. * * @return a [MutableSet] of all provided items in iterables. */ fun <T> mutableSetFrom(vararg list: Iterable<T>): MutableSet<T> { return mutableSetOf<T>().apply { list.forEach(::addAll) } } /** * Combine any [Iterable] of the same type to one [Set]. * * @return a [Set] of all provided items in iterables. */ fun <T> setFrom(vararg list: Iterable<T>): ImmutableSet<T> = mutableSetFrom(*list).toImmutableSet() /** * Provides the last existing index of any [Collection] */ val Collection<*>.lastIndex: Int get() = this.size - 1 /** * Run [List.subList] on any [Collection] safely without throwing any exception if the provided start/end values do not exist. * * @return a [ImmutableList] which only holds elements of the original [Collection] within it's provided bounds. */ fun <T> Collection<T>.safeSubList(from: Int, to: Int): ImmutableList<T> { if (this.isEmpty() || from > lastIndex) { return persistentListOf() } val safeFrom = max(min(from, lastIndex), 0) return this.toList().subList( safeFrom, max(safeFrom, min(to, size)) ).toImmutableList() } /** * Run [List.subList] on any [Collection] safely without throwing any exception if the provided start/end values do not exist. * * @return a [ImmutableSet] which only holds elements of the original [Collection] within it's provided bounds. */ fun <T> Collection<T>.safeSubSet(from: Int, to: Int): ImmutableSet<T> = toSet().safeSubList(from, to).toImmutableSet() /** * Check if a [String]-[Iterable] contains a specific element with the option to ignore case-sensitivity. * * @return whether the [Iterable] contains such an element or not */ fun Iterable<String>.contains(element: String, ignoreCase: Boolean = false): Boolean { return if (ignoreCase) { this.any { it.equals(element, true) } } else { this.defaultContains(element) } }
0
Kotlin
0
3
11f8ee76909f12d96e4f1889e8b6daa7ae28ddd2
2,854
tooling
Apache License 2.0
lib-chartio/src/main/java/github/com/st235/lib_chartio/drawingdelegates/grid/GridDrawingDelegate.kt
st235
208,612,941
false
null
package github.com.st235.lib_chartio.drawingdelegates.grid import android.graphics.Canvas import android.graphics.RectF import github.com.st235.lib_chartio.internal.PointsTransformationHelper internal interface GridDrawingDelegate { fun getPadding(): RectF fun prepare(chartBounds: RectF, viewportBounds: RectF, pointsTransformerHelper: PointsTransformationHelper) fun draw(canvas: Canvas) companion object { fun retrieveDelegate(delegate: GridDrawingDelegate, forceDisable: Boolean): GridDrawingDelegate { if (forceDisable) { return NoGridDrawingDelegate() } return delegate } } }
0
Kotlin
0
13
00b43f548089464ce578d6d05e1e4a701706bb84
677
Chartio
MIT License
data/src/main/java/cn/nekocode/template/data/service/GankService.kt
zzmjohn
91,941,855
true
{"Kotlin": 5030}
package cn.nekocode.template.data.service import cn.nekocode.template.data.DO.Meizi import cn.nekocode.template.data.exception.GankServiceException import cn.nekocode.template.data.api.GankApi import io.paperdb.Paper import io.reactivex.Observable import io.reactivex.schedulers.Schedulers /** * @author nekocode ([email protected]) */ object GankService { fun getMeizis(count: Int, pageNum: Int): Observable<ArrayList<Meizi>> = GankApi.IMPL.getMeizis(count, pageNum) .subscribeOn(Schedulers.io()) .map { Paper.book().write("meizis-$pageNum", it.results) it.results } .onErrorResumeNext { err: Throwable -> val list: ArrayList<Meizi> = Paper.book().read("meizis-$pageNum") ?: throw GankServiceException(err.message) Observable.just(list) } }
0
Kotlin
0
0
f9f2c84b7d2a93a684c5a0dd489c5f08f16ee9ea
995
Kotlin-Android-Template
Apache License 2.0
solutions/src/main/kotlin/io/github/tomplum/aoc/solutions/Day8.kt
TomPlum
724,225,748
false
{"Kotlin": 141244}
package io.github.tomplum.aoc.solutions import io.github.tomplum.aoc.network.DesertNetwork import io.github.tomplum.aoc.network.strategy.EtherealNavigation import io.github.tomplum.aoc.network.strategy.LeftRightNavigation import io.github.tomplum.libs.input.Day import io.github.tomplum.libs.input.InputReader import io.github.tomplum.libs.solutions.Solution class Day8 : Solution<Long, Long> { private val documents = InputReader.read<String>(Day(8)).value private val network = DesertNetwork() override fun part1(): Long { val strategy = LeftRightNavigation(documents) return network.stepsRequiredToReachEnd(strategy) } override fun part2(): Long { val strategy = EtherealNavigation(documents) return network.stepsRequiredToReachEnd(strategy) } }
0
Kotlin
0
1
d1f941a3c5bacd126177ace6b9f576c9af07fed6
808
advent-of-code-2023
Apache License 2.0
modules/domain/sources/api/RaptorAggregateEventBatch.kt
fluidsonic
246,018,343
false
null
package io.fluidsonic.raptor.domain public data class RaptorAggregateEventBatch< out AggregateId : RaptorAggregateId, out Change : RaptorAggregateChange<AggregateId>, >( val aggregateId: AggregateId, val events: List<RaptorAggregateEvent<AggregateId, Change>>, val version: Int, ) : RaptorAggregateStreamMessage<AggregateId, Change> { init { require(events.isNotEmpty()) { "'events' must not be empty." } require(events.all { it.aggregateId == aggregateId }) { "'events' must all have the same 'aggregateId' as the batch: $this" } // We're getting rid of batching anyway… // require(events.all { it.lastVersionInBatch == version }) { "'events' must all have the same 'lastVersionInBatch' as the batch 'version': $this" } } }
0
null
2
6
aa106d096b700d6eadbcf9ef5df8ec102f7a3fac
743
raptor
Apache License 2.0
src/test/kotlin/com/example/activity/DeckardActivityTest.kt
GAumala
109,865,161
true
{"Kotlin": 1803}
package com.example.activity import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.robolectric.Shadows.shadowOf @RunWith(RobolectricTestRunner::class) class DeckardActivityTest { @Test @Throws(Exception::class) fun testSomething() { assertNotNull(shadowOf(RuntimeEnvironment.application)) assertTrue(Robolectric.setupActivity(DeckardActivity::class.java) != null) } }
0
Kotlin
0
0
77e47381d73e0564a9b2490797e1b31b30f1d9eb
610
deckard-kotlin
The Unlicense
src/commonTest/kotlin/org/tix/config/merge/TixMergerTest.kt
ncipollo
336,920,234
false
null
package org.tix.config.merge import org.tix.config.data.raw.* import org.tix.serialize.dynamic.DynamicElement import kotlin.test.Test import kotlin.test.expect class TixMergerTest { private val configs = listOf(1, 2, 3).map { index -> RawTixConfiguration( include = DynamicElement("config$index"), github = RawGithubConfiguration( fields = RawGithubFieldConfiguration( default = mapOf("github$index" to DynamicElement(index)) ) ).takeIf { index < 3 }, jira = RawJiraConfiguration( fields = RawJiraFieldConfiguration( default = mapOf("jira$index" to DynamicElement(index)) ) ).takeIf { index < 3 }, variables = mapOf("config$index" to "$index") ) } @Test fun flatten() { val expected = RawTixConfiguration( include = DynamicElement("config3"), github = RawGithubConfiguration( fields = RawGithubFieldConfiguration( default = mapOf( "github1" to DynamicElement(1), "github2" to DynamicElement(2) ) ) ), jira = RawJiraConfiguration( fields = RawJiraFieldConfiguration( default = mapOf( "jira1" to DynamicElement(1), "jira2" to DynamicElement(2) ) ) ), variables = mapOf( "config1" to "1", "config2" to "2", "config3" to "3" ) ) expect(expected) { configs.flatten() } } }
1
Kotlin
0
2
544ef659aeecac908887977d54d0c91677091c87
1,779
tix-core
MIT License
domain/src/main/java/akio/apps/myrun/domain/activity/ExportTempTcxFileUsecase.kt
khoi-nguyen-2359
297,064,437
false
{"Kotlin": 818250, "Java": 177639}
package akio.apps.myrun.domain.activity import akio.apps.myrun.data.activity.api.ActivityRepository import akio.apps.myrun.data.activity.api.ActivityTcxFileWriter import akio.apps.myrun.data.activity.api.model.ActivityLocation import akio.apps.myrun.data.activity.api.model.BaseActivityModel import android.app.Application import java.io.File import java.text.SimpleDateFormat import java.util.Locale import javax.inject.Inject class ExportTempTcxFileUsecase @Inject constructor( private val application: Application, private val activityTcxFileWriter: ActivityTcxFileWriter, private val activityRepository: ActivityRepository, ) { private val timeFormatter = SimpleDateFormat("ddMMyyyy_HHmm", Locale.US) /** * Exports content the of activity with given [activityId] to a TCX file. Returns null if error * happened. */ suspend fun export(activityId: String): File? { val activityModel = activityRepository.getActivity(activityId) ?: return null val fileName = makeFileName(activityModel) val externalFileDir = application.getExternalFilesDir(null) val storeDir = if (externalFileDir != null) { File("${externalFileDir.absolutePath}/$DIR_NAME") } else { File("${application.cacheDir.absolutePath}/$DIR_NAME") } storeDir.mkdirs() val storeFile = File("${storeDir.absolutePath}/$fileName") if (storeFile.isFile && storeFile.exists()) { return storeFile } storeFile.createNewFile() if (externalFileDir == null) { // delete cache file after used storeFile.deleteOnExit() } val activityLocations = getActivityLocations(activityId) activityTcxFileWriter.writeTcxFile( activity = activityModel, locations = activityLocations, cadences = emptyList(), outputFile = storeFile, zip = false ) return storeFile } private fun makeFileName(activity: BaseActivityModel): String = "${activity.activityType.name}_${timeFormatter.format(activity.startTime)}.tcx" private suspend fun getActivityLocations(activityId: String): List<ActivityLocation> { return activityRepository.getActivityLocationDataPoints(activityId) } companion object { private const val DIR_NAME = "Exported Activities" } }
0
Kotlin
3
7
31cc16d0fb37816db4dc434c925360624e38e35c
2,437
myrun
MIT License
domain/src/main/java/com/llyods/domain/model/Product.kt
Avtar-Guleria
761,036,391
false
{"Kotlin": 75728}
package com.llyods.domain.model data class Product( val productId: String, val title: String, val description: String, val price: Double, val brand: String, val category: String, val thumbnail: String, val images: List<String> )
0
Kotlin
0
0
552008c12849a952955b06b84291c58363a26122
262
RetailProductApp
Apache License 2.0
app/src/main/java/com/teo/recipes/App.kt
tejoakk
270,687,051
false
null
package com.teo.recipes import android.app.Activity import android.app.Application import com.teo.recipes.di.AppInjector import com.teo.recipes.util.CrashReportingTree import com.facebook.stetho.Stetho import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import timber.log.Timber import javax.inject.Inject class App : Application(), HasActivityInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity> override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) Stetho.initializeWithDefaults(this) if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree()) else Timber.plant(CrashReportingTree()) AppInjector.init(this) } override fun activityInjector() = dispatchingAndroidInjector }
0
Kotlin
0
0
c538a3d7c874fc9158b06bf51863f2472bf34ed2
832
Recipes-app
Apache License 2.0
buildSrc/src/main/kotlin/korlibs/korge/gradle/ProjectDependencyTree.kt
korlibs
80,095,683
false
{"Kotlin": 3929805, "C++": 20878, "HTML": 3853, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "Batchfile": 41, "CSS": 33}
package korlibs.korge.gradle import korlibs.* import org.gradle.api.* import org.gradle.api.artifacts.* fun Project.directDependantProjects(): Set<Project> { val key = "directDependantProjects" if (!project.selfExtra.has(key)) { //if (true) { project.selfExtra.set(key, (project.configurations .flatMap { it.dependencies.withType(ProjectDependency::class.java).toList() } .map { it.dependencyProject } .toSet() - project)) } return project.selfExtra.get(key) as Set<Project> } fun Project.allDependantProjects(): Set<Project> { val key = "allDependantProjects" if (!project.selfExtra.has(key)) { //if (true) { val toExplore = arrayListOf<Project>(this) val out = LinkedHashSet<Project>() val explored = LinkedHashSet<Project>() while (toExplore.isNotEmpty()) { val item = toExplore.removeLast() if (item in explored) continue val directDependencies = item.directDependantProjects() explored += item out += directDependencies toExplore += directDependencies } project.selfExtra.set(key, out - this) } return project.selfExtra.get(key) as Set<Project> }
461
Kotlin
120
2,394
0ca8644eb43c2ea8148dcd94d5c2a063466b0079
1,259
korge
Apache License 2.0
app/src/main/java/dev/eyosiyas/smsblocker/adapter/MessageListAdapter.kt
devEyosiyas
293,549,507
false
null
package dev.eyosiyas.smsblocker.adapter import android.net.Uri import android.view.ContextMenu import android.view.ContextMenu.ContextMenuInfo import android.view.LayoutInflater import android.view.View import android.view.View.OnCreateContextMenuListener import android.view.ViewGroup import android.widget.Toast import androidx.core.content.res.ResourcesCompat import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.amulyakhare.textdrawable.TextDrawable import com.amulyakhare.textdrawable.util.ColorGenerator import dev.eyosiyas.smsblocker.R import dev.eyosiyas.smsblocker.databinding.ItemMessageReceivedBinding import dev.eyosiyas.smsblocker.databinding.ItemMessageSentBinding import dev.eyosiyas.smsblocker.model.Message import dev.eyosiyas.smsblocker.util.Constant import dev.eyosiyas.smsblocker.util.Core import dev.eyosiyas.smsblocker.util.MessageDiffUtil class MessageListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { //class MessageListAdapter constructor(private val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var messages = emptyList<Message>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return if (viewType == VIEW_TYPE_MESSAGE_SENT) SentVH(LayoutInflater.from(parent.context).inflate(R.layout.item_message_sent, parent, false)) else ReceivedVH(LayoutInflater.from(parent.context).inflate(R.layout.item_message_received, parent, false)) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val message: Message = messages[position] when (holder.itemViewType) { VIEW_TYPE_MESSAGE_SENT -> (holder as SentVH).bind(message) VIEW_TYPE_MESSAGE_RECEIVED -> (holder as ReceivedVH).bind(message) } } override fun getItemCount(): Int { return messages.size } override fun getItemViewType(position: Int): Int { val message: Message = messages[position] return if (message.type.equals("received", ignoreCase = true)) VIEW_TYPE_MESSAGE_RECEIVED else VIEW_TYPE_MESSAGE_SENT } fun populate(newMessages: List<Message>) { val results = DiffUtil.calculateDiff(MessageDiffUtil(messages, newMessages)) messages = newMessages results.dispatchUpdatesTo(this) } inner class SentVH constructor(itemView: View) : RecyclerView.ViewHolder(itemView), OnCreateContextMenuListener { private val binder: ItemMessageSentBinding = ItemMessageSentBinding.bind(itemView) fun bind(sentMessage: Message?) { binder.txtSentMessage.text = sentMessage!!.body binder.txtMessageSentTime.text = Core.readableTime(sentMessage.timestamp, itemView.context) itemView.setOnCreateContextMenuListener(this) } override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo) { getContextMenu(menu, v) } } inner class ReceivedVH constructor(itemView: View) : RecyclerView.ViewHolder(itemView), OnCreateContextMenuListener { private val binder: ItemMessageReceivedBinding = ItemMessageReceivedBinding.bind(itemView) fun bind(receivedMessage: Message?) { binder.txtSenderMessage.text = receivedMessage!!.body binder.txtSenderTimestamp.text = Core.readableTime(receivedMessage.timestamp, itemView.context) itemView.setOnCreateContextMenuListener(this) val sender = if (receivedMessage.sender != receivedMessage.displayName) receivedMessage.displayName else receivedMessage.sender if (receivedMessage.picture == Constant.DEFAULT_PROFILE) { val initial: Char = sender.toCharArray()[0] if (receivedMessage.displayName != receivedMessage.sender) { if (initial.isLetter()) binder.SenderProfile.setImageDrawable(TextDrawable.builder() .buildRound(initial.toString(), ColorGenerator.MATERIAL.getColor(sender))) } else binder.SenderProfile.setImageDrawable(ResourcesCompat.getDrawable(itemView.context.resources, R.drawable.ic_user, null)) } else binder.SenderProfile.setImageURI(Uri.parse(receivedMessage.picture)) } override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo) { getContextMenu(menu, v) } } private fun getContextMenu(menu: ContextMenu, v: View) { menu.setHeaderTitle(v.context.getString(R.string.message_options)) menu.add(0, v.id, 0, R.string.delete).setOnMenuItemClickListener { Toast.makeText(v.context, "Delete coming soon!", Toast.LENGTH_SHORT).show() false } menu.add(0, v.id, 0, R.string.copy_text).setOnMenuItemClickListener { Toast.makeText(v.context, "Copy text coming soon!", Toast.LENGTH_SHORT).show() false } menu.add(0, v.id, 0, R.string.forward).setOnMenuItemClickListener { Toast.makeText(v.context, "Forward text coming soon!", Toast.LENGTH_SHORT).show() false } } companion object { private const val VIEW_TYPE_MESSAGE_SENT: Int = 1 private const val VIEW_TYPE_MESSAGE_RECEIVED: Int = 2 } }
0
Kotlin
7
23
ea2350248a601b5d93e47083bde0485c0823e4d8
5,455
FreedomSMSBlocker
MIT License
app/src/main/java/com/nelsonxilv/gstoutimetable/data/database/GroupLessonCrossRef.kt
nelson-xilv
771,139,815
false
{"Kotlin": 76381}
package com.nelsonxilv.gstoutimetable.data.database import androidx.room.Entity @Entity( tableName = "lesson_group_cross_ref", primaryKeys = ["lessonId", "groupName"] ) data class GroupLessonCrossRef( val groupName: String, val lessonId: Int )
0
Kotlin
0
1
8c48c561293c9a84d977e58a9ba764850f4f1b75
262
GSTOU_Timetable
Apache License 2.0
src/test/kotlin/test/acntech/easycontainers/ShowCaseTests.kt
acntech
739,332,140
false
{"Kotlin": 369659, "HTML": 485}
package test.acntech.easycontainers import no.acntech.easycontainers.Environment.defaultRegistryEndpoint import no.acntech.easycontainers.GenericContainer import no.acntech.easycontainers.model.* import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import org.slf4j.LoggerFactory import java.util.concurrent.TimeUnit class ShowCaseTests { companion object { private val log = LoggerFactory.getLogger(ShowCaseTests::class.java) } @Test @Disabled fun `Showcase Docker`() { val imageName = "container-test" val container = GenericContainer.builder().apply { withName(ContainerName.of("easycontainers-$imageName")) withImage(ImageURL.of("$defaultRegistryEndpoint/test/$imageName:latest")) withContainerPlatformType(ContainerPlatformType.DOCKER) withEnv("LOG_TIME_MESSAGE", "Hello from Docker!!!") withOutputLineCallback { line -> println("DOCKER-CONTAINER-OUTPUT: $line") } // HTTP withExposedPort(PortMappingName.HTTP, NetworkPort.HTTP) withPortMapping(NetworkPort.HTTP, NetworkPort.of(8080)) // SSH withExposedPort(PortMappingName.SSH, NetworkPort.SSH) withPortMapping(NetworkPort.SSH, NetworkPort.of(8022)) }.build() val runtime = container.getRuntime() runtime.start() log.debug("Container state: ${container.getState()}") TimeUnit.SECONDS.sleep(5 * 60) container.getRuntime().delete() } @Test @Disabled fun `Showcase Kubernetes`() { val imageName = "container-test" val container = GenericContainer.builder().apply { withNamespace("test") withName(ContainerName.of("easycontainers-$imageName")) withImage(ImageURL.of("${defaultRegistryEndpoint}/test/$imageName:latest")) withContainerPlatformType(ContainerPlatformType.KUBERNETES) withIsEphemeral(true) withEnv("LOG_TIME_MESSAGE", "Hello from Kube!!!") withOutputLineCallback { line -> println("KUBERNETES-CONTAINER-OUTPUT: $line") } // HTTP withExposedPort("http", 80) withPortMapping(80, 30080) // SSH withExposedPort("ssh", 22) withPortMapping(22, 30022) }.build() val runtime = container.getRuntime() runtime.start() log.debug("Container state: ${container.getState()}") TimeUnit.SECONDS.sleep(5 * 60) container.getRuntime().delete() } }
3
Kotlin
0
1
896e213887aee8c3baf8fe38fa4023b60c35be77
2,490
easycontainers
Apache License 2.0