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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
VCL/src/test/java/io/velocitycareerlabs/infrastructure/resources/valid/VCLJwtServiceMock.kt | velocitycareerlabs | 525,006,413 | false | {"Kotlin": 614928} | /**
* Created by <NAME> on 05/09/2023.
*
* Copyright 2022 Velocity Career Labs inc.
* SPDX-License-Identifier: Apache-2.0
*/
package io.velocitycareerlabs.infrastructure.resources.valid
import io.velocitycareerlabs.api.entities.VCLPublicJwk
import io.velocitycareerlabs.api.entities.VCLJwt
import io.velocitycareerlabs.api.entities.VCLJwtDescriptor
import io.velocitycareerlabs.api.entities.VCLResult
import io.velocitycareerlabs.api.jwt.VCLJwtService
class VCLJwtServiceMock: VCLJwtService {
override fun sign(
kid: String?,
nonce: String?,
jwtDescriptor: VCLJwtDescriptor,
completionBlock: (VCLResult<VCLJwt>) -> Unit
) {
}
override fun verify(
jwt: VCLJwt,
publicPublic: VCLPublicJwk,
completionBlock: (VCLResult<Boolean>) -> Unit
) {
}
} | 0 | Kotlin | 0 | 1 | daaf7fdd029d6a1cb152fd8506b43b1789fd1b88 | 830 | WalletAndroid | Apache License 2.0 |
Clase3/GamesApp/app/src/main/java/torres/gabriel/gamesapp/Models/Game.kt | gabtorrespen | 145,050,264 | false | null | package torres.gabriel.gamesapp.Models
import java.io.Serializable
class Game(id:Int,name: String, developer: String, description: String) : Serializable {
var id:Int? = id
var name:String?= name
var developer:String? = developer
var description:String? = description
var image:ByteArray? =null
var idImage:Int?=null
constructor(id:Int,name: String, developer: String, description: String,idImage:Int)
: this(id,name,developer,description) {
this.idImage = idImage
}
} | 0 | Kotlin | 0 | 0 | ce4b37f4ea2c4b61a7a2113a192673c93b4c4581 | 525 | EjerciciosAndroid | Apache License 2.0 |
Extensions/Cryptography/src/main/kotlin/net/sourcebot/module/cryptography/commands/OngCommand.kt | TheSourceCodeLLC | 271,902,483 | false | null | package net.sourcebot.module.cryptography.commands
import me.hwiggy.kommander.arguments.Adapter
import me.hwiggy.kommander.arguments.Arguments
import me.hwiggy.kommander.arguments.Synopsis
import net.dv8tion.jda.api.entities.Message
import net.sourcebot.api.command.RootCommand
import net.sourcebot.api.command.SourceCommand
import net.sourcebot.api.response.Response
import net.sourcebot.api.response.StandardInfoResponse
class OngCommand : RootCommand() {
override val name = "ong"
override val description = "Use the Ong language."
override val permission = "cryptography.$name"
init {
register(
OngEncodeCommand(),
OngDecodeCommand()
)
}
inner class OngEncodeCommand : SourceCommand() {
override val name = "encode"
override val description = "Encode using the Ong language."
override val synopsis = Synopsis {
reqParam("input", "The text to encode into Ong.", Adapter.slurp(" "))
}
override val permission by lazy { "${parent!!.permission}.$name" }
override fun execute(sender: Message, arguments: Arguments.Processed): Response {
val input = arguments.required<String>("input", "You did not specify text to encode!")
val encoded = input.replace("([^aeiou\\W\\d])".toRegex(), "$1ong")
return StandardInfoResponse("Ong Encode Result", encoded)
}
}
inner class OngDecodeCommand : SourceCommand() {
override val name = "decode"
override val description = "Decode from the Ong language."
override val synopsis = Synopsis {
reqParam("input", "The text to decode from Ong.", Adapter.slurp(" "))
}
override val permission by lazy { "${parent!!.permission}.$name" }
override fun execute(sender: Message, arguments: Arguments.Processed): Response {
val input = arguments.required<String>("input", "You did not specify text to decode!")
val decoded = input.replace("ong", "")
return StandardInfoResponse("Ong Decode Result", decoded)
}
}
} | 5 | Kotlin | 8 | 9 | ff4a07c69a009d118b10bc4d57f6e567334ed768 | 2,125 | Source | MIT License |
app/src/main/java/com/zyqzyq/eyepetizer/ui/view/discover/category/CategoryScrollCardItem.kt | zyqzyq | 102,337,521 | false | null | package com.zyqzyq.eyepetizer.ui.view.discover.category
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import com.youth.banner.BannerConfig
import com.zyqzyq.eyepetizer.R
import com.zyqzyq.eyepetizer.mvp.model.bean.HomeItem
import com.zyqzyq.eyepetizer.ui.view.discover.GlideImageLoader
import kotlinx.android.synthetic.main.item_category_scroll.view.*
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.SpannableString
import android.text.style.RelativeSizeSpan
import com.zyqzyq.eyepetizer.durationFormat
import com.zyqzyq.eyepetizer.ui.activities.PlayActivity
class CategoryScrollCardItem: FrameLayout{
constructor(context: Context?) : this(context, null)
constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
private fun init(){
initView()
}
private fun initView(){
View.inflate(context, R.layout.item_category_scroll,this)
}
fun setData(data: HomeItem?){
categoryTitle.text = data?.data?.header?.title ?: "热门排行"
if (data?.data?.header?.title == "最近更新"){
categoryForceBtn.visibility = View.GONE
categorySubTitle.visibility = View.GONE
}
else{
categorySubTitle.visibility = View.VISIBLE
}
categoryTitle.paint.isFakeBoldText = true
categoryTitle.setTextColor(Color.BLACK)
categorySubTitle.text = data?.data?.header?.subtitle ?: " "
val images = arrayListOf<String>()
val titles = arrayListOf<SpannableString>()
for (i in 0 until data?.data?.itemList!!.size){
images.add(data.data.itemList[i].data?.cover?.feed!! )
val title = data.data.itemList[i].data?.title!!
val category = data.data.itemList[i].data?.category
val duration = durationFormat(data.data.itemList[i].data?.duration)
val startPoint = title.length
var spannableString = SpannableString("$title\n #$category / $duration")
// titles.add(data.data.itemList[i].data?.title!! + data.data.itemList[i].data?.category)
spannableString.setSpan(ForegroundColorSpan(Color.parseColor("#B5B5B5")), startPoint, spannableString.length, Spanned.SPAN_EXCLUSIVE_INCLUSIVE )
spannableString.setSpan(RelativeSizeSpan(.8f), startPoint, spannableString.length, Spanned.SPAN_EXCLUSIVE_INCLUSIVE )
titles.add(spannableString)
}
// val images = arrayListOf(R.drawable.icon_detail_player_back,R.mipmap.ic_action_full_screen,R.mipmap.ic_action_favorites_without_padding)
categoryBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE)
//设置图片加载器
categoryBanner.setImageLoader(GlideImageLoader())
//设置图片集合
categoryBanner.setImages(images)
//设置banner样式
//设置banner动画效果
// categoryBanner.setBannerAnimation(Transformer.DepthPage)
//设置标题集合(当banner样式有显示title时)
categoryBanner.setBannerTitles(titles)
//设置自动轮播,默认为true
categoryBanner.isAutoPlay(false)
//设置轮播时间
// banner.setDelayTime(1500)
//设置指示器位置(当banner模式中有指示器时)
categoryBanner.setOnBannerListener { i ->
val intent = Intent(context, PlayActivity::class.java)
intent.putExtra("data", data.data.itemList[i])
context.startActivity(intent)
}
categoryBanner.setIndicatorGravity(BannerConfig.CENTER)
//banner设置方法全部调用完毕时最后调用
categoryBanner.start()
}
} | 0 | Kotlin | 2 | 18 | 8771e0000301aa258512858652a484a33fc6c71c | 3,794 | Eyepetizer-kotlin | MIT License |
http/http-server-symbol-processor/src/main/kotlin/ru/tinkoff/kora/http/server/symbol/procesor/ExtractorFunction.kt | Tinkoff | 568,800,636 | false | null | package ru.tinkoff.kora.http.server.symbol.procesor
import com.squareup.kotlinpoet.MemberName
private const val extractorsPackage = "ru.tinkoff.kora.http.server.common.handler"
enum class ExtractorFunction(val memberName: MemberName) {
STRING_PATH(MemberName(extractorsPackage, "extractStringPathParameter")),
UUID_PATH(MemberName(extractorsPackage, "extractUUIDPathParameter")),
INT_PATH(MemberName(extractorsPackage, "extractIntPathParameter")),
LONG_PATH(MemberName(extractorsPackage, "extractLongPathParameter")),
DOUBLE_PATH(MemberName(extractorsPackage, "extractDoublePathParameter")),
STRING_HEADER(MemberName(extractorsPackage, "extractStringHeaderParameter")),
STRING_NULLABLE_HEADER(MemberName(extractorsPackage, "extractNullableStringHeaderParameter")),
LIST_STRING_HEADER(MemberName(extractorsPackage, "extractStringListHeaderParameter")),
LIST_STRING_NULLABLE_HEADER(MemberName(extractorsPackage, "extractNullableStringListHeaderParameter")),
UUID_QUERY(MemberName(extractorsPackage, "extractUuidQueryParameter")),
UUID_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableUuidQueryParameter")),
UUID_LIST_QUERY(MemberName(extractorsPackage, "extractUuidListQueryParameter")),
UUID_LIST_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableUuidListQueryParameter")),
STRING_QUERY(MemberName(extractorsPackage, "extractStringQueryParameter")),
STRING_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableStringQueryParameter")),
STRING_LIST_QUERY(MemberName(extractorsPackage, "extractStringListQueryParameter")),
STRING_LIST_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableStringListQueryParameter")),
INT_QUERY(MemberName(extractorsPackage, "extractIntQueryParameter")),
INT_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableIntQueryParameter")),
INT_LIST_QUERY(MemberName(extractorsPackage, "extractIntListQueryParameter")),
INT_LIST_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableIntListQueryParameter")),
LONG_QUERY(MemberName(extractorsPackage, "extractLongQueryParameter")),
LONG_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableLongQueryParameter")),
LONG_LIST_QUERY(MemberName(extractorsPackage, "extractLongListQueryParameter")),
LONG_LIST_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableLongListQueryParameter")),
DOUBLE_QUERY(MemberName(extractorsPackage, "extractDoubleQueryParameter")),
DOUBLE_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableDoubleQueryParameter")),
DOUBLE_LIST_QUERY(MemberName(extractorsPackage, "extractDoubleListQueryParameter")),
DOUBLE_LIST_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableDoubleListQueryParameter")),
BOOLEAN_QUERY(MemberName(extractorsPackage, "extractBooleanQueryParameter")),
BOOLEAN_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableBooleanQueryParameter")),
BOOLEAN_LIST_QUERY(MemberName(extractorsPackage, "extractBooleanListQueryParameter")),
BOOLEAN_LIST_NULLABLE_QUERY(MemberName(extractorsPackage, "extractNullableBooleanListQueryParameter")),
}
| 21 | null | 23 | 146 | bb6f65080d9f50b674c8a77dac08116b2ee9eebf | 3,183 | kora | Apache License 2.0 |
app/src/test/java/com/example/kotlinSub2Ara/presenter/EventPresenterTest.kt | arakoswara | 177,001,059 | false | null | package com.example.kotlinSub2Ara.presenter
import com.example.kotlinSub2Ara.BuildConfig
import com.example.kotlinSub2Ara.CoroutineContextProvider
import com.example.kotlinSub2Ara.EventView
import com.example.kotlinSub2Ara.TestContextProvider
import com.example.kotlinSub2Ara.api.ApiRepository
import com.example.kotlinSub2Ara.model.Event
import com.example.kotlinSub2Ara.model.EventList
import com.google.gson.Gson
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import org.mockito.*
class EventPresenterTest {
@Mock
private lateinit var view: EventView
@Mock
private lateinit var gson: Gson
@Mock
private lateinit var apiRepository: ApiRepository
@Mock
private lateinit var presenter: EventPresenter
@Mock
private lateinit var apiResponse: Deferred<String>
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
presenter = EventPresenter(view, apiRepository, gson, TestContextProvider())
}
@Test
fun getEventList() {
val events: MutableList<Event> = mutableListOf()
val response = EventList(events)
val league = BuildConfig.NEXT_MATCH
val idLeague = "4328"
runBlocking {
Mockito.`when`(apiRepository.doRequest(ArgumentMatchers.anyString()))
.thenReturn(apiResponse)
Mockito.`when`(apiResponse.await()).thenReturn("")
Mockito.`when`(
gson.fromJson("", EventList::class.java)
).thenReturn(response)
presenter.getEventList(league, idLeague)
Mockito.verify(view).showEventList(events)
}
}
@Test
fun getEventListPast() {
val events: MutableList<Event> = mutableListOf()
val response = EventList(events)
val league = BuildConfig.LAST_MATCH
val idLeague = "4328"
runBlocking {
Mockito.`when`(apiRepository.doRequest(ArgumentMatchers.anyString()))
.thenReturn(apiResponse)
Mockito.`when`(apiResponse.await()).thenReturn("")
Mockito.`when`(
gson.fromJson("", EventList::class.java)
).thenReturn(response)
presenter.getEventList(league, idLeague)
Mockito.verify(view).showEventList(events)
}
}
} | 0 | Kotlin | 0 | 0 | 5cf5973aa35ab69401aaefa0f08e886df89ddbdc | 2,373 | kotlin-unit-test | MIT License |
src/main/kotlin/ca/warp7/rt/view/api/Selection.kt | yuliu2016 | 188,286,975 | false | {"CSS": 157703, "Kotlin": 80493} | package ca.warp7.rt.view.api
data class Selection(
val rows: MutableSet<Int> = mutableSetOf(),
val cols: MutableSet<Int> = mutableSetOf()
) {
val minRow get() = rows.min() ?: 0
val maxRow get() = rows.max() ?: 0
val minCol get() = cols.min() ?: 0
val maxCol get() = cols.max() ?: 0
} | 1 | CSS | 0 | 0 | b0fa118a1fbc06efe9d618e0bd711fd639b4986c | 316 | RT-View | MIT License |
app/src/main/kotlin/za/co/dvt/android/showcase/ui/viewapp/screenshots/ScreenshotAdapter.kt | DVT | 87,165,643 | false | null | package za.co.dvt.android.showcase.ui.viewapp.screenshots
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import timber.log.Timber
import za.co.dvt.android.showcase.databinding.ListItemScreenshotBinding
/**
* @author rebeccafranks
* @since 2017/07/19.
*/
class ScreenshotAdapter(val screenshots: List<String>, val screenshotNavigator: ScreenshotNavigator) : RecyclerView.Adapter<ScreenshotViewHolder>() {
override fun getItemCount(): Int {
return screenshots.size
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ScreenshotViewHolder {
val view = ListItemScreenshotBinding.inflate(LayoutInflater.from(parent?.context))
val viewHolder = ScreenshotViewHolder(view.root, view, screenshotNavigator)
return viewHolder
}
override fun onBindViewHolder(holder: ScreenshotViewHolder?, position: Int) {
val item = screenshots[position]
Timber.d("Screenshot Url: $item at $position ")
holder?.bind(item)
}
} | 1 | null | 1 | 8 | e31003c1be94ca3aa77a07e87a1c58934722223c | 1,070 | showcase-android | Apache License 2.0 |
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/carousel/CarouselItemScope.kt | androidx | 256,589,781 | false | {"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019} | /*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3.carousel
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.toRect
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.addOutline
import androidx.compose.ui.platform.LocalDensity
/** Receiver scope for [Carousel] item content. */
@ExperimentalMaterial3Api
sealed interface CarouselItemScope {
/**
* Information regarding the carousel item, such as its minimum and maximum size.
*
* The item information is updated after every scroll. If you use it in a composable function,
* it will be recomposed on every change causing potential performance issues. Avoid using it in
* the composition.
*/
val carouselItemInfo: CarouselItemInfo
/**
* Clips the composable to the given [shape], taking into account the item's size in the cross
* axis and mask in the main axis.
*
* @param shape the shape to be applied to the composable
*/
@Composable fun Modifier.maskClip(shape: Shape): Modifier
/**
* Draw a border on the composable using the given [shape], taking into account the item's size
* in the cross axis and mask in the main axis.
*
* @param border the border to be drawn around the composable
* @param shape the shape of the border
*/
@Composable fun Modifier.maskBorder(border: BorderStroke, shape: Shape): Modifier
/**
* Converts and remembers [shape] into a [GenericShape] that uses the intersection of the
* carousel item's mask Rect and Size as the final shape's bounds.
*
* This method is useful if using a [Shape] in a Modifier other than [maskClip] and [maskBorder]
* where the shape should follow the changes in the item's mask size.
*
* @param shape The shape that will be converted and remembered and react to changes in the
* item's mask.
*/
@Composable fun rememberMaskShape(shape: Shape): GenericShape
}
@ExperimentalMaterial3Api
internal class CarouselItemScopeImpl(private val itemInfo: CarouselItemInfo) : CarouselItemScope {
override val carouselItemInfo: CarouselItemInfo
get() = itemInfo
@Composable
override fun Modifier.maskClip(shape: Shape): Modifier = clip(rememberMaskShape(shape = shape))
@Composable
override fun Modifier.maskBorder(border: BorderStroke, shape: Shape): Modifier =
border(border, rememberMaskShape(shape = shape))
@Composable
override fun rememberMaskShape(shape: Shape): GenericShape {
val density = LocalDensity.current
return remember(carouselItemInfo, density) {
GenericShape { size, direction ->
val rect = carouselItemInfo.maskRect.intersect(size.toRect())
addOutline(shape.createOutline(rect.size, direction, density))
translate(Offset(rect.left, rect.top))
}
}
}
}
| 29 | Kotlin | 946 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 3,899 | androidx | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/stepfunctions/StateMachinePropsDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.stepfunctions
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Boolean
import kotlin.Deprecated
import kotlin.String
import kotlin.Unit
import kotlin.collections.Map
import software.amazon.awscdk.Duration
import software.amazon.awscdk.RemovalPolicy
import software.amazon.awscdk.services.iam.IRole
import software.amazon.awscdk.services.stepfunctions.DefinitionBody
import software.amazon.awscdk.services.stepfunctions.IChainable
import software.amazon.awscdk.services.stepfunctions.LogOptions
import software.amazon.awscdk.services.stepfunctions.StateMachineProps
import software.amazon.awscdk.services.stepfunctions.StateMachineType
/**
* Properties for defining a State Machine.
*
* Example:
* ```
* import software.amazon.awscdk.services.stepfunctions.*;
* Pipeline pipeline = new Pipeline(this, "MyPipeline");
* Artifact inputArtifact = new Artifact();
* Pass startState = new Pass(this, "StartState");
* StateMachine simpleStateMachine = StateMachine.Builder.create(this, "SimpleStateMachine")
* .definition(startState)
* .build();
* StepFunctionInvokeAction stepFunctionAction = StepFunctionInvokeAction.Builder.create()
* .actionName("Invoke")
* .stateMachine(simpleStateMachine)
* .stateMachineInput(StateMachineInput.filePath(inputArtifact.atPath("assets/input.json")))
* .build();
* pipeline.addStage(StageOptions.builder()
* .stageName("StepFunctions")
* .actions(List.of(stepFunctionAction))
* .build());
* ```
*/
@CdkDslMarker
public class StateMachinePropsDsl {
private val cdkBuilder: StateMachineProps.Builder = StateMachineProps.builder()
/**
* @param definition Definition for this state machine.
* @deprecated use definitionBody: DefinitionBody.fromChainable()
*/
@Deprecated(message = "deprecated in CDK")
public fun definition(definition: IChainable) {
cdkBuilder.definition(definition)
}
/** @param definitionBody Definition for this state machine. */
public fun definitionBody(definitionBody: DefinitionBody) {
cdkBuilder.definitionBody(definitionBody)
}
/** @param definitionSubstitutions substitutions for the definition body aas a key-value map. */
public fun definitionSubstitutions(definitionSubstitutions: Map<String, String>) {
cdkBuilder.definitionSubstitutions(definitionSubstitutions)
}
/** @param logs Defines what execution history events are logged and where they are logged. */
public fun logs(logs: LogOptionsDsl.() -> Unit = {}) {
val builder = LogOptionsDsl()
builder.apply(logs)
cdkBuilder.logs(builder.build())
}
/** @param logs Defines what execution history events are logged and where they are logged. */
public fun logs(logs: LogOptions) {
cdkBuilder.logs(logs)
}
/** @param removalPolicy The removal policy to apply to state machine. */
public fun removalPolicy(removalPolicy: RemovalPolicy) {
cdkBuilder.removalPolicy(removalPolicy)
}
/** @param role The execution role for the state machine service. */
public fun role(role: IRole) {
cdkBuilder.role(role)
}
/** @param stateMachineName A name for the state machine. */
public fun stateMachineName(stateMachineName: String) {
cdkBuilder.stateMachineName(stateMachineName)
}
/** @param stateMachineType Type of the state machine. */
public fun stateMachineType(stateMachineType: StateMachineType) {
cdkBuilder.stateMachineType(stateMachineType)
}
/** @param timeout Maximum run time for this state machine. */
public fun timeout(timeout: Duration) {
cdkBuilder.timeout(timeout)
}
/**
* @param tracingEnabled Specifies whether Amazon X-Ray tracing is enabled for this state
* machine.
*/
public fun tracingEnabled(tracingEnabled: Boolean) {
cdkBuilder.tracingEnabled(tracingEnabled)
}
public fun build(): StateMachineProps = cdkBuilder.build()
}
| 4 | null | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 4,226 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/com/saadkhan/mvvmuserapp/fragments/UserFragment.kt | SaadKhanJadoon | 571,951,523 | false | null | package com.saadkhan.mvvmuserapp.fragments
class UserFragment {
} | 0 | Kotlin | 2 | 1 | 104d199747031af0ea50c63157d72b77163561bb | 66 | MVVM_User_App | MIT License |
domain/src/test/java/com/phicdy/mycuration/domain/util/DateParserTest.kt | phicdy | 24,188,186 | false | {"Kotlin": 688608, "HTML": 1307, "Shell": 1127} | package com.phicdy.mycuration.domain.util
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class DateParserTest {
@Test
fun testTimeZone() {
assertThat(DateParser.changeToJapaneseDate("Mon, 01 Jan 2018 01:23:45 +0900")).isEqualTo((1514737425000L))
}
@Test
fun testNoTimeZone() {
assertThat(DateParser.changeToJapaneseDate("2018-01-01 01:23:45")).isEqualTo((1514737425000L))
}
@Test
fun testWithTandTimeZone() {
//2014-07-27T14:38:34+09:00
assertThat(DateParser.changeToJapaneseDate("2018-01-01T01:23:45+0900")).isEqualTo((1514737425000L))
}
@Test
fun testWithTandTimeZoneWithColon() {
//2014-07-27T14:38:34+09:00
assertThat(DateParser.changeToJapaneseDate("2018-01-01T01:23:45+09:00")).isEqualTo((1514737425000L))
}
@Test
fun testWithTandTimeZoneWithColonAndMillisecond() {
//2014-07-27T14:38:34+09:00
assertThat(DateParser.changeToJapaneseDate("2018-01-01T01:23:45.000+09:00")).isEqualTo((1514737425000L))
}
@Test
fun testWithTandZ() {
assertThat(DateParser.changeToJapaneseDate("2018-01-01T01:23:45Z")).isEqualTo((1514737425000L))
}
@Test
fun testInvalid() {
assertThat(DateParser.changeToJapaneseDate("gjrajgh@")).isEqualTo((0L))
}
@Test
fun testEmpty() {
assertThat(DateParser.changeToJapaneseDate("")).isEqualTo((0L))
}
} | 46 | Kotlin | 9 | 30 | 052bc1776a80df0457399e96e001c9ad527d53f2 | 1,442 | MyCuration | The Unlicense |
src/Day05.kt | rod41732 | 728,131,475 | false | {"Kotlin": 21048} | /**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
val testInput = readInput("Day05_test")
val input = readInput("Day05")
data class MapRule(val destStart: Long, val srcStart: Long, val length: Long) {
fun mapOrNull(number: Long): Long? {
return if (srcStart <= number && number <= srcStart + length - 1) {
number + destStart - srcStart
} else {
null
}
}
fun inverse(): MapRule {
return MapRule(srcStart, destStart, length)
}
}
fun List<MapRule>.map(value: Long): Long {
return this.firstNotNullOfOrNull { it.mapOrNull(value) } ?: value
}
fun List<List<MapRule>>.map(value: Long): Long {
return this.fold(value) { acc, layer -> layer.map(acc) }
}
fun parseInput(input: List<String>): Pair<List<Long>, List<List<MapRule>>> {
val chunks = input.windowWhen { it == "" }
val seedLine = chunks.first().first()
val seeds = seedLine.substringAfter(": ").split(" ").map { it.toLong() }
// layer of maps, i.e. listOf(seed-to-soil, soil-to-fertilizer, ...)
val mapLayers = chunks.drop(1).map {
val mapLines = it.drop(1)
val mapData = mapLines.map { it.split(" ").map { it.toLong() }.let { (a, b, c) -> MapRule(a, b, c) } }
mapData
}
return Pair(seeds, mapLayers)
}
fun part1(input: List<String>): Long {
val (seeds, mapLayers) = parseInput(input)
return seeds.minOf { mapLayers.map(it) }
}
fun part2(input: List<String>): Long {
val (seeds, mapLayers) = parseInput(input)
val boundaryPoints = buildSet {
val inverseMapLayers = mapLayers.reversed().map { layer -> layer.map { it.inverse() } }
// calculate boundary point for all layers
inverseMapLayers.forEachIndexed { index, currentLayer ->
val restLayers = inverseMapLayers.drop(index + 1)
// calculate boundary point for each layer
currentLayer.forEach {
val src = it.destStart
val origToAchieve = restLayers.map(src)
add(origToAchieve)
}
}
}
val seedsToCheck = seeds.chunked(2).flatMap { (start, length) ->
val seedRange = start..(start + length - 1)
boundaryPoints.filter { seedRange.contains(it) } + seedRange.start
}
return seedsToCheck.minOf { mapLayers.map(it) }
}
assertEqual(part1(testInput), 35)
assertEqual(part2(testInput), 46)
println("Part1: ${part1(input)}")
println("Part2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 80104607449dad450bcd4d54245e498ff9da9291 | 2,760 | aoc-23 | Apache License 2.0 |
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/hierarchy/HierarchyUtils.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.hierarchy
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.matches
fun getCurrentElement(dataContext: DataContext, project: Project): PsiElement? {
val editor = CommonDataKeys.EDITOR.getData(dataContext)
if (editor != null) {
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return null
if (!RootKindFilter.projectAndLibrarySources.matches(file)) return null
return TargetElementUtil.findTargetElement(editor, TargetElementUtil.getInstance().allAccepted)
}
return CommonDataKeys.PSI_ELEMENT.getData(dataContext)
}
| 191 | null | 4372 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,141 | intellij-community | Apache License 2.0 |
fotoapparat/src/main/java/io/fotoapparat/configuration/Configuration.kt | RedApparat | 85,997,051 | false | null | package io.fotoapparat.configuration
import io.fotoapparat.selector.*
import io.fotoapparat.util.FrameProcessor
interface Configuration {
val flashMode: FlashSelector?
val focusMode: FocusModeSelector?
val jpegQuality: QualitySelector?
val exposureCompensation: ExposureSelector?
val frameProcessor: FrameProcessor?
val previewFpsRange: FpsRangeSelector?
val antiBandingMode: AntiBandingModeSelector?
val sensorSensitivity: SensorSensitivitySelector?
val previewResolution: ResolutionSelector?
val pictureResolution: ResolutionSelector?
} | 91 | null | 418 | 3,813 | 9454f3e4d1d222799049b00f3d84b274c3e02ee6 | 580 | Fotoapparat | Apache License 2.0 |
shuttle/permissions/domain/src/main/kotlin/shuttle/permissions/domain/usecase/HasBackgroundLocation.kt | fardavide | 462,194,990 | false | {"Kotlin": 465845, "Shell": 11573} | package shuttle.permissions.domain.usecase
import com.google.accompanist.permissions.MultiplePermissionsState
import com.google.accompanist.permissions.PermissionStatus
import org.koin.core.annotation.Factory
import shuttle.permissions.domain.model.BackgroundLocation
import shuttle.util.android.IsAndroidQ
@Factory
class HasBackgroundLocation(
private val isAndroidQ: IsAndroidQ
) {
operator fun invoke(state: MultiplePermissionsState) = isAndroidQ().not() ||
state.permissions.any { it.permission == BackgroundLocation && it.status == PermissionStatus.Granted }
}
| 12 | Kotlin | 1 | 14 | ce2910eae0ec07880184628e2b2cc34e09da3ab2 | 586 | Shuttle | Apache License 2.0 |
Vinylsg12/app/src/main/java/co/edu/uniandes/vinylsg12/ui/musicians/MusiciansFragment.kt | je-guerreroa1-uniandes | 621,087,798 | false | null | package co.edu.uniandes.vinylsg12.ui.musicians
import android.animation.ObjectAnimator
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import co.edu.uniandes.vinylsg12.common.api.models.Album
import co.edu.uniandes.vinylsg12.common.api.models.Musician
import co.edu.uniandes.vinylsg12.databinding.FragmentMusiciansBinding
import co.edu.uniandes.vinylsg12.ui.musicians.adapters.MusicianAdapter
class MusiciansFragment: Fragment() {
private var _binding: FragmentMusiciansBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val musiciansViewModel =
ViewModelProvider(this).get(MusiciansViewModel::class.java)
_binding = FragmentMusiciansBinding.inflate(inflater, container, false)
val root: View = binding.root
subscribeToViewModel(musiciansViewModel)
musiciansViewModel.fetchData()
return root
}
private fun subscribeToViewModel(musiciansViewModel: MusiciansViewModel) {
val recyclerView: RecyclerView = binding.musiciansRecyclerView
recyclerView.layoutManager = LinearLayoutManager(requireContext())
val adapter = MusicianAdapter(listOf())
recyclerView.adapter = adapter
musiciansViewModel.musicians.observe(viewLifecycleOwner) {
adapter.musicians = it
adapter.notifyDataSetChanged()
binding.progressBar.visibility = View.GONE
}
binding.progressBar.visibility = View.VISIBLE
val anim = ObjectAnimator.ofInt(binding.progressBar, "progress", 0, 100)
anim.duration = 2000 // 2 seconds
anim.start()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 3 | Kotlin | 0 | 2 | 6865a740c91eb55f059936af96f72f874d7b8c3b | 2,208 | grupo-12-software-mobile | MIT License |
src/player/main/sp/it/pl/core/CoreSerializerJson.kt | sghpjuikit | 18,862,317 | false | null | package sp.it.pl.core
import de.jensd.fx.glyphs.GlyphIcons
import java.io.File
import java.io.FileNotFoundException
import java.net.URI
import java.nio.charset.Charset
import java.nio.file.Path
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.Year
import java.time.ZoneId
import java.util.Locale
import java.util.UUID
import java.util.regex.Pattern
import javafx.geometry.BoundingBox
import javafx.geometry.Bounds
import javafx.geometry.Insets
import javafx.geometry.Point2D
import javafx.geometry.Point3D
import javafx.scene.effect.Effect
import javafx.scene.text.Font
import javafx.util.Duration
import kotlin.reflect.KClass
import kotlin.text.Charsets.UTF_8
import mu.KLogging
import sp.it.pl.audio.playlist.PlaylistSong
import sp.it.pl.audio.tagging.Metadata
import sp.it.pl.audio.tagging.MetadataGroup
import sp.it.pl.conf.Command
import sp.it.pl.layout.BiContainerDb
import sp.it.pl.layout.ContainerFreeFormUi
import sp.it.pl.layout.FreeFormContainerDb
import sp.it.pl.layout.NoComponentDb
import sp.it.pl.layout.RootContainerDb
import sp.it.pl.layout.SwitchContainerDb
import sp.it.pl.layout.UniContainerDb
import sp.it.pl.layout.Widget
import sp.it.pl.layout.WidgetDb
import sp.it.pl.main.APP
import sp.it.pl.main.AppUi
import sp.it.pl.main.FileFilter
import sp.it.pl.ui.objects.table.TableColumnInfo
import sp.it.pl.ui.objects.window.stage.WindowDb
import sp.it.util.access.fieldvalue.ColumnField
import sp.it.util.access.fieldvalue.FileField
import sp.it.util.access.fieldvalue.IconField
import sp.it.util.dev.Blocks
import sp.it.util.dev.fail
import sp.it.util.file.json.JsArray
import sp.it.util.file.json.JsConverter
import sp.it.util.file.json.JsString
import sp.it.util.file.json.JsValue
import sp.it.util.file.json.Json
import sp.it.util.file.json.toPrettyS
import sp.it.util.file.properties.PropVal
import sp.it.util.file.properties.PropVal.PropVal1
import sp.it.util.file.properties.PropVal.PropValN
import sp.it.util.file.type.MimeExt
import sp.it.util.file.type.MimeGroup
import sp.it.util.file.type.MimeType
import sp.it.util.file.writeSafely
import sp.it.util.file.writeTextTry
import sp.it.util.functional.PF
import sp.it.util.functional.Try
import sp.it.util.functional.Try.Java.error
import sp.it.util.functional.asIs
import sp.it.util.functional.invoke
import sp.it.util.math.StrExF
import sp.it.util.text.StringSplitParser
import sp.it.util.units.Bitrate
import sp.it.util.units.FileSize
import sp.it.util.units.NofX
class CoreSerializerJson: Core {
val encoding = UTF_8
val json = Json()
override fun init() {
json.typeAliases {
// @formatter:off
"no-container" alias NoComponentDb::class
"root-container" alias RootContainerDb::class
"uni-container" alias UniContainerDb::class
"bi-container" alias BiContainerDb::class
"free-container" alias FreeFormContainerDb::class
"free-container-window" alias ContainerFreeFormUi.WindowPosition::class
"switch-container" alias SwitchContainerDb::class
"widget" alias WidgetDb::class
"window" alias WindowDb::class
"component-loading" alias Widget.LoadType::class
"orientation" alias javafx.geometry.Orientation::class
"prop-val" alias PropVal::class
"1-prop-val" alias PropVal1::class
"n-prop-val" alias PropValN::class
// @formatter:on
}
json.converters {
PropVal::class convert object: JsConverter<PropVal> {
override fun toJson(value: PropVal): JsValue = when (value) {
is PropVal1 -> JsString(value.value)
is PropValN -> JsArray(value.value.map { JsString(it) })
}
override fun fromJson(value: JsValue) = when (value) {
is JsString -> PropVal1(value.value)
is JsArray -> PropValN(value.value.mapNotNull { it.asJsStringValue() })
else -> fail { "Unexpected value=$value, which is not ${JsString::class} or ${JsArray::class}" }
}
}
@Suppress("RemoveRedundantQualifierName")
val classes = setOf(
StringSplitParser::class,
Path::class,
File::class,
UUID::class,
URI::class,
Pattern::class,
Bitrate::class,
Duration::class,
Locale::class,
Charset::class,
ZoneId::class,
Instant::class,
LocalTime::class,
LocalDate::class,
LocalDateTime::class,
Year::class,
FileSize::class,
StrExF::class,
NofX::class,
MimeGroup::class,
MimeType::class,
MimeExt::class,
ColumnField::class,
IconField::class,
FileFilter::class,
FileField::class,
PlaylistSong.Field::class,
sp.it.pl.audio.Song::class,
sp.it.pl.audio.tagging.Metadata::class,
Metadata.Field::class,
MetadataGroup.Field::class,
TableColumnInfo::class,
TableColumnInfo.ColumnInfo::class,
TableColumnInfo.ColumnSortInfo::class,
Font::class,
GlyphIcons::class,
Effect::class,
Class::class,
KClass::class,
PF::class,
javafx.scene.paint.Paint::class,
javafx.scene.paint.Color::class,
javafx.scene.paint.RadialGradient::class,
javafx.scene.paint.LinearGradient::class,
javafx.scene.paint.ImagePattern::class,
BoundingBox::class,
Bounds::class,
Point2D::class,
Point3D::class,
Insets::class,
Command::class,
Command.CommandActionId::class,
Command.CommandComponentId::class,
AppUi.SkinCss::class,
)
classes.forEach { c ->
c.asIs<KClass<Any>>() convert object: JsConverter<Any> {
val toS = APP.converter.general.parsersToS[c]!!
val ofS = APP.converter.general.parsersFromS[c]!!
override fun canConvert(value: Any) = c.isInstance(value)
override fun toJson(value: Any): JsValue = JsString(toS(value).orThrow)
override fun fromJson(value: JsValue): Any? = value.asJsStringValue()?.let { ofS(it).orThrow }
}
}
}
}
@Blocks
inline fun <reified T: Any> toJson(t: T, file: File): Try<Nothing?, Throwable> {
return file.writeSafely {
it.writeTextTry(json.toJsonValue(t).toPrettyS())
}.ifError {
logger.error(it) { "Couldn't serialize " + t.javaClass + " to file=$file" }
}
}
// TODO: error handling on call sites
@Blocks
inline fun <reified T> fromJson(file: File): Try<T, Throwable> {
return if (!file.exists())
error<T, Throwable>(Exception("Couldn't deserialize ${T::class} from file $file", FileNotFoundException(file.absolutePath)))
else
json.fromJson<T>(file).ifError {
logger.error(it) { "Couldn't deserialize ${T::class} from file$file" }
}
}
companion object: KLogging()
} | 12 | null | 2 | 19 | 46ab4d264435b122cc4993931501a664fadc7fd6 | 7,332 | player | X.Net License |
app/common/src/desktopMain/kotlin/com/denchic45/studiversity/ui/components/theme/Typo.kt | denchic45 | 435,895,363 | false | null | package com.denchic45.studiversity.ui.components.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import com.denchic45.studiversity.ui.components.tokens.TypographyKeyTokens
fun Typography.fromToken(value: TypographyKeyTokens): TextStyle {
return when (value) {
TypographyKeyTokens.DisplayLarge -> displayLarge
TypographyKeyTokens.DisplayMedium -> displayMedium
TypographyKeyTokens.DisplaySmall -> displaySmall
TypographyKeyTokens.HeadlineLarge -> headlineLarge
TypographyKeyTokens.HeadlineMedium -> headlineMedium
TypographyKeyTokens.HeadlineSmall -> headlineSmall
TypographyKeyTokens.TitleLarge -> titleLarge
TypographyKeyTokens.TitleMedium -> titleMedium
TypographyKeyTokens.TitleSmall -> titleSmall
TypographyKeyTokens.BodyLarge -> bodyLarge
TypographyKeyTokens.BodyMedium -> bodyMedium
TypographyKeyTokens.BodySmall -> bodySmall
TypographyKeyTokens.LabelLarge -> labelLarge
TypographyKeyTokens.LabelMedium -> labelMedium
TypographyKeyTokens.LabelSmall -> labelSmall
}
} | 0 | null | 0 | 7 | 93947301de4c4a9cb6c3d9fa36903f857c50e6c2 | 1,147 | Studiversity | Apache License 2.0 |
reposilite-backend/src/test/kotlin/com/reposilite/ReposiliteSpecification.kt | XiamLiTechnologies | 416,864,246 | true | {"Kotlin": 328983, "Vue": 40726, "JavaScript": 37270, "HTML": 7753, "CSS": 2344, "Shell": 2126, "Dockerfile": 1108} | /*
* Copyright (c) 2021 dzikoysk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reposilite
import com.reposilite.token.api.CreateAccessTokenRequest
import com.reposilite.token.api.Route
import com.reposilite.token.api.RoutePermission
internal abstract class ReposiliteSpecification : ReposiliteRunner() {
val base: String
get() = "http://localhost:$port"
fun usePredefinedTemporaryAuth(): Pair<String, String> =
Pair("manager", "manager-secret")
fun useAuth(name: String, secret: String, routes: Map<String, RoutePermission> = emptyMap()): Pair<String, String> {
val accessTokenFacade = reposilite.accessTokenFacade
var accessToken = accessTokenFacade.createAccessToken(CreateAccessTokenRequest(name, secret)).accessToken
routes.forEach { (route, permission) ->
accessToken = accessTokenFacade.updateToken(accessToken.withRoute(Route(route, setOf(permission))))
}
return Pair(name, secret)
}
} | 0 | null | 0 | 0 | f8b7de3e2bbf2f4f71e8364e1f918a2af7e31092 | 1,514 | reposilite | Apache License 2.0 |
packages/internal/generators-files/spring-boot/application/shared/kotlin/src/test/kotlin/__packageDirectory__/HelloControllerTests.kt | khalilou88 | 404,925,430 | false | {"TypeScript": 838028, "HTML": 489236, "JavaScript": 11111, "Java": 8153, "Kotlin": 7713, "Groovy": 5393, "Shell": 255} | package <%= packageName %>
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.test.web.client.getForEntity
import org.springframework.http.HttpStatus
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class HelloControllerTests(@Autowired val restTemplate: TestRestTemplate) {
@BeforeAll
fun setup() {
println(">> Setup")
}
@Test
fun `Should return Hello World`() {
println(">> Should return Hello World")
val entity = restTemplate.getForEntity<String>("/")
assertThat(entity.statusCode).isEqualTo(HttpStatus.OK)
assertThat(entity.body).contains("Hello World")
}
@AfterAll
fun teardown() {
println(">> Tear down")
}
}
| 13 | TypeScript | 15 | 63 | 21b99d4530ca1be867a33da28fbcebd5548489de | 1,021 | jnxplus | MIT License |
runtime/runtime-core/common/src/aws/smithy/kotlin/runtime/retries/delay/StandardRetryTokenBucket.kt | awslabs | 294,823,838 | false | null | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package aws.smithy.kotlin.runtime.retries.delay
import aws.smithy.kotlin.runtime.retries.policy.RetryErrorType
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.min
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
private const val MS_PER_S = 1_000
/**
* The standard implementation of a [RetryTokenBucket].
* @param options The configuration to use for this bucket.
* @param timeSource A monotonic time source to use for calculating the temporal token fill of the bucket.
*/
@OptIn(ExperimentalTime::class)
public class StandardRetryTokenBucket constructor(
public val options: StandardRetryTokenBucketOptions = StandardRetryTokenBucketOptions.Default,
private val timeSource: TimeSource = TimeSource.Monotonic,
) : RetryTokenBucket {
internal var capacity = options.maxCapacity
private set
private var lastTimeMark = timeSource.markNow()
private val mutex = Mutex()
/**
* Acquire a token from the token bucket. This method should be called before the initial retry attempt for a block
* of code. This method may delay if there are already insufficient tokens in the bucket due to prior retry
* failures or large numbers of simultaneous requests.
*/
override suspend fun acquireToken(): RetryToken {
checkoutCapacity(options.initialTryCost)
return StandardRetryToken(options.initialTrySuccessIncrement)
}
private suspend fun checkoutCapacity(size: Int): Unit = mutex.withLock {
refillCapacity()
if (size <= capacity) {
capacity -= size
} else {
if (options.circuitBreakerMode) {
throw RetryCapacityExceededException("Insufficient capacity to attempt another retry")
}
val extraRequiredCapacity = size - capacity
val delayMs = ceil(extraRequiredCapacity.toDouble() / options.refillUnitsPerSecond * MS_PER_S).toLong()
delay(delayMs)
capacity = 0
}
lastTimeMark = timeSource.markNow()
}
private fun refillCapacity() {
val refillMs = lastTimeMark.elapsedNow().inWholeMilliseconds
val refillSize = floor(options.refillUnitsPerSecond.toDouble() / MS_PER_S * refillMs).toInt()
capacity = min(options.maxCapacity, capacity + refillSize)
}
private suspend fun returnCapacity(size: Int): Unit = mutex.withLock {
refillCapacity()
capacity = min(options.maxCapacity, capacity + size)
lastTimeMark = timeSource.markNow()
}
/**
* A standard implementation of a [RetryToken].
* @param returnSize The amount of capacity to return to the bucket on a successful try.
*/
internal inner class StandardRetryToken(public val returnSize: Int) : RetryToken {
/**
* Completes this token because retrying has been abandoned. This implementation doesn't actually increment any
* capacity upon failure...capacity just refills based on time.
*/
override suspend fun notifyFailure() {
// Do nothing
}
/**
* Completes this token because the previous retry attempt was successful.
*/
override suspend fun notifySuccess() {
returnCapacity(returnSize)
}
/**
* Completes this token and requests another one because the previous retry attempt was unsuccessful.
*/
override suspend fun scheduleRetry(reason: RetryErrorType): RetryToken {
val size = when (reason) {
RetryErrorType.Timeout, RetryErrorType.Throttling -> options.timeoutRetryCost
else -> options.retryCost
}
checkoutCapacity(size)
return StandardRetryToken(size)
}
}
}
/**
* The configuration options for a [StandardRetryTokenBucket].
* @param maxCapacity The maximum capacity for the bucket.
* @param refillUnitsPerSecond The amount of capacity to return per second.
* @param circuitBreakerMode When true, indicates that attempts to acquire tokens or schedule retries should fail if all
* capacity has been depleted. When false, calls to acquire tokens or schedule retries will delay until sufficient
* capacity is available.
* @param retryCost The amount of capacity to decrement for standard retries.
* @param timeoutRetryCost The amount of capacity to decrement for timeout or throttling retries.
* @param initialTryCost The amount of capacity to decrement for the initial try.
* @param initialTrySuccessIncrement The amount of capacity to return if the initial try is successful.
*/
public data class StandardRetryTokenBucketOptions(
public val maxCapacity: Int,
public val refillUnitsPerSecond: Int,
public val circuitBreakerMode: Boolean,
public val retryCost: Int,
public val timeoutRetryCost: Int,
public val initialTryCost: Int,
public val initialTrySuccessIncrement: Int,
) {
public companion object {
/**
* The default configuration for a [StandardRetryTokenBucket].
*/
public val Default: StandardRetryTokenBucketOptions = StandardRetryTokenBucketOptions(
maxCapacity = 500,
refillUnitsPerSecond = 10,
circuitBreakerMode = false,
retryCost = 5,
timeoutRetryCost = 10,
initialTryCost = 0,
initialTrySuccessIncrement = 1,
)
}
}
| 30 | null | 16 | 28 | 6f68ac0fc38a2cf3e3ed8b27769d505af67b99b0 | 5,674 | smithy-kotlin | Apache License 2.0 |
platform/platform-impl/src/com/intellij/ui/dsl/gridLayout/JBGridImpl.kt | stroyerr | 401,048,382 | true | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.gridLayout
import java.awt.Dimension
import java.awt.Rectangle
import javax.swing.JComponent
import kotlin.math.max
import kotlin.math.min
internal class JBGridImpl : JBGrid {
override var resizableColumns = emptySet<Int>()
override var resizableRows = emptySet<Int>()
override var columnsGaps = emptyList<ColumnGaps>()
override var rowsGaps = emptyList<RowGaps>()
val visible: Boolean
get() = cells.any { it.visible }
private val layoutData = JBLayoutData()
private val cells = mutableListOf<JBCell>()
fun register(component: JComponent, constraints: JBConstraints) {
if (!isEmpty(constraints)) {
throw UiDslException("Some cells are occupied already: $constraints")
}
cells.add(JBComponentCell(constraints, component))
}
fun registerSubGrid(constraints: JBConstraints): JBGrid {
if (!isEmpty(constraints)) {
throw UiDslException("Some cells are occupied already: $constraints")
}
val result = JBGridImpl()
cells.add(JBGridCell(constraints, result))
return result
}
fun unregister(component: JComponent): Boolean {
val iterator = cells.iterator()
for (cell in iterator) {
when (cell) {
is JBComponentCell -> {
if (cell.component == component) {
iterator.remove()
return true
}
}
is JBGridCell -> {
if (cell.content.unregister(component)) {
return true
}
}
}
}
return false
}
fun getPreferredSize(): Dimension {
calculateLayoutData(-1, -1)
return Dimension(layoutData.preferredWidth, layoutData.preferredHeight)
}
/**
* Layouts components
*/
fun layout(rect: Rectangle) {
layoutData.visibleCellsData.forEach { layoutCellData ->
val cell = layoutCellData.cell
val constraints = cell.constraints
val paddedX = rect.x + constraints.gaps.left + layoutCellData.columnGaps.left + layoutData.columnsCoord[constraints.x]
val paddedY = rect.y + constraints.gaps.top + layoutCellData.rowGaps.top + layoutData.rowsCoord[constraints.y]
val paddedWidth = layoutData.getPaddedWidth(layoutCellData)
val fullPaddedWidth = layoutData.getFullPaddedWidth(layoutCellData)
val paddedHeight = layoutData.getFullPaddedHeight(layoutCellData)
when (cell) {
is JBComponentCell -> {
layoutComponent(cell.component, layoutCellData, paddedX, paddedY, paddedWidth, fullPaddedWidth, paddedHeight)
}
is JBGridCell -> {
// todo constraints are not used
cell.content.layout(Rectangle(paddedX, paddedY, fullPaddedWidth, paddedHeight))
}
}
}
}
/**
* Calculates [layoutData]
*
* @param width if negative - calculates layout for preferred size, otherwise uses [width]
* @param height if negative - calculates layout for preferred size, otherwise uses [height]
*/
fun calculateLayoutData(width: Int, height: Int) {
calculateLayoutDataStep1()
calculateLayoutDataStep2(width)
calculateLayoutDataStep3()
calculateLayoutDataStep4(height)
}
/**
* Step 1 of [layoutData] calculations
*/
fun calculateLayoutDataStep1() {
layoutData.columnsSizeCalculator.reset()
val visibleCellsData = mutableListOf<LayoutCellData>()
for (cell in cells) {
var preferredSize: Dimension
when (cell) {
is JBComponentCell -> {
val component = cell.component
if (!component.isVisible) {
continue
}
preferredSize = component.preferredSize
}
is JBGridCell -> {
val grid = cell.content
if (!grid.visible) {
continue
}
grid.calculateLayoutDataStep1()
preferredSize = Dimension(grid.layoutData.preferredWidth, 0)
}
}
val layoutCellData: LayoutCellData
with(cell.constraints) {
layoutCellData = LayoutCellData(cell = cell,
preferredSize = preferredSize,
columnGaps = ColumnGaps(
left = columnsGaps.getOrNull(x)?.left ?: 0,
right = columnsGaps.getOrNull(x + width - 1)?.right ?: 0),
rowGaps = RowGaps(
top = rowsGaps.getOrNull(y)?.top ?: 0,
bottom = rowsGaps.getOrNull(y + height - 1)?.bottom ?: 0)
)
}
visibleCellsData.add(layoutCellData)
layoutData.columnsSizeCalculator.addConstraint(cell.constraints.x, cell.constraints.width, layoutCellData.cellPaddedWidth)
}
layoutData.visibleCellsData = visibleCellsData
layoutData.preferredWidth = layoutData.columnsSizeCalculator.calculatePreferredSize()
}
/**
* Step 2 of [layoutData] calculations
*
* @param width see [calculateLayoutData]
*/
fun calculateLayoutDataStep2(width: Int) {
val calcWidth = if (width < 0) layoutData.preferredWidth else width
layoutData.columnsCoord = layoutData.columnsSizeCalculator.calculateCoords(calcWidth, resizableColumns)
for (layoutCellData in layoutData.visibleCellsData) {
val cell = layoutCellData.cell
if (cell is JBGridCell) {
cell.content.calculateLayoutDataStep2(layoutData.getFullPaddedWidth(layoutCellData))
}
}
}
/**
* Step 3 of [layoutData] calculations
*/
fun calculateLayoutDataStep3() {
layoutData.rowsSizeCalculator.reset()
initBaselineData()
for (layoutCellData in layoutData.visibleCellsData) {
when (val cell = layoutCellData.cell) {
is JBComponentCell -> {
val rowBaselineData = layoutCellData.rowBaselineData
if (rowBaselineData == null) {
continue
}
val constraints = layoutCellData.cell.constraints
val componentWidth = layoutData.getPaddedWidth(layoutCellData) + layoutCellData.cell.constraints.visualPaddings.width
val baseline: Int
if (componentWidth >= 0) {
baseline = cell.component.getBaseline(componentWidth, layoutCellData.preferredSize.height)
// getBaseline changes preferredSize, at least for JLabel
layoutCellData.preferredSize.height = cell.component.preferredSize.height
}
else {
baseline = -1
}
if (baseline < 0) {
layoutCellData.rowBaselineData = null
}
else {
layoutCellData.baseline = baseline
with(rowBaselineData) {
maxAboveBaseline = max(maxAboveBaseline,
baseline + layoutCellData.rowGaps.top + constraints.gaps.top - constraints.visualPaddings.top)
maxBelowBaseline = max(maxBelowBaseline,
layoutCellData.preferredSize.height - baseline + layoutCellData.rowGaps.bottom + constraints.gaps.bottom - constraints.visualPaddings.bottom)
}
}
}
is JBGridCell -> {
val grid = cell.content
grid.calculateLayoutDataStep3()
layoutCellData.preferredSize.height = grid.layoutData.preferredHeight
// todo use subgrid baseline
layoutCellData.rowBaselineData = null
}
}
}
for (layoutCellData in layoutData.visibleCellsData) {
val constraints = layoutCellData.cell.constraints
layoutData.rowsSizeCalculator.addConstraint(constraints.y, constraints.height, layoutCellData.cellPaddedHeight)
}
layoutData.preferredHeight = layoutData.rowsSizeCalculator.calculatePreferredSize()
}
/**
* Step 4 of [layoutData] calculations
*
* @param height see [calculateLayoutData]
*/
fun calculateLayoutDataStep4(height: Int) {
val calcHeight = if (height < 0) layoutData.preferredHeight else height
layoutData.rowsCoord = layoutData.rowsSizeCalculator.calculateCoords(calcHeight, resizableRows)
for (layoutCellData in layoutData.visibleCellsData) {
val cell = layoutCellData.cell
if (cell is JBGridCell) {
cell.content.calculateLayoutDataStep4(layoutData.getFullPaddedHeight(layoutCellData))
}
}
}
/**
* Assigns [LayoutCellData.rowBaselineData]
*/
private fun initBaselineData() {
for (layoutCellData in layoutData.visibleCellsData) {
layoutCellData.baseline = null
layoutCellData.rowBaselineData = null
}
layoutData.visibleCellsData
.filter { it.cell.constraints.verticalAlign != VerticalAlign.FILL && it.cell.constraints.height == 1 }
.groupBy { it.cell.constraints.y }
.forEach { cellsByRow ->
cellsByRow.value.groupBy { it.cell.constraints.verticalAlign }.forEach { cellsByAlign ->
val rowBaselineData = RowBaselineData()
for (layoutCellData in cellsByAlign.value) {
layoutCellData.rowBaselineData = rowBaselineData
}
}
}
}
/**
* Layouts [component] in such way that its padded bounds (size of component minus visualPaddings) equal provided rect
*/
private fun layoutComponent(component: JComponent,
layoutCellData: LayoutCellData,
paddedX: Int,
paddedY: Int,
paddedWidth: Int,
fullPaddedWidth: Int,
paddedHeight: Int) {
val constraints = layoutCellData.cell.constraints
val visualPaddings = constraints.visualPaddings
val resultPaddedHeight = if (constraints.verticalAlign == VerticalAlign.FILL)
paddedHeight
else
min(paddedHeight, layoutCellData.preferredSize.height - visualPaddings.height)
val resultPaddedX = paddedX +
when (constraints.horizontalAlign) {
HorizontalAlign.LEFT -> 0
HorizontalAlign.CENTER -> (fullPaddedWidth - paddedWidth) / 2
HorizontalAlign.RIGHT -> fullPaddedWidth - paddedWidth
HorizontalAlign.FILL -> 0
}
val resultPaddedY = paddedY +
when (constraints.verticalAlign) {
VerticalAlign.TOP -> 0
VerticalAlign.CENTER -> (paddedHeight - resultPaddedHeight) / 2
VerticalAlign.BOTTOM -> paddedHeight - resultPaddedHeight
VerticalAlign.FILL -> 0
}
component.setBounds(
resultPaddedX - visualPaddings.left, resultPaddedY - visualPaddings.top,
paddedWidth + visualPaddings.width, resultPaddedHeight + visualPaddings.height
)
}
private fun isEmpty(constraints: JBConstraints): Boolean {
cells.forEach { cell ->
with(cell.constraints) {
if (constraints.x + constraints.width > x &&
x + width > constraints.x &&
constraints.y + constraints.height > y &&
y + height > constraints.y
) {
return false
}
}
}
return true
}
}
/**
* Data that collected before layout/preferred size calculations
*/
private class JBLayoutData {
//
// Step 1
//
var visibleCellsData = emptyList<LayoutCellData>()
val columnsSizeCalculator = JBColumnsSizeCalculator()
var preferredWidth = 0
//
// Step 2
//
var columnsCoord = emptyArray<Int>()
//
// Step 3
//
val rowsSizeCalculator = JBColumnsSizeCalculator()
var preferredHeight = 0
//
// Step 4
//
var rowsCoord = emptyArray<Int>()
fun getPaddedWidth(layoutCellData: LayoutCellData): Int {
val fullPaddedWidth = getFullPaddedWidth(layoutCellData)
return if (layoutCellData.cell.constraints.horizontalAlign == HorizontalAlign.FILL)
fullPaddedWidth
else
min(fullPaddedWidth, layoutCellData.preferredSize.width - layoutCellData.cell.constraints.visualPaddings.width)
}
fun getFullPaddedWidth(layoutCellData: LayoutCellData): Int {
val constraints = layoutCellData.cell.constraints
return columnsCoord[constraints.x + constraints.width] - columnsCoord[constraints.x] - layoutCellData.gapWidth
}
fun getFullPaddedHeight(layoutCellData: LayoutCellData): Int {
val constraints = layoutCellData.cell.constraints
return rowsCoord[constraints.y + constraints.height] - rowsCoord[constraints.y] - layoutCellData.gapHeight
}
}
/**
* For sub-grids height of [preferredSize] calculated on late steps of [JBGridImpl.calculateLayoutData]
*/
private data class LayoutCellData(val cell: JBCell, val preferredSize: Dimension,
val columnGaps: ColumnGaps, val rowGaps: RowGaps) {
/**
* Calculated on late steps of [JBGridImpl.calculateLayoutData]
*/
var baseline: Int? = null
/**
* Calculated on late steps of [JBGridImpl.calculateLayoutData]. null for cells without baseline, height > 1 or vertical align FILL
*/
var rowBaselineData: RowBaselineData? = null
val gapWidth: Int
get() = cell.constraints.gaps.width + columnGaps.width
val gapHeight: Int
get() = cell.constraints.gaps.height + rowGaps.height
/**
* Cell width including gaps and excluding visualPaddings
*/
val cellPaddedWidth: Int
get() = preferredSize.width + gapWidth - cell.constraints.visualPaddings.width
/**
* Cell height including gaps and excluding visualPaddings
*/
val cellPaddedHeight: Int
get() {
val baselineData = rowBaselineData
if (baselineData == null) {
return preferredSize.height + gapHeight - cell.constraints.visualPaddings.height
}
return baselineData.maxAboveBaseline + baselineData.maxBelowBaseline
}
}
/**
* Max sizes for a row which include gaps and exclude paddings
*/
private data class RowBaselineData(var maxAboveBaseline: Int = 0, var maxBelowBaseline: Int = 0)
private sealed class JBCell(val constraints: JBConstraints) {
abstract val visible: Boolean
}
private class JBComponentCell(constraints: JBConstraints, val component: JComponent) : JBCell(constraints) {
override val visible: Boolean
get() = component.isVisible
}
private class JBGridCell(constraints: JBConstraints, val content: JBGridImpl) : JBCell(constraints) {
override val visible: Boolean
get() = content.visible
}
| 0 | null | 0 | 0 | 04f1339375633c0129929d05d7744bfdd1a93a9a | 14,368 | intellij-community | Apache License 2.0 |
serialization/src/main/kotlin/net/corda/serialization/internal/amqp/custom/OffsetDateTimeSerializer.kt | corda | 70,137,417 | false | {"Kotlin": 10675960, "Java": 275115, "C++": 239894, "Python": 37811, "Shell": 28324, "CSS": 23544, "Groovy": 14725, "CMake": 5393, "Dockerfile": 2574, "Batchfile": 1777, "PowerShell": 660, "C": 454} | package net.corda.serialization.internal.amqp.custom
import net.corda.core.KeepForDJVM
import net.corda.serialization.internal.amqp.CustomSerializer
import net.corda.serialization.internal.amqp.SerializerFactory
import java.time.LocalDateTime
import java.time.OffsetDateTime
import java.time.ZoneOffset
/**
* A serializer for [OffsetDateTime] that uses a proxy object to write out the date and zone offset.
*/
class OffsetDateTimeSerializer(
factory: SerializerFactory
) : CustomSerializer.Proxy<OffsetDateTime, OffsetDateTimeSerializer.OffsetDateTimeProxy>(
OffsetDateTime::class.java,
OffsetDateTimeProxy::class.java,
factory
) {
override val additionalSerializers: Iterable<CustomSerializer<out Any>> = listOf(
LocalDateTimeSerializer(factory),
ZoneIdSerializer(factory)
)
override fun toProxy(obj: OffsetDateTime): OffsetDateTimeProxy = OffsetDateTimeProxy(obj.toLocalDateTime(), obj.offset)
override fun fromProxy(proxy: OffsetDateTimeProxy): OffsetDateTime = OffsetDateTime.of(proxy.dateTime, proxy.offset)
@KeepForDJVM
data class OffsetDateTimeProxy(val dateTime: LocalDateTime, val offset: ZoneOffset)
} | 62 | Kotlin | 1090 | 3,989 | d27aa0e6850d3804d0982024054376d452e7073a | 1,198 | corda | Apache License 2.0 |
src/test/kotlin/aoc2015/ReindeerOlympicsTest.kt | komu | 113,825,414 | false | null | package komu.adventofcode.aoc2015
import komu.adventofcode.utils.readTestInput
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class ReindeerOlympicsTest {
@Test
fun `part 1`() {
assertEquals(2696, reindeerOlympics1(readTestInput("/2015/ReindeerOlympics.txt")))
}
@Test
fun `part 2`() {
assertEquals(1084, reindeerOlympics2(readTestInput("/2015/ReindeerOlympics.txt")))
}
}
| 0 | Kotlin | 0 | 0 | e59e8dec81de9ac6e7c9d6918eafb12353e87d75 | 436 | advent-of-code | MIT License |
app/src/main/java/eu/kanade/tachiyomi/source/manga/MangaSourceExtensions.kt | aniyomiorg | 358,887,741 | false | null | package eu.kanade.tachiyomi.source.manga
import android.graphics.drawable.Drawable
import eu.kanade.domain.source.service.SourcePreferences
import eu.kanade.tachiyomi.extension.manga.MangaExtensionManager
import eu.kanade.tachiyomi.source.MangaSource
import tachiyomi.domain.source.manga.model.MangaSourceData
import tachiyomi.domain.source.manga.model.StubMangaSource
import tachiyomi.source.local.entries.manga.isLocal
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
fun MangaSource.icon(): Drawable? = Injekt.get<MangaExtensionManager>().getAppIconForSource(this.id)
fun MangaSource.getPreferenceKey(): String = "source_$id"
fun MangaSource.toSourceData(): MangaSourceData = MangaSourceData(id = id, lang = lang, name = name)
fun MangaSource.getNameForMangaInfo(): String {
val preferences = Injekt.get<SourcePreferences>()
val enabledLanguages = preferences.enabledLanguages().get()
.filterNot { it in listOf("all", "other") }
val hasOneActiveLanguages = enabledLanguages.size == 1
val isInEnabledLanguages = lang in enabledLanguages
return when {
// For edge cases where user disables a source they got manga of in their library.
hasOneActiveLanguages && !isInEnabledLanguages -> toString()
// Hide the language tag when only one language is used.
hasOneActiveLanguages && isInEnabledLanguages -> name
else -> toString()
}
}
fun MangaSource.isLocalOrStub(): Boolean = isLocal() || this is StubMangaSource
| 180 | null | 315 | 4,992 | 823099f775ef608b7c11f096da1f50762dab82df | 1,507 | aniyomi | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/oauth2server/resource/api/UserControllerTest.kt | ministryofjustice | 118,512,431 | false | null | @file:Suppress("ClassName")
package uk.gov.justice.digital.hmpps.oauth2server.resource.api
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.mockito.ArgumentMatchers.anyString
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.Pageable
import org.springframework.security.authentication.TestingAuthenticationToken
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UsernameNotFoundException
import uk.gov.justice.digital.hmpps.oauth2server.auth.model.Authority
import uk.gov.justice.digital.hmpps.oauth2server.auth.model.User
import uk.gov.justice.digital.hmpps.oauth2server.auth.model.UserFilter
import uk.gov.justice.digital.hmpps.oauth2server.auth.model.UserHelper.Companion.createSampleUser
import uk.gov.justice.digital.hmpps.oauth2server.model.EmailAddress
import uk.gov.justice.digital.hmpps.oauth2server.model.ErrorDetail
import uk.gov.justice.digital.hmpps.oauth2server.model.UserDetail
import uk.gov.justice.digital.hmpps.oauth2server.model.UserRole
import uk.gov.justice.digital.hmpps.oauth2server.nomis.model.AccountStatus
import uk.gov.justice.digital.hmpps.oauth2server.nomis.model.NomisUserPersonDetails
import uk.gov.justice.digital.hmpps.oauth2server.nomis.model.NomisUserPersonDetailsHelper.Companion.createSampleNomisUser
import uk.gov.justice.digital.hmpps.oauth2server.resource.api.UserController.MfaOptions
import uk.gov.justice.digital.hmpps.oauth2server.security.AuthSource
import uk.gov.justice.digital.hmpps.oauth2server.security.AuthSource.auth
import uk.gov.justice.digital.hmpps.oauth2server.security.AuthSource.nomis
import uk.gov.justice.digital.hmpps.oauth2server.security.UserService
import java.time.LocalDateTime
import java.util.Optional
import java.util.UUID
class UserControllerTest {
private val userService: UserService = mock()
private val userController = UserController(userService)
private val authentication = UsernamePasswordAuthenticationToken("bob", "pass", listOf())
private val principal = TestingAuthenticationToken("joe", "credentials")
@Test
fun user_nomisUserNoCaseload() {
setupFindUserCallForNomis(activeCaseLoadId = null, enabled = false)
val user = userController.user("joe")
assertThat(user).usingRecursiveComparison().isEqualTo(
UserDetail(
"principal",
false,
"Joe Bloggs",
nomis,
5L,
null,
"5",
UUID.fromString(USER_ID),
),
)
}
@Test
fun user_nomisUser() {
setupFindUserCallForNomis(enabled = false)
val user = userController.user("joe")
assertThat(user).usingRecursiveComparison().isEqualTo(
UserDetail(
"principal",
false,
"Joe Bloggs",
nomis,
5L,
"somecase",
"5",
UUID.fromString(USER_ID),
),
)
}
@Test
fun user_authUser() {
setupFindUserCallForAuth()
val user = userController.user("joe")
assertThat(user).usingRecursiveComparison().isEqualTo(
UserDetail(
"principal",
true,
"Joe Bloggs",
auth,
null,
null,
USER_ID,
UUID.fromString(USER_ID),
),
)
}
@Test
fun userandsource_notFound() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(Optional.empty())
assertThatThrownBy { userController.findUserId("joe", nomis) }
.isInstanceOf(UsernameNotFoundException::class.java)
.hasMessage("Account for username joe not found")
}
@Test
fun userandsource_found() {
whenever(userService.getOrCreateUser(anyString(), any<AuthSource>())).thenReturn(Optional.of(createSampleUser()))
val authUserId = userController.findUserId("joe", nomis)
assertThat(authUserId.uuid).isEqualTo(USER_ID)
}
@Test
fun me_userNotFound() {
assertThat(userController.me(principal)).usingRecursiveComparison().isEqualTo(UserDetail.fromUsername("joe"))
}
@Test
fun me_nomisUserNoCaseload() {
setupFindUserCallForNomis(activeCaseLoadId = null, enabled = false)
assertThat(userController.me(principal)).usingRecursiveComparison().isEqualTo(
UserDetail(
"principal",
false,
"Joe Bloggs",
nomis,
5L,
null,
"5",
UUID.fromString(USER_ID),
),
)
}
@Test
fun me_nomisUser() {
setupFindUserCallForNomis(enabled = false)
assertThat(userController.me(principal)).usingRecursiveComparison().isEqualTo(
UserDetail(
"principal",
false,
"Joe Bloggs",
nomis,
5L,
"somecase",
"5",
UUID.fromString(USER_ID),
),
)
}
@Test
fun me_authUser() {
setupFindUserCallForAuth()
assertThat(userController.me(principal)).usingRecursiveComparison().isEqualTo(
UserDetail(
"principal",
true,
"Joe Bloggs",
auth,
null,
null,
USER_ID,
UUID.fromString(USER_ID),
),
)
}
@Test
fun myRoles() {
val authorities = listOf(SimpleGrantedAuthority("ROLE_BOB"), SimpleGrantedAuthority("ROLE_JOE_FRED"))
val token = UsernamePasswordAuthenticationToken("principal", "credentials", authorities)
assertThat(userController.myRoles(token)).containsOnly(UserRole("BOB"), UserRole("JOE_FRED"))
}
@Test
fun myRoles_noRoles() {
val token = UsernamePasswordAuthenticationToken("principal", "credentials", emptyList())
assertThat(userController.myRoles(token)).isEmpty()
}
@Test
fun userRoles_authUser() {
setupFindUserCallForAuth()
assertThat(userController.userRoles("JOE")).contains(UserRole("TEST_1"), UserRole("TEST_2"))
}
@Test
fun userRoles_nomisUser() {
setupFindUserCallForNomis()
assertThat(userController.userRoles("JOE")).contains(UserRole("PRISON"))
}
@Test
fun userRoles_notFound() {
whenever(userService.findMasterUserPersonDetails(anyString())).thenReturn(Optional.empty())
assertThatThrownBy { userController.userRoles("JOE") }
.isInstanceOf(UsernameNotFoundException::class.java)
.hasMessage("Account for username JOE not found")
}
@Test
fun myEmail() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(
Optional.of(
createSampleUser(username = "JOE", verified = true, email = "someemail"),
),
)
val responseEntity = userController.myEmail(principal = principal)
assertThat(responseEntity.statusCodeValue).isEqualTo(200)
assertThat(responseEntity.body).usingRecursiveComparison().isEqualTo(EmailAddress("JOE", "someemail", true))
}
@Test
fun userEmailWhenUserStoredInAuth() {
whenever(userService.getUser(anyString())).thenReturn(createSampleUser(username = "JOE", verified = true, email = "someemail"))
val username = "JOE_USER"
userController.getUserEmailStoredInAuth(username)
}
@Test
fun userEmailWhenUserNotStoredInAuth() {
whenever(userService.getUser(anyString())).thenThrow(
UsernameNotFoundException("JOE not found"),
)
assertThatThrownBy { userController.getUserEmailStoredInAuth("JOE") }
.isInstanceOf(UsernameNotFoundException::class.java)
.hasMessage("JOE not found")
}
@Test
fun userEmail_found() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(
Optional.of(
createSampleUser(username = "JOE", verified = true, email = "someemail"),
),
)
val responseEntity = userController.getUserEmail("joe")
assertThat(responseEntity.statusCodeValue).isEqualTo(200)
assertThat(responseEntity.body).usingRecursiveComparison().isEqualTo(EmailAddress("JOE", "someemail", true))
}
@Test
fun userEmail_found_unverified() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(
Optional.of(
createSampleUser(username = "JOE", verified = false, email = "someemail"),
),
)
val responseEntity = userController.getUserEmail("joe", unverified = true)
assertThat(responseEntity.statusCodeValue).isEqualTo(200)
assertThat(responseEntity.body).usingRecursiveComparison().isEqualTo(EmailAddress("JOE", "someemail", false))
}
@Test
fun userEmail_notFound() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(Optional.empty())
val responseEntity = userController.getUserEmail("joe")
assertThat(responseEntity.statusCodeValue).isEqualTo(404)
assertThat(responseEntity.body).usingRecursiveComparison().isEqualTo(
ErrorDetail(
"Not Found",
"Account for username joe not found",
"username",
),
)
}
@Test
fun userEmail_notVerified() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(Optional.of(createSampleUser("JOE")))
val responseEntity = userController.getUserEmail("joe")
assertThat(responseEntity.statusCodeValue).isEqualTo(204)
assertThat(responseEntity.body).isNull()
}
@Test
fun userEmail_null() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(Optional.of(createSampleUser("JOE")))
val responseEntity = userController.getUserEmail("joe", unverified = true)
assertThat(responseEntity.statusCodeValue).isEqualTo(200)
assertThat(responseEntity.body).usingRecursiveComparison().isEqualTo(EmailAddress("JOE", null, false))
}
private val fakeUser: User
get() = createSampleUser(
id = UUID.fromString(USER_ID),
username = "authentication",
email = "email",
verified = true,
enabled = true,
firstName = "Joe",
lastName = "Bloggs",
lastLoggedIn = LocalDateTime.of(2019, 1, 1, 12, 0),
)
@Test
fun userSearch_multipleSourceSystems() {
val unpaged = Pageable.unpaged()
whenever(userService.searchUsersInMultipleSourceSystems(anyString(), any(), anyString(), any(), any(), anyOrNull()))
.thenReturn(PageImpl(listOf(fakeUser)))
val pageOfUsers = userController.searchForUsersInMultipleSourceSystems(
"somename",
UserFilter.Status.ALL,
listOf(auth, nomis),
unpaged,
authentication,
)
assertThat(pageOfUsers.totalElements).isEqualTo(1)
verify(userService).searchUsersInMultipleSourceSystems(
"somename",
unpaged,
"bob",
emptyList(),
UserFilter.Status.ALL,
listOf(auth, nomis),
)
}
@Test
fun userSearch_multipleSourcesDefaultValues() {
val unpaged = Pageable.unpaged()
whenever(userService.searchUsersInMultipleSourceSystems(anyString(), any(), anyString(), any(), any(), anyOrNull()))
.thenReturn(PageImpl(listOf(fakeUser)))
val pageOfUsers = userController.searchForUsersInMultipleSourceSystems(
"somename",
UserFilter.Status.ALL,
null,
unpaged,
authentication,
)
assertThat(pageOfUsers.totalElements).isEqualTo(1)
verify(userService).searchUsersInMultipleSourceSystems(
"somename",
unpaged,
"bob",
emptyList(),
UserFilter.Status.ALL,
null,
)
}
@Test
fun userSearch_multipleSourcesWithStatusFilterActive() {
val unpaged = Pageable.unpaged()
whenever(userService.searchUsersInMultipleSourceSystems(anyString(), any(), anyString(), any(), any(), anyOrNull()))
.thenReturn(PageImpl(listOf(fakeUser)))
val pageOfUsers = userController.searchForUsersInMultipleSourceSystems(
"somename",
UserFilter.Status.ACTIVE,
listOf(auth, nomis, AuthSource.delius),
unpaged,
authentication,
)
assertThat(pageOfUsers.totalElements).isEqualTo(1)
verify(userService).searchUsersInMultipleSourceSystems(
"somename",
unpaged,
"bob",
emptyList(),
UserFilter.Status.ACTIVE,
listOf(auth, nomis, AuthSource.delius),
)
}
@Nested
inner class myMfa {
@Test
internal fun `should return email verified`() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(
Optional.of(
createSampleUser(username = "JOE", verified = true, email = "someemail"),
),
)
val mfaOptions = userController.myMfa(principal = principal)
assertThat(mfaOptions).isEqualTo(MfaOptions(emailVerified = true, mobileVerified = false, backupVerified = false))
}
@Test
internal fun `should return mobile verified`() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(
Optional.of(
createSampleUser(username = "JOE", mobileVerified = true, mobile = "someemail"),
),
)
val mfaOptions = userController.myMfa(principal = principal)
assertThat(mfaOptions).isEqualTo(MfaOptions(emailVerified = false, mobileVerified = true, backupVerified = false))
}
@Test
internal fun `should return backup verified`() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(
Optional.of(
createSampleUser(username = "JOE", secondaryEmailVerified = true, secondaryEmail = "someemail"),
),
)
val mfaOptions = userController.myMfa(principal = principal)
assertThat(mfaOptions).isEqualTo(MfaOptions(emailVerified = false, mobileVerified = false, backupVerified = true))
}
@Test
internal fun `should throw exception if user doesn't exist`() {
whenever(userService.getOrCreateUser(anyString())).thenReturn(Optional.empty())
assertThatThrownBy { userController.myMfa(principal = principal) }
.isInstanceOf(UsernameNotFoundException::class.java)
.hasMessage("Account for username joe not found")
}
}
private fun setupFindUserCallForNomis(activeCaseLoadId: String? = "somecase", enabled: Boolean = true): NomisUserPersonDetails {
val user = createSampleNomisUser(
firstName = "Joe",
lastName = "Bloggs",
userId = "5",
username = "principal",
accountStatus = AccountStatus.EXPIRED_LOCKED,
activeCaseLoadId = activeCaseLoadId,
enabled = enabled,
)
whenever(userService.findMasterUserPersonDetails(anyString())).thenReturn(Optional.of(user))
whenever(userService.findMasterUserBasicPersonDetails(anyString())).thenReturn(Optional.of(user))
whenever(userService.getOrCreateUser(anyString())).thenReturn(Optional.of(createSampleUser()))
return user
}
private fun setupFindUserCallForAuth() {
whenever(userService.findMasterUserPersonDetails(anyString())).thenReturn(Optional.of(createSampleUser()))
whenever(userService.findMasterUserBasicPersonDetails(anyString())).thenReturn(Optional.of(createSampleUser()))
whenever(userService.getOrCreateUser(anyString())).thenReturn(Optional.of(createSampleUser()))
}
private fun createSampleUser() = createSampleUser(
id = UUID.fromString(USER_ID),
username = "principal",
email = "email",
verified = true,
firstName = "Joe",
lastName = "Bloggs",
enabled = true,
source = auth,
authorities = setOf(
Authority(roleCode = "ROLE_TEST_1", roleName = "Test 1"),
Authority(roleCode = "ROLE_TEST_2", roleName = "Test 2"),
),
)
companion object {
private const val USER_ID = "07395ef9-53ec-4d6c-8bb1-0dc96cd4bd2f"
}
}
| 6 | null | 4 | 8 | 6b962b2a7c4b34195a9b4cbd3bb0e5ccdca53869 | 15,567 | hmpps-auth | MIT License |
dd-sdk-android/src/main/kotlin/com/datadog/android/v2/api/EventBatchWriter.kt | DataDog | 219,536,756 | false | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.api.storage
import androidx.annotation.WorkerThread
/**
* Writer allowing [FeatureScope] to write events in the storage exposing current batch metadata.
*/
interface EventBatchWriter {
/**
* @return the metadata of the current writeable file
*/
@WorkerThread
fun currentMetadata(): ByteArray?
/**
* Writes the content of the event to the current available batch.
* @param event the event to write (content + metadata)
* @param batchMetadata the optional updated batch metadata
*
* @return true if event was written, false otherwise.
*/
@WorkerThread
fun write(
event: RawBatchEvent,
batchMetadata: ByteArray?
): Boolean
}
| 52 | null | 60 | 86 | bcf0d12fd978df4e28848b007d5fcce9cb97df1c | 991 | dd-sdk-android | Apache License 2.0 |
app/src/main/java/vn/loitp/up/a/cv/tv/zoom/ZoomTextViewActivity.kt | tplloi | 126,578,283 | false | null | package vn.loitp.up.a.cv.tv.zoom
import android.os.Bundle
import com.loitp.annotation.IsFullScreen
import com.loitp.annotation.LogTag
import com.loitp.core.base.BaseActivityFont
import com.loitp.core.common.NOT_FOUND
import com.loitp.core.ext.setSafeOnClickListenerElastic
import vn.loitp.R
import vn.loitp.databinding.ATvZoomBinding
@LogTag("ZoomTextViewActivity")
@IsFullScreen(false)
class ZoomTextViewActivity : BaseActivityFont() {
private lateinit var binding: ATvZoomBinding
override fun setLayoutResourceId(): Int {
return NOT_FOUND
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ATvZoomBinding.inflate(layoutInflater)
setContentView(binding.root)
setupViews()
}
private fun setupViews() {
binding.lActionBar.apply {
this.ivIconLeft.setSafeOnClickListenerElastic(runnable = {
onBaseBackPressed()
})
this.ivIconRight?.setImageResource(R.color.transparent)
this.tvTitle?.text = ZoomTextViewActivity::class.java.simpleName
}
}
}
| 1 | Kotlin | 1 | 9 | 1bf1d6c0099ae80c5f223065a2bf606a7542c2b9 | 1,142 | base | Apache License 2.0 |
utbot-rd/src/main/kotlin/org/utbot/rd/loggers/UtRdConsoleLogger.kt | UnitTestBot | 480,810,501 | false | null | package org.utbot.rd.loggers
import com.jetbrains.rd.util.*
import org.utbot.common.timeFormatter
import java.io.PrintStream
import java.time.LocalDateTime
class UtRdConsoleLogger(
private val loggersLevel: LogLevel,
private val streamToWrite: PrintStream,
private val category: String
) : Logger {
override fun isEnabled(level: LogLevel): Boolean {
return level >= loggersLevel
}
private fun format(category: String, level: LogLevel, message: Any?, throwable: Throwable?) : String {
val throwableToPrint = if (level < LogLevel.Error) throwable else throwable ?: Exception("No exception was actually thrown, this exception is used purely to log trace")
val rdCategory = if (category.isNotEmpty()) "RdCategory: ${category.substringAfterLast('.').padEnd(25)} | " else ""
return "${LocalDateTime.now().format(timeFormatter)} | ${level.toString().uppercase().padEnd(5)} | $rdCategory${message?.toString()?:""} ${throwableToPrint?.getThrowableText()?.let { "| $it" }?:""}"
}
override fun log(level: LogLevel, message: Any?, throwable: Throwable?) {
if (!isEnabled(level))
return
val msg = format(category, level, message, throwable)
streamToWrite.println(msg)
}
} | 396 | null | 31 | 91 | ca7df7c1665cdab2a5d8bc2619611e02e761a228 | 1,269 | UTBotJava | Apache License 2.0 |
health/connect/connect-client/src/main/java/androidx/health/platform/client/request/UnregisterFromDataNotificationsRequest.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.platform.client.request
import android.os.Parcelable
import androidx.annotation.RestrictTo
import androidx.health.platform.client.impl.data.ProtoParcelable
import androidx.health.platform.client.proto.RequestProto
@RestrictTo(RestrictTo.Scope.LIBRARY)
class UnregisterFromDataNotificationsRequest(
override val proto: RequestProto.UnregisterFromDataNotificationsRequest
) : ProtoParcelable<RequestProto.UnregisterFromDataNotificationsRequest>() {
companion object {
@JvmField
val CREATOR: Parcelable.Creator<UnregisterFromDataNotificationsRequest> = newCreator {
UnregisterFromDataNotificationsRequest(
RequestProto.UnregisterFromDataNotificationsRequest.parseFrom(it)
)
}
}
}
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 1,397 | androidx | Apache License 2.0 |
data/src/test/java/com/hoc/flowmvi/data/UserRepositoryImplRealAPITest.kt | Kotlin-Android-Open-Source | 343,622,644 | false | null | package com.hoc.flowmvi.data
import android.util.Log
import com.hoc.flowmvi.core.dispatchers.AppCoroutineDispatchers
import com.hoc.flowmvi.domain.repository.UserRepository
import com.hoc.flowmvi.test_utils.rightValueOrThrow
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import kotlin.test.Test
import kotlin.test.assertTrue
import kotlin.time.ExperimentalTime
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.rules.TestWatcher
import org.junit.runner.Description
import org.koin.core.logger.Level
import org.koin.dsl.module
import org.koin.test.KoinTest
import org.koin.test.KoinTestRule
import org.koin.test.inject
import timber.log.Timber
@FlowPreview
@ExperimentalCoroutinesApi
@ExperimentalTime
@ExperimentalStdlibApi
class UserRepositoryImplRealAPITest : KoinTest {
@get:Rule
val koinRuleTest = KoinTestRule.create {
printLogger(Level.DEBUG)
modules(
dataModule,
module {
factory<AppCoroutineDispatchers> {
object : AppCoroutineDispatchers {
override val main: CoroutineDispatcher get() = Main
override val io: CoroutineDispatcher get() = IO
override val mainImmediate: CoroutineDispatcher get() = Main.immediate
}
}
}
)
}
@get:Rule
val timberRule = TimberRule()
private val userRepo by inject<UserRepository>()
@Test
fun getUsers() = runBlocking {
kotlin.runCatching {
val result = userRepo
.getUsers()
.first()
assertTrue(result.isRight())
assertTrue(result.rightValueOrThrow.isNotEmpty())
}
Unit
}
}
class TimberRule : TestWatcher() {
private val tree = ConsoleTree()
override fun starting(description: Description) {
Timber.plant(tree)
}
override fun finished(description: Description) {
Timber.uproot(tree)
}
}
class ConsoleTree : Timber.DebugTree() {
private val anonymousClassPattern = """(\$\d+)+$""".toRegex()
private val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
val dateTime = LocalDateTime.now().format(dateTimeFormatter)
val priorityChar = when (priority) {
Log.VERBOSE -> 'V'
Log.DEBUG -> 'D'
Log.INFO -> 'I'
Log.WARN -> 'W'
Log.ERROR -> 'E'
Log.ASSERT -> 'A'
else -> '?'
}
println("$dateTime $priorityChar/$tag: $message")
}
override fun createStackElementTag(element: StackTraceElement): String {
val className = element.className
val tag = if (anonymousClassPattern.containsMatchIn(className)) {
anonymousClassPattern.replace(className, "")
} else {
className
}
return tag.substringAfterLast('.')
}
}
| 6 | null | 84 | 95 | 09d9ef5d45972c2b1f22459ffe07358013fca742 | 3,049 | Jetpack-Compose-MVI-Coroutines-Flow | MIT License |
library-mvvmlazy/src/main/java/com/rui/mvvmlazy/utils/constant/MemoryConstants.kt | jirywell | 418,722,038 | false | {"Kotlin": 779701, "Java": 48117} | package com.rui.mvvmlazy.utils.constant
import com.rui.mvvmlazy.utils.app.PathUtils.Companion.getExtStoragePath
import com.rui.mvvmlazy.utils.app.PathUtils.Companion.getExtDownloadsPath
import com.rui.mvvmlazy.utils.app.PathUtils.Companion.getExtPicturesPath
import com.rui.mvvmlazy.utils.app.PathUtils.Companion.getExtDCIMPath
import androidx.annotation.IntDef
import com.rui.mvvmlazy.utils.constant.MemoryConstants
import com.rui.mvvmlazy.utils.constant.PathConstants
import android.annotation.SuppressLint
import android.Manifest.permission
import androidx.annotation.StringDef
import com.rui.mvvmlazy.utils.constant.TimeConstants
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
/**
* Created by zjr on 2020/5/14.
* 存储相关常量
*/
object MemoryConstants {
/**
* Byte与Byte的倍数
*/
const val BYTE = 1
/**
* KB与Byte的倍数
*/
const val KB = 1024
/**
* MB与Byte的倍数
*/
const val MB = 1048576
/**
* GB与Byte的倍数
*/
const val GB = 1073741824
@IntDef(BYTE, KB, MB, GB)
@Retention(RetentionPolicy.SOURCE)
annotation class Unit
} | 0 | Kotlin | 7 | 27 | b37dcb02d8b93699299aada9ec98a1c3ae10e346 | 1,135 | MvvmLazy-kotlin | Apache License 2.0 |
src/main/kotlin/ua/pp/lumivoid/network/SendPacket.kt | Bumer-32 | 779,465,671 | false | {"Kotlin": 128264, "Java": 9764, "Groovy": 2980} | package ua.pp.lumivoid.network
import net.minecraft.server.network.ServerPlayerEntity
import ua.pp.lumivoid.Constants
object SendPacket {
private val logger = Constants.LOGGER
fun sendPacket(sendingClass: Record) {
logger.debug("Sending packet to server")
Constants.NET_CHANNEL.clientHandle().send(sendingClass)
}
fun sendToPlayer(player: ServerPlayerEntity, sendingClass: Record) {
logger.debug("Sending packet to player")
Constants.NET_CHANNEL.serverHandle(player).send(sendingClass)
}
}
| 0 | Kotlin | 1 | 2 | 3b71886ac917816ce72e5cd82da0afaedc36c569 | 548 | Redstone-Helper | Apache License 2.0 |
MapboxSearch/sample/src/main/java/com/mapbox/search/sample/api/OfflineSearchAlongRouteExampleActivity.kt | mapbox | 438,355,708 | false | null | package com.mapbox.search.sample.api
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ArrayAdapter
import android.widget.SeekBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.mapbox.android.gestures.Utils
import com.mapbox.common.TileRegionLoadOptions
import com.mapbox.common.TileStore
import com.mapbox.common.location.Location
import com.mapbox.common.location.LocationServiceFactory
import com.mapbox.geojson.LineString
import com.mapbox.geojson.Point
import com.mapbox.geojson.utils.PolylineUtils
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.EdgeInsets
import com.mapbox.maps.MapView
import com.mapbox.maps.MapboxMap
import com.mapbox.maps.Style
import com.mapbox.maps.plugin.annotation.AnnotationConfig
import com.mapbox.maps.plugin.annotation.annotations
import com.mapbox.maps.plugin.annotation.generated.CircleAnnotation
import com.mapbox.maps.plugin.annotation.generated.CircleAnnotationOptions
import com.mapbox.maps.plugin.annotation.generated.PolylineAnnotationOptions
import com.mapbox.maps.plugin.annotation.generated.createCircleAnnotationManager
import com.mapbox.maps.plugin.annotation.generated.createPolylineAnnotationManager
import com.mapbox.search.common.AsyncOperationTask
import com.mapbox.search.offline.OfflineResponseInfo
import com.mapbox.search.offline.OfflineSearchCallback
import com.mapbox.search.offline.OfflineSearchEngine
import com.mapbox.search.offline.OfflineSearchEngineSettings
import com.mapbox.search.offline.OfflineSearchOptions
import com.mapbox.search.offline.OfflineSearchResult
import com.mapbox.search.sample.R
import com.mapbox.search.sample.databinding.ActivityOfflineSearchAlongRouteBinding
import com.mapbox.search.ui.view.CommonSearchViewConfiguration
import com.mapbox.search.ui.view.DistanceUnitType
import com.mapbox.search.ui.view.SearchResultAdapterItem
import com.mapbox.search.ui.view.SearchResultsView
import com.mapbox.turf.TurfConstants
import com.mapbox.turf.TurfMeasurement
import com.mapbox.turf.TurfMisc
import com.mapbox.turf.TurfTransformation
import kotlinx.coroutines.launch
class OfflineSearchAlongRouteExampleActivity : AppCompatActivity() {
private lateinit var mapView: MapView
private lateinit var mapboxMap: MapboxMap
private lateinit var mapAnnotationsManager: AnnotationsManager
private lateinit var binding: ActivityOfflineSearchAlongRouteBinding
private lateinit var viewModel: SearchAlongRouteViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityOfflineSearchAlongRouteBinding.inflate(layoutInflater)
viewModel = ViewModelProvider(this)[SearchAlongRouteViewModel::class.java]
setContentView(binding.root)
binding.distanceAlongRoute.isEnabled = false
mapView = binding.map
mapboxMap = mapView.mapboxMap
mapAnnotationsManager = AnnotationsManager(mapView)
mapboxMap.loadStyle(Style.MAPBOX_STREETS)
binding.searchResultsView.initialize(
SearchResultsView.Configuration(
commonConfiguration = CommonSearchViewConfiguration(DistanceUnitType.IMPERIAL)
)
)
val routes = resources.getStringArray(R.array.routes)
val arrayAdapter = ArrayAdapter(this, R.layout.route_dropdown_item, routes)
binding.routesAutoComplete.setAdapter(arrayAdapter)
fun Location.toPoint(): Point = Point.fromLngLat(longitude, latitude)
val locationService = LocationServiceFactory.getOrCreate()
.getDeviceLocationProvider(null)
.value
locationService?.getLastLocation { location ->
location?.toPoint()?.let {
mapView.mapboxMap.setCamera(
CameraOptions.Builder()
.center(it)
.zoom(9.0)
.build()
)
viewModel.updateProximity(it)
}
}
binding.queryText.setOnEditorActionListener { v, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
viewModel.updateSearchQuery(binding.queryText.text.toString())
v.hideKeyboard()
true
} else {
false
}
}
binding.routesAutoComplete.setOnItemClickListener { _, view, position, _ ->
// these are the route polylines and correspond to the drop down items defined in strings.xml -> "routes"
val routePolylines = listOf(
"}~xnFfbrrMrQq@~AvnArjKnpDjzDzfJphVf{U~k\\vhSdeIt_IzI~]ikAjuEfNh_A`kLvvUzlDp`E~jSzgIrlDp|Hbqp@jy\\~uKzmKtiKvaB`vJghB~cWfvBrbo@yzKrij@{j@xwElaDphEkfErvAkw@bMzFqRn^gB{AZm@",
"{f}lFzopuMmFjKlCnBhJuDuDup@mUmc@d@c`@qjA{@aX`CeFiBwHqs@ug@ge@wDwLbDsvC{Pog@}BgWjEer@kBal@lFih@a[_tB?k[`Geq@Iug@mPy}BCqk@nMml@rJqRhEwBxxAfVte@nDvaAra@pWdBd@sE",
"a{jlFft_uMyLlLhE}@h@rf@sBlLdArdEmK|SnEvLlFhj@BbLqD`K_[hIeG~Je@tc@dK|e@iIzg@bI`w@fG|IrYtRjVhtAr^~^nObb@b@r}@m]dzA}JxX_FjAyCh]dNlSjHnVrKjQ"
)
val polyline = routePolylines[position]
val selectedRoute = PolylineUtils.decode(polyline, 5)
val pointAlongRoute = selectedRoute.first()
binding.distanceAlongRoute.progress = 0
viewModel.updateRoute(selectedRoute, pointAlongRoute)
view.hideKeyboard()
}
binding.distanceAlongRoute.setOnSeekBarChangeListener(object :
SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seek: SeekBar,
progress: Int,
fromUser: Boolean
) {
// do nothing
}
override fun onStartTrackingTouch(seek: SeekBar) {
// do nothing
}
override fun onStopTrackingTouch(seek: SeekBar) {
val percent = seek.progress
val route = mapAnnotationsManager.route
if (route != null) {
val proximity = if (percent > 0) {
val segments = route.zipWithNext()
val totalDistance = segments.sumOf { segment ->
TurfMeasurement.distance(segment.first, segment.second)
}
val distanceTravelled = totalDistance * (percent / 100.0)
TurfMisc.lineSliceAlong(
LineString.fromLngLats(route),
0.0,
distanceTravelled,
TurfConstants.UNIT_KILOMETERS
).coordinates().last()
} else {
route.first()
}
viewModel.updateProximity(proximity)
}
}
})
if (!isPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
),
PERMISSIONS_REQUEST_LOCATION
)
}
}
override fun onResume() {
super.onResume()
viewModel.searchOptionsData.observe(this, Observer {
handleOnSearchOptionsUpdated(it)
})
viewModel.uiStateData.observe(this, Observer { uiState ->
when (uiState) {
is UiState.Ready -> {
handleOnReady()
}
is UiState.Searching -> {
handleOnSearching()
}
is UiState.Success -> {
handleOnSuccess(uiState)
}
is UiState.Error -> {
Toast.makeText(this, "Error: ${uiState.message}", Toast.LENGTH_LONG).show()
}
}
})
}
private fun handleOnReady() {
binding.searchResultsView.isVisible = false
binding.progressBar.isVisible = false
binding.noResultsText.isVisible = false
binding.queryText.isEnabled = true
Toast.makeText(this, "Offline search is ready", Toast.LENGTH_SHORT).show()
}
private fun handleOnSearching() {
binding.searchResultsView.isVisible = false
binding.noResultsText.isVisible = false
binding.progressBar.isVisible = true
}
private fun handleOnSuccess(uiState: UiState.Success) = if (uiState.searchResults.isEmpty()) {
displayNoResults()
} else {
displayResults(uiState.searchResults)
}
private fun handleOnSearchOptionsUpdated(options: SearchAlongRouteOptions) {
mapAnnotationsManager.clearAll()
if (options.route.isNotEmpty()) {
mapAnnotationsManager.showRoute(options.route, options.proximity)
binding.distanceAlongRoute.isEnabled = true
}
}
private fun displayResults(searchResults: List<OfflineSearchResult>) {
val coordinates = searchResults.map { it.coordinate }
mapAnnotationsManager.showMarkers(coordinates)
val items = searchResults.map { result ->
val title = result.name
val subtitle = if (result.descriptionText?.isNotBlank() == true) {
result.descriptionText
} else {
result.address.toString()
}
SearchResultAdapterItem.Result(
title = title,
subtitle = subtitle,
distanceMeters = result.distanceMeters,
drawable = com.mapbox.search.ui.R.drawable.mapbox_search_sdk_ic_search_result_address,
payload = result
)
}
binding.searchResultsView.setAdapterItems(items)
binding.progressBar.isVisible = false
binding.noResultsText.isVisible = false
binding.searchResultsView.isVisible = true
}
private fun displayNoResults() {
binding.progressBar.isVisible = false
binding.searchResultsView.isVisible = false
binding.noResultsText.isVisible = true
}
private fun Context.isPermissionGranted(permission: String): Boolean =
ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
private fun View.hideKeyboard() =
(getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(windowToken, 0)
private companion object {
val MARKERS_EDGE_OFFSET = Utils.dpToPx(32f).toDouble()
val PLACE_CARD_HEIGHT = Utils.dpToPx(300f).toDouble()
val MARKERS_INSETS = EdgeInsets(
MARKERS_EDGE_OFFSET, MARKERS_EDGE_OFFSET, MARKERS_EDGE_OFFSET, MARKERS_EDGE_OFFSET
)
val MARKERS_INSETS_OPEN_CARD = EdgeInsets(
MARKERS_EDGE_OFFSET, MARKERS_EDGE_OFFSET, PLACE_CARD_HEIGHT, MARKERS_EDGE_OFFSET
)
const val PERMISSIONS_REQUEST_LOCATION = 0
}
private class AnnotationsManager(mapView: MapView) {
private val mapboxMap = mapView.mapboxMap
private val circleAnnotationManager = mapView.annotations.createCircleAnnotationManager(
AnnotationConfig(
layerId = "markers"
)
)
private val polylineAnnotationManager = mapView.annotations.createPolylineAnnotationManager(
AnnotationConfig(
layerId = "route",
belowLayerId = "markers"
)
)
private val markers = mutableMapOf<String, CircleAnnotation>()
private var pointAlongRoute: CircleAnnotation? = null
var route: List<Point>? = null
private set
var onMarkersChangeListener: (() -> Unit)? = null
val hasRoute: Boolean
get() = route != null
val hasMarkers: Boolean
get() = markers.isNotEmpty()
fun clearMarkers() {
circleAnnotationManager.delete(markers.values.toList())
markers.clear()
}
fun clearRoute() {
route = null
polylineAnnotationManager.deleteAll()
if (pointAlongRoute != null) {
circleAnnotationManager.delete(pointAlongRoute!!)
pointAlongRoute = null
}
}
fun clearAll() {
clearMarkers()
clearRoute()
}
fun showMarker(coordinate: Point) {
showMarkers(listOf(coordinate))
}
fun showMarkers(coordinates: List<Point>) {
clearMarkers()
if (coordinates.isEmpty()) {
onMarkersChangeListener?.invoke()
return
}
coordinates.forEach { coordinate ->
val circleAnnotationOptions: CircleAnnotationOptions = CircleAnnotationOptions()
.withPoint(coordinate)
.withCircleRadius(8.0)
.withCircleColor("#ee4e8b")
.withCircleStrokeWidth(2.0)
.withCircleStrokeColor("#ffffff")
val annotation = circleAnnotationManager.create(circleAnnotationOptions)
markers[annotation.id] = annotation
}
if (route != null) {
mapboxMap.cameraForCoordinates(
route!! + coordinates, MARKERS_INSETS, bearing = null, pitch = null
)
} else if (coordinates.size == 1) {
CameraOptions.Builder()
.center(coordinates.first())
.padding(MARKERS_INSETS_OPEN_CARD)
.zoom(14.0)
.build()
} else {
mapboxMap.cameraForCoordinates(
coordinates, MARKERS_INSETS, bearing = null, pitch = null
)
}.also {
mapboxMap.setCamera(it)
}
onMarkersChangeListener?.invoke()
}
fun showRoute(route: List<Point>, par: Point? = null) {
if (route.isEmpty()) {
return
}
clearAll()
this.route = route
val polylineAnnotationOptions: PolylineAnnotationOptions = PolylineAnnotationOptions()
.withPoints(route)
.withLineColor("#007bff")
.withLineBorderColor("#0056b3")
.withLineWidth(5.0)
polylineAnnotationManager.create(polylineAnnotationOptions)
if (par != null) {
val circleAnnotationOptions: CircleAnnotationOptions = CircleAnnotationOptions()
.withPoint(par)
.withCircleRadius(6.0)
.withCircleColor("#4caf50")
.withCircleStrokeWidth(2.0)
.withCircleStrokeColor("#ffffff")
pointAlongRoute = circleAnnotationManager.create(circleAnnotationOptions)
}
val cameraOptions = mapboxMap.cameraForCoordinates(
route, MARKERS_INSETS, bearing = null, pitch = null
)
mapboxMap.setCamera(cameraOptions)
}
}
class SearchAlongRouteViewModel() : ViewModel() {
val uiStateData = MediatorLiveData<UiState>()
val offlineSearchData = MutableLiveData(OfflineSearchState())
val searchOptionsData = MutableLiveData<SearchAlongRouteOptions>()
private val searchEngine: OfflineSearchEngine
private var searchRequestTask: AsyncOperationTask? = null
private val searchCallback = object : OfflineSearchCallback {
override fun onResults(results: List<OfflineSearchResult>, responseInfo: OfflineResponseInfo) {
uiStateData.value = UiState.Success(results)
}
override fun onError(e: Exception) {
uiStateData.value = UiState.Error("Search failed with message ${e.message}")
}
}
init {
uiStateData.addSource(offlineSearchData) { offlineSearchState ->
when (offlineSearchState) {
OfflineSearchState(failed = true) -> uiStateData.value = UiState.Error("Failed to initialize Offline Search")
OfflineSearchState(tilesLoaded = true, searchEngineReady = true, failed = false) -> uiStateData.value = UiState.Ready
}
}
uiStateData.addSource(searchOptionsData) { searchOptions ->
updateSearchAlongRouteOptions(searchOptions)?.let {
uiStateData.value = it
}
}
val tileStore = TileStore.create()
val tileRegionId = "Washington DC"
val tileDescriptors = listOf(OfflineSearchEngine.createTilesetDescriptor("mbx-main", language = "en"))
val washingtonDc = Point.fromLngLat(-77.0339911055176, 38.899920004207516)
val tileGeometry = TurfTransformation.circle(washingtonDc, 200.0, 32, TurfConstants.UNIT_KILOMETERS)
val tileRegionLoadOptions = TileRegionLoadOptions.Builder()
.descriptors(tileDescriptors)
.geometry(tileGeometry)
.acceptExpired(true)
.build()
tileStore.loadTileRegion(
tileRegionId,
tileRegionLoadOptions,
{ progress -> Log.i(OfflineSearchAlongRouteExampleActivity::javaClass.name, "Loading progress: $progress") },
{ result ->
viewModelScope.launch {
val currentOfflineSearchState = offlineSearchData.value
val newOfflineSearchState = if (result.isValue) {
currentOfflineSearchState?.copy(tilesLoaded = true)
} else {
currentOfflineSearchState?.copy(failed = true)
}
offlineSearchData.value = newOfflineSearchState
}
}
)
searchEngine = OfflineSearchEngine.create(
OfflineSearchEngineSettings(
tileStore = tileStore
),
)
searchEngine.addEngineReadyCallback(object : OfflineSearchEngine.EngineReadyCallback {
override fun onEngineReady() {
viewModelScope.launch {
val offlineSearchState = offlineSearchData.value
offlineSearchData.postValue(offlineSearchState?.copy(searchEngineReady = true))
}
}
})
}
fun updateSearchQuery(query: String) {
val currentRequest = searchOptionsData.value
searchOptionsData.value = currentRequest?.copy(query = query) ?: SearchAlongRouteOptions(query = query)
}
fun updateRoute(route: List<Point>, pointAlongRoute: Point) {
val currentRequest = searchOptionsData.value
searchOptionsData.value = currentRequest?.copy(route = route, proximity = pointAlongRoute) ?: SearchAlongRouteOptions(route = route, proximity = pointAlongRoute)
}
fun updateProximity(proximity: Point) {
cancelSearch()
val currentRequest = searchOptionsData.value
searchOptionsData.value = currentRequest?.copy(proximity = proximity) ?: SearchAlongRouteOptions(proximity = proximity)
}
private fun runSearch(options: SearchAlongRouteOptions) {
searchRequestTask = if (options.route.isNotEmpty()) {
searchEngine.searchAlongRoute(
query = options.query,
proximity = options.proximity,
route = options.route,
callback = searchCallback
)
} else {
searchEngine.search(
query = options.query,
options = OfflineSearchOptions(),
callback = searchCallback
)
}
}
private fun cancelSearch() {
if (searchRequestTask != null && searchRequestTask?.isDone != true) {
searchRequestTask!!.cancel()
}
}
private fun updateSearchAlongRouteOptions(options: SearchAlongRouteOptions): UiState? {
cancelSearch()
return if (options.query.isNotBlank()) {
runSearch(options)
UiState.Searching(options)
} else {
null
}
}
}
sealed class UiState {
object Ready : UiState()
data class Searching(val searchOptions: SearchAlongRouteOptions) : UiState()
data class Success(val searchResults: List<OfflineSearchResult>) : UiState()
data class Error(val message: String) : UiState()
}
data class OfflineSearchState(
val tilesLoaded: Boolean = false,
val searchEngineReady: Boolean = false,
val failed: Boolean = false
)
data class SearchAlongRouteOptions(
val query: String = "",
val proximity: Point = Point.fromLngLat(0.0, 0.0),
val route: List<Point> = arrayListOf()
)
}
| 18 | null | 7 | 33 | d7307c6a874fac106806f2ccfcaba1a5654b6ed9 | 22,045 | mapbox-search-android | Apache License 2.0 |
app/src/main/java/com/solana/mwallet/ui/signpayload/SignPayloadFragment.kt | solana-mobile | 741,187,528 | false | {"Kotlin": 72999} | /*
* Copyright (c) 2022 Solana Mobile Inc.
*/
package com.solana.mwallet.ui.signpayload
import android.net.Uri
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 androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import com.solana.mwallet.MobileWalletAdapterViewModel
import com.solana.mwallet.MobileWalletAdapterViewModel.MobileWalletAdapterServiceRequest
import com.solana.mwallet.R
import com.solana.mwallet.databinding.FragmentSignMessageBinding
import com.solana.mwallet.extensions.loadImage
import kotlinx.coroutines.launch
class SignPayloadFragment : Fragment() {
private val activityViewModel: MobileWalletAdapterViewModel by activityViewModels()
private lateinit var viewBinding: FragmentSignMessageBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
viewBinding = FragmentSignMessageBinding.inflate(layoutInflater, container, false)
return viewBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.CREATED) {
activityViewModel.mobileWalletAdapterServiceEvents.collect { request ->
when (request) {
is MobileWalletAdapterServiceRequest.SignPayloads -> {
if (request.request.identityUri?.isAbsolute == true &&
request.request.iconRelativeUri?.isHierarchical == true
) {
val uri = Uri.withAppendedPath(
request.request.identityUri!!,
request.request.iconRelativeUri!!.encodedPath
)
viewBinding.imageIcon.loadImage(uri.toString())
}
viewBinding.textName.text = request.request.identityName ?: "<no name>"
val res =
if (request is MobileWalletAdapterServiceRequest.SignTransactions) {
R.string.label_requesting_transactions
} else {
R.string.label_sign_messages
}
viewBinding.textSubtitle.setText(res)
if (request is MobileWalletAdapterServiceRequest.SignTransactions) {
viewBinding.textMessageTitle.visibility = View.GONE
viewBinding.textMessage.visibility = View.GONE
} else {
viewBinding.textMessage.text = request.request.payloads.first().decodeToString()
}
viewBinding.btnApprove.setOnClickListener {
activityViewModel.signPayloadsSimulateSign(request)
}
viewBinding.btnCancel.setOnClickListener {
activityViewModel.signPayloadsDeclined(request)
}
}
is MobileWalletAdapterServiceRequest.SignAndSendTransactions -> {
request.signatures?.run {
// When signatures are present, move on to sending the transaction
findNavController().navigate(SignPayloadFragmentDirections.actionSendTransaction())
return@collect
}
viewBinding.textSubtitle.setText(R.string.label_requesting_transactions)
viewBinding.btnApprove.setOnClickListener {
activityViewModel.signAndSendTransactionsSimulateSign(request)
}
viewBinding.btnCancel.setOnClickListener {
activityViewModel.signAndSendTransactionsDeclined(request)
}
}
else -> {
// If several events are emitted back-to-back (e.g. during session
// teardown), this fragment may not have had a chance to transition
// lifecycle states. Only navigate if we believe we are still here.
findNavController().let { nc ->
if (nc.currentDestination?.id == R.id.fragment_sign_payload) {
nc.navigate(SignPayloadFragmentDirections.actionSignPayloadComplete())
}
}
}
}
}
}
}
}
} | 5 | Kotlin | 0 | 0 | ed0cab942f207eeff6b8a77cd612b43ba169f603 | 5,332 | mwallet | Apache License 2.0 |
shared/src/commonMain/kotlin/com/kashif/kmmnewsapp/data/repository/AbstractRepository.kt | khaled2252 | 532,294,800 | false | null | package com.kashif.kmmnewsapp.data.repository
import com.kashif.kmmnewsapp.data.remote.dto.HeadlinesDTO
import com.kashif.kmmnewsapp.domain.util.DataState
abstract class AbstractRepository {
abstract suspend fun getAllHeadlines(
page: Int,
pageSize: Int,
country: String
): DataState<HeadlinesDTO>
} | 0 | Kotlin | 0 | 0 | d8201ec4bfab9f2ea5dc02a68a6d2211ab432ac2 | 336 | TodoExcel | Apache License 2.0 |
src/jsMain/kotlin/css/KrontabPartsStylesheet.kt | InsanusMokrassar | 715,177,162 | false | null | package dev.inmo.krontab.predictor.css
import org.jetbrains.compose.web.ExperimentalComposeWebApi
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.css.keywords.auto
object KrontabPartsStylesheet : StyleSheet() {
val containerWidth = 600.px
val containerItemsGap = 16.px
val containerItems = 8
val container by style {
display(DisplayStyle.Grid)
margin(16.px, auto.unsafeCast<CSSNumeric>())
width(containerWidth)
gridTemplateColumns(
(0 until containerItems).joinToString(" ") { _ -> "1fr" }
)
gap(containerItemsGap)
}
@OptIn(ExperimentalComposeWebApi::class)
val element by style {
display(DisplayStyle.Grid)
textAlign("center")
gridTemplateColumns("1fr")
transitions {
properties("transform") {
duration(0.3.s)
timingFunction(AnimationTimingFunction.EaseInOut)
}
}
}
@OptIn(ExperimentalComposeWebApi::class)
val elementFocused by style {
transform {
scale(1.2, 1.2)
}
}
val input by style {
minWidth(0.px)
textAlign("center")
}
val labelContainer by style {
minWidth(0.px)
textAlign("center")
}
} | 0 | null | 0 | 1 | 9cff838d8566ea221c943c1744614bd1a8af7df8 | 1,302 | KrontabPredictor | MIT License |
compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/TypeArgumentMapping.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.resolve.calls
import org.jetbrains.kotlin.fir.declarations.FirTypeParameterRefsOwner
import org.jetbrains.kotlin.fir.types.FirTypeProjection
import org.jetbrains.kotlin.fir.types.impl.FirTypePlaceholderProjection
sealed class TypeArgumentMapping {
abstract operator fun get(typeParameterIndex: Int): FirTypeProjection
object NoExplicitArguments : TypeArgumentMapping() {
override fun get(typeParameterIndex: Int): FirTypeProjection = FirTypePlaceholderProjection
}
class Mapped(private val ordered: List<FirTypeProjection>) : TypeArgumentMapping() {
override fun get(typeParameterIndex: Int): FirTypeProjection {
return ordered.getOrElse(typeParameterIndex) { FirTypePlaceholderProjection }
}
}
}
internal object MapTypeArguments : ResolutionStage() {
override suspend fun check(candidate: Candidate, sink: CheckerSink, callInfo: CallInfo) {
val typeArguments = callInfo.typeArguments
if (typeArguments.isEmpty()) {
candidate.typeArgumentMapping = TypeArgumentMapping.NoExplicitArguments
return
}
val owner = candidate.symbol.fir as FirTypeParameterRefsOwner
if (typeArguments.size == owner.typeParameters.size || callInfo.callKind == CallKind.DelegatingConstructorCall) {
candidate.typeArgumentMapping = TypeArgumentMapping.Mapped(typeArguments)
} else {
candidate.typeArgumentMapping = TypeArgumentMapping.Mapped(emptyList())
sink.yieldApplicability(CandidateApplicability.INAPPLICABLE)
}
}
}
internal object NoTypeArguments : ResolutionStage() {
override suspend fun check(candidate: Candidate, sink: CheckerSink, callInfo: CallInfo) {
if (callInfo.typeArguments.isNotEmpty()) {
sink.yieldApplicability(CandidateApplicability.INAPPLICABLE)
}
candidate.typeArgumentMapping = TypeArgumentMapping.NoExplicitArguments
}
}
| 157 | null | 5209 | 42,102 | 65f712ab2d54e34c5b02ffa3ca8c659740277133 | 2,196 | kotlin | Apache License 2.0 |
app/src/main/java/com/mohmmed/mosa/eg/towmmen/data/local/db/migration/Migration_5_6.kt | M4A28 | 842,519,543 | false | {"Kotlin": 877792} | package com.mohmmed.mosa.eg.towmmen.data.local.db.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
val migration_5_6 = object: Migration(5, 6){
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(" ALTER TABLE invoice_items ADD COLUMN 'purchaseDate' INTEGER NOT NULL DEFAULT 1000000")
db.execSQL("CREATE TABLE IF NOT EXISTS expanse (`expanseId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
" `expanse` TEXT NOT NULL," + " `payDate` INTEGER NOT NULL, `amount` REAL NOT NULL)")
}
} | 0 | Kotlin | 0 | 0 | 37a6e192262f4995f599978957d1b39257fd88a9 | 584 | Towmmen | MIT License |
app/src/main/java/com/example/androidcurriculum/data/LoginDataSource.kt | rinnki30 | 805,174,014 | false | {"Kotlin": 35561} | package com.example.androidcurriculum.data
import android.database.Cursor
import com.example.androidcurriculum.Database.MyDatabaseHelper
import com.example.androidcurriculum.MyApplication
import com.example.androidcurriculum.data.model.LoggedInUser
/**
* Class that handles authentication w/ login credentials and retrieves user information.
*/
//这个类是用来处理登录验证的,包括登录凭证和获取用户信息
class LoginDataSource {
private val dbHelper = MyDatabaseHelper(MyApplication.context, "Login.db", 1)
// fun login(username: String, password: String): Result<LoggedInUser> {
// try {
// // TODO: handle loggedInUser authentication
// val fakeUser = LoggedInUser(java.util.UUID.randomUUID().toString(), username, password)
// return Result.Success(fakeUser)
// } catch (e: Throwable) {
// return Result.Error(IOException("Error logging in", e))
// }
// }
fun login(username: String, password: String): Result<LoggedInUser>? {
val db = dbHelper.readableDatabase
val cursor: Cursor = db.query(
"Login",
arrayOf("id", "username", "password"),
"username = ? and password = ?",
arrayOf(username, password),
null,
null,
null
)
with(cursor) {
if (moveToFirst()) {
val id = getString(getColumnIndexOrThrow("id"))
val username = getString(getColumnIndexOrThrow("username"))
val password = getString(getColumnIndexOrThrow("password"))
return Result.Success(LoggedInUser(id, username, password))
}
}
cursor.close()
db.close()
return null
}
fun logout() {
// TODO: revoke authentication
}
} | 0 | Kotlin | 0 | 0 | 07e22511ed98fa4f949655fe93dd15986ad5fa57 | 1,793 | Android-Curriculum | Apache License 2.0 |
app/src/main/java/org/d3if2146/hitungbmi/ui/histori/HistoriViewModel.kt | naufalmng | 522,475,438 | false | {"Kotlin": 35041} | package org.d3if2146.hitungbmi.ui.histori
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.d3if2146.hitungbmi.core.data.repository.AppRepository
import org.d3if2146.hitungbmi.core.data.source.db.BmiDao
import org.d3if2146.hitungbmi.core.data.source.db.BmiEntity
class HistoriViewModel(private val db: BmiDao): ViewModel() {
private val appRepository: AppRepository = AppRepository(db)
val listDataBmi : LiveData<List<BmiEntity>> get() = (appRepository.getListDataBmi())
var dataBmi: BmiEntity? = null
private var _isLoading = MutableLiveData<Boolean>()
val isLoading : LiveData<Boolean> get() =_isLoading
suspend fun clearAllData() = viewModelScope.launch {
withContext(Dispatchers.IO){
appRepository.clearAllData()
}
}
suspend fun updateData(id: Long, date: Long, berat: Float,tinggi: Float,isMale: Boolean) = viewModelScope.launch(Dispatchers.IO) {
val dataBmi = BmiEntity(id = id,tanggal = date,berat = berat,tinggi = tinggi,isMale = isMale)
appRepository.updateData(dataBmi)
}
fun hapusData(bmi: BmiEntity?){
viewModelScope.launch(Dispatchers.IO) {
appRepository.removeData(bmi)
}
}
fun setIsLoading(boolean: Boolean){
_isLoading.value = boolean
}
} | 0 | Kotlin | 0 | 0 | 49a1660db7db23ea8c5bac69aab6a3d87d5c8312 | 1,519 | hitungBmi | Apache License 2.0 |
yabapi-core/src/commonMain/kotlin/moe/sdl/yabapi/data/live/commands/InteractWordCmd.kt | SDLMoe | 437,756,989 | false | null | @file:UseSerializers(BooleanJsSerializer::class)
package moe.sdl.yabapi.data.live.commands
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.decodeFromJsonElement
import moe.sdl.yabapi.data.RgbColor
import moe.sdl.yabapi.data.live.GuardLevel
import moe.sdl.yabapi.data.live.GuardLevel.UNKNOWN
import moe.sdl.yabapi.serializer.BooleanJsSerializer
import moe.sdl.yabapi.serializer.data.RgbColorIntSerializer
@Serializable
public data class InteractWordCmd(
@SerialName("cmd") override val operation: String,
@SerialName("data") val data: InteractWordData,
) : LiveCommand {
public companion object : LiveCommandFactory() {
override val operation: String = "INTERACT_WORD"
override fun decode(json: Json, data: JsonElement): InteractWordCmd = json.decodeFromJsonElement(data)
}
}
@Serializable
public data class InteractWordData(
@SerialName("contribution") val contribution: Contribution,
@SerialName("dmscore") val danmakuScore: Int,
@SerialName("fans_medal") val fansMedal: LiveMedal? = null,
@SerialName("identities") val identities: List<Int> = emptyList(),
@SerialName("is_spread") val isSpread: Boolean,
@SerialName("msg_type") val msgType: Int,
@SerialName("roomid") val roomId: Int,
@SerialName("score") val score: Long,
@SerialName("spread_desc") val spreadDesc: String,
@SerialName("spread_info") val spreadInfo: String,
@SerialName("tail_icon") val tailIcon: Int,
@SerialName("timestamp") val timestamp: Long,
@SerialName("trigger_time") val triggerTime: Long,
@SerialName("uid") val uid: Int,
@SerialName("uname") val userName: String,
@SerialName("uname_color") val userNameColor: String,
) {
@Serializable
public data class Contribution(
@SerialName("grade") val grade: Int,
)
@Serializable
public data class LiveMedal(
@SerialName("anchor_roomid") val roomId: Int, // 房间id
@SerialName("guard_level") val guardLevel: GuardLevel = UNKNOWN, // 等级
@SerialName("icon_id") val iconId: Int, // icon id
@SerialName("is_lighted") val isLighted: Boolean, // 是否点亮
@Serializable(RgbColorIntSerializer::class)
@SerialName("medal_color") val medalColor: RgbColor,
@Serializable(RgbColorIntSerializer::class)
@SerialName("medal_color_border") val medalColorBorder: RgbColor,
@Serializable(RgbColorIntSerializer::class)
@SerialName("medal_color_end") val medalColorEnd: RgbColor,
@Serializable(RgbColorIntSerializer::class)
@SerialName("medal_color_start") val medalColorStart: RgbColor,
@SerialName("medal_level") val level: Int,
@SerialName("medal_name") val name: String,
@SerialName("score") val score: Int,
@SerialName("special") val special: String,
@SerialName("target_id") val targetId: Int, // 主播 mid
)
}
| 0 | null | 1 | 26 | c8be46f9b5e4db1e429c33b0821643fd94789fa1 | 3,075 | Yabapi | Creative Commons Zero v1.0 Universal |
app/src/main/kotlin/se/bylenny/colorballs/models/Rect.kt | lennynilsson | 103,952,342 | false | null | package se.bylenny.colorballs.models
class Rect(
var x: Float = 0f,
var y: Float = 0f,
var w: Float = 0f,
var h: Float = 0f
) {
var x2: Float
set(value) { w = x2 - x }
get() = x + w
var y2: Float
set(value) { h = y2 - y }
get() = y + h
fun plus(other: Rect) = Rect(
Math.min(x, other.x),
Math.min(y, other.y),
Math.max(x2, other.x2),
Math.max(y2, other.y2)
)
} | 0 | Kotlin | 0 | 0 | 6392cee0f39d67a07177f0af7919888c2860e059 | 458 | ColorBalls | Apache License 2.0 |
shared/src/commonMain/kotlin/dev/sasikanth/rss/reader/placeholder/PlaceholderScreen.kt | msasikanth | 632,826,313 | false | {"Kotlin": 858776, "Swift": 8517, "JavaScript": 3432, "CSS": 947, "Shell": 227} | /*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.sasikanth.rss.reader.placeholder
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.text.style.TextAlign
import androidx.compose.ui.unit.dp
import dev.sasikanth.rss.reader.resources.strings.LocalStrings
import dev.sasikanth.rss.reader.ui.AppTheme
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.delay
@Composable
fun PlaceholderScreen(modifier: Modifier = Modifier) {
var isVisible by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
delay(3.seconds)
isVisible = true
}
Box(
modifier =
modifier.background(AppTheme.colorScheme.surfaceContainerLowest).padding(horizontal = 24.dp),
contentAlignment = Alignment.Center
) {
AnimatedVisibility(
visible = isVisible,
enter = fadeIn(),
exit = fadeOut(),
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
CircularProgressIndicator(
color = AppTheme.colorScheme.tintedForeground,
modifier = Modifier.requiredSize(24.dp),
strokeWidth = 2.dp
)
Spacer(Modifier.requiredHeight(4.dp))
Text(
text = LocalStrings.current.databaseMaintainenceTitle,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.titleLarge,
color = AppTheme.colorScheme.textEmphasisHigh,
)
Text(
text = LocalStrings.current.databaseMaintainenceSubtitle,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodySmall,
color = AppTheme.colorScheme.textEmphasisHigh,
)
}
}
}
}
| 35 | Kotlin | 72 | 1,713 | e7b3f1057d8295e1d83a041df68aec7bfefcd6e8 | 3,273 | twine | Apache License 2.0 |
src/main/kotlin/sk/mkiss/algorithms/dynamic/LongestIncreasingSubsequence.kt | marek-kiss | 430,858,906 | false | null | package sk.mkiss.algorithms.dynamic
import kotlin.math.max
object LongestIncreasingSubsequence {
/**
* get the size of the longest increasing subsequence of the given sequence
* time complexity: Θ(n^2)
*
* @param sequence
* @return
*/
fun getSizeOfLIS(sequence: List<Int>): Int {
val longestEndingAt = calculateLISEndingInX(sequence)
return longestEndingAt.maxOrNull() ?: 0
}
private fun calculateLISEndingInX(sequence: List<Int>): List<Int> {
val longestEndingAt = MutableList(sequence.size) { 1 }
(sequence.indices).forEach { i ->
(0 until i).forEach { j ->
if (sequence[j] < sequence[i]) {
longestEndingAt[i] = max(longestEndingAt[i], longestEndingAt[j] + 1)
}
}
}
return longestEndingAt
}
fun getLIS(sequence: List<Int>): List<Int> {
if (sequence.isEmpty()) return emptyList()
val longestEndingAt = calculateLISEndingInX(sequence)
val lis = mutableListOf<Int>()
// reconstruct the LIS from longestEndingAt
var nextIndex = getNextIndex(longestEndingAt, sequence, end = sequence.size, prevValue = Int.MAX_VALUE)
while (nextIndex != null) {
lis.add(sequence[nextIndex])
nextIndex = getNextIndex(longestEndingAt, sequence, end = nextIndex, prevValue = sequence[nextIndex])
}
return lis.reversed()
}
private fun getNextIndex(longestEndingAt: List<Int>, sequence: List<Int>, end: Int, prevValue: Int): Int? {
var maxL = 0
var index: Int? = null
(0 until end).forEach { i ->
if (prevValue > sequence[i] && longestEndingAt[i] > maxL) {
maxL = longestEndingAt[i]
index = i
}
}
return index
}
/**
* get the size of the longest increasing subsequence of the given sequence
* time complexity: O(nlogn)
*
* @param sequence
* @return
*/
fun getSizeOfLISFast(sequence: List<Int>): Int {
if (sequence.isEmpty()) return 0
// for each size of increasing subsequence keep the smallest ending of this sequence
val subsequenceOfSizeEndings = mutableListOf(sequence[0])
sequence.forEach { x ->
if (subsequenceOfSizeEndings.last() < x) {
subsequenceOfSizeEndings.add(x)
} else if (subsequenceOfSizeEndings.last() > x) {
val index = getIndexOfSmallestBigger(subsequenceOfSizeEndings, 0, subsequenceOfSizeEndings.size, x)
subsequenceOfSizeEndings[index] = x
}
}
// the last element in the subsequenceOfSizeEndings is the ending of the longest increasing subsequence
return subsequenceOfSizeEndings.size
}
private fun getIndexOfSmallestBigger(sortedList: List<Int>, s: Int, e: Int, x: Int): Int {
require(s in sortedList.indices)
require(e <= sortedList.size)
require(s < e)
if (s == e - 1) return s
val m = s + ((e - s) / 2)
return if (sortedList[m - 1] >= x) {
getIndexOfSmallestBigger(sortedList, s, m, x)
} else {
getIndexOfSmallestBigger(sortedList, m, e, x)
}
}
} | 0 | Kotlin | 0 | 0 | 296cbd2e04a397597db223a5721b6c5722eb0c60 | 3,319 | algo-in-kotlin | MIT License |
lightbulb-easyrecyclerview/src/main/java/com/github/rooneyandshadows/lightbulb/easyrecyclerview/layout_managers/HorizontalFlowLayoutManager.kt | RooneyAndShadows | 424,519,760 | false | null | package com.github.rooneyandshadows.lightbulb.easyrecyclerview.layout_managers
import androidx.recyclerview.widget.RecyclerView
import com.github.rooneyandshadows.lightbulb.easyrecyclerview.EasyRecyclerView
import com.github.rooneyandshadows.lightbulb.recycleradapters.abstraction.EasyRecyclerAdapter
import com.github.rooneyandshadows.lightbulb.recycleradapters.abstraction.data.EasyAdapterDataModel
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import kotlin.math.abs
class HorizontalFlowLayoutManager<ItemType : EasyAdapterDataModel>(
private val easyRecyclerView: EasyRecyclerView<ItemType>,
) : FlexboxLayoutManager(easyRecyclerView.context, FlexDirection.COLUMN) {
private var scrollingHorizontally = false
private var scrollingVertically = false
init {
justifyContent = JustifyContent.FLEX_START
}
@Override
override fun canScrollVertically(): Boolean {
return easyRecyclerView.pullToRefreshEnabled && !scrollingHorizontally
}
@Override
override fun canScrollHorizontally(): Boolean {
return !scrollingVertically
}
@Override
override fun scrollVerticallyBy(dy: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
scrollingVertically = true
return super.scrollVerticallyBy(dy, recycler, state)
}
@Override
override fun onScrollStateChanged(state: Int) {
super.onScrollStateChanged(state)
if (state != 0) return
if (scrollingHorizontally) scrollingHorizontally = false
if (scrollingVertically) scrollingVertically = false
}
@Override
override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
val scrollRange = super.scrollHorizontallyBy(dx, recycler, state)
scrollingHorizontally = true
//val overScroll = dx - scrollRange
if (abs(dx) > 20) easyRecyclerView.parent.requestDisallowInterceptTouchEvent(true)
if (needToLoadMoreData(dx)) handleLoadMore()
return scrollRange
}
private fun needToLoadMoreData(dx: Int): Boolean {
return easyRecyclerView.hasMoreDataToLoad() &&
!easyRecyclerView.isShowingLoadingHeader &&
!easyRecyclerView.isAnimating &&
!easyRecyclerView.isShowingRefreshLayout &&
!easyRecyclerView.isShowingLoadingFooter && dx > 0
}
private fun handleLoadMore() {
if (!easyRecyclerView.supportsLazyLoading) return
val lastView = getChildAt(childCount - 1) ?: return
val recyclerAdapter: EasyRecyclerAdapter<ItemType> = easyRecyclerView.adapter
val size = easyRecyclerView.adapter.collection.size()
val last =
(lastView.layoutParams as RecyclerView.LayoutParams).absoluteAdapterPosition - recyclerAdapter.headersCount
if (last == size - 1) easyRecyclerView.loadMoreData()
}
} | 0 | Kotlin | 2 | 5 | 72e65f7d03fbd9bcef929e5ce59be930b786db1f | 3,026 | lightbulb-easyrecyclerview | Apache License 2.0 |
src/main/kotlin/me/sd_master92/customvoting/constants/enumerations/VotePartyType.kt | sanderderks | 306,723,396 | false | null | package me.sd_master92.customvoting.constants.enumerations
import me.sd_master92.customvoting.constants.interfaces.CarouselEnum
import me.sd_master92.customvoting.constants.interfaces.EnumCompanion
import java.util.*
enum class VotePartyType(private val label_: PMessage) : CarouselEnum
{
RANDOMLY(PMessage.ENUM_VOTE_PARTY_TYPE_RANDOM),
RANDOM_CHEST_AT_A_TIME(PMessage.ENUM_VOTE_PARTY_TYPE_RANDOM_CHEST_AT_A_TIME),
ALL_CHESTS_AT_ONCE(PMessage.ENUM_VOTE_PARTY_TYPE_ALL_CHESTS_AT_ONCE),
ONE_CHEST_AT_A_TIME(PMessage.ENUM_VOTE_PARTY_TYPE_ONE_CHEST_AT_A_TIME),
ADD_TO_INVENTORY(PMessage.ENUM_VOTE_PARTY_TYPE_ADD_TO_INVENTORY),
EXPLODE_CHESTS(PMessage.ENUM_VOTE_PARTY_TYPE_EXPLODE_CHESTS),
SCARY(PMessage.ENUM_VOTE_PARTY_TYPE_SCARY),
PIG_HUNT(PMessage.ENUM_VOTE_PARTY_TYPE_PIG_HUNT);
fun label(locale: Locale? = null): String
{
return label_.getValue(locale)
}
override fun next(): VotePartyType
{
return if (ordinal < values().size - 1)
{
valueOf(ordinal + 1)
} else
{
valueOf(0)
}
}
companion object : EnumCompanion
{
fun random(): VotePartyType
{
return values()[Random().nextInt(1, values().size)]
}
override fun valueOf(key: Int): VotePartyType
{
return try
{
values()[key]
} catch (_: Exception)
{
values()[0]
}
}
}
} | 0 | Kotlin | 1 | 0 | 7e1e23d09862390d05fe9aac92e46c9e5bf48a0d | 1,516 | CustomVoting | MIT License |
kotlin-in-action/src/annotation/kotlin_annoation/JvmNameTest.kt | chiclaim | 97,095,916 | false | null |
@file:JvmName("JavaClassName")
package annotation.kotlin_annoation
@JvmName("java_method_name")
fun javaMethodName(){
println("java method name")
}
fun main() {
//kotlin invoke
javaMethodName()
} | 0 | Kotlin | 10 | 25 | da08018c2fe20595293a4dbb1a08de75c3db3042 | 213 | KotlinTutorials | Apache License 2.0 |
library/resource-noexec-tor/src/nativeTest/kotlin/io/matthewnelson/kmp/tor/resource/noexec/tor/ResourceLoaderNoExecNativeUnitTest.kt | 05nelsonm | 734,754,650 | false | {"Kotlin": 322914, "Shell": 1152, "Java": 1086, "JavaScript": 14} | /*
* Copyright (c) 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package io.matthewnelson.kmp.tor.resource.noexec.tor
import kotlin.experimental.ExperimentalNativeApi
import kotlin.test.Test
@OptIn(ExperimentalNativeApi::class)
class ResourceLoaderNoExecNativeUnitTest: ResourceLoaderNoExecBaseTest(
runTorMainCount = when (Platform.osFamily) {
// TODO: Dynamic lib
OsFamily.IOS -> 0
OsFamily.WINDOWS -> RUN_TOR_MAIN_COUNT_WINDOWS
else -> RUN_TOR_MAIN_COUNT_UNIX
}
) {
@Test
fun stub() {}
}
| 13 | Kotlin | 0 | 1 | 54b305c97e9b5c8a959a65d4d1ee378afb3dd8f6 | 1,073 | kmp-tor-resource | Apache License 2.0 |
app/src/androidTest/java/com/noisyninja/androidlistpoc/modules/NetworkModuleTest.kt | LinxFae | 162,831,019 | true | {"Kotlin": 71084, "Java": 15779} | package com.noisyninja.androidlistpoc.modules
import android.support.test.runner.AndroidJUnit4
import com.noisyninja.androidlistpoc.BuildConfig
import com.noisyninja.androidlistpoc.BuildConfig.RESULT_COUNT
import com.noisyninja.androidlistpoc.layers.network.NetworkModule
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
/**
* Created by sudiptadutta on 23/05/18.
*/
@RunWith(AndroidJUnit4::class)
class NetworkModuleTest : BaseRepository() {
@Before
fun setup(){
setupEnvironment()
setupLoopers()
}
@After
fun teardown(){
tearDownLoopers()
}
@Test
fun serverCallWithSuccess() {
val url = BuildConfig.BASE_URL
setupServer(url)
val networkObservable =
mNetworkModule.getPeople(RESULT_COUNT.toInt())
networkObservable.subscribe(mSubscriber)
mSubscriber.assertNoErrors()
mSubscriber.assertValue({ it ->
it.people.size == 100
})
mSubscriber.assertValue({ it ->
it.info != null
it.people.get(0).name != null
it.people.get(0).name.first != null
it.people.get(0).name.title != null
it.people.get(0).name.last != null
it.people.get(0).picture.large != null
it.people.get(0).picture.medium != null
it.people[0].picture.thumbnail != null
})
}
/**
* test for network availability
*/
@Test
fun serverCallWithError() {
//this is an invalid uri
val url = BuildConfig.BASE_URL + BuildConfig.API_URI + "/"
setupServer(url)
val networkObservable =
mNetworkModule.getPeople(BuildConfig.RESULT_COUNT.toInt())
networkObservable.subscribe(mSubscriber)
mSubscriber.assertError({ t: Throwable -> t.message!!.isNotEmpty() })
}
}
| 0 | Kotlin | 0 | 0 | 67a2bb55a1c7bc3ab6f259954d87ed4f38839b03 | 2,128 | AndroidArch | Apache License 2.0 |
app/shared/ktor-client/public/src/commonMain/kotlin/build/wallet/ktor/result/HttpBodyError.kt | proto-at-block | 761,306,853 | false | {"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.ktor.result
import io.ktor.client.call.HttpClientCall
sealed class HttpBodyError : NetworkingError() {
/**
* [HttpClientCall.body] can be only called once. This error indicates that [HttpClientCall.body]
* was already called.
*/
data class DoubleReceiveError(
override val cause: Throwable,
) : HttpBodyError()
/**
* Indicates that we failed to deserialize body from response.
*/
data class SerializationError(
override val cause: Throwable,
) : HttpBodyError()
/**
* Indicates some error that we don't handle.
*/
data class UnhandledError(
override val cause: Throwable,
) : HttpBodyError()
}
| 0 | C | 10 | 98 | 1f9f2298919dac77e6791aa3f1dbfd67efe7f83c | 670 | bitkey | MIT License |
src/fr/anisama/src/eu/kanade/tachiyomi/animeextension/fr/anisama/AniSamaFilters.kt | almightyhak | 817,607,446 | false | {"Kotlin": 4066862} | package eu.kanade.tachiyomi.animeextension.fr.anisama
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.OkHttpClient
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
class AniSamaFilters(
private val baseUrl: String,
private val client: OkHttpClient,
) {
private var error = false
private lateinit var filterList: AnimeFilterList
interface QueryParameterFilter { fun toQueryParameter(): Pair<String, String?> }
private class Checkbox(name: String, state: Boolean = false) : AnimeFilter.CheckBox(name, state)
private class CheckboxList(name: String, private val paramName: String, private val pairs: List<Pair<String, String>>) :
AnimeFilter.Group<AnimeFilter.CheckBox>(name, pairs.map { Checkbox(it.first) }), QueryParameterFilter {
override fun toQueryParameter() = Pair(
paramName,
state.asSequence()
.filter { it.state }
.map { checkbox -> pairs.find { it.first == checkbox.name }!!.second }
.filter(String::isNotBlank)
.joinToString(","),
)
}
private class Select(name: String, private val paramName: String, private val pairs: List<Pair<String, String>>) :
AnimeFilter.Select<String>(name, pairs.map { it.first }.toTypedArray()), QueryParameterFilter {
override fun toQueryParameter() = Pair(paramName, pairs[state].second)
}
fun getFilterList(): AnimeFilterList {
return if (error) {
AnimeFilterList(AnimeFilter.Header("Erreur lors de la récupération des filtres."))
} else if (this::filterList.isInitialized) {
filterList
} else {
AnimeFilterList(AnimeFilter.Header("Utilise \"Réinitialiser\" pour charger les filtres."))
}
}
fun fetchFilters() {
if (!this::filterList.isInitialized) {
runCatching {
error = false
filterList = client.newCall(GET("$baseUrl/filter"))
.execute()
.asJsoup()
.let(::filtersParse)
}.onFailure { error = true }
}
}
private fun Elements.parseFilterValues(name: String): List<Pair<String, String>> =
select(".item:has(.btn:contains($name)) li").map {
Pair(it.text(), it.select("input").attr("value"))
}
private fun filtersParse(document: Document): AnimeFilterList {
val form = document.select(".block_area-filter")
return AnimeFilterList(
CheckboxList("Genres", "genre", form.parseFilterValues("Genre")),
CheckboxList("Saisons", "season", form.parseFilterValues("Saison")),
CheckboxList("Années", "year", form.parseFilterValues("Année")),
CheckboxList("Types", "type", form.parseFilterValues("Type")),
CheckboxList("Status", "status", form.parseFilterValues("Status")),
CheckboxList("Langues", "language", form.parseFilterValues("Langue")),
Select("Trié par", "sort", form.parseFilterValues("Sort")),
)
}
}
| 55 | Kotlin | 28 | 93 | 507dddff536702999357b17577edc48353eab5ad | 3,262 | aniyomi-extensions | Apache License 2.0 |
plugin/src/main/java/app/cash/paraphrase/plugin/model/ResourceFolder.kt | cashapp | 568,984,928 | false | {"Kotlin": 116632} | /*
* Copyright (C) 2023 Cash App
*
* 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.paraphrase.plugin.model
/**
* Represents "values-es" in `res/values-es/strings.xml`
*/
@JvmInline
internal value class ResourceFolder(val name: String) {
companion object {
val Default = ResourceFolder("values")
}
}
| 16 | Kotlin | 5 | 165 | b11af777ea4379724427aed1c64fadf81449fc37 | 841 | paraphrase | Apache License 2.0 |
kotlin-antd/src/main/kotlin/antd/button/Button.kt | oxiadenine | 206,398,615 | false | {"Kotlin": 1619835, "HTML": 1515} | @file:JsModule("antd/lib/button")
@file:JsNonModule
package antd.button
import antd.*
import antd.ReactNode
import antd.configprovider.SizeType
import org.w3c.dom.HTMLElement
import react.*
@JsName("default")
external object ButtonComponent : Component<ButtonProps, ButtonState> {
val Group: ButtonGroupComponent
override fun render(): ReactElement?
}
external interface ButtonProps : AnchorButtonProps, NativeButtonProps, RefAttributes<HTMLElement>, Props
external interface ButtonState : State {
var loading: Any? /* Boolean | ButtonLoading */
var hasTwoCNChar: Boolean
}
external interface AnchorButtonProps : BaseButtonProps, AnchorHTMLAttributes<Any> {
override var href: String?
override var target: String?
override var onClick: MouseEventHandler<Any /* HTMLElement */>?
}
external interface NativeButtonProps : BaseButtonProps, ButtonHTMLAttributes<Any> {
var htmlType: ButtonHTMLType?
override var onClick: MouseEventHandler<Any /* HTMLElement */>?
}
external interface BaseButtonProps {
var type: ButtonType?
var icon: ReactNode?
var shape: ButtonShape?
var size: SizeType?
var loading: Any? /* Boolean | ButtonLoadingProps */
var prefixCls: String?
var style: dynamic
var className: String?
var ghost: Boolean?
var danger: Boolean?
var block: Boolean?
var children: Any?
}
external interface ButtonLoadingProps {
var delay: Number?
}
| 1 | Kotlin | 8 | 50 | e0017a108b36025630c354c7663256347e867251 | 1,443 | kotlin-js-wrappers | Apache License 2.0 |
kstore/src/main/kotlin/react/kstore/dependency/DependsOn5MergeBuilder.kt | minorbyte | 194,674,817 | false | null | @file:Suppress("UNCHECKED_CAST")
package react.kstore.dependency
import react.kstore.UpdateableStore
open class DependsOn5MergeBuilder<STATE : Any, D1 : Any, D2 : Any, D3 : Any, D4 : Any, D5 : Any>(
store: UpdateableStore<STATE>,
dependencies: Array<out Any>
) : DependsOnMergeArrayBuilder<STATE>(
store, dependencies
) {
infix fun merge(merge: (d1: D1, d2: D2, d3: D3, d4: D4, d5: D5, state: STATE) -> STATE)
: DependsOn5MergeBuilder<STATE, D1, D2, D3, D4, D5> {
super.merge { it, state ->
merge(
it[0] as @kotlin.ParameterName(name = "d1") D1,
it[1] as @kotlin.ParameterName(name = "d2") D2,
it[2] as @kotlin.ParameterName(name = "d3") D3,
it[3] as @kotlin.ParameterName(name = "d4") D4,
it[4] as @kotlin.ParameterName(name = "d5") D5,
state
)
}
return this
}
infix fun rewrite(rewrite: (d1: D1, d2: D2, d3: D3, d4: D4, d5: D5) -> STATE)
: DependsOn5MergeBuilder<STATE, D1, D2, D3, D4, D5> {
super.rewrite { it ->
rewrite(
it[0] as @kotlin.ParameterName(name = "d1") D1,
it[1] as @kotlin.ParameterName(name = "d2") D2,
it[2] as @kotlin.ParameterName(name = "d3") D3,
it[3] as @kotlin.ParameterName(name = "d4") D4,
it[4] as @kotlin.ParameterName(name = "d5") D5
)
}
return this
}
infix fun react(react: (d1: D1, d2: D2, d3: D3, d4: D4, d5: D5) -> Unit)
: DependsOn5MergeBuilder<STATE, D1, D2, D3, D4, D5> {
super.react { it ->
react(
it[0] as @kotlin.ParameterName(name = "d1") D1,
it[1] as @kotlin.ParameterName(name = "d2") D2,
it[2] as @kotlin.ParameterName(name = "d3") D3,
it[3] as @kotlin.ParameterName(name = "d4") D4,
it[4] as @kotlin.ParameterName(name = "d5") D5
)
}
return this
}
}
| 0 | Kotlin | 0 | 0 | b91a6a00d4e60a84dc8bceba5dd02c3aa352ca88 | 2,149 | kotlin-reactive-store | MIT License |
src/commonMain/kotlin/baaahs/client/document/DocumentManager.kt | baaahs | 174,897,412 | false | {"Kotlin": 4817815, "C": 1529197, "C++": 661363, "GLSL": 412779, "JavaScript": 61944, "HTML": 56277, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450} | package baaahs.client.document
import baaahs.DocumentState
import baaahs.PubSub
import baaahs.client.Notifier
import baaahs.doc.DocumentType
import baaahs.doc.FileType
import baaahs.io.Fs
import baaahs.io.RemoteFsSerializer
import baaahs.plugin.Plugins
import baaahs.show.mutable.EditHandler
import baaahs.sm.webapi.*
import baaahs.ui.DialogHolder
import baaahs.ui.confirm
import baaahs.util.UndoStack
import kotlinx.serialization.KSerializer
import kotlinx.serialization.modules.SerializersModule
abstract class DocumentManager<T, TState>(
val documentType: DocumentType,
private val pubSub: PubSub.Client,
topic: PubSub.Topic<DocumentState<T, TState>?>,
private val remoteFsSerializer: RemoteFsSerializer,
private val plugins: Plugins,
private val notifier: Notifier,
private val fileDialog: IFileDialog,
private val tSerializer: KSerializer<T>
) {
abstract val facade: Facade
private val fileType: FileType get() = documentType.fileType
var file: Fs.File? = null
private set
var document: T? = null
private set
var isUnsaved: Boolean = false
private set
private var documentAsSaved: T? = null
val isLoaded: Boolean
get() = document != null
var everSynced: Boolean = false
private set
private val isSynced: Boolean
get() = editState == localState
val editMode = EditMode(EditMode.Mode.Never)
protected val undoStack = object : UndoStack<DocumentState<T, TState>>() {
override fun undo(): DocumentState<T, TState> {
return super.undo().also { (document, documentState) ->
facade.onEdit(document, documentState, pushToUndoStack = false)
}
}
override fun redo(): DocumentState<T, TState> {
return super.redo().also { (document, documentState) ->
facade.onEdit(document, documentState, pushToUndoStack = false)
}
}
}
private val stateChannels = mutableListOf<PubSub.Channel<*>>()
protected var localState: DocumentState<T, TState>? = null
protected var editState by
pubSub.state(topic, null, stateChannels) { incoming ->
localState = incoming
switchTo(incoming, false)
undoStack.reset(incoming)
facade.notifyChanged()
}
private val serverCommands = object {
private val commands = Topics.DocumentCommands(documentType.channelName, tSerializer, SerializersModule {
include(remoteFsSerializer.serialModule)
include(plugins.serialModule)
})
val newCommand = pubSub.commandSender(commands.newCommand)
val switchToCommand = pubSub.commandSender(commands.switchToCommand)
val saveCommand = pubSub.commandSender(commands.saveCommand)
val saveAsCommand = pubSub.commandSender(commands.saveAsCommand)
}
abstract suspend fun onNew(dialogHolder: DialogHolder)
suspend fun onNew(newDocument: T? = null) {
serverCommands.newCommand(NewCommand(newDocument))
}
suspend fun onOpen() {
confirmCloseIfUnsaved() || return
fileDialog.open(fileType, file)
?.withExtension(fileType.extension)
?.also { serverCommands.switchToCommand(SwitchToCommand(it)) }
}
suspend fun onOpen(file: Fs.File?) {
serverCommands.switchToCommand(SwitchToCommand(file))
}
suspend fun onSave() {
if (file == null) {
onSaveAs()
} else {
serverCommands.saveCommand(SaveCommand())
}
}
suspend fun onSaveAs() {
fileDialog.saveAs(fileType, file)
?.withExtension(fileType.extension)
?.also { serverCommands.saveAsCommand(SaveAsCommand(it)) }
}
suspend fun onSaveAs(file: Fs.File) {
serverCommands.saveAsCommand(SaveAsCommand(file))
}
abstract suspend fun onDownload()
abstract suspend fun onUpload(name: String, content: String)
suspend fun onClose() {
confirmCloseIfUnsaved() || return
serverCommands.switchToCommand(SwitchToCommand(null))
}
protected abstract fun switchTo(documentState: DocumentState<T, TState>?, isLocalEdit: Boolean)
protected fun update(newDocument: T?, newFile: Fs.File?, newIsUnsaved: Boolean) {
document = newDocument
file = newFile
isUnsaved = newIsUnsaved
if (!newIsUnsaved) documentAsSaved = newDocument
everSynced = true
}
fun isModified(newDocument: T): Boolean {
return documentAsSaved?.equals(newDocument) != true
}
protected fun confirmCloseIfUnsaved(): Boolean {
if (!isUnsaved) return true
// TODO: Use react dialog instead.
return confirm("${documentType.title} is unsaved, okay to close it?")
}
protected fun launch(block: suspend () -> Unit) {
notifier.facade.launchAndReportErrors(block)
}
fun release() {
stateChannels.forEach { it.unsubscribe() }
}
abstract inner class Facade : baaahs.ui.Facade(), EditHandler<T, TState> {
val documentType get() = [email protected]
val documentTypeTitle get() = [email protected]
val file get() = [email protected]
val isLoaded get() = [email protected]
val isSynced get() = [email protected]
val everSynced get() = [email protected]
val isUnsaved get() = [email protected]
val canUndo get() = undoStack.canUndo()
val canRedo get() = undoStack.canRedo()
val editMode get() = [email protected]
suspend fun onNew(dialogHolder: DialogHolder) = [email protected](dialogHolder)
suspend fun onNew(document: T) = [email protected](document)
suspend fun onOpen() = [email protected]()
suspend fun onOpen(file: Fs.File) = [email protected](file)
suspend fun onSave() = [email protected]()
suspend fun onSaveAs() = [email protected]()
suspend fun onSaveAs(file: Fs.File) = [email protected](file)
suspend fun onDownload() = [email protected]()
fun confirmCloseIfUnsaved() = [email protected]()
suspend fun onUpload(name: String, content: String) = [email protected](name, content)
suspend fun onClose() = [email protected]()
fun sync() {
[email protected] = localState
}
fun undo() = undoStack.undo()
fun redo() = undoStack.redo()
override fun onEdit(document: T, documentState: TState, pushToUndoStack: Boolean, syncToServer: Boolean) {
val isUnsaved = [email protected](document)
val newEditState = DocumentState(document, documentState, isUnsaved, file)
if (syncToServer) {
[email protected] = newEditState
}
switchTo(newEditState, true)
if (pushToUndoStack) {
undoStack.changed(newEditState)
}
notifyChanged()
}
}
} | 83 | Kotlin | 5 | 40 | 77ad22b042fc0ac440410619dd27b468c3b3a600 | 7,274 | sparklemotion | MIT License |
feature/timers/presentation/src/commonMain/kotlin/org/timemates/app/timers/ui/TimerItem.kt | timemates | 575,537,317 | false | null | package io.timemates.app.timers.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import io.timemates.app.localization.compose.LocalStrings
import io.timemates.app.style.system.theme.AppTheme
import io.timemates.sdk.timers.types.Timer
import io.timemates.sdk.timers.types.Timer.State.ConfirmationWaiting
import io.timemates.sdk.timers.types.Timer.State.Inactive
import io.timemates.sdk.timers.types.Timer.State.Paused
import io.timemates.sdk.timers.types.Timer.State.Rest
import io.timemates.sdk.timers.types.Timer.State.Running
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import kotlinx.datetime.TimeZone
import kotlinx.datetime.minus
import kotlinx.datetime.toLocalDateTime
@Composable
fun TimerItem(
timer: Timer,
onClick: () -> Unit,
) {
OutlinedCard(
modifier = Modifier
.fillMaxWidth(),
border = BorderStroke(1.dp, AppTheme.colors.secondary),
colors = CardDefaults.outlinedCardColors(containerColor = AppTheme.colors.background),
) {
Row(
modifier = Modifier.fillMaxWidth().clickable(
onClick = onClick
),
verticalAlignment = Alignment.CenterVertically,
) {
Column(
modifier = Modifier.padding(12.dp).weight(1f),
) {
Row(
modifier = Modifier,
) {
Text(
text = timer.name.string,
modifier = Modifier,
style = MaterialTheme.typography.titleMedium,
)
OnlineIndicator(
modifier = Modifier.padding(3.dp),
isOnline = timer.state is Running,
)
}
Text(
text = timerItemSubtext(timer),
modifier = Modifier,
style = MaterialTheme.typography.bodyMedium,
)
}
Box(
modifier = Modifier.padding(12.dp),
) {
Icon(
imageVector = Icons.Filled.ArrowForward,
contentDescription = "Navigate To Timer",
modifier = Modifier
.align(Alignment.CenterEnd),
tint = Color.Gray,
)
}
}
}
}
@Stable
@Composable
private fun timerItemSubtext(timer: Timer): String {
return when(timer.state) {
is Running, is Rest -> LocalStrings.current.runningTimerDescription(timer.membersCount.int)
is Paused, is Inactive -> LocalStrings.current.inactiveTimerDescription(daysSinceInactive(timer.state.publishTime))
is ConfirmationWaiting -> LocalStrings.current.confirmationWaitingTimerDescription
}
}
@Stable
private fun daysSinceInactive(pausedInstant: Instant): Int {
val currentInstant = Clock.System.now()
return (currentInstant.toLocalDateTime(TimeZone.UTC).date.minus(pausedInstant.toLocalDateTime(TimeZone.UTC).date)).days
}
@Composable
private fun OnlineIndicator(
modifier: Modifier = Modifier,
isOnline: Boolean,
indicatorSize: Dp = 6.dp,
onlineColor: Color = AppTheme.colors.positive,
) {
Box(
modifier = modifier
.size(indicatorSize)
.background(
shape = CircleShape,
brush = Brush.radialGradient(
colors = if (isOnline) listOf(onlineColor, onlineColor) else listOf(Color.Transparent, Color.Transparent),
radius = 60f
),
),
)
}
| 21 | null | 0 | 27 | af5f6048c2cef30ac56d80754de54849650d78d2 | 4,722 | app | MIT License |
ethereumkit/src/test/java/io/horizontalsystems/ethereumkit/core/ExtensionsKtTest.kt | horizontalsystems | 152,531,605 | false | null | package io.horizontalsystems.ethereumkit.core
import org.junit.Test
class ExtensionsKtTest {
@Test
fun removeLeadingZeros() {
val testString1 = "0000F4545"
val testString2 = "0F4545"
val testString3 = "F454500"
assert(testString1.removeLeadingZeros() == "F4545")
assert(testString2.removeLeadingZeros() == "F4545")
assert(testString3.removeLeadingZeros() == "F454500")
}
} | 10 | null | 54 | 98 | 3d83900bc513f4df6575277519277f1a7cc77ab6 | 436 | ethereum-kit-android | MIT License |
app/src/main/java/com/robert/android/lostpets/domain/interactors/AdsInteractor.kt | robertene1994 | 303,119,114 | false | null | package com.robert.android.lostpets.domain.interactors
import com.robert.android.lostpets.domain.interactors.base.BaseCallbackInteractor
import com.robert.android.lostpets.domain.interactors.base.Interactor
import com.robert.android.lostpets.domain.model.Ad
/**
* Interfaz del interactor que se encarga de recuperar todos los anuncios de mascotas perdidas.
*
* @author <NAME>
*/
interface AdsInteractor : Interactor {
/**
* Interfaz que es utilizada por el interactor para notificar los resultados de las operaciones
* que tiene asignadas.
*
* @author <NAME>
*/
interface Callback : BaseCallbackInteractor {
/**
* Método que notifica que los anuncios de mascotas perdidas han sido recuperadas.
*
* @param ads los anuncios de mascotas perdidas.
*/
fun onAdsRetrieved(ads: List<Ad>)
/**
* Método que notifica que no existen anuncios de mascotas perdidas.
*/
fun onAdsEmpty()
}
}
| 0 | Kotlin | 0 | 0 | a7af7de031d3ab4e2d14851a117d3729330cd875 | 1,009 | lostpets-android | MIT License |
app/src/main/java/com/videoengager/demoapp/Globals.kt | VideoEngager | 367,585,600 | false | null | //
// DemoPureCloud
//
// Copyright © 2021 VideoEngager. All rights reserved.
//
package com.videoengager.demoapp
import com.videoengager.sdk.VideoEngager
class Globals {
companion object {
var chat:VideoEngager?=null
var params:Params?=null
var agentName=""
}
} | 0 | Kotlin | 0 | 0 | b1da4439461aa46f65d22099a4c2069eb1d7339c | 296 | SmartVideo-Android-SDK-Demo-App | MIT License |
client_delivery/shared/src/commonMain/kotlin/presentation/login/composable/WrongPermissionBottomSheet.kt | TheChance101 | 671,967,732 | false | {"Kotlin": 2473455, "Ruby": 8872, "HTML": 6083, "Swift": 4726, "JavaScript": 3082, "CSS": 1436, "Dockerfile": 1407, "Shell": 1140} | package presentation.login.composable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.beepbeep.designSystem.ui.composable.BpButton
import com.beepbeep.designSystem.ui.composable.BpTransparentButton
import com.beepbeep.designSystem.ui.theme.Theme
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
import presentation.login.PermissionInteractionListener
import resources.Resources
@OptIn(ExperimentalResourceApi::class, ExperimentalMaterial3Api::class)
@Composable
fun WrongPermissionBottomSheet(listener: PermissionInteractionListener,
modifier: Modifier = Modifier) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier.wrapContentHeight()
.padding(horizontal = 16.dp, vertical =24.dp)
) {
Icon(
modifier = Modifier.background(
color = Theme.colors.hover,
shape = RoundedCornerShape(Theme.radius.medium)
).padding(8.dp),
painter = painterResource(Resources.images.warningIcon),
tint = Theme.colors.primary,
contentDescription = null
)
Text(
text = Resources.strings.wrongPermission,
style = Theme.typography.titleLarge,
color = Theme.colors.contentPrimary,
textAlign = TextAlign.Center,
modifier = Modifier.padding(16.dp)
)
Text(
text = Resources.strings.wrongPermissionMessage,
style = Theme.typography.body,
color = Theme.colors.contentSecondary,
textAlign = TextAlign.Center,
modifier = Modifier.padding(bottom = 24.dp, start = 32.dp,end=32.dp)
)
BpButton(
onClick = listener::onRequestPermissionClicked,
title = Resources.strings.requestAPermission,
modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp)
)
BpTransparentButton(
onClick = listener::onCancelClicked,
title = Resources.strings.close,
modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp)
)
}
} | 4 | Kotlin | 55 | 572 | 1d2e72ba7def605529213ac771cd85cbab832241 | 2,828 | beep-beep | Apache License 2.0 |
src/main/kotlin/playground/common/idempotencyjpa/jpa/IdempotencyRecord.kt | dtkmn | 596,118,171 | false | {"Kotlin": 334372, "Dockerfile": 763} | package playground.common.idempotencyjpa.jpa
import jakarta.persistence.EmbeddedId
import jakarta.persistence.Entity
import jakarta.persistence.Lob
import jakarta.persistence.Table
import org.springframework.data.domain.Persistable
import playground.common.idempotencyjpa.jpa.IdempotencyPK
import java.time.Instant
@Entity
@Table(name = "commons_idempotency_record")
data class IdempotencyRecord(
@EmbeddedId
val key: IdempotencyPK,
val createdAt: Instant,
@Lob
val data: String?,
val data2: String?,
val final: Boolean
) : Persistable<IdempotencyPK> {
// Force always creating a new entity.
override fun isNew() = true
override fun getId() = key
}
| 0 | Kotlin | 0 | 0 | 06b6e996d3d319a7ad390dab9b3f33132f5f0378 | 695 | kotlin-playground | MIT License |
app/src/main/java/com/spring/musk/antibloater/viewmodels/MainActivityViewModel.kt | springmusk026 | 793,017,854 | false | {"Kotlin": 26101, "CMake": 1652, "C++": 273} | package com.spring.musk.antibloater.viewmodels
import android.app.Application
import android.os.Build
import androidx.core.content.edit
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import android.preference.PreferenceManager
import androidx.annotation.RequiresApi
import androidx.lifecycle.viewModelScope
import com.spring.musk.antibloater.addon.ADB
import com.spring.musk.antibloater.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.io.File
@RequiresApi(Build.VERSION_CODES.O)
class MainActivityViewModel(application: Application) : AndroidViewModel(application) {
private val _outputText = MutableLiveData<String>()
val outputText: LiveData<String> = _outputText
val isPairing = MutableLiveData<Boolean>()
private val sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(application.applicationContext)
val adb = ADB.getInstance(getApplication<Application>().applicationContext)
init {
startOutputThread()
}
fun startADBServer(callback: ((Boolean) -> (Unit))? = null) {
viewModelScope.launch(Dispatchers.IO) {
val success = adb.initServer()
if (success)
startShellDeathThread()
callback?.invoke(success)
}
}
private fun startOutputThread() {
viewModelScope.launch(Dispatchers.IO) {
while (isActive) {
val out = readOutputFile(adb.outputBufferFile)
val currentText = _outputText.value
if (out != currentText)
_outputText.postValue(out)
Thread.sleep(ADB.OUTPUT_BUFFER_DELAY_MS)
}
}
}
private fun startShellDeathThread() {
viewModelScope.launch(Dispatchers.IO) {
adb.waitForDeathAndReset()
}
}
fun clearOutputText() {
adb.outputBufferFile.writeText("")
}
fun needsToPair(): Boolean {
val context = getApplication<Application>().applicationContext
return !sharedPreferences.getBoolean(context.getString(R.string.paired_key), false) &&
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
}
fun setPairedBefore(value: Boolean) {
val context = getApplication<Application>().applicationContext
sharedPreferences.edit {
putBoolean(context.getString(R.string.paired_key), value)
}
}
private fun readOutputFile(file: File): String {
val out = ByteArray(adb.getOutputBufferSize())
synchronized(file) {
if (!file.exists())
return ""
file.inputStream().use {
val size = it.channel.size()
if (size <= out.size)
return String(it.readBytes())
val newPos = (it.channel.size() - out.size)
it.channel.position(newPos)
it.read(out)
}
}
return String(out)
}
} | 0 | Kotlin | 0 | 0 | 65ca33d01cba8ed10e9713569aa930f02a309f1d | 3,095 | AntiBloater | MIT License |
app/src/test/java/com/mustafa/movieguideapp/viewmodel/MovieSearchViewModelTest.kt | Mustafashahoud | 231,958,118 | false | null | package com.mustafa.movieguideapp.viewmodel
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.mustafa.movieguideapp.models.Resource
import com.mustafa.movieguideapp.models.entity.Movie
import com.mustafa.movieguideapp.repository.DiscoverRepository
import com.mustafa.movieguideapp.utils.MockTestUtil.Companion.mockMovie
import com.mustafa.movieguideapp.view.ui.search.MovieSearchViewModel
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito.*
@RunWith(JUnit4::class)
class MovieSearchViewModelTest {
@Rule
@JvmField
val instantTaskExecutorRule = InstantTaskExecutorRule()
private lateinit var viewModel: MovieSearchViewModel
private val repository = mock<DiscoverRepository>()
@Before
fun init() {
viewModel = MovieSearchViewModel(repository)
}
@Test
fun movieSuggestionsNullQueryTest() {
val observer = mock<Observer<List<Movie>>>()
viewModel.movieSuggestions.observeForever(observer)
viewModel.setMovieSuggestionsQuery(null)
verifyNoMoreInteractions(repository)
verify(repository, never()).getMovieSuggestionsFromRoom(anyString())
}
@Test
fun searchMoviesTest() {
val observer = mock<Observer<Resource<List<Movie>>>>()
val searchMoviesResultLiveData = MutableLiveData<Resource<List<Movie>>>()
val searchMovies = Resource.success(listOf(mockMovie()), true)
`when`(repository.searchMovies(anyString(), anyInt())).thenReturn(
searchMoviesResultLiveData
)
viewModel.searchMovieListLiveData.observeForever(observer)
viewModel.setSearchMovieQueryAndPage("query", 1)
searchMoviesResultLiveData.postValue(searchMovies)
verify(repository).searchMovies("query", 1)
verify(observer).onChanged(searchMovies)
}
@Test
fun searchMoviesNullQueryOrEmptyTest() {
val observer = mock<Observer<Resource<List<Movie>>>>()
viewModel.searchMovieListLiveData.observeForever(observer)
viewModel.setSearchMovieQueryAndPage("", 1)
verifyNoMoreInteractions(repository)
verify(repository, never()).searchMovies(anyString(), anyInt())
viewModel.setSearchMovieQueryAndPage(null, 1)
verifyNoMoreInteractions(repository)
verify(repository, never()).searchMovies(anyString(), anyInt())
}
@Test
fun movieSuggestionsTest() {
val observer = mock<Observer<List<Movie>>>()
val suggestionResultLiveData = MutableLiveData<List<Movie>>()
val movieSuggestions = listOf(mockMovie())
`when`(repository.getMovieSuggestionsFromRoom(anyString())).thenReturn(
suggestionResultLiveData
)
viewModel.movieSuggestions.observeForever(observer)
viewModel.setMovieSuggestionsQuery("Movie")
suggestionResultLiveData.postValue(movieSuggestions)
verify(repository).getMovieSuggestionsFromRoom("Movie")
verify(observer).onChanged(movieSuggestions)
}
} | 2 | Kotlin | 10 | 98 | 5f12624e566610349ba31d1eece34a32b90aa344 | 3,378 | MoviesApp | Apache License 2.0 |
src/main/kotlin/dev/yjyoon/alreadyme/data/model/PullRequestResponse.kt | readme-generator | 519,125,238 | false | {"Kotlin": 58476} | package dev.yjyoon.alreadyme.data.model
import kotlinx.serialization.Serializable
@Serializable
data class PullRequestResponse(
val pullRequestUrl: String
)
| 0 | Kotlin | 7 | 45 | 5daff682957cff97ec0caa762e606116e3501d19 | 163 | alreadyme-desktop | Apache License 2.0 |
src/commonMain/kotlin/data/buffs/TheRestrainedEssenceOfSapphiron.kt | marisa-ashkandi | 332,658,265 | false | null | package data.buffs
import character.Ability
import character.Buff
import character.Stats
import sim.SimParticipant
class TheRestrainedEssenceOfSapphiron : Buff() {
override val id: Int = 28779
override val name: String = "The Restrained Essence of Sapphiron (static)"
override val icon: String = "inv_trinket_naxxramas06.jpg"
override val durationMs: Int = -1
override val hidden: Boolean = true
val buffDurationMs = 20000
val buff = object : Buff() {
override val name: String = "The Restrained Essence of Sapphiron"
override val icon: String = "inv_trinket_naxxramas06.jpg"
override val durationMs: Int = buffDurationMs
override fun modifyStats(sp: SimParticipant): Stats? {
return Stats(
spellDamage = 130
)
}
}
val ability = object : Ability() {
override val id: Int = 28779
override val name: String = "The Restrained Essence of Sapphiron"
override val icon: String = "inv_trinket_naxxramas06.jpg"
override fun gcdMs(sp: SimParticipant): Int = 0
override fun cooldownMs(sp: SimParticipant): Int = 120000
override fun trinketLockoutMs(sp: SimParticipant): Int = buffDurationMs
override fun cast(sp: SimParticipant) {
sp.addBuff(buff)
}
}
override fun activeTrinketAbility(sp: SimParticipant): Ability = ability
}
| 21 | null | 11 | 25 | 9cb6a0e51a650b5d04c63883cb9bf3f64057ce73 | 1,426 | tbcsim | MIT License |
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/input/UndoState.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.text2.input
import androidx.compose.foundation.ExperimentalFoundationApi
/**
* Defines an interactable undo history.
*/
@ExperimentalFoundationApi
class UndoState internal constructor(private val state: TextFieldState) {
/**
* Whether it is possible to execute a meaningful undo action right now. If this value is false,
* calling `undo` would be a no-op.
*/
@Suppress("GetterSetterNames")
@get:Suppress("GetterSetterNames")
val canUndo: Boolean
get() = state.textUndoManager.canUndo
/**
* Whether it is possible to execute a meaningful redo action right now. If this value is false,
* calling `redo` would be a no-op.
*/
@Suppress("GetterSetterNames")
@get:Suppress("GetterSetterNames")
val canRedo: Boolean
get() = state.textUndoManager.canRedo
/**
* Reverts the latest edit action or a group of actions that are merged together. Calling it
* repeatedly can continue undoing the previous actions.
*/
fun undo() {
state.textUndoManager.undo(state)
}
/**
* Re-applies a change that was previously reverted via [undo].
*/
fun redo() {
state.textUndoManager.redo(state)
}
/**
* Clears all undo and redo history up to this point.
*/
fun clearHistory() {
state.textUndoManager.clearHistory()
}
}
| 29 | null | 950 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 2,027 | androidx | Apache License 2.0 |
plugins/amazonq/codewhisperer/jetbrains-community/src/software/aws/toolkits/jetbrains/services/codewhisperer/language/classresolver/CodeWhispererPythonClassResolver.kt | aws | 91,485,909 | false | null | // Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.codewhisperer.language.classresolver
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.PsiFile
import com.jetbrains.python.psi.PyFile
class CodeWhispererPythonClassResolver : CodeWhispererClassResolver {
override fun resolveClassAndMembers(psiFile: PsiFile): Map<ClassResolverKey, List<String>> {
if (psiFile !is PyFile) {
return emptyMap()
}
val classNames = runReadAction {
psiFile.topLevelClasses.mapNotNull { it.name }
}
val methodNames = runReadAction {
psiFile.topLevelClasses.mapNotNull { clazz ->
clazz.methods.mapNotNull { method ->
method.name
}
}
}.flatten()
return mapOf(
ClassResolverKey.ClassName to classNames,
ClassResolverKey.MethodName to methodNames
)
}
override fun resolveTopLevelFunction(psiFile: PsiFile): List<String> {
if (psiFile !is PyFile) {
return emptyList()
}
val functionNames = runReadAction {
psiFile.topLevelFunctions.mapNotNull { it.name }
}
return functionNames
}
}
| 519 | null | 220 | 757 | a81caf64a293b59056cef3f8a6f1c977be46937e | 1,370 | aws-toolkit-jetbrains | Apache License 2.0 |
app-features/show-details/src/main/kotlin/com/thomaskioko/showdetails/SimilarShowsScreen.kt | c0de-wizard | 361,393,353 | false | null | package com.thomaskioko.showdetails
import androidx.compose.runtime.Composable
@Composable
fun SimilarShowsScreen() {
}
| 2 | Kotlin | 1 | 16 | d1f9432b58155a1f1e2deadc569aac122fcdbe83 | 122 | tv-maniac | Apache License 2.0 |
app/src/main/java/com/login/demo/appview/authentication/login/view/LoginFragment.kt | teamSolutionAnalysts | 507,778,254 | false | {"Kotlin": 114748, "Java": 1080} | package com.login.demo.appview.authentication.login.view
import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import com.login.base.base.BaseFragment
import com.login.base.base.IFragmentState
import com.login.base.model.Resource
import com.login.base.model.local.preference.PreferenceManager
import com.login.base.utils.CommonUtils
import com.login.demo.R
import com.login.demo.appview.authentication.login.viewmodel.LoginViewModel
import com.login.demo.appview.authentication.home.view.HomeActivity
import com.login.demo.customview.CustomDialog
import com.login.demo.databinding.FragmentLoginBinding
import com.login.demo.utils.*
import com.login.demo.utils.extension.addFragment
import kotlinx.android.synthetic.main.custom_edittext.view.*
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.android.synthetic.main.toolbar_with_title_lrarrow.*
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
class LoginFragment : BaseFragment() {
private lateinit var mFragmentBinding: FragmentLoginBinding
private val mPreferenceManger by inject<PreferenceManager>()
private val mViewModel by viewModel<LoginViewModel>()
override fun getLayoutId(): Int {
return R.layout.fragment_login
}
override fun preDataBinding(arguments: Bundle?) {
}
override fun postDataBinding(binding: ViewDataBinding): ViewDataBinding {
mFragmentBinding = binding as FragmentLoginBinding
mFragmentBinding.viewModel = mViewModel
mFragmentBinding.lifecycleOwner = this
return mFragmentBinding
}
override fun initializeComponent(view: View?) {
toolbarTitleTxt.visibility = View.GONE
toolbarImgBack.setOnClickListener {
}
customViewClickListeners()
// Handle spinner click event
customMobileNumber?.txtSpinner?.setOnClickListener {
ViewUtils.showCountryPicker(requireContext(),
object : ViewUtils.CountrySelectedListener {
override fun onCountrySelect(countryCode: String) {
mViewModel.countryCode.set(countryCode)
}
})
}
mViewModel.notifyClick.observe(this, Observer {
when (it) {
R.id.btnLogin -> {
if ((requireActivity() as HomeActivity).isNetworkAvailable()) {
if (validateLogInFields()) {
mViewModel.apiLogin()
}
} else {
(requireActivity() as HomeActivity).showSnackBar(R.string.error_no_internet)
}
}
R.id.btnRegister -> {
navigateToRegister()
}
}
})
mViewModel.resultLiveData.observe(this, Observer {
when (it) {
is Resource.Success -> {
ProgressUtils.closeProgressIndicator()
mPreferenceManger.setLoggedIn(true)
(requireActivity() as HomeActivity).addFragment<Any>(
R.id.flContainer,
FragmentState.F_DASHBOARD,
null,
true
)
}
is Resource.Error -> {
//handle progress visibility
ProgressUtils.closeProgressIndicator()
it.error.message?.let { errorMsg ->
ViewUtils.showCustomDialog(requireActivity(),
resources.getString(R.string.app_name),
errorMsg,
resources.getString(R.string.str_ok),
null,
object : CustomDialog.ButtonClickListener {
override fun onPositiveClick(dialog: CustomDialog) {
dialog.dismiss()
}
override fun onNegativeClick(dialog: CustomDialog) {
}
})
}
}
is Resource.Loading -> {
ProgressUtils.showProgressIndicator(context)
}
}
})
}
private fun navigateToRegister() {
(requireActivity() as HomeActivity).addFragment<Any>(
R.id.flContainer,
FragmentState.F_REGISTER,
null,
true
)
}
private fun validateLogInFields(): Boolean {
if (mViewModel.logInFields.mobile.trim().isEmpty()) {
mViewModel.errMobile.set(resources.getString(R.string.error_enter_mobile))
mViewModel.isMobileValid = false
} else if (!CommonUtils.isValidPhoneNumber(
mViewModel.utilPhoneNumberUtil!!,
mViewModel.countryCode.get() + mViewModel.logInFields.mobile
)
) {
mViewModel.errMobile.set(resources.getString(R.string.error_invalid_mobile_num))
mViewModel.isMobileValid = false
} else {
mViewModel.errMobile.set("")
mViewModel.isMobileValid = true
}
if (mViewModel.logInFields.password.trim().isEmpty()) {
mViewModel.errPassword.set(resources.getString(R.string.error_enter_password))
mViewModel.isPasswordValid = false
} else {
mViewModel.errPassword.set("")
mViewModel.isPasswordValid = true
}
return mViewModel.isMobileValid && mViewModel.isPasswordValid
}
private fun customViewClickListeners() {
customPassword.iconRight.setOnClickListener {
if (mViewModel?.isPasswordVisible.value == 1) {
mViewModel?.isPasswordVisible.value = 0
} else {
mViewModel?.isPasswordVisible.value = 1
}
}
}
override fun <T> setUpFragmentConfig(currentState: IFragmentState, keys: T?) {
}
override fun pageVisible() {
}
}
| 0 | Kotlin | 0 | 0 | a0b288cd96a406ba62aff9ca8344ff6b779954bf | 6,294 | android-snippet | Apache License 2.0 |
idea/idea-completion/testData/basic/java/ExtensionFromStandardLibrary.kt | BytesZero | 50,323,841 | true | {"Java": 15985622, "Kotlin": 12340628, "JavaScript": 177557, "Protocol Buffer": 42724, "HTML": 28743, "Lex": 16598, "ANTLR": 9689, "CSS": 9358, "Groovy": 6859, "Shell": 4638, "IDL": 4580, "Batchfile": 3703} | package first
import java.util.HashMap
fun firstFun() {
val a = HashMap<Int, String>()
a.toLinke<caret>
}
// INVOCATION_COUNT: 1
// EXIST: { lookupString:"toLinkedMap", itemText:"toLinkedMap", tailText:"() for Map<K, V> in kotlin" }
// NOTHING_ELSE
| 0 | Java | 0 | 1 | aca19ed27a751d7d6b0d276e7d2cfbf579fe1f87 | 256 | kotlin | Apache License 2.0 |
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/ext/unit/Async.kt | tsegismont | 136,018,012 | false | {"Maven POM": 7, "Ignore List": 1, "EditorConfig": 1, "Text": 1, "Markdown": 1, "JAR Manifest": 2, "Java": 200, "AsciiDoc": 66, "XML": 10, "Java Properties": 1, "Groovy": 14, "Ruby": 27, "Kotlin": 245, "JavaScript": 40, "FreeMarker": 1, "JSON": 1} | package io.vertx.kotlin.ext.unit
import io.vertx.ext.unit.Async
import io.vertx.kotlin.coroutines.awaitResult
/**
* Completion handler to receive a completion signal when this completions completes.
*
* @param completionHandler the completion handler
*
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.unit.Async original] using Vert.x codegen.
*/
suspend fun Async.handlerAwait() : Unit? {
return awaitResult{
this.handler({ ar -> it.handle(ar.mapEmpty()) })}
}
| 1 | null | 1 | 1 | 5bed3976c3e3a08efad73123dcf024e067825c98 | 515 | vertx-base-stack | Apache License 2.0 |
exercises/exercise_13/StepCounter/app/src/main/java/fi/tuni/sinipelto/stepcounter/UserPrompt.kt | sinipelto | 405,707,763 | false | {"Kotlin": 337051, "HTML": 6061, "Java": 1248} | package fi.tuni.sinipelto.stepcounter
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
// Class for creating yes-no, neutral, or non-interactive dialog prompts to the user.
// Allows for either accept-only or both accept/deny dialogs with caller-provided action callbacks
// If no listener is provided for the input (null), the dialog is simply closed when the action is called.
class UserPrompt(
ctx: Context,
private val title: String,
private val message: String,
private val acceptValue: String?,
private val acceptCallback: DialogInterface.OnClickListener?,
private val denyValue: String?,
private val denyCallback: DialogInterface.OnClickListener?,
private val dismissCallback: DialogInterface.OnDismissListener?
) : AlertDialog.Builder(ctx) {
// Set cancellability based on the dialog denial value. If no such provided, cannot cancel
override fun setCancelable(cancelable: Boolean): AlertDialog.Builder {
return super.setCancelable(!denyValue.isNullOrBlank())
}
// Create the dialog display. Showing the dialog is left on caller responsibility
// Call .show() to show the dialog
override fun create(): AlertDialog? {
this.setTitle(title)
this.setMessage(message)
// Both actions (accept/deny) defined
if (acceptValue != null && denyValue != null) {
this.setPositiveButton(acceptValue, acceptCallback)
this.setNegativeButton(denyValue, denyCallback) // denyCallback also NULL
}
// Only single action defined (accept)
else if (denyValue == null) {
this.setNeutralButton(acceptValue, acceptCallback)
}
// else: no actions defined -> must define dismissCallback to close the dialog
else {
this.setOnDismissListener(dismissCallback)
}
return super.create()
}
} | 0 | Kotlin | 0 | 0 | c91c376880f0d1be540266b84d1f57a3a86a8fd9 | 1,935 | android-dev | MIT License |
exercises/exercise_13/StepCounter/app/src/main/java/fi/tuni/sinipelto/stepcounter/UserPrompt.kt | sinipelto | 405,707,763 | false | {"Kotlin": 337051, "HTML": 6061, "Java": 1248} | package fi.tuni.sinipelto.stepcounter
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
// Class for creating yes-no, neutral, or non-interactive dialog prompts to the user.
// Allows for either accept-only or both accept/deny dialogs with caller-provided action callbacks
// If no listener is provided for the input (null), the dialog is simply closed when the action is called.
class UserPrompt(
ctx: Context,
private val title: String,
private val message: String,
private val acceptValue: String?,
private val acceptCallback: DialogInterface.OnClickListener?,
private val denyValue: String?,
private val denyCallback: DialogInterface.OnClickListener?,
private val dismissCallback: DialogInterface.OnDismissListener?
) : AlertDialog.Builder(ctx) {
// Set cancellability based on the dialog denial value. If no such provided, cannot cancel
override fun setCancelable(cancelable: Boolean): AlertDialog.Builder {
return super.setCancelable(!denyValue.isNullOrBlank())
}
// Create the dialog display. Showing the dialog is left on caller responsibility
// Call .show() to show the dialog
override fun create(): AlertDialog? {
this.setTitle(title)
this.setMessage(message)
// Both actions (accept/deny) defined
if (acceptValue != null && denyValue != null) {
this.setPositiveButton(acceptValue, acceptCallback)
this.setNegativeButton(denyValue, denyCallback) // denyCallback also NULL
}
// Only single action defined (accept)
else if (denyValue == null) {
this.setNeutralButton(acceptValue, acceptCallback)
}
// else: no actions defined -> must define dismissCallback to close the dialog
else {
this.setOnDismissListener(dismissCallback)
}
return super.create()
}
} | 0 | Kotlin | 0 | 0 | c91c376880f0d1be540266b84d1f57a3a86a8fd9 | 1,935 | android-dev | MIT License |
app/src/main/java/com/example/efpro/notizen/Activities/LoginActivity.kt | diegoestradaXO | 171,679,139 | false | null | package com.example.efpro.notizen.Activities
/*This is an activity from Firebase al copyrights reserved*/
/*We took these activity from Firebase and make some changes*/
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.example.efpro.notizen.R
import com.example.efpro.notizen.ViewHolder.NoteViewModel
import com.example.efpro.notizen.models.User
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import kotlinx.android.synthetic.main.activity_emailpassword.*
class LoginActivity : AppCompatActivity(), View.OnClickListener {
// [START declare_auth]
private lateinit var auth: FirebaseAuth
// [END declare_auth]
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_emailpassword)
// Buttons
emailSignInButton.setOnClickListener(this)
emailCreateAccountButton.setOnClickListener(this)
signOutButton.setOnClickListener(this)
verifyEmailButton.setOnClickListener(this)
// [START initialize_auth]
// Initialize Firebase Auth
auth = FirebaseAuth.getInstance()
// [END initialize_auth]
}
// [START on_start_check_user]
public override fun onStart() {
super.onStart()
val currentUser = auth.currentUser
// Check if user is signed in (non-null) and update UI accordingly.
if(currentUser!=null){
val intento = Intent(this, navigate::class.java)//Redirigimos a contactos
when {
intent?.action == Intent.ACTION_SEND -> {
if ("text/plain" == intent.type) {
val message = intent.getStringExtra(Intent.EXTRA_TEXT)
intento.putExtra("content",message)
}
}
}
startActivity(intento)
this.finish()
}
updateUI(currentUser)
}
// [END on_start_check_user]
//Function to create account, requires an email and password
private fun createAccount(email: String, password: String) {
if (!validateForm()) {
return
}
//showProgressDialog()
// [START create_user_with_email]
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success")
val user = auth.currentUser
Toast.makeText(this,"DON´T FORGET TO SEND VERIFICATION EMAIL",Toast.LENGTH_LONG).show()
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.exception)
Toast.makeText(baseContext, "Authentication failed, probably this email is already in use",
Toast.LENGTH_SHORT).show()
updateUI(null)
}
// [START_EXCLUDE]
//hideProgressDialog()
// [END_EXCLUDE]
}
// [END create_user_with_email]
}
//Function to Sign In, in order to get into the app, the user must fill the spaces
private fun signIn(email: String, password: String) {
Log.d(TAG, "signIn:$email")
if (!validateForm()) {
return
}
//showProgressDialog()
// [START sign_in_with_email]
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success")
val user = auth.currentUser
updateUI(user)
val intento = Intent(this, navigate::class.java)//Redirigimos a contactos
startActivity(intento)
this.finish()
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.exception)
Toast.makeText(baseContext, "Authentication failed.",
Toast.LENGTH_SHORT).show()
updateUI(null)
}
// [START_EXCLUDE]
if (!task.isSuccessful) {
status.setText(R.string.auth_failed)
}
//hideProgressDialog()
// [END_EXCLUDE]
}
// [END sign_in_with_email]
}
private fun signOut() {
auth.signOut()
updateUI(null)
}
//After the user filled the spaces with the info required, a verification msg is sent to the user´s mail
//The user must click the verification URL in order to sign In
private fun sendEmailVerification() {
// Disable button
verifyEmailButton.isEnabled = false
// Send verification email
// [START send_email_verification]
val user = auth.currentUser
user?.sendEmailVerification()
?.addOnCompleteListener(this) { task ->
// [START_EXCLUDE]
// Re-enable button
verifyEmailButton.isEnabled = true
if (task.isSuccessful) {
Toast.makeText(baseContext,
"Verification email sent to ${user.email} ",
Toast.LENGTH_SHORT).show()
} else {
Log.e(TAG, "sendEmailVerification", task.exception)
Toast.makeText(baseContext,
"Failed to send verification email.",
Toast.LENGTH_SHORT).show()
}
// [END_EXCLUDE]
}
// [END send_email_verification]
}
//This function is used in the Sign In fun. Verify if the user has filled the text fields, if
//not, the fun returns false, and the sign in can not be completed
private fun validateForm(): Boolean {
var valid = true
val email = fieldEmail.text.toString()
if (TextUtils.isEmpty(email)) {
fieldEmail.error = "Required."
valid = false
} else {
fieldEmail.error = null
}
val password = fieldPassword.text.toString()
if (TextUtils.isEmpty(password)) {
fieldPassword.error = "Required."
valid = false
} else {
fieldPassword.error = null
}
return valid
}
private fun updateUI(user: FirebaseUser?) {
//hideProgressDialog()
if (user != null) {
status.text = getString(R.string.emailpassword_status_fmt,
user.email, user.isEmailVerified)
detail.text = getString(R.string.firebase_status_fmt, user.uid)
emailPasswordButtons.visibility = View.GONE
emailPasswordFields.visibility = View.GONE
signedInButtons.visibility = View.VISIBLE
verifyEmailButton.isEnabled = !user.isEmailVerified
} else {
status.setText(R.string.signed_out)
detail.text = null
emailPasswordButtons.visibility = View.VISIBLE
emailPasswordFields.visibility = View.VISIBLE
signedInButtons.visibility = View.GONE
}
}
//Adds the new Acount to the global list in the DB
private fun writeNewUser(){
var mDatabase = FirebaseDatabase.getInstance().reference
val user = auth.currentUser
val seguidores = listOf<String>(user!!.uid)
val seguidos= listOf<String>(user.uid)
val newuser= User(user.uid, user.email!!,"NoBiography","UnNamed",seguidores,seguidos)
mDatabase.child("users").child(user.uid).setValue(newuser)
}
override fun onClick(v: View) {
val i = v.id
when (i) {
R.id.emailCreateAccountButton -> createAccount(fieldEmail.text.toString(), fieldPassword.text.toString())
R.id.emailSignInButton -> signIn(fieldEmail.text.toString(), fieldPassword.text.toString())
R.id.signOutButton -> signOut()
R.id.verifyEmailButton -> {
sendEmailVerification()
writeNewUser()
}
}
}
companion object {
private const val TAG = "EmailPassword"
}
} | 0 | Kotlin | 0 | 0 | 27c280c3e013c97195609c394e561ec9519f2928 | 9,178 | Notizen-App | MIT License |
ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/NettyRequestQueue.kt | LloydFinch | 166,520,021 | false | null | package io.ktor.server.netty.cio
import io.ktor.server.netty.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.internal.*
import java.util.concurrent.atomic.*
internal class NettyRequestQueue(internal val readLimit: Int, internal val runningLimit: Int) {
init {
require(readLimit > 0) { "readLimit should be positive: $readLimit" }
require(runningLimit > 0) { "executeLimit should be positive: $runningLimit" }
}
private val incomingQueue = Channel<CallElement>(Channel.UNLIMITED)
val elements: ReceiveChannel<CallElement> = incomingQueue
fun schedule(call: NettyApplicationCall) {
val element = CallElement(call)
try {
incomingQueue.offer(element)
} catch (t: Throwable) {
element.tryDispose()
}
}
fun close() {
incomingQueue.close()
}
fun cancel() {
incomingQueue.close()
while (true) {
incomingQueue.poll()?.tryDispose() ?: break
}
}
fun canRequestMoreEvents(): Boolean = incomingQueue.isEmpty
@UseExperimental(InternalCoroutinesApi::class)
internal class CallElement(val call: NettyApplicationCall) : LockFreeLinkedListNode() {
@kotlin.jvm.Volatile
private var scheduled: Int = 0
fun ensureRunning(): Boolean {
if (Scheduled.compareAndSet(this, 0, 1)) {
call.context.fireChannelRead(call)
return true
}
return scheduled == 1
}
fun tryDispose() {
if (Scheduled.compareAndSet(this, 0, 2)) {
call.dispose()
}
}
companion object {
private val Scheduled = AtomicIntegerFieldUpdater.newUpdater(CallElement::class.java, CallElement::scheduled.name)!!
}
}
}
| 0 | null | 0 | 2 | 9b9fc6c3b853c929a806c65cf6bf7c104b4c07fc | 1,867 | ktor | Apache License 2.0 |
kotlin.web.demo.server/examples/Kotlin in Action/Chapter 6/6.3/5_3_Arrays2.kt | arrow-kt | 117,599,238 | false | null | package ch06.ex3_5_3_Arrays2
fun main(args: Array<String>) {
val strings = listOf("a", "b", "c")
println("%s/%s/%s".format(*strings.toTypedArray()))
}
| 2 | null | 4 | 7 | 7165d9568d725c9784a1e7525f35bab93241f292 | 160 | try.arrow-kt.io | Apache License 2.0 |
app/src/test/java/com/example/adidaschallenge/models/ProductTest.kt | Mansourx | 364,721,597 | false | null | package com.example.adidaschallenge.models
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
/**
* Created by <NAME> on 5/8/21
* Dubai, UAE.
*/
class ProductTest {
private var mCurrency = "EU"
private var mPrice = 300
private var mId = "F123"
private var mName = "Adidas"
private var mDescription = "Adidas Floy Floy is the Full Natural Material"
private var mImageUrl = ""
@MockK
lateinit var productModel: Product
@Before
fun setup() {
MockKAnnotations.init(this)
productModel.apply {
every { currency } returns mCurrency
every { price } returns mPrice
every { id } returns mId
every { name } returns mName
every { description } returns mDescription
every { imgUrl } returns mImageUrl
}
}
@Test
fun getCurrency() {
val expected = mCurrency
val actual = productModel.currency
assertThat(actual).isEqualTo(expected)
}
@Test
fun getPrice() {
val expected = mPrice
val actual = productModel.price
assertThat(actual).isEqualTo(expected)
}
@Test
fun getId() {
val expected = mId
val actual = productModel.id
assertThat(actual).isEqualTo(expected)
}
@Test
fun getName() {
val expected = mName
val actual = productModel.name
assertThat(actual).isEqualTo(expected)
}
@Test
fun getDescription() {
val expected = mDescription
val actual = productModel.description
assertThat(actual).isEqualTo(expected)
}
@Test
fun getImgUrl() {
val expected = mImageUrl
val actual = productModel.imgUrl
assertThat(actual).isEqualTo(expected)
}
@Test
fun getCurrencyIncorrect() {
val expected = "mCurrency"
val actual = productModel.currency
assertThat(actual).isNotEqualTo(expected)
}
@Test
fun getPriceIncorrect() {
val expected = "mPrice"
val actual = productModel.price
assertThat(actual).isNotEqualTo(expected)
}
@Test
fun getIdIncorrect() {
val expected = "mId"
val actual = productModel.id
assertThat(actual).isNotEqualTo(expected)
}
@Test
fun getNameIncorrect() {
val expected = "mName"
val actual = productModel.name
assertThat(actual).isNotEqualTo(expected)
}
@Test
fun getDescriptionIncorrect() {
val expected = "mDescription"
val actual = productModel.description
assertThat(actual).isNotEqualTo(expected)
}
@Test
fun getImgUrlIncorrect() {
val expected = "mImageUrl"
val actual = productModel.imgUrl
assertThat(actual).isNotEqualTo(expected)
}
@After
fun teardown() {
}
} | 0 | Kotlin | 0 | 1 | 08c60ebc9453a7a85c6acca778dc265e8f813cc2 | 3,029 | Adidas-App | Apache License 2.0 |
validk-micronaut/sample-project/src/main/kotlin/com/test/controller/rest/RestManualValidation.kt | cosmin-marginean | 632,603,727 | false | null | package com.test.controller.rest
import com.test.controller.CreateUserForm
import io.micronaut.http.HttpResponse
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.*
import io.validk.micronaut.validateRequest
@Controller
class RestManualValidation {
@Post("/users/create/manual-validation")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
fun createUser(@Body form: CreateUserForm): HttpResponse<*> {
return form.validateRequest(
onErrors = { HttpResponse.badRequest(mapOf("message" to "This won't fly")) },
onSuccess = { HttpResponse.ok(mapOf("success" to true)) }
)
}
}
| 0 | Kotlin | 0 | 3 | 97d42924b219997e1c19cf5fb12fd43d03e5830c | 653 | validk | Apache License 2.0 |
server/src/ru/spbstu/gyboml/server/session/SessionListener.kt | zhenyatos | 240,080,036 | false | {"Java": 217578, "PLSQL": 19910, "Kotlin": 12390} | package ru.spbstu.gyboml.server.session
import com.esotericsoftware.kryonet.Connection
import com.esotericsoftware.kryonet.Listener
import ru.spbstu.gyboml.core.Player
import ru.spbstu.gyboml.core.PlayerType.FIRST_PLAYER
import ru.spbstu.gyboml.core.PlayerType.SECOND_PLAYER
import ru.spbstu.gyboml.core.net.SessionRequests
import ru.spbstu.gyboml.core.net.SessionResponses
import ru.spbstu.gyboml.core.net.SessionResponses.NameRegistred
import ru.spbstu.gyboml.server.Controller
import ru.spbstu.gyboml.server.GybomlConnection
import ru.spbstu.gyboml.server.game.Game
class SessionListener(private val controller: Controller) : Listener() {
override fun disconnected(connection: Connection?) {
connection as GybomlConnection
connection.player?.let {
if (connection.inSession) {
controller.removeFromSession(it.sessionId, it.type)
controller.notifyAllPlayers()
}
}
}
override fun received(connection: Connection?, request: Any?) {
connection as GybomlConnection
if (connection.player == null && request !is SessionRequests.RegisterName) return
when (request) {
is SessionRequests.RegisterName ->
registerName(connection, request.playerName)
is SessionRequests.GetSessions ->
controller.notifyOne(connection)
is SessionRequests.ConnectSession ->
connectSession(connection, controller.getSession(request.sessionId) ?: return)
is SessionRequests.ExitSession ->
exitSession(connection, request.player)
is SessionRequests.CreateSession ->
createSession(connection, request.sessionName)
is SessionRequests.Ready ->
setReady(connection, controller.getSession(request.player.sessionId) ?: return, request.player.ready)
}
}
private fun registerName(connection: GybomlConnection, name: String) {
with (connection) {
player = Player(name, FIRST_PLAYER)
sendTCP(NameRegistred())
}
}
private fun connectSession(connection: GybomlConnection, session: Session) = with (connection) {
if (session.spaces() == 0) return@with
player?.let {
it.ready = false
it.setSessionId(session.id)
inSession = true
session.add(connection, it)
sendTCP(SessionResponses.SessionConnected(it))
controller.notifyAllPlayers()
}
}
private fun exitSession(connection: GybomlConnection, player: Player) = with (connection) {
inSession = false
controller.removeFromSession(player.sessionId, player.type)
sendTCP(SessionResponses.SessionExited())
controller.notifyAllPlayers()
}
private fun createSession(connection: GybomlConnection, name: String) = with (connection) {
connection.sendTCP(SessionResponses.SessionCreated(controller.addSession(name)))
controller.notifyAllPlayers()
}
private fun setReady(connection: GybomlConnection, session: Session, ready: Boolean) = with(connection) {
player?.let {
session.setReady(it.type, !ready)
sendTCP(SessionResponses.ReadyApproved(!ready))
controller.notifySessionPlayers(it.sessionId)
startGameIfReady(session.firstPlayer ?: return@let, session.secondPlayer ?: return@let, session)
}
}
private fun startGameIfReady(firstPlayer: NetPlayer, secondPlayer: NetPlayer, session: Session) = with(session) {
firstPlayer.player?.let {first ->
secondPlayer.player?.let {second ->
if (first.ready && second.ready) {
first.type = FIRST_PLAYER
second.type = SECOND_PLAYER
first.ready = false
second.ready = false
firstPlayer.connection.sendTCP(SessionResponses.SessionStarted(first))
secondPlayer.connection.sendTCP(SessionResponses.SessionStarted(second))
game = Game(first, second)
}
}}
}
} | 1 | Java | 0 | 2 | 7f9c05c8ed5af43405b7e6f2abf8358a5be47c5a | 4,144 | GYBoML | MIT License |
networksurvey/src/main/java/com/craxiom/networksurvey/ui/wifi/WifiSpectrumScreen.kt | christianrowlands | 156,117,885 | false | null | package com.craxiom.networksurvey.ui.wifi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.craxiom.networksurvey.fragments.WifiSpectrumFragment
import com.craxiom.networksurvey.ui.wifi.model.CHANNELS_2_4_GHZ
import com.craxiom.networksurvey.ui.wifi.model.CHANNELS_2_4_GHZ_CHART_VIEW
import com.craxiom.networksurvey.ui.wifi.model.CHANNELS_5_GHZ_GROUP_1
import com.craxiom.networksurvey.ui.wifi.model.CHANNELS_5_GHZ_GROUP_1_CHART_VIEW
import com.craxiom.networksurvey.ui.wifi.model.CHANNELS_5_GHZ_GROUP_2
import com.craxiom.networksurvey.ui.wifi.model.CHANNELS_5_GHZ_GROUP_2_CHART_VIEW
import com.craxiom.networksurvey.ui.wifi.model.CHANNELS_5_GHZ_GROUP_3
import com.craxiom.networksurvey.ui.wifi.model.CHANNELS_5_GHZ_GROUP_3_CHART_VIEW
import com.craxiom.networksurvey.ui.wifi.model.WifiSpectrum24ViewModel
import com.craxiom.networksurvey.ui.wifi.model.WifiSpectrum5Group1ViewModel
import com.craxiom.networksurvey.ui.wifi.model.WifiSpectrum5Group2ViewModel
import com.craxiom.networksurvey.ui.wifi.model.WifiSpectrum5Group3ViewModel
import com.craxiom.networksurvey.ui.wifi.model.WifiSpectrumScreenViewModel
/**
* A Compose screen that shows the usage of the Wi-Fi spectrum.
*/
@Composable
internal fun WifiSpectrumScreen(
screenViewModel: WifiSpectrumScreenViewModel,
viewModel24Ghz: WifiSpectrum24ViewModel,
viewModel5GhzGroup1: WifiSpectrum5Group1ViewModel,
viewModel5GhzGroup2: WifiSpectrum5Group2ViewModel,
viewModel5GhzGroup3: WifiSpectrum5Group3ViewModel,
wifiSpectrumFragment: WifiSpectrumFragment
) {
val scanRate by screenViewModel.scanRate.collectAsStateWithLifecycle()
LazyColumn(
state = rememberLazyListState(),
contentPadding = PaddingValues(padding),
verticalArrangement = Arrangement.spacedBy(padding),
) {
chartItems(
viewModel24Ghz,
viewModel5GhzGroup1,
viewModel5GhzGroup2,
viewModel5GhzGroup3,
scanRate,
wifiSpectrumFragment
)
}
}
private fun LazyListScope.chartItems(
viewModel24Ghz: WifiSpectrum24ViewModel,
viewModel5GhzGroup1: WifiSpectrum5Group1ViewModel,
viewModel5GhzGroup2: WifiSpectrum5Group2ViewModel,
viewModel5GhzGroup3: WifiSpectrum5Group3ViewModel,
scanRate: Int,
wifiSpectrumFragment: WifiSpectrumFragment
) {
item {
Card(
modifier = Modifier
.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = CardDefaults.elevatedCardColors()
) {
Row(
modifier = Modifier
.padding(horizontal = padding)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
Text(
text = "Scan Rate: ",
style = MaterialTheme.typography.labelMedium
)
Text(
text = "$scanRate seconds",
style = MaterialTheme.typography.titleMedium
)
Spacer(modifier = Modifier.weight(1f))
ScanRateInfoButton()
OpenSettingsBtn(wifiSpectrumFragment)
}
}
}
cardItem {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Wi-Fi 2.4 GHz Spectrum",
style = MaterialTheme.typography.titleMedium
)
val wifiList by viewModel24Ghz.wifiNetworkInfoList.collectAsStateWithLifecycle()
WifiSpectrumChart(
wifiList, viewModel24Ghz.modelProducer,
CHANNELS_2_4_GHZ_CHART_VIEW[0].toFloat(),
CHANNELS_2_4_GHZ_CHART_VIEW[CHANNELS_2_4_GHZ_CHART_VIEW.size - 1].toFloat(),
CHANNELS_2_4_GHZ
)
}
}
cardItem {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Wi-Fi 5 GHz Group 1",
style = MaterialTheme.typography.titleMedium
)
val wifiList by viewModel5GhzGroup1.wifiNetworkInfoList.collectAsStateWithLifecycle()
WifiSpectrumChart(
wifiList,
viewModel5GhzGroup1.modelProducer,
CHANNELS_5_GHZ_GROUP_1_CHART_VIEW[0].toFloat(),
CHANNELS_5_GHZ_GROUP_1_CHART_VIEW[CHANNELS_5_GHZ_GROUP_1_CHART_VIEW.size - 1].toFloat(),
CHANNELS_5_GHZ_GROUP_1
)
}
}
cardItem {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Wi-Fi 5 GHz Group 2",
style = MaterialTheme.typography.titleMedium
)
val wifiList by viewModel5GhzGroup2.wifiNetworkInfoList.collectAsStateWithLifecycle()
WifiSpectrumChart(
wifiList,
viewModel5GhzGroup2.modelProducer,
CHANNELS_5_GHZ_GROUP_2_CHART_VIEW[0].toFloat(),
CHANNELS_5_GHZ_GROUP_2_CHART_VIEW[CHANNELS_5_GHZ_GROUP_2_CHART_VIEW.size - 1].toFloat(),
CHANNELS_5_GHZ_GROUP_2,
everyOtherLabel = true
)
}
}
cardItem {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Wi-Fi 5 GHz Group 3",
style = MaterialTheme.typography.titleMedium
)
val wifiList by viewModel5GhzGroup3.wifiNetworkInfoList.collectAsStateWithLifecycle()
WifiSpectrumChart(
wifiList,
viewModel5GhzGroup3.modelProducer,
CHANNELS_5_GHZ_GROUP_3_CHART_VIEW[0].toFloat(),
CHANNELS_5_GHZ_GROUP_3_CHART_VIEW[CHANNELS_5_GHZ_GROUP_3_CHART_VIEW.size - 1].toFloat(),
CHANNELS_5_GHZ_GROUP_3
)
}
}
}
private fun LazyListScope.cardItem(content: @Composable () -> Unit) {
item {
Card(shape = MaterialTheme.shapes.large, colors = CardDefaults.elevatedCardColors()) {
Box(Modifier.padding(padding)) {
content()
}
}
}
}
@Composable
fun OpenSettingsBtn(fragment: WifiSpectrumFragment) {
IconButton(onClick = {
fragment.navigateToSettings()
}) {
Icon(
Icons.Default.Settings,
contentDescription = "Settings Button",
)
}
}
private val padding = 16.dp
| 5 | null | 25 | 95 | 866b838da2d2fd74e343d6f153ab9f869a255e4a | 7,764 | android-network-survey | Apache License 2.0 |
src/main/kotlin/api/utils/Documents.kt | sszuev | 118,141,450 | false | null | package com.github.sszuev.ontconverter.api.utils
import com.github.owlcs.ontapi.OntFormat
import com.github.owlcs.ontapi.OntGraphDocumentSource
import org.apache.jena.graph.Graph
import org.semanticweb.owlapi.io.FileDocumentSource
import org.semanticweb.owlapi.io.IRIDocumentSource
import org.semanticweb.owlapi.io.OWLOntologyDocumentSource
import org.semanticweb.owlapi.model.IRI
import java.nio.file.Path
/**
* Creates a document-source from [file] and [format].
*
* @param [file][Path]
* @param [format][OntFormat] or `null`
* @return [OWLOntologyDocumentSource]
*/
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") // in owl-api:5.1.20, OWLDocumentFormat can be null
@Throws(java.lang.RuntimeException::class)
fun createSource(file: Path, format: OntFormat?): OWLOntologyDocumentSource {
return FileDocumentSource(file.toFile(), format?.createOwlFormat())
}
/**
* Creates a document-source from [iri] and [format].
*
* @param [iri][IRI]
* @param [format][OntFormat] or `null`
* @return [OWLOntologyDocumentSource]
*/
fun createSource(iri: IRI, format: OntFormat?): OWLOntologyDocumentSource {
if (iri.scheme == "file") {
return createSource(Path.of(iri.toURI()), format)
}
return IRIDocumentSource(iri, format?.createOwlFormat(), null)
}
/**
* Creates a document-source from [iri] and [graph].
*
* @param [iri][IRI]
* @param [graph][Graph]
* @return [OWLOntologyDocumentSource]
*/
fun createSource(iri: IRI, graph: Graph): OWLOntologyDocumentSource {
return object : OntGraphDocumentSource() {
override fun getDocumentIRI(): IRI {
return iri
}
override fun getGraph(): Graph {
return graph
}
}
} | 1 | Kotlin | 7 | 19 | eb2d0c6dc9f6fa3c2113f6003ff8f2fb3cbfcb76 | 1,720 | ont-converter | Apache License 2.0 |
app/src/main/java/com/mobjoy/gemini_tryout/MainActivity.kt | MohamedElattar22 | 737,571,461 | false | {"Kotlin": 4279} | package com.mobjoy.gemini_tryout
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.view.WindowCompat
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.google.ai.client.generativeai.GenerativeModel
import com.mobjoy.gemini_tryout.databinding.ActivityMainBinding
import com.mobjoy.gemini_tryout.viewMolde.MainViewModel
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private lateinit var viewBinding : ActivityMainBinding
private lateinit var viewModel : MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewBinding = ActivityMainBinding.inflate(layoutInflater)
viewModel = ViewModelProvider(this)[MainViewModel::class.java]
viewBinding.vm = viewModel
viewBinding.lifecycleOwner = this
setContentView(viewBinding.root)
}
override fun onStart() {
super.onStart()
}
private suspend fun modelCall(){
val generativeModel = modelIntialize.intializeModel()
viewBinding.generateBtn.setOnClickListener {
val prompt = viewBinding.promptText.text.toString()
lifecycleScope.launch {
val response = generativeModel.generateContent(prompt)
viewBinding.HeaderTV.text = prompt
viewBinding.prombotAnswerTV.text = response.text
viewBinding.promptText.text = null
}
}
}
} | 0 | Kotlin | 0 | 0 | 874d91b5b4ab86e3e48cf6b60e5582b04499ca5a | 1,631 | Gemini_Tryout | MIT License |
.teamcity/settings.kts | DTS-STN | 462,800,260 | false | {"JavaScript": 123975, "Kotlin": 15339, "Mustache": 1688, "Dockerfile": 1033, "CSS": 609, "Shell": 312} | import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.dockerCommand
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.script
import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.vcs
import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.schedule
import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.ScheduleTrigger
/*
The settings script is an entry point for defining a TeamCity
project hierarchy. The script should contain a single call to the
project() function with a Project instance or an init function as
an argument.
VcsRoots, BuildTypes, Templates, and subprojects can be
registered inside the project using the vcsRoot(), buildType(),
template(), and subProject() methods respectively.
To debug settings scripts in command-line, run the
mvnDebug org.jetbrains.teamcity:teamcity-configs-maven-plugin:generate
command and attach your debugger to the port 8000.
To debug in IntelliJ Idea, open the 'Maven Projects' tool window (View
-> Tool Windows -> Maven Projects), find the generate task node
(Plugins -> teamcity-configs -> teamcity-configs:generate), the
'Debug' option is available in the context menu for the task.
*/
version = "2020.2"
project {
vcsRoot(Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerRelease)
vcsRoot(Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerDynamic)
vcsRoot(Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerPerformance)
vcsRoot(Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerProduction)
buildType(Build_Performance)
buildType(Build_Production)
buildType(Build_Release)
buildType(Build_Dynamic)
buildType(CleanUpWeekly)
}
object Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerRelease : GitVcsRoot({
name = "https://github.com/DTS-STN/scrum-poker/tree/_release"
url = "<EMAIL>:DTS-STN/Scrum-Poker.git"
branch = "refs/heads/main"
branchSpec = "+:refs/heads/main"
authMethod = uploadedKey {
userName = "git"
uploadedKey = "dtsrobot"
}
})
object Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerDynamic : GitVcsRoot({
name = "https://github.com/DTS-STN/scrum-poker/tree/_dynamic"
url = "<EMAIL>:DTS-STN/Scrum-Poker.git"
branch = "refs/heads/main"
branchSpec = "+:refs/heads/*"
authMethod = uploadedKey {
userName = "git"
uploadedKey = "dtsrobot"
}
})
object Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerPerformance : GitVcsRoot({
name = "https://github.com/DTS-STN/scrum-poker/tree/_performance"
url = "[email protected]:DTS-STN/Scrum-Poker.git"
branch = "refs/heads/main"
branchSpec = "+:refs/heads/main"
authMethod = uploadedKey {
userName = "git"
uploadedKey = "dtsrobot"
}
})
object Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerProduction : GitVcsRoot({
name = "https://github.com/DTS-STN/scrum-poker/tree/_production"
url = "[email protected]:DTS-STN/Scrum-Poker.git"
useTagsAsBranches = true
branch = "refs/heads/main"
branchSpec = "+:refs/tags/*"
authMethod = uploadedKey {
userName = "git"
uploadedKey = "dtsrobot"
}
})
/* Try and keep env.PROJECT value will be used throughout the helm scripts */
/* to build urls, name the application and many other things. folders and files in the */
/* helmfile directory should also match this value. */
object Build_Release: BuildType({
name = "Build_Release"
description = "Builds and deploys our main branch on update to main url"
params {
param("teamcity.vcsTrigger.runBuildInNewEmptyBranch", "true")
param("env.PROJECT", "scrum-poker")
param("env.BASE_DOMAIN","bdm-dev.dts-stn.com")
param("env.SUBSCRIPTION", "%vault:dts-sre/data/azure!/decd-dev-subscription-id%")
param("env.K8S_CLUSTER_NAME", "ESdCDPSBDMK8SDev-K8S")
param("env.RG_DEV", "ESdCDPSBDMK8SDev")
param("env.TARGET", "main")
param("env.BRANCH", "main")
param("env.NEXT_PUBLIC_GRAPHQL_HTTP", "%vault:dts-secrets-dev/data/scrumPoker!/NEXT_PUBLIC_GRAPHQL_HTTP%")
param("env.NEXT_PUBLIC_GRAPHQL_WS", "%vault:dts-secrets-dev/data/scrumPoker!/NEXT_PUBLIC_GRAPHQL_WS%")
}
vcs {
root(Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerRelease)
}
steps {
dockerCommand {
name = "Build & Tag Docker Image"
commandType = build {
source = file {
path = "Dockerfile"
}
namesAndTags = "%env.ACR_DOMAIN%/%env.PROJECT%:%env.DOCKER_TAG%"
commandArgs = "--pull --build-arg NEXT_BUILD_DATE=%system.build.start.date% --build-arg TC_BUILD=%build.number% --build-arg NEXT_PUBLIC_GRAPHQL_HTTP=%env.NEXT_PUBLIC_GRAPHQL_HTTP% --build-arg NEXT_PUBLIC_GRAPHQL_WS=%env.NEXT_PUBLIC_GRAPHQL_WS%"
}
}
script {
name = "Login to Azure and ACR"
scriptContent = """
az login --service-principal -u %TEAMCITY_USER% -p %TEAMCITY_PASS% --tenant %env.TENANT-ID%
az account set -s %env.SUBSCRIPTION%
az acr login -n MTSContainers
""".trimIndent()
}
dockerCommand {
name = "Push Image to ACR"
commandType = push {
namesAndTags = "%env.ACR_DOMAIN%/%env.PROJECT%:%env.DOCKER_TAG%"
}
}
script {
name = "Deploy w/ Helmfile"
scriptContent = """
cd ./helmfile
az account set -s %env.SUBSCRIPTION%
az aks get-credentials --overwrite-existing --admin --resource-group %env.RG_DEV% --name %env.K8S_CLUSTER_NAME%
helmfile -e %env.TARGET% apply
""".trimIndent()
}
}
triggers {
vcs {
branchFilter = "+:*"
}
}
})
object Build_Production: BuildType({
name = "Build_Production"
description = "Pushes release tags as defacto production builds"
params {
param("teamcity.vcsTrigger.runBuildInNewEmptyBranch", "true")
param("env.PROJECT", "scrum-poker")
param("env.BASE_DOMAIN","bdm-dev.dts-stn.com")
param("env.SUBSCRIPTION", "%vault:dts-sre/data/azure!/decd-dev-subscription-id%")
param("env.K8S_CLUSTER_NAME", "ESdCDPSBDMK8SDev-K8S")
param("env.RG_DEV", "ESdCDPSBDMK8SDev")
param("env.TARGET", "prod")
param("env.BRANCH", "prod")
param("env.NEXT_PUBLIC_GRAPHQL_HTTP", "%vault:dts-secrets-dev/data/scrumPoker!/NEXT_PUBLIC_GRAPHQL_HTTP_PROD%")
param("env.NEXT_PUBLIC_GRAPHQL_WS", "%vault:dts-secrets-dev/data/scrumPoker!/NEXT_PUBLIC_GRAPHQL_WS_PROD%")
}
vcs {
root(Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerProduction)
}
steps {
dockerCommand {
name = "Build & Tag Docker Image"
commandType = build {
source = file {
path = "Dockerfile"
}
namesAndTags = "%env.ACR_DOMAIN%/%env.PROJECT%:%env.DOCKER_TAG%"
commandArgs = "--pull --build-arg NEXT_BUILD_DATE=%system.build.start.date% --build-arg TC_BUILD=%build.number% --build-arg NEXT_PUBLIC_GRAPHQL_HTTP=%env.NEXT_PUBLIC_GRAPHQL_HTTP% --build-arg NEXT_PUBLIC_GRAPHQL_WS=%env.NEXT_PUBLIC_GRAPHQL_WS%"
}
}
script {
name = "Login to Azure and ACR"
scriptContent = """
az login --service-principal -u %TEAMCITY_USER% -p %TEAMCITY_PASS% --tenant %env.TENANT-ID%
az account set -s %env.SUBSCRIPTION%
az acr login -n MTSContainers
""".trimIndent()
}
dockerCommand {
name = "Push Image to ACR"
commandType = push {
namesAndTags = "%env.ACR_DOMAIN%/%env.PROJECT%:%env.DOCKER_TAG%"
}
}
script {
name = "Deploy w/ Helmfile"
scriptContent = """
cd ./helmfile
az account set -s %env.SUBSCRIPTION%
az aks get-credentials --overwrite-existing --admin --resource-group %env.RG_DEV% --name %env.K8S_CLUSTER_NAME%
helmfile -e %env.TARGET% apply
""".trimIndent()
}
}
triggers {
vcs {
branchFilter = """
+:*
-:refs/heads/main
""".trimIndent()
}
}
})
object Build_Dynamic: BuildType({
name = "Build_Dynamic"
description = "Dynamic branching; builds and deploys every branch"
params {
param("teamcity.vcsTrigger.runBuildInNewEmptyBranch", "true")
param("env.PROJECT", "scrum-poker")
param("env.BASE_DOMAIN","bdm-dev.dts-stn.com")
param("env.SUBSCRIPTION", "%vault:dts-sre/data/azure!/decd-dev-subscription-id%")
param("env.K8S_CLUSTER_NAME", "ESdCDPSBDMK8SDev-K8S")
param("env.RG_DEV", "ESdCDPSBDMK8SDev")
param("env.TARGET", "main")
param("env.BRANCH", "dyna-%teamcity.build.branch%")
param("env.NEXT_PUBLIC_GRAPHQL_HTTP", "%vault:dts-secrets-dev/data/scrumPoker!/NEXT_PUBLIC_GRAPHQL_HTTP%")
param("env.NEXT_PUBLIC_GRAPHQL_WS", "%vault:dts-secrets-dev/data/scrumPoker!/NEXT_PUBLIC_GRAPHQL_WS%")
}
vcs {
root(Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerDynamic)
}
steps {
dockerCommand {
name = "Build & Tag Docker Image"
commandType = build {
source = file {
path = "Dockerfile"
}
namesAndTags = "%env.ACR_DOMAIN%/%env.PROJECT%:%env.DOCKER_TAG%"
commandArgs = "--pull --build-arg NEXT_BUILD_DATE=%system.build.start.date% --build-arg TC_BUILD=%build.number% --build-arg NEXT_PUBLIC_GRAPHQL_HTTP=%env.NEXT_PUBLIC_GRAPHQL_HTTP% --build-arg NEXT_PUBLIC_GRAPHQL_WS=%env.NEXT_PUBLIC_GRAPHQL_WS%"
}
}
script {
name = "Login to Azure and ACR"
scriptContent = """
az login --service-principal -u %TEAMCITY_USER% -p %TEAMCITY_PASS% --tenant %env.TENANT-ID%
az account set -s %env.SUBSCRIPTION%
az acr login -n MTSContainers
""".trimIndent()
}
dockerCommand {
name = "Push Image to ACR"
commandType = push {
namesAndTags = "%env.ACR_DOMAIN%/%env.PROJECT%:%env.DOCKER_TAG%"
}
}
script {
name = "Deploy w/ Helmfile"
scriptContent = """
cd ./helmfile
az account set -s %env.SUBSCRIPTION%
az aks get-credentials --overwrite-existing --admin --resource-group %env.RG_DEV% --name %env.K8S_CLUSTER_NAME%
helmfile -e %env.TARGET% apply
""".trimIndent()
}
}
triggers {
vcs {
branchFilter = """
+:*
-:main
-:gh-pages
""".trimIndent()
}
}
})
object Build_Performance: BuildType({
name = "Build_Performance"
description = "Builds and deploys our main branch on update to perf url"
params {
param("teamcity.vcsTrigger.runBuildInNewEmptyBranch", "true")
param("env.PROJECT", "scrum-poker")
param("env.BASE_DOMAIN","bdm-dev.dts-stn.com")
param("env.SUBSCRIPTION", "%vault:dts-sre/data/azure!/decd-dev-subscription-id%")
param("env.K8S_CLUSTER_NAME", "ESdCDPSBDMK8SDev-K8S")
param("env.RG_DEV", "ESdCDPSBDMK8SDev")
param("env.TARGET", "main")
param("env.BRANCH", "perf")
param("env.NEXT_PUBLIC_GRAPHQL_HTTP", "%vault:dts-secrets-dev/data/scrumPoker!/NEXT_PUBLIC_GRAPHQL_HTTP_PERF%")
param("env.NEXT_PUBLIC_GRAPHQL_WS", "%vault:dts-secrets-dev/data/scrumPoker!/NEXT_PUBLIC_GRAPHQL_WS_PERF%")
}
vcs {
root(Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerPerformance)
}
steps {
dockerCommand {
name = "Build & Tag Docker Image"
commandType = build {
source = file {
path = "Dockerfile"
}
namesAndTags = "%env.ACR_DOMAIN%/%env.PROJECT%:%env.DOCKER_TAG%"
commandArgs = "--pull --build-arg NEXT_BUILD_DATE=%system.build.start.date% --build-arg TC_BUILD=%build.number% --build-arg NEXT_PUBLIC_GRAPHQL_HTTP=%env.NEXT_PUBLIC_GRAPHQL_HTTP% --build-arg NEXT_PUBLIC_GRAPHQL_WS=%env.NEXT_PUBLIC_GRAPHQL_WS%"
}
}
script {
name = "Login to Azure and ACR"
scriptContent = """
az login --service-principal -u %TEAMCITY_USER% -p %TEAMCITY_PASS% --tenant %env.TENANT-ID%
az account set -s %env.SUBSCRIPTION%
az acr login -n MTSContainers
""".trimIndent()
}
dockerCommand {
name = "Push Image to ACR"
commandType = push {
namesAndTags = "%env.ACR_DOMAIN%/%env.PROJECT%:%env.DOCKER_TAG%"
}
}
script {
name = "Deploy w/ Helmfile"
scriptContent = """
cd ./helmfile
az account set -s %env.SUBSCRIPTION%
az aks get-credentials --overwrite-existing --admin --resource-group %env.RG_DEV% --name %env.K8S_CLUSTER_NAME%
helmfile -e %env.TARGET% apply
""".trimIndent()
}
}
triggers {
vcs {
branchFilter = "+:*"
}
}
})
object CleanUpWeekly: BuildType({
name = "CleanUpWeekly"
description = "Deletes deployments every saturday"
params {
param("teamcity.vcsTrigger.runBuildInNewEmptyBranch", "true")
param("env.PROJECT", "scrum-poker")
param("env.BASE_DOMAIN","bdm-dev.dts-stn.com")
param("env.SUBSCRIPTION", "%vault:dts-sre/data/azure!/decd-dev-subscription-id%")
param("env.K8S_CLUSTER_NAME", "ESdCDPSBDMK8SDev-K8S")
param("env.RG_DEV", "ESdCDPSBDMK8SDev")
param("env.TARGET", "main")
param("env.BRANCH", "%teamcity.build.branch%")
}
vcs {
root(Dev_ScrumPoker_HttpsGithubComDtsStnscrumPokerDynamic)
}
steps {
script {
name = "Login and Delete Deployment"
scriptContent = """
az login --service-principal -u %TEAMCITY_USER% -p %TEAMCITY_PASS% --tenant %env.TENANT-ID%
az account set -s %env.SUBSCRIPTION%
echo %env.PROJECT%-branch
kubectl get namespace | awk '/^%env.PROJECT%-dyna/{system("kubectl delete namespace " $1)}'
""".trimIndent()
}
}
triggers {
schedule {
schedulingPolicy = weekly {
dayOfWeek = ScheduleTrigger.DAY.Saturday
hour = 15
minute = 15
timezone = "America/New_York"
}
branchFilter = "+:main"
triggerBuild = always()
withPendingChangesOnly = false
triggerBuildOnAllCompatibleAgents = true
}
}
})
| 12 | JavaScript | 1 | 0 | 6f05e281e49294d7f3613248901cc790bca8a53a | 15,325 | Scrum-Poker | MIT License |
spark/src/main/kotlin/com/adevinta/spark/components/toggles/SwitchDefaults.kt | adevinta | 598,741,849 | false | null | /*
* Copyright (c) 2023 Adevinta
*
* 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.adevinta.spark.components.toggles
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import com.adevinta.spark.SparkTheme
import com.adevinta.spark.components.buttons.SparkButtonDefaults.disabled
import androidx.compose.material3.SwitchDefaults as MaterialSwitchDefaults
public object SwitchDefaults {
@Composable
internal fun colors(
checkedTrackColor: Color,
checkedThumbColor: Color = SparkTheme.colors.surface,
checkedBorderColor: Color = Color.Transparent,
checkedIconColor: Color = checkedTrackColor,
uncheckedThumbColor: Color = SparkTheme.colors.surface,
uncheckedTrackColor: Color = SparkTheme.colors.outline,
uncheckedBorderColor: Color = Color.Transparent,
uncheckedIconColor: Color = uncheckedTrackColor,
disabledCheckedThumbColor: Color = checkedThumbColor,
disabledCheckedTrackColor: Color = checkedTrackColor.disabled,
disabledCheckedBorderColor: Color = checkedBorderColor,
disabledCheckedIconColor: Color = checkedIconColor.disabled,
disabledUncheckedThumbColor: Color = uncheckedThumbColor,
disabledUncheckedTrackColor: Color = uncheckedTrackColor.disabled,
disabledUncheckedBorderColor: Color = checkedBorderColor,
disabledUncheckedIconColor: Color = uncheckedIconColor.disabled,
) = MaterialSwitchDefaults.colors(
checkedThumbColor = checkedThumbColor,
checkedTrackColor = checkedTrackColor,
checkedBorderColor = checkedBorderColor,
checkedIconColor = checkedIconColor,
uncheckedThumbColor = uncheckedThumbColor,
uncheckedTrackColor = uncheckedTrackColor,
uncheckedBorderColor = uncheckedBorderColor,
uncheckedIconColor = uncheckedIconColor,
disabledCheckedThumbColor = disabledCheckedThumbColor,
disabledCheckedTrackColor = disabledCheckedTrackColor,
disabledCheckedBorderColor = disabledCheckedBorderColor,
disabledCheckedIconColor = disabledCheckedIconColor,
disabledUncheckedThumbColor = disabledUncheckedThumbColor,
disabledUncheckedTrackColor = disabledUncheckedTrackColor,
disabledUncheckedBorderColor = disabledUncheckedBorderColor,
disabledUncheckedIconColor = disabledUncheckedIconColor,
)
public val icons: SwitchIcons = SwitchIcons()
}
| 45 | null | 6 | 67 | bb0e00f2b574a3c57c5c3bd91969362c7c91c7fa | 3,507 | spark-android | MIT License |
src/test/kotlin/no/nav/syfo/pdl/client/TestData.kt | navikt | 238,714,111 | false | null | package no.nav.syfo.pdl.client
fun getTestData(): String {
return "{\n" +
" \"data\": {\n" +
" \"person\": {\n" +
" \"navn\": [\n" +
" {\n" +
" \"fornavn\": \"RASK\",\n" +
" \"mellomnavn\": null,\n" +
" \"etternavn\": \"SAKS\"\n" +
" }\n" +
" ],\n" +
" \"adressebeskyttelse\": [\n" +
" {\n" +
" \"gradering\": \"UGRADERT\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"identer\": {\n" +
" \"identer\": [\n" +
" {\n" +
" \"ident\": \"99999999999\",\n" +
" \"gruppe\": \"AKTORID\"\n" +
" },\n" +
" {\n" +
" \"ident\": \"12345678901\",\n" +
" \"gruppe\": \"FOLKEREGISTERIDENT\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
"}"
}
fun getErrorResponse(): String {
return "{\n" +
" \"errors\": [\n" +
" {\n" +
" \"message\": \"Ikke tilgang til å se person\",\n" +
" \"locations\": [\n" +
" {\n" +
" \"line\": 2,\n" +
" \"column\": 3\n" +
" }\n" +
" ],\n" +
" \"path\": [\n" +
" \"hentPerson\"\n" +
" ],\n" +
" \"extensions\": {\n" +
" \"code\": \"unauthorized\",\n" +
" \"classification\": \"ExecutionAborted\"\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"data\": {\n" +
" \"hentPerson\": null\n" +
" }\n" +
"}"
}
| 0 | Kotlin | 0 | 0 | 76b5aa68d376b85cef31905bdffe41dd2e387c0d | 1,777 | sykmeldinger-backend | MIT License |
src/test/kotlin/io/andrewohara/dynamokt/samples/BeanTableExtensions.kt | oharaandrew314 | 421,600,664 | false | {"Kotlin": 50709} | package io.andrewohara.dynamokt.samples
import io.andrewohara.dynamokt.DataClassTableSchema
import io.andrewohara.dynamokt.DynamoKtPartitionKey
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import org.http4k.aws.AwsSdkClient
import org.http4k.connect.amazon.dynamodb.FakeDynamoDb
import org.junit.jupiter.api.Test
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient
import software.amazon.awssdk.enhanced.dynamodb.Key
import software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension
import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension
import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAutoGeneratedTimestampAttribute
import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbVersionAttribute
import software.amazon.awssdk.regions.Region
import software.amazon.awssdk.services.dynamodb.DynamoDbClient
import java.time.Clock
import java.time.Instant
import java.time.ZoneId
import java.time.ZoneOffset
class BeanTableExtensions {
private val time = Instant.parse("2023-11-19T12:00:00Z")
private val clock = object: Clock() {
override fun getZone() = ZoneOffset.UTC
override fun withZone(zone: ZoneId?) = TODO()
override fun instant() = time
}
private val dynamo = DynamoDbEnhancedClient.builder()
.dynamoDbClient(
DynamoDbClient.builder()
.httpClient(AwsSdkClient(FakeDynamoDb()))
.credentialsProvider { AwsBasicCredentials.create("key", "id") }
.region(Region.CA_CENTRAL_1)
.build()
)
.extensions(
AutoGeneratedTimestampRecordExtension.builder().baseClock(clock).build(),
VersionedRecordExtension.builder().build()
)
.build()
@Test
fun `auto generated timestamp`() {
data class Person(
@DynamoKtPartitionKey
val name: String,
@get:DynamoDbAutoGeneratedTimestampAttribute
var dob: Instant? = null
)
val table = dynamo
.table("people", DataClassTableSchema(Person::class))
.also { it.createTable() }
table.putItem(Person("John"))
table.getItem(Key.builder().partitionValue("John").build())
.shouldNotBeNull()
.dob shouldBe time
}
@Test
fun `version attribute`() {
data class Person(
@DynamoKtPartitionKey
val id: Int,
val name: String,
@get:DynamoDbVersionAttribute
val version: Int = 0
)
val table = dynamo
.table("people", DataClassTableSchema(Person::class))
.also { it.createTable() }
// increment version on insert
table.putItem(Person(1337,"John", 0))
table.getItem(Key.builder().partitionValue(1337).build())
.shouldNotBeNull()
.version shouldBe 1
// increment version on update
table.putItem(Person(1337, "Jim", 1))
table.getItem(Key.builder().partitionValue(1337).build())
.shouldNotBeNull()
.version shouldBe 2
}
} | 1 | Kotlin | 3 | 20 | cf9f6f1d2991b2c7ecbbe2f8836008855462db5f | 3,317 | dynamodb-kotlin-module | Apache License 2.0 |
app/src/main/kotlin/com/glodanif/bluetoothchat/data/model/MessagesStorageImpl.kt | Andrulko | 131,834,733 | true | {"Kotlin": 285127} | package com.glodanif.bluetoothchat.data.model
import android.content.Context
import android.os.Handler
import com.glodanif.bluetoothchat.data.database.Storage
import com.glodanif.bluetoothchat.data.database.MessagesDao
import com.glodanif.bluetoothchat.data.entity.ChatMessage
import java.io.File
import kotlin.concurrent.thread
class MessagesStorageImpl(val context: Context) : MessagesStorage {
private val dao: MessagesDao = Storage.getInstance(context).db.messagesDao()
override suspend fun insertMessage(message: ChatMessage) {
dao.insert(message)
}
override suspend fun getMessagesByDevice(address: String): List<ChatMessage> {
val messages = dao.getMessagesByDevice(address)
messages.forEach {
if (it.filePath != null) {
it.fileExists = File(it.filePath).exists()
}
}
return messages
}
override suspend fun getMessageById(uid: Long): ChatMessage? {
return dao.getFileMessageById(uid)
}
override suspend fun getFileMessagesByDevice(address: String?): List<ChatMessage> {
return (if (address != null)
dao.getFileMessagesByDevice(address) else dao.getAllFilesMessages())
.filter { !it.filePath.isNullOrEmpty() && File(it.filePath).exists() }
}
override suspend fun updateMessage(message: ChatMessage) {
dao.updateMessage(message)
}
override suspend fun updateMessages(messages: List<ChatMessage>) {
dao.updateMessages(messages)
}
override suspend fun removeFileInfo(messageId: Long) {
dao.removeFileInfo(messageId)
}
}
| 1 | Kotlin | 0 | 0 | 5d99bba804bdf7d78c7c9a38e1209d38746bb34f | 1,641 | BluetoothChat | Apache License 2.0 |
dependency-guard/src/main/kotlin/com/dropbox/gradle/plugins/dependencyguard/internal/utils/DependencyListDiffResult.kt | dropbox | 469,908,487 | false | {"Kotlin": 90632} | package com.dropbox.gradle.plugins.dependencyguard.internal.utils
import java.io.File
internal sealed class DependencyListDiffResult {
internal class BaselineCreated(
projectPath: String,
configurationName: String,
baselineFile: File,
) : DependencyListDiffResult() {
private val baselineMessage = """
Dependency Guard baseline created for $projectPath for configuration $configurationName.
File: file://${baselineFile.canonicalPath}
""".trimIndent()
fun baselineCreatedMessage(withColor: Boolean): String = if (withColor) {
ColorTerminal.colorify(ColorTerminal.ANSI_YELLOW, baselineMessage)
} else {
baselineMessage
}
}
internal sealed class DiffPerformed : DependencyListDiffResult() {
internal class NoDiff(
projectPath: String,
configurationName: String,
) : DiffPerformed() {
val noDiffMessage: String =
"No Dependency Changes Found in $projectPath for configuration \"$configurationName\""
}
internal data class HasDiff(
val projectPath: String,
val configurationName: String,
val removedAndAddedLines: RemovedAndAddedLines,
) : DiffPerformed() {
private val dependenciesChangedMessage =
"""Dependencies Changed in $projectPath for configuration $configurationName"""
private val rebaselineMessage = Messaging.rebaselineMessage(projectPath)
fun createDiffMessage(withColor: Boolean): String = buildString {
appendLine(
if (withColor) {
ColorTerminal.colorify(ColorTerminal.ANSI_YELLOW, dependenciesChangedMessage)
} else {
dependenciesChangedMessage
}
)
appendLine(
if (withColor) {
removedAndAddedLines.diffTextWithPlusAndMinusWithColor
} else {
removedAndAddedLines.diffTextWithPlusAndMinus
}
)
appendLine(
if (withColor) {
ColorTerminal.colorify(ColorTerminal.ANSI_RED, rebaselineMessage)
} else {
rebaselineMessage
}
)
}
}
}
}
| 18 | Kotlin | 12 | 293 | 6ece4590df4728cd03250936ca0155392562a129 | 2,499 | dependency-guard | Apache License 2.0 |
plot-base-portable/src/commonMain/kotlin/jetbrains/datalore/plot/base/stat/StatUtil.kt | b7w | 397,769,862 | true | {"Kotlin": 5197304, "Python": 774830, "C": 2832, "CSS": 1948, "Shell": 1773, "JavaScript": 1121} | /*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.base.stat
import jetbrains.datalore.plot.base.DataFrame
import jetbrains.datalore.plot.base.data.TransformVar
import jetbrains.datalore.plot.base.util.MutableDouble
import jetbrains.datalore.plot.common.data.SeriesUtil
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
object StatUtil {
private const val MAX_BIN_COUNT = 500
fun weightAtIndex(data: DataFrame): (Int) -> Double {
if (data.has(TransformVar.WEIGHT)) {
val weights = data.getNumeric(TransformVar.WEIGHT)
return { index ->
val weight = weights[index]
SeriesUtil.asFinite(weight, 0.0)
}
}
return { 1.0 }
}
fun weightVector(dataLength: Int, data: DataFrame): List<Double?> {
return if (data.has(TransformVar.WEIGHT)) {
data.getNumeric(TransformVar.WEIGHT)
} else List(dataLength) { 1.0 }
}
fun binCountAndWidth(dataRange: Double, binOptions: BinOptions): CountAndWidth {
var binCount = binOptions.binCount
val binWidth: Double
if (binOptions.hasBinWidth()) {
binWidth = binOptions.binWidth!!
var count = dataRange / binWidth
count = min(MAX_BIN_COUNT.toDouble(), count)
binCount = ceil(count).toInt()
} else {
binWidth = dataRange / binCount
}
return CountAndWidth(binCount, binWidth)
}
/*
public static List<Double> pickAtIndices(List<Double> list, List<Integer> indices) {
List<Double> result = new ArrayList<>();
for (Integer index : indices) {
result.add(list.get(index));
}
return result;
}
*/
fun computeBins(
valuesX: List<Double?>,
startX: Double,
binCount: Int,
binWidth: Double,
weightAtIndex: (Int) -> Double,
densityNormalizingFactor: Double): BinsData {
var totalCount = 0.0
val countByBinIndex = HashMap<Int, MutableDouble>()
val dataIndicesByBinIndex = HashMap<Int, MutableList<Int>>()
for (dataIndex in valuesX.indices) {
val x = valuesX[dataIndex]
if (!SeriesUtil.isFinite(x)) {
continue
}
val weight = weightAtIndex(dataIndex)
totalCount += weight
val binIndex = floor((x!! - startX) / binWidth).toInt()
if (!countByBinIndex.containsKey(binIndex)) {
countByBinIndex[binIndex] = MutableDouble(0.0)
}
countByBinIndex[binIndex]!!.getAndAdd(weight)
if (!dataIndicesByBinIndex.containsKey(binIndex)) {
dataIndicesByBinIndex[binIndex] = ArrayList()
}
dataIndicesByBinIndex[binIndex]!!.add(dataIndex)
}
val x = ArrayList<Double>()
val counts = ArrayList<Double>()
val densities = ArrayList<Double>()
val x0 = startX + binWidth / 2
for (i in 0 until binCount) {
x.add(x0 + i * binWidth)
var count = 0.0
// some bins are left empty (not excluded from map)
if (countByBinIndex.containsKey(i)) {
count = countByBinIndex[i]!!.get()
}
counts.add(count)
val density = count / totalCount * densityNormalizingFactor
densities.add(density)
}
return BinsData(x, counts, densities, dataIndicesByBinIndex)
}
class BinOptions(binCount: Int, val binWidth: Double? // optional
) {
val binCount: Int = min(MAX_BIN_COUNT, max(1, binCount))
fun hasBinWidth(): Boolean {
return binWidth != null && binWidth > 0
}
}
class CountAndWidth(val count: Int, val width: Double)
class BinsData(
internal val x: List<Double>,
internal val count: List<Double>,
internal val density: List<Double>,
private val dataIndicesByBinIndex: Map<Int, List<Int>>)
}
| 1 | null | 0 | 0 | d75d67cd94448b548c59520392385ec41de84bfe | 4,210 | lets-plot | MIT License |
feature_feed_url_hook/src/main/java/com/phicdy/mycuration/feedurlhook/FeedUrlHookPresenter.kt | phicdy | 24,188,186 | false | {"Kotlin": 688608, "HTML": 1307, "Shell": 1127} | package com.phicdy.mycuration.feedurlhook
import android.content.Intent
import com.phicdy.mycuration.data.repository.RssRepository
import com.phicdy.mycuration.domain.rss.RssParseExecutor
import com.phicdy.mycuration.domain.rss.RssParseResult
import com.phicdy.mycuration.domain.rss.RssParser
import com.phicdy.mycuration.domain.rss.RssUrlHookIntentData
import com.phicdy.mycuration.domain.task.NetworkTaskManager
import com.phicdy.mycuration.util.UrlUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import javax.inject.Inject
class FeedUrlHookPresenter @Inject constructor(
private val view: FeedUrlHookView,
private val rssUrlHookIntentData: RssUrlHookIntentData,
private val rssRepository: RssRepository,
private val networkTaskManager: NetworkTaskManager,
private val coroutineScope: CoroutineScope,
private val parser: RssParser
) {
var callback: RssParseExecutor.RssParseCallback = object : RssParseExecutor.RssParseCallback {
override fun succeeded(rssUrl: String) {
coroutineScope.launch {
val newFeed = rssRepository.getFeedByUrl(rssUrl)
newFeed?.let {
networkTaskManager.updateFeed(newFeed)
}
view.showSuccessToast()
view.finishView()
}
}
override fun failed(reason: RssParseResult.FailedReason, url: String) {
if (reason === RssParseResult.FailedReason.INVALID_URL) {
view.showInvalidUrlErrorToast()
} else {
view.showGenericErrorToast()
}
view.trackFailedUrl(url)
view.finishView()
}
}
suspend fun create() {
if (rssUrlHookIntentData.action != Intent.ACTION_VIEW && rssUrlHookIntentData.action != Intent.ACTION_SEND) {
view.finishView()
return
}
var url: String? = null
if (rssUrlHookIntentData.action == Intent.ACTION_VIEW) {
url = rssUrlHookIntentData.dataString
} else if (rssUrlHookIntentData.action == Intent.ACTION_SEND) {
// For Chrome
url = rssUrlHookIntentData.extrasText.toString()
}
if (url != null) {
handle(rssUrlHookIntentData.action, url)
}
}
private suspend fun handle(action: String, url: String) {
if (action == Intent.ACTION_VIEW || action == Intent.ACTION_SEND) {
if (UrlUtil.isCorrectUrl(url)) {
val executor = RssParseExecutor(parser, rssRepository)
executor.start(url, callback)
} else {
view.showInvalidUrlErrorToast()
view.trackFailedUrl(url)
}
} else {
view.finishView()
}
}
}
| 43 | Kotlin | 9 | 30 | 6c8bafba7341c1003da2196bd618b9505f32e42c | 2,819 | MyCuration | MIT License |
kmp/remote/cloud/src/commonTest/kotlin/io/github/reactivecircus/kstreamlined/kmp/remote/mapper/FeedSourceMappersTest.kt | ReactiveCircus | 513,535,591 | false | {"Kotlin": 529824} | package io.github.reactivecircus.kstreamlined.kmp.remote.mapper
import io.github.reactivecircus.kstreamlined.graphql.FeedSourcesQuery
import io.github.reactivecircus.kstreamlined.graphql.type.FeedSourceKey
import io.github.reactivecircus.kstreamlined.kmp.remote.model.FeedSource
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class FeedSourceMappersTest {
@Test
fun `FeedSource_Key maps to expected FeedSourceKey`() {
assertEquals(FeedSourceKey.KOTLIN_BLOG, FeedSource.Key.KotlinBlog.asApolloModel())
assertEquals(FeedSourceKey.KOTLIN_YOUTUBE_CHANNEL, FeedSource.Key.KotlinYouTubeChannel.asApolloModel())
assertEquals(FeedSourceKey.TALKING_KOTLIN_PODCAST, FeedSource.Key.TalkingKotlinPodcast.asApolloModel())
assertEquals(FeedSourceKey.KOTLIN_WEEKLY, FeedSource.Key.KotlinWeekly.asApolloModel())
}
@Test
fun `FeedSourcesQuery_FeedSource maps to expected FeedSource`() {
FeedSource.Key.entries.forEach { key ->
val apolloKey = key.asApolloModel()
val apolloFeedSource = FeedSourcesQuery.FeedSource(
key = apolloKey,
title = "Title for $key",
description = "Description for $key",
)
val expectedFeedOrigin = FeedSource(
key = key,
title = "Title for $key",
description = "Description for $key",
)
assertEquals(expectedFeedOrigin, apolloFeedSource.asExternalModel())
}
}
@Test
fun `returns null when mapping unknown FeedSourcesQuery_FeedSource to FeedSource`() {
val apolloFeedSource = FeedSourcesQuery.FeedSource(
key = FeedSourceKey.UNKNOWN__,
title = "Unknown feed source title",
description = "Unknown feed source description",
)
assertNull(apolloFeedSource.asExternalModel())
}
}
| 3 | Kotlin | 0 | 4 | 3925f94003740930ff8af4648aea746d070459dc | 1,941 | kstreamlined-mobile | Apache License 2.0 |
blockball-bukkit-plugin/src/main/java/com/github/shynixn/blockball/bukkit/logic/business/extension/ExtensionMethods.kt | yoloyolicko | 184,437,057 | true | {"Kotlin": 1179158, "Java": 99604, "Shell": 2544} | @file:Suppress("unused", "DEPRECATION")
package com.github.shynixn.blockball.bukkit.logic.business.extension
import com.github.shynixn.blockball.api.business.enumeration.*
import com.github.shynixn.blockball.api.business.enumeration.GameMode
import com.github.shynixn.blockball.api.persistence.entity.*
import com.github.shynixn.blockball.bukkit.BlockBallPlugin
import com.github.shynixn.blockball.bukkit.logic.business.coroutine.DispatcherContainer
import com.github.shynixn.blockball.bukkit.logic.business.nms.VersionSupport
import com.github.shynixn.blockball.core.logic.persistence.entity.PositionEntity
import com.mojang.authlib.GameProfile
import com.mojang.authlib.properties.Property
import kotlinx.coroutines.Dispatchers
import org.bukkit.*
import org.bukkit.ChatColor
import org.bukkit.configuration.MemorySection
import org.bukkit.configuration.file.FileConfiguration
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.PlayerInventory
import org.bukkit.inventory.meta.LeatherArmorMeta
import org.bukkit.inventory.meta.SkullMeta
import org.bukkit.plugin.Plugin
import org.bukkit.plugin.java.JavaPlugin
import org.bukkit.util.Vector
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder
import java.lang.reflect.InvocationTargetException
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.logging.Level
import kotlin.coroutines.CoroutineContext
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
/**
* Minecraft async dispatcher.
*/
val Dispatchers.async: CoroutineContext
get() = DispatcherContainer.async
/**
* Minecraft sync dispatcher.
*/
val Dispatchers.minecraft: CoroutineContext
get() = DispatcherContainer.sync
/**
* Executes the given [f] for the given [plugin] on main thread.
*/
inline fun Any.sync(plugin: Plugin, delayTicks: Long = 0L, repeatingTicks: Long = 0L, crossinline f: () -> Unit) {
if (repeatingTicks > 0) {
plugin.server.scheduler.runTaskTimer(plugin, Runnable {
f.invoke()
}, delayTicks, repeatingTicks)
} else {
plugin.server.scheduler.runTaskLater(plugin,Runnable {
f.invoke()
}, delayTicks)
}
}
/**
* Deserializes the configuraiton section path to a map.
*/
fun FileConfiguration.deserializeToMap(path: String): Map<String, Any?> {
val section = getConfigurationSection(path).getValues(false)
deserialize(section)
return section
}
/**
* Deserializes the given section.
*/
private fun deserialize(section: MutableMap<String, Any?>) {
section.keys.forEach { key ->
if (section[key] is MemorySection) {
val map = (section[key] as MemorySection).getValues(false)
deserialize(map)
section[key] = map
}
}
}
/**
* Finds the corresponding version.
*/
fun VersionSupport.toVersion(): Version {
return Version.values().find { v -> this.simpleVersionText == v.id }!!
}
/**
* Updates this inventory.
*/
fun PlayerInventory.updateInventory() {
(this.holder as Player).updateInventory()
}
/**
* Is the player touching the ground?
*/
fun Player.isTouchingGround(): Boolean {
return this.isOnGround
}
/**
* Set displayname.
*/
fun ItemStack.setDisplayName(displayName: String): ItemStack {
val meta = itemMeta
meta.displayName = displayName.convertChatColors()
itemMeta = meta
return this
}
/**
* Executes the given [f] for the given [plugin] asynchronly.
*/
inline fun Any.async(plugin: Plugin, delayTicks: Long = 0L, repeatingTicks: Long = 0L, crossinline f: () -> Unit) {
if (repeatingTicks > 0) {
plugin.server.scheduler.runTaskTimerAsynchronously(plugin,Runnable {
f.invoke()
}, delayTicks, repeatingTicks)
} else {
plugin.server.scheduler.runTaskLaterAsynchronously(plugin,Runnable {
f.invoke()
}, delayTicks)
}
}
/**
* Sets the [Server] modt with the given [text].
*/
internal fun Server.setModt(text: String) {
val builder = java.lang.StringBuilder("[")
builder.append((text.replace("[", "").replace("]", "")))
builder.append(ChatColor.RESET.toString())
builder.append("]")
val minecraftServerClazz = Class.forName("net.minecraft.server.VERSION.MinecraftServer".replace("VERSION", VersionSupport.getServerVersion().versionText))
val craftServerClazz = Class.forName("org.bukkit.craftbukkit.VERSION.CraftServer".replace("VERSION", VersionSupport.getServerVersion().versionText))
val setModtMethod = minecraftServerClazz.getDeclaredMethod("setMotd", String::class.java)
val getServerConsoleMethod = craftServerClazz.getDeclaredMethod("getServer")
val console = getServerConsoleMethod!!.invoke(Bukkit.getServer())
setModtMethod!!.invoke(console, builder.toString().convertChatColors())
}
/**
* Refactors a list to a single line.
*/
internal fun List<String>.toSingleLine(): String {
val builder = StringBuilder()
this.forEachIndexed { index, p ->
builder.append(org.bukkit.ChatColor.translateAlternateColorCodes('&', p))
if (index + 1 != this.size)
builder.append('\n')
builder.append(org.bukkit.ChatColor.RESET)
}
return builder.toString()
}
/**
* Converts all placeholders.
*/
internal fun String.replaceGamePlaceholder(game: Game, teamMeta: TeamMeta? = null, team: List<Player>? = null): String {
val plugin = JavaPlugin.getPlugin(BlockBallPlugin::class.java)
var cache = this.replace(PlaceHolder.TEAM_RED.placeHolder, game.arena.meta.redTeamMeta.displayName)
.replace(PlaceHolder.ARENA_DISPLAYNAME.placeHolder, game.arena.displayName)
.replace(PlaceHolder.TEAM_BLUE.placeHolder, game.arena.meta.blueTeamMeta.displayName)
.replace(PlaceHolder.RED_COLOR.placeHolder, game.arena.meta.redTeamMeta.prefix)
.replace(PlaceHolder.BLUE_COLOR.placeHolder, game.arena.meta.blueTeamMeta.prefix)
.replace(PlaceHolder.RED_GOALS.placeHolder, game.redScore.toString())
.replace(PlaceHolder.BLUE_GOALS.placeHolder, game.blueScore.toString())
.replace(PlaceHolder.ARENA_SUM_CURRENTPLAYERS.placeHolder, game.ingamePlayersStorage.size.toString())
.replace(PlaceHolder.ARENA_SUM_MAXPLAYERS.placeHolder, (game.arena.meta.blueTeamMeta.maxAmount + game.arena.meta.redTeamMeta.maxAmount).toString())
if (teamMeta != null) {
cache = cache.replace(PlaceHolder.ARENA_TEAMCOLOR.placeHolder, teamMeta.prefix)
.replace(PlaceHolder.ARENA_TEAMDISPLAYNAME.placeHolder, teamMeta.displayName)
.replace(PlaceHolder.ARENA_MAX_PLAYERS_ON_TEAM.placeHolder, teamMeta.maxAmount.toString())
}
if (team != null) {
cache = cache.replace(PlaceHolder.ARENA_PLAYERS_ON_TEAM.placeHolder, team.size.toString())
}
val stateSignEnabled = plugin.config.getString("messages.state-sign-enabled").convertChatColors()
val stateSignDisabled = plugin.config.getString("messages.state-sign-disabled").convertChatColors()
val stateSignRunning = plugin.config.getString("messages.state-sign-running").convertChatColors()
when {
game.status == GameStatus.RUNNING -> cache = cache.replace(PlaceHolder.ARENA_STATE.placeHolder, stateSignRunning)
game.status == GameStatus.ENABLED -> cache = cache.replace(PlaceHolder.ARENA_STATE.placeHolder, stateSignEnabled)
game.status == GameStatus.DISABLED -> cache = cache.replace(PlaceHolder.ARENA_STATE.placeHolder, stateSignDisabled)
}
if (game.arena.gameType == GameType.HUBGAME) {
cache = cache.replace(PlaceHolder.TIME.placeHolder, "∞")
} else if (game is MiniGame) {
cache = cache.replace(PlaceHolder.TIME.placeHolder, game.gameCountdown.toString())
.replace(PlaceHolder.REMAINING_PLAYERS_TO_START.placeHolder, (game.arena.meta.redTeamMeta.minAmount + game.arena.meta.blueTeamMeta.minAmount - game.ingamePlayersStorage.size).toString())
}
if (game.lastInteractedEntity != null && game.lastInteractedEntity is Player) {
cache = cache.replace(PlaceHolder.LASTHITBALL.placeHolder, (game.lastInteractedEntity as Player).name)
}
return cache.convertChatColors()
}
/**
* Sets the color of the itemstack if it has a leather meta.
*/
internal fun ItemStack.setColor(color: Color): ItemStack {
if (this.itemMeta is LeatherArmorMeta) {
val leatherMeta = this.itemMeta as LeatherArmorMeta
leatherMeta.color = color
this.itemMeta = leatherMeta
}
return this
}
/**
* Returns if the given [player] has got this [Permission].
*/
internal fun Permission.hasPermission(player: Player): Boolean {
return player.hasPermission(this.permission)
}
/** Returns if the given [location] is inside of this area selection. */
fun Selection.isLocationInSelection(location: Location): Boolean {
if (location.world.name == this.upperCorner.worldName) {
if (this.upperCorner.x >= location.x && this.lowerCorner.x <= location.x) {
if (this.upperCorner.y >= location.y + 1 && this.lowerCorner.y <= location.y + 1) {
if (this.upperCorner.z >= location.z && this.lowerCorner.z <= location.z) {
return true
}
}
}
}
return false
}
/**
* Sends the given [packet] to this player.
*/
@Throws(ClassNotFoundException::class, IllegalAccessException::class, NoSuchMethodException::class, InvocationTargetException::class, NoSuchFieldException::class)
fun Player.sendPacket(packet: Any) {
val version = VersionSupport.getServerVersion()
val craftPlayer = Class.forName("org.bukkit.craftbukkit.VERSION.entity.CraftPlayer".replace("VERSION", version.versionText)).cast(player)
val methodHandle = craftPlayer.javaClass.getDeclaredMethod("getHandle")
val entityPlayer = methodHandle.invoke(craftPlayer)
val field = Class.forName("net.minecraft.server.VERSION.EntityPlayer".replace("VERSION", version.versionText)).getDeclaredField("playerConnection")
field.isAccessible = true
val connection = field.get(entityPlayer)
val sendMethod = connection.javaClass.getDeclaredMethod("sendPacket", packet.javaClass.interfaces[0])
sendMethod.invoke(connection, packet)
}
/**
* Converts the chatcolors of this string.
*/
internal fun String.convertChatColors(): String {
return ChatColor.translateAlternateColorCodes('&', this)
}
/**
* Removes the chatColors.
*/
internal fun String.stripChatColors(): String {
return ChatColor.stripColor(this)
}
/**
* Accepts the action safely.
*/
fun <T> CompletableFuture<T>.thenAcceptSafely(f: (T) -> Unit) {
this.thenAccept(f).exceptionally { e ->
JavaPlugin.getPlugin(BlockBallPlugin::class.java).logger.log(Level.WARNING, "Failed to execute Task.", e)
throw RuntimeException(e)
}
}
/**
* Tries to return the [ParticleType] from the given name.
*/
fun String.toParticleType(): ParticleType {
ParticleType.values().forEach { p ->
if (p.gameId_18.equals(this, true) || p.gameId_113.equals(this, true) || p.name.equals(this, true) || p.minecraftId_112.equals(this, true)) {
return p
}
}
throw IllegalArgumentException("ParticleType cannot be parsed from '" + this + "'.")
}
/**
* Sets the skin of an itemstack.
*/
internal fun ItemStack.setSkin(skin: String) {
val currentMeta = this.itemMeta
if (currentMeta !is SkullMeta) {
return
}
var newSkin = skin
if (newSkin.contains("textures.minecraft.net")) {
if (!newSkin.startsWith("http://")) {
newSkin = "http://$newSkin"
}
val newSkinProfile = GameProfile(UUID.randomUUID(), null)
val cls = Class.forName("org.bukkit.craftbukkit.VERSION.inventory.CraftMetaSkull".replace("VERSION", VersionSupport.getServerVersion().versionText))
val real = cls.cast(currentMeta)
val field = real.javaClass.getDeclaredField("profile")
newSkinProfile.properties.put("textures", Property("textures", Base64Coder.encodeString("{textures:{SKIN:{url:\"$newSkin\"}}}")))
field.isAccessible = true
field.set(real, newSkinProfile)
itemMeta = SkullMeta::class.java.cast(real)
} else {
currentMeta.owner = skin
itemMeta = currentMeta
}
}
/**
* Converts the given Location to a position.
*/
internal fun Location.toPosition(): Position {
val position = PositionEntity()
position.worldName = this.world.name
position.x = this.x
position.y = this.y
position.z = this.z
position.yaw = this.yaw.toDouble()
position.pitch = this.pitch.toDouble()
return position
}
/**
* Converts the given gamemode to a bukkit gamemode.
*/
internal fun GameMode.toGameMode(): org.bukkit.GameMode {
return org.bukkit.GameMode.valueOf(this.name)
}
/**
* Converts the given position to a bukkit Location.
*/
internal fun Position.toLocation(): Location {
return Location(Bukkit.getWorld(this.worldName), this.x, this.y, this.z, this.yaw.toFloat(), this.pitch.toFloat())
}
/**
* Converts the given position to a bukkit vector.
*/
internal fun Position.toVector(): Vector {
return Vector(this.x, this.y, this.z)
} | 0 | Kotlin | 0 | 0 | d64bdbb78fc730cfb52e7cb0d5c55808e69370ac | 14,392 | BlockBall | Apache License 2.0 |
src/test/kotlin/org/rust/ide/navigation/goto/RsGotoTypeDeclarationTest.kt | intellij-rust | 42,619,487 | false | null | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.navigation.goto
import com.intellij.openapi.actionSystem.IdeActions.ACTION_GOTO_TYPE_DECLARATION
import org.intellij.lang.annotations.Language
import org.rust.RsTestBase
class RsGotoTypeDeclarationTest : RsTestBase() {
fun `test function declaration`() = doTest("""
struct /*caret_after*/Foo;
fn foo/*caret_before*/() -> Foo { unimplemented!() }
""")
fun `test method declaration`() = doTest("""
enum /*caret_after*/Bar { BAR }
struct Foo;
impl Foo {
fn bar/*caret_before*/(&self) -> Bar { unimplemented!() }
}
""")
fun `test field declaration`() = doTest("""
struct /*caret_after*/Bar;
struct Foo {
bar/*caret_before*/: Bar
}
""")
fun `test const declaration`() = doTest("""
struct /*caret_after*/Foo;
const FOO/*caret_before*/: Foo = Foo;
""")
fun `test variable declaration`() = doTest("""
struct /*caret_after*/Foo;
fn main() {
let a/*caret_before*/ = Foo;
}
""")
fun `test argument declaration`() = doTest("""
struct /*caret_after*/Foo;
fn foo(foo/*caret_before*/: Foo) { unimplemented!() }
""")
fun `test function call`() = doTest("""
struct /*caret_after*/Foo;
fn foo() -> Foo { unimplemented!() }
fn main() {
foo/*caret_before*/();
}
""")
fun `test method call`() = doTest("""
enum /*caret_after*/Bar { BAR }
struct Foo;
impl Foo {
fn bar(&self) -> Bar { unimplemented!() }
}
fn main() {
Foo.bar/*caret_before*/();
}
""")
fun `test field using`() = doTest("""
struct /*caret_after*/Bar;
struct Foo {
bar: Bar
}
fn foo(foo: Foo) -> Bar {
foo.bar/*caret_before*/
}
""")
fun `test variable using`() = doTest("""
struct /*caret_after*/Foo;
fn main() {
let a = Foo;
a/*caret_before*/;
}
""")
fun `test reference type`() = doTest("""
struct /*caret_after*/Foo;
fn foo/*caret_before*/<'a>(_: &'a i32) -> &'a Foo { unimplemented!() }
""")
fun `test pointer type`() = doTest("""
struct /*caret_after*/Foo;
fn foo/*caret_before*/() -> *const Foo { unimplemented!() }
""")
fun `test array type`() = doTest("""
struct /*caret_after*/Foo;
fn foo/*caret_before*/() -> [Foo; 2] { unimplemented!() }
""")
fun `test slice type`() = doTest("""
struct /*caret_after*/Foo;
fn foo/*caret_before*/<'a>(_: &'a i32) -> &'a [Foo] { unimplemented!() }
""")
fun `test trait object type`() = doTest("""
trait /*caret_after*/Foo {}
fn foo/*caret_before*/<'a>(_: &'a i32) -> &'a Foo { unimplemented!() }
""")
fun `test type parameter`() = doTest("""
fn foo</*caret_after*/T>() -> T { unimplemented!() }
fn main() {
let x = foo/*caret_before*/::<i32>();
}
""")
fun `test associated type`() = doTest("""
trait Foo {
type Bar;
fn foo(&self) -> Self::Bar;
}
struct Baz;
struct /*caret_after*/Qwe;
impl Foo for Baz {
type Bar = Qwe;
fn foo(&self) -> Self::Bar {
unimplemented!()
}
}
fn main() {
let x = Baz.foo/*caret_before*/();
}
""")
fun `test impl trait`() = doTest("""
trait /*caret_after*/Foo {}
fn foo() -> impl Foo { unimplemented!() }
fn main() {
foo/*caret_before*/();
}
""")
fun `test self param in impl`() = doTest("""
struct /*caret_after*/Foo;
impl Foo {
fn bar(/*caret_before*/self) {}
}
""")
fun `test &self param in impl`() = doTest("""
struct /*caret_after*/Foo;
impl Foo {
fn bar(&self/*caret_before*/) {}
}
""")
fun `test &mut self param in impl`() = doTest("""
struct /*caret_after*/Foo;
impl Foo {
fn bar(&mut /*caret_before*/self) {}
}
""")
fun `test &mut self param in impl with spacing`() = doTest("""
struct /*caret_after*/Foo;
impl Foo {
fn bar( & mut /*caret_before*/self) {}
}
""")
fun `test self param in trait`() = doTest("""
trait /*caret_after*/Foo {
fn bar(/*caret_before*/self) {}
}
""")
fun `test &self param in trait`() = doTest("""
trait /*caret_after*/Foo {
fn bar(&self/*caret_before*/) {}
}
""")
fun `test &mut self param in trait`() = doTest("""
trait /*caret_after*/Foo {
fn bar(&mut /*caret_before*/self) {}
}
""")
fun `test &mut self param in trait with spacing`() = doTest("""
trait /*caret_after*/Foo {
fn bar( & mut /*caret_before*/self) {}
}
""")
fun `test type declared by a macro`() = doTest("""
macro_rules! as_is { ($($ t:tt)*) => { $($ t)* }; }
as_is! { struct /*caret_after*/S; }
fn main() {
let /*caret_before*/a = S;
}
""")
private fun doTest(@Language("Rust") code: String) = checkCaretMove(code) {
myFixture.performEditorAction(ACTION_GOTO_TYPE_DECLARATION)
}
}
| 1,841 | null | 380 | 4,528 | c6657c02bb62075bf7b7ceb84d000f93dda34dc1 | 5,596 | intellij-rust | MIT License |
app/src/main/java/com/pri/architecture_boilerplate/binding/FragmentBindingAdapters.kt | priyanka-rani | 218,155,486 | false | null | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pri.architecture_boilerplate.binding
import android.view.ActionMode
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.BindingAdapter
import com.google.android.material.textfield.TextInputLayout
import com.pri.architecture_boilerplate.R
import com.pri.architecture_boilerplate.util.Validator
import com.pri.architecture_boilerplate.util.afterTextChanged
import com.pri.architecture_boilerplate.util.isValid
/**
* Binding adapters that work with a fragment instance.
*/
class FragmentBindingAdapters {
@BindingAdapter("visibleGone")
fun showHide(view: View, show: Boolean) {
view.visibility = if (show) View.VISIBLE else View.GONE
}
@BindingAdapter("visibleInvisible")
fun showInvisible(view: View, show: Boolean) {
view.visibility = if (show) View.VISIBLE else View.INVISIBLE
}
@BindingAdapter("txtColor")
fun bindTextColor(textView: TextView, res: Int?) {
res?.let { textView.setTextColor(ContextCompat.getColor(textView.context, it)) }
}
@BindingAdapter("textToFormat", "android:text")
fun setFormattedValue(view: TextView, textToFormat: Int, value: String) {
view.text = String.format(view.context.resources.getString(textToFormat), value)
}
@BindingAdapter("validation", "errorMsg", requireAll = false)
fun bindValidation(textInputLayout: TextInputLayout, validator: Validator?, errorMsg: Int?) {
textInputLayout.editText?.afterTextChanged {
textInputLayout.error = when {
validator == null || validator.validate(it) -> null
else -> when {
it.isBlank() -> null
else -> textInputLayout.context.getString(errorMsg
?: validator.errorMsg)
}
}
}
}
@BindingAdapter("android:longClickable")
fun disableCopyPaste(editText: EditText, enableCopyPaste: Boolean) {
if (!enableCopyPaste) {
val actionModeCallBack = object : ActionMode.Callback {
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
override fun onDestroyActionMode(mode: ActionMode) {}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return false
}
}
editText.customSelectionActionModeCallback = actionModeCallBack
editText.setTextIsSelectable(false)
editText.isLongClickable = false
/* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
editText.customInsertionActionModeCallback = actionModeCallBack
}*/
}
}
@BindingAdapter("android:onClick", "listOfTil")
fun bindValidationToButton(button: Button, clickListener: View.OnClickListener, textFields: List<View>?) {
button.setOnClickListener {
if (textFields.isNullOrEmpty() || textFields.isValid()) {
clickListener.onClick(button)
}
}
}
}
| 1 | null | 1 | 1 | 18a74203aebf027e66254925663023aefb6b685b | 4,062 | architecture_dagger_binding_pri | Apache License 2.0 |
src/main/kotlin/no/nav/helseidnavtest/edi20/EDI20DialogmeldingGenerator.kt | navikt | 754,033,318 | false | {"Kotlin": 156431} | package no.nav.helseidnavtest.edi20
import jakarta.xml.bind.Marshaller
import no.nav.helseidnavtest.dialogmelding.Fødselsnummer
import no.nav.helseidnavtest.dialogmelding.HerId
import no.nav.helseidnavtest.dialogmelding.Pasient
import no.nav.helseidnavtest.oppslag.person.PDLClient
import org.springframework.stereotype.Component
import org.springframework.web.multipart.MultipartFile
import java.io.StringWriter
import java.net.URI
@Component
class EDI20DialogmeldingGenerator(private val marshaller: Marshaller,
private val mapper: EDI20DialogmeldingMapper, private val pdl: PDLClient) {
fun hodemelding(fra: HerId, til: HerId, pasient: Fødselsnummer, vedlegg: Pair<URI, String>?) =
StringWriter().let {
marshaller.marshal(mapper.hodemelding(fra, til, pasient(pasient), vedlegg), it)
"$it"
}
fun hodemelding(fra: HerId, til: HerId, pasient: Fødselsnummer, vedlegg: MultipartFile?) =
StringWriter().let {
marshaller.marshal(mapper.hodemelding(fra, til, pasient(pasient), vedlegg), it)
"$it"
}
private fun pasient(pasient: Fødselsnummer) = Pasient(pasient, pdl.navn(pasient))
}
| 2 | Kotlin | 0 | 0 | 3a0e2d517550c94bbe24eb90d4d2a196ecb06791 | 1,210 | helseid-nav-test | MIT License |
neo4j-store/src/main/resources/OnRegionApprovedAction.kts | ostelco | 112,729,477 | false | {"Gradle Kotlin DSL": 51, "YAML": 65, "Go": 13, "Go Checksums": 1, "Markdown": 48, "Shell": 48, "Text": 3, "Ignore List": 24, "Batchfile": 1, "Go Module": 1, "Kotlin": 372, "JSON": 24, "Dockerfile": 11, "XML": 28, "Java": 11, "Java Properties": 3, "Protocol Buffer": 2, "Python": 2, "SQL": 4, "PLpgSQL": 2, "GraphQL": 2, "OASv2-yaml": 6, "SVG": 17, "PlantUML": 18, "Cypher": 1} | import arrow.core.Either
import arrow.core.extensions.fx
import org.ostelco.prime.auditlog.AuditLog
import org.ostelco.prime.dsl.WriteTransaction
import org.ostelco.prime.dsl.withId
import org.ostelco.prime.model.Customer
import org.ostelco.prime.storage.StoreError
import org.ostelco.prime.storage.graph.OnRegionApprovedAction
import org.ostelco.prime.storage.graph.PrimeTransaction
import org.ostelco.prime.storage.graph.model.Segment
object : OnRegionApprovedAction {
override fun apply(
customer: Customer,
regionCode: String,
transaction: PrimeTransaction
): Either<StoreError, Unit> {
return Either.fx {
WriteTransaction(transaction).apply {
val segmentId = get(Segment withId "plan-country-${regionCode.toLowerCase()}")
.fold(
{ get(Segment withId "country-${regionCode.toLowerCase()}").bind() },
{ it }
)
.id
fact { (Customer withId customer.id) belongsToSegment (Segment withId segmentId) }.bind()
AuditLog.info(customer.id, "Added customer to segment - $segmentId")
}
Unit
}
}
} | 23 | Kotlin | 13 | 37 | b072ada4aca8c4bf5c3c2f6fe0d36a5ff16c11af | 1,274 | ostelco-core | Apache License 2.0 |
fetch2/src/main/java/com/tonyodev/fetch2/database/migration/MigrationTwoToThree.kt | SanthosiBrt | 138,884,041 | false | {"Java Properties": 3, "YAML": 1, "Gradle": 11, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 4, "Ignore List": 9, "Proguard": 8, "Java": 45, "XML": 142, "Kotlin": 100, "JSON": 109} | package com.tonyodev.fetch2.database.migration
import android.arch.persistence.db.SupportSQLiteDatabase
import com.tonyodev.fetch2.EnqueueAction
import com.tonyodev.fetch2.database.DownloadDatabase
class MigrationTwoToThree : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE ${DownloadDatabase.TABLE_NAME} "
+ " ADD COLUMN ${DownloadDatabase.COLUMN_ENQUEUE_ACTION} INTEGER DEFAULT ${EnqueueAction.REPLACE_EXISTING.value}")
}
} | 1 | null | 1 | 1 | 5e4fcb0ae4d7037f0b949e947d1f2084383e2e3f | 517 | Fetch | Apache License 2.0 |
kaff4-core/kaff4-core-test/src/main/kotlin/net/navatwo/kaff4/UnderTest.kt | Nava2 | 555,850,412 | false | null | package net.navatwo.kaff4
import javax.inject.Qualifier
/**
* Defines a value that is provided from a test rule.
*/
@Target(
AnnotationTarget.PROPERTY,
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.FUNCTION,
AnnotationTarget.FIELD,
)
@Qualifier
annotation class UnderTest
| 7 | Kotlin | 0 | 1 | b0df931c9be6378bd9fc7f6d182d1a35b3034c2f | 289 | kaff4 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.