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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tmp/arrays/youTrackTests/8538.kt
|
DaniilStepanov
| 228,623,440
| false
| null |
// Original bug: KT-20577
var x = listOf<Array<String>>()
var y = arrayOf("", "")
var z = x + y // plus(elements: Array<out T>) is called, but it should be plus(element: T)
// z is now List<Any>, but was expected to be List<Array<String>>
| 1
| null |
8
| 1
|
602285ec60b01eee473dcb0b08ce497b1c254983
| 240
|
bbfgradle
|
Apache License 2.0
|
mbprotokit/src/main/java/com/daimler/mbprotokit/dto/car/zev/VehicleChargingProgramParameter.kt
|
Daimler
| 199,815,262
| false
| null |
package com.daimler.mbprotokit.dto.car.zev
import com.daimler.mbprotokit.generated.VehicleEvents
data class VehicleChargingProgramParameter(
/**
* The charging program.
*/
val program: ChargingProgram?,
/**
* Values need to be between 50 and 100 and divisible by ten.
* Maximum value for the state of charge of the HV battery [in %].
* Valid value range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100].
*/
val maxSoc: Int,
/**
* Denotes whether the charge cable should be unlocked automatically
* if the HV battery is fully charged resp. charged until [maxSoc] value.
*/
val autoUnlock: Boolean,
/**
* Automatically switch between home and work program, based on the location of the car.
*/
val locationBasedCharging: Boolean,
val weeklyProfile: Boolean,
val clockTimer: Boolean,
/**
* Current max charging amount.
*/
val maxChargingCurrent: Int,
/**
* True if ECO charging mode is activated.
*/
val ecoCharging: Boolean
) {
companion object {
fun mapToVehicleChargingProgramParameters(): (VehicleEvents.ChargeProgramsValue?) -> List<VehicleChargingProgramParameter>? = {
it?.chargeProgramParametersList?.map { param ->
VehicleChargingProgramParameter(
program = ChargingProgram.map(param.chargeProgram),
maxSoc = param.maxSoc,
autoUnlock = param.autoUnlock,
locationBasedCharging = param.locationBasedCharging,
weeklyProfile = param.weeklyProfile,
clockTimer = param.clockTimer,
maxChargingCurrent = param.maxChargingCurrent,
ecoCharging = param.ecoCharging
)
}
}
}
}
| 1
|
Kotlin
|
8
| 15
|
3721af583408721b9cd5cf89dd7b99256e9d7dda
| 1,844
|
MBSDK-Mobile-Android
|
MIT License
|
app/src/main/java/io/github/vishalecho/android/cnews/data/model/NewsDataContract.kt
|
vishalecho
| 278,807,537
| false
| null |
package io.github.vishalecho.android.cnews.data.model
import com.vishalecho.android.core.network.Response
import io.reactivex.Single
import io.reactivex.subjects.PublishSubject
interface NewsDataContract {
interface Repository {
val newsFetchResponse: PublishSubject<Response<List<News>>>
fun fetchNews()
fun refreshNews()
fun recentNews()
fun popularNews()
fun handleError(error: Throwable)
}
interface Remote {
fun getNews(): Single<List<News>>
}
}
| 0
|
Kotlin
|
0
| 0
|
43bfb84254c1200b99893f6d864c95f4b914c24b
| 526
|
CNews
|
Apache License 2.0
|
src/main/kotlin/br/com/acmattos/hdc/common/tool/server/prometheus/StatisticsHandlerCollector.kt
|
acmattos
| 225,613,144
| false
|
{"Kotlin": 955728, "JavaScript": 151772, "HTML": 26378, "CSS": 4190}
|
package br.com.acmattos.hdc.common.tool.server.prometheus
import io.prometheus.client.Collector
import io.prometheus.client.CollectorRegistry
import java.util.Collections.emptyList
import org.eclipse.jetty.server.handler.StatisticsHandler
/**
* @author ACMattos
* @since 09/06/2020.
*/
class StatisticsHandlerCollector private constructor(
private val statisticsHandler: StatisticsHandler
) : Collector() {
override fun collect(): List<MetricFamilySamples> {
return listOf(
buildCounter(
"jetty_requests_total",
"Number of requests",
statisticsHandler.requests.toDouble()
),
buildGauge(
"jetty_requests_active",
"Number of requests currently active",
statisticsHandler.requestsActive.toDouble()
),
buildGauge(
"jetty_requests_active_max",
"Maximum number of requests that have been active at once",
statisticsHandler.requestsActiveMax.toDouble()
),
buildGauge(
"jetty_request_time_max_seconds",
"Maximum time spent handling requests",
statisticsHandler.requestTimeMax / 1000.0
),
buildCounter(
"jetty_request_time_seconds_total",
"Total time spent in all request handling",
statisticsHandler.requestTimeTotal / 1000.0
),
buildCounter(
"jetty_dispatched_total",
"Number of dispatches",
statisticsHandler.dispatched.toDouble()
),
buildGauge(
"jetty_dispatched_active",
"Number of dispatches currently active",
statisticsHandler.dispatchedActive.toDouble()
),
buildGauge(
"jetty_dispatched_active_max",
"Maximum number of active dispatches being handled",
statisticsHandler.dispatchedActiveMax.toDouble()
),
buildGauge(
"jetty_dispatched_time_max",
"Maximum time spent in dispatch handling",
statisticsHandler.dispatchedTimeMax.toDouble()
),
buildCounter(
"jetty_dispatched_time_seconds_total",
"Total time spent in dispatch handling",
statisticsHandler.dispatchedTimeTotal / 1000.0
),
buildCounter(
"jetty_async_requests_total",
"Total number of async requests",
statisticsHandler.asyncRequests.toDouble()
),
buildGauge(
"jetty_async_requests_waiting",
"Currently waiting async requests",
statisticsHandler.asyncRequestsWaiting.toDouble()
),
buildGauge(
"jetty_async_requests_waiting_max",
"Maximum number of waiting async requests",
statisticsHandler.asyncRequestsWaitingMax.toDouble()
),
buildCounter(
"jetty_async_dispatches_total",
"Number of requested that have been asynchronously dispatched",
statisticsHandler.asyncDispatches.toDouble()
),
buildCounter(
"jetty_expires_total",
"Number of async requests requests that have expired",
statisticsHandler.expires.toDouble()
),
buildStatusCounter(),
buildGauge(
"jetty_stats_seconds",
"Time in seconds stats have been collected for",
statisticsHandler.statsOnMs / 1000.0
),
buildCounter(
"jetty_responses_bytes_total",
"Total number of bytes across all responses",
statisticsHandler.responsesBytesTotal.toDouble()
)
)
}
private fun buildStatusCounter(): MetricFamilySamples {
val name = "jetty_responses_total"
return MetricFamilySamples(
name,
Type.COUNTER,
"Number of requests with response status",
listOf(
buildStatusSample(
name,
"1xx",
statisticsHandler.responses1xx.toDouble()
),
buildStatusSample(
name,
"2xx",
statisticsHandler.responses2xx.toDouble()
),
buildStatusSample(
name,
"3xx",
statisticsHandler.responses3xx.toDouble()
),
buildStatusSample(
name,
"4xx",
statisticsHandler.responses4xx.toDouble()
),
buildStatusSample(
name,
"5xx",
statisticsHandler.responses5xx.toDouble()
)
)
)
}
companion object {
fun initialize(
statisticsHandler: StatisticsHandler,
enableDefaultRegistry: Boolean = true
): StatisticsHandlerCollector {
val statisticsHandlerCollector = StatisticsHandlerCollector(
statisticsHandler
)
if(enableDefaultRegistry) {
statisticsHandlerCollector.register<StatisticsHandlerCollector>()
} else {
statisticsHandlerCollector.register<StatisticsHandlerCollector>(CollectorRegistry())
}
return statisticsHandlerCollector
}
fun finalize() {
CollectorRegistry.defaultRegistry.clear()
}
private fun buildGauge(name: String, help: String, value: Double): MetricFamilySamples {
return MetricFamilySamples(
name,
Type.GAUGE,
help,
listOf(
MetricFamilySamples.Sample(
name,
emptyList(),
emptyList(),
value
)
)
)
}
private fun buildCounter(name: String, help: String, value: Double): MetricFamilySamples {
return MetricFamilySamples(
name,
Type.COUNTER,
help,
listOf(
MetricFamilySamples.Sample(
name,
emptyList(),
emptyList(),
value
)
)
)
}
private fun buildStatusSample(
name: String,
status: String,
value: Double
): MetricFamilySamples.Sample {
return MetricFamilySamples.Sample(
name, listOf("code"), listOf(status),
value
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8d7aec8840ff9cc87eb17921058d23cfc0d2ca6c
| 7,164
|
hdc
|
MIT License
|
presentation/src/main/java/com/dsm/dms/presentation/di/module/LocalModule.kt
|
DSM-DMS
| 203,186,000
| false
| null |
package com.dsm.dms.presentation.di.module
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
import android.content.Context
import androidx.room.Room
import com.dsm.dms.data.local.database.Database
import com.dsm.dms.data.local.pref.LocalStorage
import com.dsm.dms.data.local.pref.SharedPrefStorage
@Module
class LocalModule {
@Provides
@Singleton
fun provideLocalStorage(context: Context) : LocalStorage = SharedPrefStorage(context)
@Provides
@Singleton
fun provideDatabase(
context: Context
): Database =
Room.databaseBuilder(context, Database::class.java, "dms.db").build()
}
| 0
|
Kotlin
|
2
| 14
|
ae7de227cee270d22a72a4f59090bff07c43f019
| 653
|
DMS-Android-V4
|
MIT License
|
bigbone/src/main/kotlin/social/bigbone/api/method/EndorsementMethods.kt
|
andregasser
| 565,112,249
| false
|
{"Kotlin": 957002, "Java": 28473, "Ruby": 15997, "Dockerfile": 1263, "Shell": 118}
|
package social.bigbone.api.method
import social.bigbone.MastodonClient
import social.bigbone.MastodonRequest
import social.bigbone.api.Pageable
import social.bigbone.api.Range
import social.bigbone.api.entity.Account
/**
* Feature other profiles on your own profile. See also accounts/:id/{pin,unpin}.
* @see <a href="https://docs.joinmastodon.org/methods/endorsements/">Mastodon endorsement API methods</a>
*/
class EndorsementMethods(private val client: MastodonClient) {
private val endpoint = "api/v1/endorsements"
/**
* Accounts that the user is currently featuring on their profile.
* @param range optional Range for the pageable return value
* @see <a href="https://docs.joinmastodon.org/methods/endorsements/#get">Mastodon API documentation: methods/endorsements/#get</a>
* @return [Pageable] of [Account]s the user is currently featuring on their profile
*/
@JvmOverloads
fun getEndorsements(
range: Range = Range()
): MastodonRequest<Pageable<Account>> {
return client.getPageableMastodonRequest<Account>(
endpoint = endpoint,
method = MastodonClient.Method.GET,
parameters = range.toParameters()
)
}
}
| 30
|
Kotlin
|
15
| 62
|
125ac29b988b8a35894dda99b7ca7ec409496836
| 1,229
|
bigbone
|
MIT License
|
utils/times/src/test/kotlin/io/bluetape4k/times/period/calendars/CalendarDateAddTest.kt
|
debop
| 625,161,599
| false
|
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
|
package io.bluetape4k.times.period.calendars
import io.bluetape4k.logging.KLogging
import io.bluetape4k.times.days
import io.bluetape4k.times.hours
import io.bluetape4k.times.nanos
import io.bluetape4k.times.nowZonedDateTime
import io.bluetape4k.times.period.AbstractPeriodTest
import io.bluetape4k.times.period.SeekBoundaryMode
import io.bluetape4k.times.period.TimeRange
import io.bluetape4k.times.period.ranges.DayRange
import io.bluetape4k.times.period.ranges.HourRangeInDay
import io.bluetape4k.times.unaryMinus
import io.bluetape4k.times.zonedDateTimeOf
import kotlinx.coroutines.test.runTest
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeNull
import org.junit.jupiter.api.Test
import java.time.LocalTime
class CalendarDateAddTest: AbstractPeriodTest() {
companion object: KLogging()
@Test
fun `no period`() = runTest {
val dateAdd = CalendarDateAdd()
val now = nowZonedDateTime()
(-10..20).forEach {
val offset = it * 5
dateAdd.add(now, offset.days()) shouldBeEqualTo now + offset.days()
dateAdd.add(now, -offset.days()) shouldBeEqualTo now - offset.days()
dateAdd.subtract(now, offset.days()) shouldBeEqualTo now - offset.days()
dateAdd.subtract(now, -offset.days()) shouldBeEqualTo now + offset.days()
}
}
@Test
fun `period with limits`() = runTest {
val start = zonedDateTimeOf(2011, 4, 12)
val period1 = TimeRange(
zonedDateTimeOf(2011, 4, 20),
zonedDateTimeOf(2011, 4, 25)
)
val period2 = TimeRange(
zonedDateTimeOf(2011, 4, 30),
null
) // 4월 30일 이후
val dateAdd = CalendarDateAdd().apply {
// 예외 기간을 설정합니다.
excludePeriods.add(period1)
excludePeriods.add(period2)
}
dateAdd.add(start, 0.days()) shouldBeEqualTo start
dateAdd.add(start, 1.days()) shouldBeEqualTo start + 1.days()
// 4월 12일에 8일을 더하면 4월 20일이지만, 20~25일까지 제외되므로, 4월 25일이 된다.
dateAdd.add(start, 8.days()) shouldBeEqualTo period1.end
// 4월 12에 20일을 더하면 4월 20~25일을 제외한 후 계산하면 4월 30 이후가 된다. (5월 3일).
// 하지만 4월 30 이후는 모두 제외되므로 결과값은 null이다.
dateAdd.add(start, 20.days()).shouldBeNull()
dateAdd.subtract(start, 3.days()) shouldBeEqualTo start - 3.days()
}
@Test
fun `period subtract with limit`() = runTest {
val start = zonedDateTimeOf(2011, 4, 30)
val period1 = TimeRange(
zonedDateTimeOf(2011, 4, 20),
zonedDateTimeOf(2011, 4, 25)
)
val period2 = TimeRange(
null,
zonedDateTimeOf(2011, 4, 6)
) // 4월 6일 까지
val dateAdd = CalendarDateAdd().apply {
// 예외 기간을 설정합니다.
excludePeriods.add(period1)
excludePeriods.add(period2)
}
dateAdd.subtract(start, 1.days()) shouldBeEqualTo start - 1.days()
// 4월 30일로부터 5일 전이면 4월 25일이지만, 예외기간이므로 4월 20일이 된다.
dateAdd.subtract(start, 5.days()) shouldBeEqualTo period1.start
// 4월 30일로부터 20일 전이면, 5월 전이 4월20일이므로, 4월 5일이 된다. 근데, 4월 6일 이전은 모두 제외기간이므로 null을 반환한다.
dateAdd.subtract(start, 20.days()).shouldBeNull()
}
@Test
fun `one exclude period`() = runTest {
val start = zonedDateTimeOf(2011, 4, 12)
val period = TimeRange(
zonedDateTimeOf(2011, 4, 15),
zonedDateTimeOf(2011, 4, 20)
)
val dateAdd = CalendarDateAdd().apply {
excludePeriods.add(period)
}
dateAdd.add(start, 0.days()) shouldBeEqualTo start
dateAdd.add(start, 1.days()) shouldBeEqualTo start + 1.days()
dateAdd.add(start, 2.days()) shouldBeEqualTo start + 2.days()
dateAdd.add(start, 3.days()) shouldBeEqualTo period.end
dateAdd.add(start, 3.days() + 1.nanos()) shouldBeEqualTo period.end + 1.nanos()
dateAdd.add(start, 5.days()) shouldBeEqualTo period.end + 2.days()
}
@Test
fun `two exclude periods`() = runTest {
val start = zonedDateTimeOf(2011, 4, 12)
val period1 = TimeRange(
zonedDateTimeOf(2011, 4, 15),
zonedDateTimeOf(2011, 4, 20)
)
val period2 = TimeRange(
zonedDateTimeOf(2011, 4, 22),
zonedDateTimeOf(2011, 4, 25)
)
val dateAdd = CalendarDateAdd().apply {
excludePeriods.add(period1)
excludePeriods.add(period2)
}
dateAdd.add(start, 0.days()) shouldBeEqualTo start
dateAdd.add(start, 1.days()) shouldBeEqualTo start + 1.days()
dateAdd.add(start, 2.days()) shouldBeEqualTo start + 2.days()
dateAdd.add(start, 3.days()) shouldBeEqualTo period1.end
dateAdd.add(start, 4.days()) shouldBeEqualTo period1.end + 1.days()
dateAdd.add(start, 5.days()) shouldBeEqualTo period2.end
dateAdd.add(start, 6.days()) shouldBeEqualTo period2.end + 1.days()
dateAdd.add(start, 7.days()) shouldBeEqualTo period2.end + 2.days()
}
@Test
fun `when seek boundary mode`() = runTest {
val dateAdd = CalendarDateAdd().apply {
addWorkingWeekdays()
excludePeriods.add(DayRange(2011, 4, 4, calendar))
workingHours.add(HourRangeInDay(8, 18))
}
val start = zonedDateTimeOf(2011, 4, 1, 9, 0)
dateAdd.add(start, 29.hours(), SeekBoundaryMode.FILL) shouldBeEqualTo zonedDateTimeOf(2011, 4, 6, 18)
dateAdd.add(start, 29.hours(), SeekBoundaryMode.NEXT) shouldBeEqualTo zonedDateTimeOf(2011, 4, 7, 8)
dateAdd.add(start, 29.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 7, 8)
}
@Test
fun `calendar date add 1`() = runTest {
val dateAdd = CalendarDateAdd().apply {
addWorkingWeekdays()
excludePeriods.add(DayRange(zonedDateTimeOf(2011, 4, 4), calendar))
workingHours.add(HourRangeInDay(8, 18))
}
val start = zonedDateTimeOf(2011, 4, 1, 9, 0)
dateAdd.add(start, 22.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 6, 11)
dateAdd.add(start, 22.hours(), SeekBoundaryMode.FILL) shouldBeEqualTo zonedDateTimeOf(2011, 4, 6, 11)
dateAdd.add(start, 29.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 7, 8)
dateAdd.add(start, 29.hours(), SeekBoundaryMode.FILL) shouldBeEqualTo zonedDateTimeOf(2011, 4, 6, 18)
}
@Test
fun `calendar date add 2`() = runTest {
val dateAdd = CalendarDateAdd().apply {
addWorkingWeekdays()
excludePeriods.add(DayRange(zonedDateTimeOf(2011, 4, 4), calendar))
workingHours.add(HourRangeInDay(8, 12))
workingHours.add(HourRangeInDay(13, 18))
}
val start = zonedDateTimeOf(2011, 4, 1, 9, 0)
dateAdd.add(start, 3.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 1, 13)
dateAdd.add(start, 4.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 1, 14)
dateAdd.add(start, 8.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 5, 8)
}
@Test
fun `calendar date add 3`() = runTest {
val dateAdd = CalendarDateAdd().apply {
addWorkingWeekdays()
excludePeriods.add(DayRange(2011, 4, 4, calendar))
workingHours.add(HourRangeInDay(LocalTime.of(8, 30), LocalTime.NOON))
workingHours.add(HourRangeInDay(LocalTime.of(13, 30), LocalTime.of(18, 0)))
}
val start = zonedDateTimeOf(2011, 4, 1, 9, 0)
dateAdd.add(start, 3.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 1, 13, 30)
dateAdd.add(start, 4.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 1, 14, 30)
dateAdd.add(start, 8.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 5, 9)
}
@Test
fun `empty start week`() = runTest {
val dateAdd = CalendarDateAdd()
// 주중(월-금)을 working time으로 추가
dateAdd.addWorkingWeekdays()
val start = zonedDateTimeOf(2011, 4, 2, 13)
// 4월 2일(토), 4월 3일(일)을 제외하면 4월 4일 0시부터 20시간
dateAdd.add(start, 20.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 4, 20)
// 4월 2일(토), 4월 3일(일) 제외하면 4월 4일 0시부터 24시간
dateAdd.add(start, 24.hours()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 5)
// 4월 2일(토), 4월 3일(일) 제외하면, 4월 4일부터 5일이면 주말인 4월 9일(토), 4월 10일(일) 제외한 4월 11일!!!
dateAdd.add(start, 5.days()) shouldBeEqualTo zonedDateTimeOf(2011, 4, 11)
}
}
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 8,494
|
bluetape4k
|
MIT License
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/grAnnotationUtil.kt
|
ingokegel
| 284,920,751
| false
| null |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.impl
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiAnnotationMemberValue
import com.intellij.psi.PsiLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
fun PsiAnnotation.findDeclaredDetachedValue(@NlsSafe attributeName: String?): PsiAnnotationMemberValue? {
return AnnotationUtil.findDeclaredAttribute(this, attributeName)?.detachedValue
}
internal fun <T : Any> PsiAnnotationMemberValue.getArrayValue(computeValue: (PsiAnnotationMemberValue) -> T?): List<T> {
return AnnotationUtil.arrayAttributeValues(this).mapNotNull(computeValue)
}
fun PsiAnnotationMemberValue?.booleanValue(): Boolean? = (this as? PsiLiteral)?.value as? Boolean
fun PsiAnnotationMemberValue?.stringValue(): String? = (this as? PsiLiteral)?.value as? String
fun GrModifierList.hasAnnotation(fqn: String): Boolean = annotations.any { it.qualifiedName == fqn }
| 1
| null |
1
| 2
|
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
| 1,175
|
intellij-community
|
Apache License 2.0
|
src/test/kotlin/io/realworld/app/web/controllers/CommentControllerTest.kt
|
Rudge
| 149,893,811
| false
| null |
package io.realworld.app.web.controllers
import io.javalin.Javalin
import io.javalin.util.HttpUtil
import io.realworld.app.config.AppConfig
import io.realworld.app.domain.Comment
import io.realworld.app.domain.CommentDTO
import io.realworld.app.domain.CommentsDTO
import org.eclipse.jetty.http.HttpStatus
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class CommentControllerTest {
private lateinit var app: Javalin
private lateinit var http: HttpUtil
@Before
fun start() {
app = AppConfig().setup().start()
http = HttpUtil(app.port())
}
@After
fun stop() {
app.stop()
}
@Test
fun `add comment for article by slug`() {
val responseArticle = http.createArticle()
val comment = Comment(body = "Very carefully.")
val response = http.post<CommentDTO>(
"/api/articles/${responseArticle.body.article?.slug}/comments",
CommentDTO(comment),
)
assertEquals(response.status, HttpStatus.OK_200)
assertEquals(response.body.comment?.body, comment.body)
}
@Test
fun `get all comments for article by slug`() {
val responseArticle = http.createArticle()
val slug = responseArticle.body.article?.slug
val comment = Comment(body = "Very carefully.")
http.post<CommentDTO>(
"/api/articles/$slug/comments",
CommentDTO(comment),
)
val response = http.get<CommentsDTO>("/api/articles/$slug/comments")
assertEquals(response.status, HttpStatus.OK_200)
assertTrue(response.body.comments.isNotEmpty())
assertEquals(response.body.comments.first().body, comment.body)
}
@Test
fun `delete comment for article by slug`() {
val responseArticle = http.createArticle()
val slug = responseArticle.body.article?.slug
val comment = Comment(body = "Very carefully.")
val responseAddComment = http.post<CommentDTO>(
"/api/articles/$slug/comments",
CommentDTO(comment),
)
val response = http.delete("/api/articles/$slug/comments/${responseAddComment.body.comment?.id}")
assertEquals(response.status, HttpStatus.OK_200)
}
}
| 4
| null |
42
| 128
|
f35739e4a13df84eaa57270a63e4739acd9882f8
| 2,335
|
kotlin-javalin-realworld-example-app
|
MIT License
|
app/src/main/java/com/revolgenx/anilib/ui/view/drawable/BaseDrawablePaint.kt
|
rev0lgenX
| 244,410,204
| false
| null |
package com.revolgenx.anilib.ui.view.drawable
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
abstract class BaseDrawablePaint : BaseDrawable() {
private var mPaint: Paint? = null
override fun onDraw(canvas: Canvas?, width: Int, height: Int) {
if (mPaint == null) {
mPaint = Paint()
mPaint!!.isAntiAlias = true
mPaint!!.color = Color.WHITE
onPreparePaint(mPaint)
}
mPaint!!.alpha = mAlpha
// mPaint!!.colorFilter = getColorFilterForDrawing()
onDraw(canvas, width, height, mPaint)
}
protected abstract fun onPreparePaint(paint: Paint?)
protected abstract fun onDraw(
canvas: Canvas?,
width: Int,
height: Int,
paint: Paint?
)
}
| 3
|
Kotlin
|
1
| 24
|
355d2b5510682d869f18e0113453237af8a1f1cc
| 816
|
AniLib
|
Apache License 2.0
|
app/src/test/java/com/rafaelds/swapi/data/model/vehicles/VehiclesDtoToVehicleListMapperTest.kt
|
themobilecoder
| 376,679,661
| false
| null |
package com.rafaelds.swapi.data.model.vehicles
import com.rafaelds.swapi.data.TestData.VEHICLE
import com.rafaelds.swapi.data.TestData.VEHICLE_DTO
import org.junit.Test
import kotlin.test.assertEquals
class VehiclesDtoToVehicleListMapperTest {
private val vehiclesDtoToVehiclesListMapper = VehiclesDtoToVehicleListMapper()
@Test
fun `should convert correctly dto with app uri`() {
val url = "http://vehicles/4"
val vehiclesDto = VehiclesDTO(1, "next", listOf(VEHICLE_DTO.copy(url = url)), "prev")
val expectedUrl = "swapi://vehicles/4"
assertEquals(listOf(VEHICLE.copy(appUri = expectedUrl)), vehiclesDtoToVehiclesListMapper.convert(vehiclesDto))
}
}
| 0
|
Kotlin
|
0
| 3
|
b13f3b682c9701c2c64d6610950fb4d4f2b02725
| 702
|
swapi
|
MIT License
|
devops-boot-project/devops-boot-core/devops-schedule/devops-schedule-server/src/main/kotlin/com/tencent/devops/schedule/discovery/WorkerDiscoveryListener.kt
|
bkdevops-projects
| 294,058,091
| false
|
{"Kotlin": 488037, "JavaScript": 47413, "Vue": 36468, "SCSS": 7290, "HTML": 620, "Java": 559}
|
package com.tencent.devops.schedule.discovery
import com.tencent.devops.schedule.enums.DiscoveryTypeEnum
import com.tencent.devops.schedule.manager.WorkerManager
import com.tencent.devops.schedule.utils.sleep
import org.slf4j.LoggerFactory
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.cloud.client.ServiceInstance
import org.springframework.cloud.client.discovery.DiscoveryClient
import org.springframework.cloud.client.discovery.event.HeartbeatEvent
import org.springframework.cloud.client.discovery.event.HeartbeatMonitor
import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent
import org.springframework.cloud.client.discovery.event.ParentHeartbeatEvent
import org.springframework.context.event.EventListener
/**
* 基于时间监听实现worker自动发现
*/
open class WorkerDiscoveryListener(
private val discoveryClient: DiscoveryClient,
private val workerManager: WorkerManager
) {
private val monitor: HeartbeatMonitor = HeartbeatMonitor()
@EventListener
fun onApplicationReady(event: ApplicationReadyEvent) {
// 启动完成后执行一次
discover()
}
@EventListener
fun onInstanceRegistered(event: InstanceRegisteredEvent<*>) {
// 自己注册不需执行
// discover()
}
@EventListener
fun onParentHeartbeat(event: ParentHeartbeatEvent) {
discoverIfNeeded(event.value)
}
@EventListener
fun onApplicationEvent(event: HeartbeatEvent) {
discoverIfNeeded(event.value)
}
private fun discoverIfNeeded(value: Any) {
if (monitor.update(value)) {
// 等待几秒,健康检查通过后才能查到新的实例
sleep(10)
discover()
}
}
private fun discover() {
logger.debug("Discovering new instances from DiscoveryClient")
val groups = workerManager.listGroupByDiscoverType(DiscoveryTypeEnum.CLOUD)
groups.forEach { group ->
group.registryList = discoveryClient.getInstances(group.name).map { convertAddress(it) }
logger.debug("update group[${group.name}], set registry list: ${group.registryList}")
workerManager.updateGroup(group)
}
}
private fun convertAddress(instance: ServiceInstance): String {
return instance.uri.toString()
}
companion object {
private val logger = LoggerFactory.getLogger(WorkerDiscoveryListener::class.java)
}
}
| 7
|
Kotlin
|
22
| 27
|
cbff03abe5d572b09cbd486830d87cddc91b938b
| 2,410
|
devops-framework
|
MIT License
|
geary-papermc-integrations/src/main/kotlin/com/mineinabyss/geary/papermc/features/items/consumable/ConsumeItemFromInventory.kt
|
MineInAbyss
| 592,086,123
| false
|
{"Kotlin": 179720}
|
package com.mineinabyss.geary.papermc.features.items.consumable
import com.mineinabyss.idofront.serialization.SerializableItemStack
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("geary:consume_item")
class ConsumeItemFromInventory(
val type: SerializableItemStack,
val amount: Int = 1,
)
//@AutoScan
//fun GearyModule.createConsumeItemAction() = listener(
// object : ListenerQuery() {
// val player by get<Player>()
// val action by source.get<ConsumeItemFromInventory>()
// }
//).exec {
// val matchedItem = player.inventory.firstOrNull { action.type.matches(it) } ?: return@exec
// matchedItem.amount -= action.amount
//}
| 3
|
Kotlin
|
0
| 1
|
11f77ed5027f117c25bbae7cdf43cf09fe1a0ffc
| 725
|
geary-papermc
|
MIT License
|
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/CheckboxIndeterminate.kt
|
Konyaco
| 574,321,009
| false
| null |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.CheckboxIndeterminate: ImageVector
get() {
if (_checkboxIndeterminate != null) {
return _checkboxIndeterminate!!
}
_checkboxIndeterminate = fluentIcon(name = "Regular.CheckboxIndeterminate") {
fluentPath {
moveTo(6.25f, 3.0f)
arcTo(3.25f, 3.25f, 0.0f, false, false, 3.0f, 6.25f)
verticalLineToRelative(11.5f)
curveTo(3.0f, 19.55f, 4.46f, 21.0f, 6.25f, 21.0f)
horizontalLineToRelative(11.5f)
curveToRelative(1.8f, 0.0f, 3.25f, -1.46f, 3.25f, -3.25f)
verticalLineTo(6.25f)
curveTo(21.0f, 4.45f, 19.54f, 3.0f, 17.75f, 3.0f)
horizontalLineTo(6.25f)
close()
moveTo(4.5f, 6.25f)
curveToRelative(0.0f, -0.97f, 0.78f, -1.75f, 1.75f, -1.75f)
horizontalLineToRelative(11.5f)
curveToRelative(0.97f, 0.0f, 1.75f, 0.78f, 1.75f, 1.75f)
verticalLineToRelative(11.5f)
curveToRelative(0.0f, 0.97f, -0.78f, 1.75f, -1.75f, 1.75f)
horizontalLineTo(6.25f)
curveToRelative(-0.97f, 0.0f, -1.75f, -0.78f, -1.75f, -1.75f)
verticalLineTo(6.25f)
close()
moveTo(7.25f, 6.0f)
curveTo(6.56f, 6.0f, 6.0f, 6.56f, 6.0f, 7.25f)
verticalLineToRelative(9.5f)
curveToRelative(0.0f, 0.69f, 0.56f, 1.25f, 1.25f, 1.25f)
horizontalLineToRelative(9.5f)
curveToRelative(0.69f, 0.0f, 1.25f, -0.56f, 1.25f, -1.25f)
verticalLineToRelative(-9.5f)
curveTo(18.0f, 6.56f, 17.44f, 6.0f, 16.75f, 6.0f)
horizontalLineToRelative(-9.5f)
close()
}
}
return _checkboxIndeterminate!!
}
private var _checkboxIndeterminate: ImageVector? = null
| 1
|
Kotlin
|
3
| 83
|
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
| 2,198
|
compose-fluent-ui
|
Apache License 2.0
|
keel-slack/src/test/kotlin/com/netflix/spinnaker/keel/slack/handlers/NotificationEventListenerTests.kt
|
ranihorev
| 338,613,105
| true
|
{"Kotlin": 2536121, "Java": 20143, "Shell": 1691, "Slim": 359}
|
package com.netflix.spinnaker.keel.slack.handlers
import com.netflix.spinnaker.keel.api.DeliveryConfig
import com.netflix.spinnaker.keel.api.Environment
import com.netflix.spinnaker.keel.api.NotificationConfig
import com.netflix.spinnaker.keel.api.NotificationFrequency
import com.netflix.spinnaker.keel.api.NotificationType
import com.netflix.spinnaker.keel.api.artifacts.DeliveryArtifact
import com.netflix.spinnaker.keel.api.artifacts.PublishedArtifact
import com.netflix.spinnaker.keel.core.api.EnvironmentArtifactPin
import com.netflix.spinnaker.keel.core.api.EnvironmentArtifactVeto
import com.netflix.spinnaker.keel.events.ApplicationActuationPaused
import com.netflix.spinnaker.keel.events.ArtifactDeployedNotification
import com.netflix.spinnaker.keel.events.PinnedNotification
import com.netflix.spinnaker.keel.lifecycle.LifecycleEvent
import com.netflix.spinnaker.keel.lifecycle.LifecycleEventScope
import com.netflix.spinnaker.keel.lifecycle.LifecycleEventStatus
import com.netflix.spinnaker.keel.lifecycle.LifecycleEventType
import com.netflix.spinnaker.keel.persistence.KeelRepository
import com.netflix.spinnaker.keel.slack.NotificationEventListener
import com.netflix.spinnaker.keel.slack.SlackService
import com.netflix.spinnaker.keel.telemetry.ArtifactVersionVetoed
import com.netflix.spinnaker.keel.test.DummyArtifact
import com.netflix.spinnaker.keel.test.DummyArtifactReferenceResourceSpec
import com.netflix.spinnaker.keel.test.resource
import com.netflix.spinnaker.time.MutableClock
import com.slack.api.model.kotlin_extension.block.SectionBlockBuilder
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import io.mockk.Runs
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.verify
import java.time.Instant
import java.time.ZoneId
import com.netflix.spinnaker.keel.notifications.NotificationType as Type
class NotificationEventListenerTests : JUnit5Minutests {
class Fixture {
val repository: KeelRepository = mockk()
val releaseArtifact = DummyArtifact(reference = "release")
val version0 = "fnord-1.0.0-h0.a0a0a0a"
val version1 = "fnord-1.0.1-h1.b1b1b1b"
val versions = listOf(version0, version1)
val clock: MutableClock = MutableClock(
Instant.parse("2020-03-25T00:00:00.00Z"),
ZoneId.of("UTC")
)
val pin = EnvironmentArtifactPin("test", releaseArtifact.reference, version0, "<EMAIL>", "comment")
val application1 = "fnord1"
val singleArtifactEnvironments = listOf(
Environment(
name = "test",
notifications = setOf(
NotificationConfig(
type = NotificationType.slack,
address = "test",
frequency = NotificationFrequency.verbose
)
),
resources = setOf(
resource(
spec = DummyArtifactReferenceResourceSpec(
artifactReference = releaseArtifact.reference
)
)
)
),
Environment(
name = "staging",
notifications = setOf(
NotificationConfig(
type = NotificationType.slack,
address = "staging",
frequency = NotificationFrequency.verbose
)
),
resources = setOf(
resource(
spec = DummyArtifactReferenceResourceSpec(
artifactReference = releaseArtifact.reference
)
)
)
),
Environment(
name = "production",
notifications = setOf(
NotificationConfig(
type = NotificationType.slack,
address = "prod",
frequency = NotificationFrequency.verbose
),
NotificationConfig(
type = NotificationType.slack,
address = "prod#2",
frequency = NotificationFrequency.quiet
),
NotificationConfig(
type = NotificationType.email,
address = "@prod",
frequency = NotificationFrequency.verbose
)
)
),
)
val singleArtifactDeliveryConfig = DeliveryConfig(
name = "manifest_$application1",
application = application1,
serviceAccount = "keel@spinnaker",
artifacts = setOf(releaseArtifact),
environments = singleArtifactEnvironments.toSet(),
)
val slackService: SlackService = mockk()
val gitDataGenerator: GitDataGenerator = mockk()
val pinnedNotificationHandler: PinnedNotificationHandler = mockk(relaxUnitFun = true) {
every {
type
} returns Type.ARTIFACT_PINNED
}
val unpinnedNotificationHandler: UnpinnedNotificationHandler = mockk(relaxUnitFun = true) {
every {
type
} returns Type.ARTIFACT_UNPINNED
}
val pausedNotificationHandler: PausedNotificationHandler = mockk(relaxUnitFun = true) {
every {
type
} returns Type.APPLICATION_PAUSED
}
val lifecycleEventNotificationHandler: LifecycleEventNotificationHandler = mockk(relaxUnitFun = true) {
every {
type
} returns Type.LIFECYCLE_EVENT
}
val artifactDeployedNotificationHandler: ArtifactDeploymentNotificationHandler = mockk(relaxUnitFun = true) {
every {
type
} returns Type.ARTIFACT_DEPLOYMENT
}
val lifecycleEvent = LifecycleEvent(
type = LifecycleEventType.BAKE,
scope = LifecycleEventScope.PRE_DEPLOYMENT,
status = LifecycleEventStatus.FAILED,
artifactRef = releaseArtifact.toLifecycleRef(),
artifactVersion = version0,
id = "bake-$version0",
)
val failedToDeployNotification = ArtifactVersionVetoed(application1,
EnvironmentArtifactVeto(
"production",
releaseArtifact.reference,
version0,
"Spinnaker",
"Automatically marked as bad because multiple deployments of this version failed."
),
singleArtifactDeliveryConfig)
val artifactDeployedNotification = ArtifactDeployedNotification(
singleArtifactDeliveryConfig,
version1,
releaseArtifact,
"test"
)
val pinnedNotification = PinnedNotification(singleArtifactDeliveryConfig, pin)
val pausedNotification = ApplicationActuationPaused(application1, clock.instant(), "user1")
val subject = NotificationEventListener(repository, clock, listOf(pinnedNotificationHandler,
pausedNotificationHandler,
unpinnedNotificationHandler,
lifecycleEventNotificationHandler,
artifactDeployedNotificationHandler))
fun Collection<String>.toArtifactVersions(artifact: DeliveryArtifact) =
map { PublishedArtifact(artifact.name, artifact.type, it) }
}
fun tests() = rootContext<Fixture> {
fixture {
Fixture()
}
context("sending notifications with a single environment handler") {
before {
every {
slackService.getUsernameByEmail(any())
} returns "@keel"
every {
slackService.sendSlackNotification("test", any(), any(), any())
} just Runs
every {
gitDataGenerator.generateData(any(), any(), any())
} returns SectionBlockBuilder()
every { repository.getArtifactVersion(releaseArtifact, any(), any()) } returns versions.toArtifactVersions(releaseArtifact).first()
every {
repository.getArtifactVersionByPromotionStatus(any(), any(), any(), any())
} returns versions.toArtifactVersions(releaseArtifact).first()
every {
repository.latestVersionApprovedIn(any(), any(), any())
} returns versions.last()
}
test("the right (pinned) slack notification was sent out just once") {
subject.onPinnedNotification(pinnedNotification)
verify(exactly = 1) {
pinnedNotificationHandler.sendMessage(any(), any())
}
verify(exactly = 0) {
unpinnedNotificationHandler.sendMessage(any(), any())
}
}
test("only slack notifications are sent out") {
subject.onPinnedNotification(pinnedNotification.copy(pin = pin.copy(targetEnvironment = "production")))
verify(exactly = 2) {
pinnedNotificationHandler.sendMessage(any(), any())
}
}
test("don't send a notification if an environment was not found") {
subject.onPinnedNotification(pinnedNotification.copy(pin = pin.copy(targetEnvironment = "test#2")))
verify(exactly = 0) {
pinnedNotificationHandler.sendMessage(any(), any())
}
}
}
context("sending notifications to multiple environments") {
before {
every {
repository.getDeliveryConfigForApplication(application1)
} returns singleArtifactDeliveryConfig
}
test("sending pause notifications") {
subject.onApplicationActuationPaused(pausedNotification)
verify(exactly = 4) {
pausedNotificationHandler.sendMessage(any(), any())
}
}
}
context("lifecycle notifications") {
before {
every {
repository.getDeliveryConfig(any())
} returns singleArtifactDeliveryConfig
every { repository.getArtifactVersion(releaseArtifact, any(), any()) } returns versions.toArtifactVersions(releaseArtifact).first()
}
test("send notifications to relevant environments only"){
subject.onLifecycleEvent(lifecycleEvent)
verify(exactly = 2) {
lifecycleEventNotificationHandler.sendMessage(any(), any())
}
}
}
context("artifact deployment notifications"){
before {
every { repository.getArtifactVersion(releaseArtifact, any(), any()) } returns versions.toArtifactVersions(releaseArtifact).first()
every {
repository.getArtifactVersionByPromotionStatus(any(), any(), any(), any())
} returns versions.toArtifactVersions(releaseArtifact).first()
every {
repository.getDeliveryConfigForApplication(application1)
} returns singleArtifactDeliveryConfig
}
test("send successful deployment notifications using the right handler to the right env") {
subject.onArtifactVersionDeployed(artifactDeployedNotification)
verify (exactly = 1) {
artifactDeployedNotificationHandler.sendMessage(any(), any())
}
}
test("send failed deployment notifications using the right handler to the right env") {
subject.onArtifactVersionVetoed(failedToDeployNotification)
verify (exactly = 2) {
artifactDeployedNotificationHandler.sendMessage(any(), any())
}
}
}
}
}
| 0
| null |
0
| 0
|
c9f3564dfe2265734364adb38af203a2aa522c8c
| 10,616
|
keel
|
Apache License 2.0
|
paging/paging-compose/integration-tests/paging-demos/src/main/java/androidx/paging/compose/demos/PagingDemos.kt
|
RikkaW
| 389,105,112
| false
| null |
/*
* Copyright 2020 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.paging.compose.demos
import androidx.compose.integration.demos.common.ComposableDemo
import androidx.compose.integration.demos.common.DemoCategory
import androidx.paging.compose.demos.room.PagingRoomDemo
import androidx.paging.compose.samples.PagingBackendSample
val PagingDemos =
DemoCategory(
"Paging",
listOf(
ComposableDemo("Paging Backend Demo") { PagingBackendSample() },
ComposableDemo("Paging Room Demo") { PagingRoomDemo() }
)
)
| 29
| null |
1011
| 7
|
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
| 1,130
|
androidx
|
Apache License 2.0
|
gateway/src/main/kotlin/org/heeheepresso/gateway/search/SearchResult.kt
|
HeeHeePresso
| 758,780,391
| false
|
{"Kotlin": 120219, "Java": 11246}
|
package org.heeheepresso.gateway.search
import org.heeheepresso.gateway.common.response.StatusCode
import org.heeheepresso.gateway.search.request.SearchRequestHandler
import org.heeheepresso.gateway.search.searcher.SearcherType
data class SearchResult(
val statusCode: StatusCode,
val searcherType: SearcherType,
val searchRequestHandler: SearchRequestHandler,
var searched: List<Any>? = null
)
| 9
|
Kotlin
|
0
| 0
|
c41fa09c4157c726c21f617e731bb980a99b901a
| 413
|
Backend
|
Apache License 2.0
|
ui/src/commonMain/kotlin/com/popalay/barnee/ui/screen/addtocollection/CreateCollectionBottomSheet.kt
|
Popalay
| 349,051,151
| false
| null |
/*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.popalay.barnee.ui.screen.addtocollection
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Done
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.popalay.barnee.R
import com.popalay.barnee.data.model.Drink
import com.popalay.barnee.ui.theme.DEFAULT_ASPECT_RATIO
import com.popalay.barnee.ui.theme.MediumSquircleShape
import com.popalay.barnee.ui.util.applyForImageUrl
import com.popalay.barnee.ui.util.toIntSize
import com.popalay.barnee.util.displayImageUrl
@Composable
fun CreateCollectionBottomSheet(
drink: Drink,
collectionName: String,
canBeSaved: Boolean,
onSaveClicked: () -> Unit,
onBackClicked: () -> Unit,
onCollectionNameChanged: (String) -> Unit
) {
val nameFocus = remember { FocusRequester() }
LaunchedEffect(Unit) {
nameFocus.requestFocus()
}
BottomSheetContent(
title = { Text(text = "New collection") },
action = {
IconButton(
onClick = onSaveClicked,
enabled = canBeSaved
) {
Icon(
imageVector = Icons.Default.Done,
contentDescription = "Save"
)
}
},
body = {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
Card(
elevation = 4.dp,
shape = MediumSquircleShape,
modifier = Modifier
.height(96.dp)
.aspectRatio(DEFAULT_ASPECT_RATIO)
) {
BoxWithConstraints {
Image(
painter = rememberImagePainter(
data = drink.displayImageUrl,
builder = { applyForImageUrl(drink.displayImageUrl, constraints.toIntSize()) },
),
contentDescription = null,
contentScale = ContentScale.Crop
)
}
}
TextField(
value = collectionName,
onValueChange = onCollectionNameChanged,
singleLine = true,
textStyle = MaterialTheme.typography.body1.copy(textAlign = TextAlign.Center),
colors = TextFieldDefaults.textFieldColors(backgroundColor = Color.Unspecified),
modifier = Modifier
.fillMaxWidth(0.3F)
.focusRequester(nameFocus)
)
}
},
navigation = {
IconButton(onClick = onBackClicked) {
Icon(
painter = painterResource(R.drawable.ic_arrow_back),
contentDescription = "Back"
)
}
}
)
}
| 21
| null |
3
| 15
|
22cd50b851d7be321339e8674099aa01fe7e1c3f
| 5,252
|
Barnee
|
MIT License
|
compiler/src/main/kotlin/io/github/apl_cornell/viaduct/backends/zkp/ZKPProtocolParser.kt
|
apl-cornell
| 169,159,978
| false
| null |
package io.github.apl_cornell.viaduct.backends.zkp
import io.github.apl_cornell.viaduct.parsing.ProtocolArguments
import io.github.apl_cornell.viaduct.parsing.ProtocolParser
import io.github.apl_cornell.viaduct.syntax.values.HostSetValue
import io.github.apl_cornell.viaduct.syntax.values.HostValue
/** Parser for the [ZKP] protocol. */
object ZKPProtocolParser : ProtocolParser<ZKP> {
override fun parse(arguments: ProtocolArguments): ZKP {
val sender = arguments.get<HostValue>("prover")
val receivers = arguments.get<HostSetValue>("verifiers")
return ZKP(sender.value, receivers)
}
}
| 26
|
Kotlin
|
5
| 15
|
e681f77562fdafa93b8fb5b929d96aca08affc1a
| 621
|
viaduct
|
MIT License
|
common/src/main/java/jp/co/soramitsu/common/utils/QrCodeGenerator.kt
|
mrZizik
| 315,566,082
| true
|
{"Kotlin": 1269808}
|
package jp.co.soramitsu.common.utils
import android.graphics.Bitmap
import com.google.zxing.EncodeHintType
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import com.google.zxing.qrcode.encoder.Encoder
class QrCodeGenerator(
private val firstColor: Int,
private val secondColor: Int
) {
companion object {
private const val RECEIVE_QR_SCALE_SIZE = 1024
private const val PADDING_SIZE = 2
}
fun generateQrBitmap(input: String): Bitmap {
val hints = HashMap<EncodeHintType, String>()
hints[EncodeHintType.CHARACTER_SET] = "UTF-8"
val qrCode = Encoder.encode(input, ErrorCorrectionLevel.H, hints)
val byteMatrix = qrCode.matrix
val width = byteMatrix.width + PADDING_SIZE
val height = byteMatrix.height + PADDING_SIZE
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
for (y in 0 until height) {
for (x in 0 until width) {
if (y == 0 || y > byteMatrix.height || x == 0 || x > byteMatrix.width) {
bitmap.setPixel(x, y, secondColor)
} else {
bitmap.setPixel(x, y, if (byteMatrix.get(x - PADDING_SIZE / 2, y - PADDING_SIZE / 2).toInt() == 1) firstColor else secondColor)
}
}
}
return Bitmap.createScaledBitmap(bitmap, RECEIVE_QR_SCALE_SIZE, RECEIVE_QR_SCALE_SIZE, false)
}
}
| 0
| null |
0
| 0
|
e4139ee7cbb9b48b4b622d6a3ddcf4a9e25dabca
| 1,439
|
fearless-Android
|
Apache License 2.0
|
recycleradapter/src/main/java/com/xingray/recycleradapter/HolderFactory.kt
|
XingRay
| 174,304,928
| false
| null |
package com.xingray.recycleradapter
import android.view.View
/**
*{@code ViewHolder}工厂
*
* @author : leixing
* @date : 19-7-14
* email : leixing1012@qq.com
*
*/
interface HolderFactory<VH> {
fun create(itemView: View): VH
}
| 0
|
Kotlin
|
1
| 2
|
1b1a781c233ad932fe123e224a3bdecdc9a17354
| 236
|
RecyclerAdapter
|
Apache License 2.0
|
firsttestdemo/src/main/java/com/hikeen/firsttestdemo/ProviderActivity.kt
|
weigg520
| 489,902,751
| false
| null |
package com.hikeen.firsttestdemo
import android.app.Activity
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.content.contentValuesOf
import kotlinx.android.synthetic.main.activity_provider.*
class ProviderActivity : Activity() ,View.OnClickListener{
private val uriStrPath = "content://com.wzz.firstlinecode.provider/book"
private var bookId:String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_provider)
bt_add.setOnClickListener(this)
bt_query.setOnClickListener(this)
bt_update.setOnClickListener(this)
bt_delete.setOnClickListener(this)
}
private fun addData(){
//添加数据
val contentValues = contentValuesOf("name" to "A Clash of Kings",
"author" to "<NAME>", "pages" to 1040, "price" to 22.85)
val uriValue = contentResolver.insert(Uri.parse(uriStrPath),contentValues)
bookId = uriValue?.pathSegments?.get(1)
Log.e("ProviderActivity", "bookId: $bookId")
}
private fun updateData(){
//更新数据
bookId?.let {
val uri = Uri.parse("$uriStrPath/$it")
val values = contentValuesOf("name" to "A Storm of Swords",
"pages" to 1216, "price" to 24.05)
val id = contentResolver.update(uri,values,null,null)
Log.e("ProviderActivity", "updateData: $id" )
}
}
private fun queryData() {
//查询
val uri = Uri.parse(uriStrPath)
contentResolver.query(uri, null, null, null, null)?.apply {
while (moveToNext()) {
Log.e(
"ProviderActivity", "book name: "
+ getString(getColumnIndex("name"))
)
Log.e(
"ProviderActivity", "book author: "
+ getString(getColumnIndex("author"))
)
Log.e(
"ProviderActivity", "book price: "
+ getString(getColumnIndex("price"))
)
Log.e(
"ProviderActivity", "book pages: "
+ getString(getColumnIndex("pages"))
)
}
close()
}
}
private fun deleteData(){
//删除数据
bookId?.let {
val uri = Uri.parse("$uriStrPath/$it")
contentResolver.delete(uri,null,null)
}
}
override fun onClick(v: View?) {
when(v?.id){
R.id.bt_add -> {
addData()
}
R.id.bt_update -> {
updateData()
}
R.id.bt_query -> {
queryData()
}
R.id.bt_delete -> {
deleteData()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7a10fe1d876f8a7f7ec55ad414c1823e24400b2b
| 2,956
|
FirsLineCode
|
Apache License 2.0
|
language-kotlin/kotlin-sample/coroutine-in-action/src/main/kotlin/com/chiclaim/coroutine/basic/example-basic-04.kt
|
qxf323
| 279,827,316
| false
| null |
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(200L)
println("Task from runBlocking")
}
// Creates a new coroutine scope
coroutineScope {
//基于该scope的coroutine
launch {
delay(500L)
println("Task from nested launch1")
}
//基于该scope的coroutine
launch {
delay(500L)
println("Task from nested launch2")
}
delay(100L)
//称之为scope域代码
println("Task from coroutine scope") // This line will be printed before nested launch
}
println("Coroutine scope is over") // This line is not printed until nested launch completes
}
/*
Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over
*/
/*
从example-basic-03s.kt的例子我们知道,如果内部的coroutine是基于外部的scope创建的,那么执行顺序为:
1, 先执行外部的scope域代码
2, 然后执行基于外部scope创建的coroutine代码
在本例子中是在example-basic-03s.kt的基础上,添加了 基于一个全新的scope创建coroutine,它的执行顺序为:
1, 先执行基于全新scope域代码
2, 然后执行基于外部scope创建的coroutine代码(如果有多个coroutine,则依次执行)
3, 在然后执行基于全新scope的coroutine代码
4, 最后执行外部scope域代码
*/
| 0
| null |
2
| 4
|
79f1f65112bc64522fcd41cb13c3ac5048d2a0d6
| 1,151
|
AndroidAll
|
Apache License 2.0
|
compiler/testData/codegen/box/operatorConventions/kt4152.kt
|
JakeWharton
| 99,388,807
| false
| null |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
public var inc: Int = 0;
public var propInc: Int = 0
get() {inc++; return field}
set(a: Int) {
inc++
field = a
}
public var dec: Int = 0;
public var propDec: Int = 0;
get() { dec--; return field}
set(a: Int) {
dec--
field = a
}
fun box(): String {
propInc++
if (inc != 2) return "fail in postfix increment: ${inc} != 2"
if (propInc != 1) return "fail in postfix increment: ${propInc} != 1"
propDec--
if (dec != -2) return "fail in postfix decrement: ${dec} != -2"
if (propDec != -1) return "fail in postfix decrement: ${propDec} != -1"
return "OK"
}
| 179
| null |
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 735
|
kotlin
|
Apache License 2.0
|
jetbrains-core/tst/software/aws/toolkits/jetbrains/services/s3/editor/S3ViewerPanelTest.kt
|
JetBrains
| 223,485,227
| false
| null |
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.s3.editor
import com.intellij.ide.DataManager
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.TestApplicationManager
import com.intellij.testFramework.runInEdtAndWait
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.mock
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response
import software.aws.toolkits.core.utils.test.aString
class S3ViewerPanelTest {
@Rule
@JvmField
val disposableRule = DisposableRule()
@Rule
@JvmField
val projectRule = ProjectRule()
private lateinit var s3Bucket: S3VirtualBucket
private lateinit var sut: S3ViewerPanel
@Before
fun setUp() {
s3Bucket = mock {
on { prefix }.thenReturn("")
on { name }.thenReturn(aString())
onBlocking { listObjects(any(), anyOrNull()) }.thenReturn(
ListObjectsV2Response.builder()
.commonPrefixes({ it.prefix("folder/") })
.build()
)
}
sut = S3ViewerPanel(disposableRule.disposable, projectRule.project, s3Bucket)
TestApplicationManager.getInstance().setDataProvider(DataManager.getDataProvider(sut.component), disposableRule.disposable)
}
@Test
fun `data provider selected nodes key returns table selected values`() {
runInEdtAndWait {
val dataProvider = DataManager.getInstance().getDataContext(sut.component)
sut.treeTable.clearSelection()
assertThat(dataProvider.getData(S3EditorDataKeys.SELECTED_NODES)).isEmpty()
sut.treeTable.addRowSelectionInterval(0, 0)
assertThat(dataProvider.getData(S3EditorDataKeys.SELECTED_NODES)).containsExactly(S3TreeDirectoryNode(s3Bucket, null, "folder/"))
}
}
@Test
fun `data provider bucket table key returns the table`() {
val dataProvider = DataManager.getInstance().getDataContext(sut.component)
assertThat(dataProvider.getData(S3EditorDataKeys.BUCKET_TABLE)).isEqualTo(sut.treeTable)
}
}
| 6
| null |
4
| 9
|
ccee3307fe58ad48f93cd780d4378c336ee20548
| 2,415
|
aws-toolkit-jetbrains
|
Apache License 2.0
|
pumping/src/test/kotlin/com/dpm/pumping/auth/presentation/AuthControllerTest.kt
|
depromeet
| 627,802,875
| false
| null |
package com.dpm.pumping.auth.presentation
import com.dpm.pumping.auth.application.AuthService
import com.dpm.pumping.auth.application.JwtTokenProvider
import com.dpm.pumping.auth.domain.LoginType
import com.dpm.pumping.auth.dto.AccessTokenResponse
import com.dpm.pumping.auth.dto.SignUpResponse
import com.dpm.pumping.auth.oauth2.OAuth2AppleClient
import com.dpm.pumping.auth.oauth2.dto.AppleLoginRequest
import com.dpm.pumping.auth.oauth2.dto.OAuth2LoginResponse
import com.dpm.pumping.auth.oauth2.dto.SignUpRequest
import com.dpm.pumping.user.domain.CharacterType
import com.dpm.pumping.user.domain.Gender
import com.dpm.pumping.user.domain.UserRepository
import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.jupiter.api.Test
import org.mockito.BDDMockito.given
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document
import org.springframework.restdocs.operation.preprocess.Preprocessors.*
import org.springframework.restdocs.payload.JsonFieldType
import org.springframework.restdocs.payload.PayloadDocumentation.*
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.post
import java.time.LocalDateTime
import java.util.*
@WebMvcTest(AuthController::class)
@AutoConfigureRestDocs
@ActiveProfiles("test")
class AuthControllerTest @Autowired constructor(
private val mockMvc: MockMvc,
private val objectMapper: ObjectMapper,
) {
@MockBean
private lateinit var oAuth2AppleClient: OAuth2AppleClient
@MockBean
private lateinit var authService: AuthService
@MockBean
private lateinit var jwtTokenProvider: JwtTokenProvider
@MockBean
private lateinit var userRepository: UserRepository
@Test
fun login() {
val request = AppleLoginRequest("tokenId")
val response = OAuth2LoginResponse(
null,
null,
LoginType.APPLE,
"OAauth_id"
)
given(oAuth2AppleClient.getAppleUserId(request)).willReturn("oauthID")
given(authService.login("oauthID")).willReturn(response)
mockMvc.post("/api/v1/oauth2/apple/login") {
contentType = MediaType.APPLICATION_JSON
content = objectMapper.writeValueAsString(request)
}
.andExpect { status { isOk() } }
.andDo {
handle(
document(
"oauth2-apple-login",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
requestFields(
fieldWithPath("idToken").type(JsonFieldType.STRING).description("redirectUrl에서 받은 id_token")
),
relaxedResponseFields(
fieldWithPath("accessToken").type(JsonFieldType.STRING)
.description("login했던 사용자면 accessToken, 최초 로그인 사용자면 null; 즉, null이면 회원가입 api 호출")
.optional(),
fieldWithPath("expiredTime").type(JsonFieldType.STRING)
.description("accessToken만료일, 최초 로그인이면 null").optional(),
fieldWithPath("loginType").type(JsonFieldType.STRING)
.description("loginType으로 애플 로그인이면 APPLE"),
fieldWithPath("oauth2Id").type(JsonFieldType.STRING)
.description("애플 로그인한 사용자의 애플 고유 id").optional(),
)
)
)
}
}
@Test
fun signUp() {
val request = SignUpRequest("name", Gender.MALE, "180.2", "90.4", CharacterType.A, LoginType.APPLE, "id")
val response = SignUpResponse("accessToken", LocalDateTime.now().plusDays(5), "userId")
given(authService.signUp(request)).willReturn(response)
mockMvc.post("/api/v1/sign-up") {
content = objectMapper.writeValueAsBytes(request)
contentType = MediaType.APPLICATION_JSON
}.andExpect {
status { isOk() }
}
.andDo {
handle(
document(
"signup",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
requestFields(
fieldWithPath("name").type(JsonFieldType.STRING).description("유저 이름"),
fieldWithPath("gender").type(JsonFieldType.STRING).description("유저 성별"),
fieldWithPath("height").type(JsonFieldType.STRING).description("유저 키"),
fieldWithPath("weight").type(JsonFieldType.STRING).description("유저 몸무게"),
fieldWithPath("characterType").type(JsonFieldType.STRING).description("케릭터 타입"),
fieldWithPath("loginType").type(JsonFieldType.STRING)
.description("loginType으로 애플 로그인이면 APPLE"),
fieldWithPath("oauth2Id").type(JsonFieldType.STRING)
.description("애플 로그인한 사용자의 애플 고유 id").optional(),
),
responseFields(
fieldWithPath("accessToken").type(JsonFieldType.STRING)
.description("login했던 사용자면 accessToken, 최초 로그인 사용자면 null; 즉, null이면 회원가입 api 호출")
.optional(),
fieldWithPath("expiredTime")
.description("accessToken만료일, 최초 로그인이면 null").optional(),
fieldWithPath("userId")
.description("user의 id"),
)
)
)
}
}
}
| 3
|
Kotlin
|
0
| 2
|
366e951c11eafc9369aa0095337579ffb23f7ec6
| 6,248
|
pumping-server
|
Apache License 2.0
|
base/courseapp-app/src/main/kotlin/il/ac/technion/cs/softwaredesign/dataTypeProxies/Channel.kt
|
avi1mizrahi
| 181,363,343
| false
|
{"Kotlin": 338899}
|
package il.ac.technion.cs.softwaredesign.dataTypeProxies
import com.google.inject.Inject
import il.ac.technion.cs.softwaredesign.*
import il.ac.technion.cs.softwaredesign.Set
import il.ac.technion.cs.softwaredesign.exceptions.NameFormatException
import il.ac.technion.cs.softwaredesign.dataTypeProxies.UserManager.User
import org.junit.jupiter.api.Assertions.assertEquals
import java.util.concurrent.CompletableFuture
// Valid names for channels start with `#`, then have any number of English alphanumeric characters, underscores
// (`_`) and hashes (`#`).
private fun isBadChannelName(name : String) : Boolean {
val alphanumeric = ('a'..'z') + ('A'..'Z') + ('0'..'9') + '_' + '#'
if (!name.startsWith("#"))
return true
if (name.drop(1).any { char -> !alphanumeric.contains(char)})
return true
return false
}
/**
* A manager handling channel logic.
*/
class ChannelManager @Inject constructor(private val _db: KeyValueStore) {
private val DB = _db.scope("channels")
private val allChannels = Array(ScopedKeyValueStore(DB, listOf("allChannels")))
private val nameToId = DB.getIntMapReference(listOf("nameToId"))
val statistics = Statistics()
inner class Statistics{
val allChannelsByUserCount = Heap(ScopedKeyValueStore(DB, listOf("ChannelsByUserCount")),
{id -> getChannelById(id).getUserCount()},
{id -> -id})
val allChannelsByActiveCount = Heap(ScopedKeyValueStore(DB, listOf("ChannelsByActiveUserCount")),
{id -> getChannelById(id).getActiveCount()},
{id -> -id})
val allChannelsByMessageCount = Heap(ScopedKeyValueStore(DB, listOf("ChannelsByMessageCount")),
{id -> getChannelById(id).getMessageCount()},
{id -> -id})
/**
* Statistics: Returns top 10 channels by user count
*/
fun getTop10ChannelsByUserCount() : List<String> {
return allChannelsByUserCount.getTop10().map { id -> getChannelById(id).getName() }
}
/**
* Statistics: Returns top 10 channels by active user count
*/
fun getTop10ChannelsByActiveUserCount() : List<String> {
return allChannelsByActiveCount.getTop10().map { id -> getChannelById(id).getName() }
}
/**
* Statistics: Returns top 10 channels by message count
*/
fun getTop10ChannelsByMessageCount() : List<String> {
return allChannelsByMessageCount.getTop10().map { id -> getChannelById(id).getName() }
}
}
/**
* Create a new channel
* Assumptions:
* -The given name is unique and is legal
*
* @param name Channel's name
*/
fun createNewChannel(name : String) : Channel {
val (channelDB, id) = allChannels.newSlot()
val channel = Channel(channelDB, id)
channel.initialize(name)
nameToId.write(name, id)
statistics.allChannelsByUserCount.addMinimum(id)
statistics.allChannelsByActiveCount.add(id)
statistics.allChannelsByMessageCount.addMinimum(id)
return channel
}
/**
* Checks a string and throws if its an illegal channel name
*/
fun throwIfBadChannelName(name : String) {
if (isBadChannelName(name)) throw NameFormatException()
}
/**
* Returns a channel by a name
* @param name Name of the channel
* @returns Channel of that name or null if not found
*/
fun getChannelByName(name : String) : Channel? {
val channelID = nameToId.read(name) ?: return null
return Channel(allChannels[channelID]!!, channelID)
}
/**
* Returns a channel by its ID
* @param id ID of the channel
* @returns Channel of that id
*/
fun getChannelById(channelID : Int) : Channel {
return Channel(allChannels[channelID]!!, channelID)
}
//
// fun channelExists(name : String) : Boolean {
// return allChannels.read(name) != null
// }
/**
* Remove a channel
* Assumptions:
* -Channel must be empty!
*
* @param c Channel to remove
*
*/
fun removeChannel(c : Channel) {
//assert(c.getUserCount() == 0)
CompletableFuture.allOf(
CompletableFuture.runAsync {nameToId.delete(c.getName())},
CompletableFuture.runAsync {statistics.allChannelsByUserCount.remove(c.getID())},
CompletableFuture.runAsync {statistics.allChannelsByActiveCount.remove(c.getID())},
CompletableFuture.runAsync {statistics.allChannelsByMessageCount.remove(c.getID())}
).join()
}
/**
* An object representing a channel on the DB
*/
inner class Channel(DB: KeyValueStore, private val id: Int) {
private val userList = Set(DB.scope("users"))
private val activeList = Set(DB.scope("activeUsers"))
private val operatorList = Set(DB.scope("operators"))
private val name = DB.getStringReference("name")
private val messageCount = DB.getIntReference("messageCount")
/**
* Return the amount of messages in the channel
*/
fun getMessageCount() = messageCount.read() ?: 0
/**
* Increment the message counter
*/
fun addToMessagesCount() {
messageCount.write(getMessageCount() + 1)
statistics.allChannelsByMessageCount.idIncremented(id)
}
/**
* Initialize the constant fields of the channel. Must be called by the managers's createNewChannel
*/
fun initialize(s : String) {
name.write(s)
}
/**
* Returns the id of the channel
*/
fun getID() = id
/**
* Returns the name of the channel
*/
fun getName() = name.read()!!
/**
* Returns the amount of users in the channel
* These values are cached and wrong reads/writes may happen if 2 instances representing the same channel use this
*/
fun getUserCount() : Int {
return userList.count()
}
/**
* Returns the amount of active users in the channel
* These values are cached and wrong reads/writes may happen if 2 instances representing the same channel use this
*/
fun getActiveCount() : Int {
return activeList.count()
}
/**
* Add a user to the channel's operator list
* @param user User to add
*/
fun addOp(user : User) {
operatorList.add(user.id())
}
/**
* Check if a user is an operator on this channel
* @param user User to check
*/
fun isOp(user : User) : Boolean = operatorList.exists(user.id())
/**
* Add a user to this channels Active user list
* @param user User to add
*/
fun addActive(user : User) {
activeList.add(user.id())
statistics.allChannelsByActiveCount.idIncremented(id)
}
/**
* Remove a user from this channels Active user list
* @param user User to remove
*/
fun removeActive(user : User) {
activeList.remove(user.id())
statistics.allChannelsByActiveCount.idDecremented(id)
}
private fun isActive(user : User) : Boolean = activeList.exists(user.id())
/**
* Add a user to this channel
* @param user User to add
*/
fun addUser(user : User) {
val userid = user.id()
userList.add(userid)
statistics.allChannelsByUserCount.idIncremented(id)
if (user.isLoggedIn())
addActive(user)
}
/**
* Remove a user from this channel
* @param user User to remove
*/
fun removeUser(user : User) {
val userid = user.id()
CompletableFuture.allOf(
CompletableFuture.runAsync {
userList.remove(userid)
statistics.allChannelsByUserCount.idDecremented(id)
},
CompletableFuture.runAsync {
if (operatorList.exists(userid))
operatorList.remove(userid)
},
CompletableFuture.runAsync {
activeList.remove(userid)
statistics.allChannelsByActiveCount.idDecremented(id)
}
).join()
if (getUserCount() == 0) {
removeChannel(this)
}
}
/**
* Run an action on the ID of each user in this channel
*/
fun forEachUser( func: (Int) -> Unit) {
userList.forEach(func)
}
/**
* returns true if the channel has given user
* @param user User to check.
*/
fun hasUser(user : User) : Boolean = userList.exists(user.id())
}
}
| 0
|
Kotlin
|
0
| 0
|
2c0d94762ffb6139294244c19943b238476ca249
| 9,155
|
CourseApp
|
MIT License
|
src/main/kotlin/util/InputReader.kt
|
andilau
| 433,504,283
| false
|
{"Kotlin": 137815}
|
package util
import java.io.File
import java.net.URI
object InputReader {
fun getInputAsString(day: Int): String = File(fromResources(day)).readText()
fun getInputAsList(day: Int): List<String> = File(fromResources(day)).readLines()
fun getInputAsListOfInt(day: Int): List<Int> = File(fromResources(day)).readLines().map(String::toInt)
fun getInputAsListOfLong(day: Int): List<Long> = File(fromResources(day)).readLines().map(String::toLong)
private fun fromResources(day: Int): URI =
javaClass.classLoader.getResource("input_day_$day.txt")?.toURI()
?: throw IllegalArgumentException("input file for day $day not found")
}
| 3
|
Kotlin
|
0
| 0
|
9bea0f233b7037ab816f7469847199131c762ea7
| 668
|
advent-of-code-2021
|
Creative Commons Zero v1.0 Universal
|
src/com/hxz/mpxjs/model/VueGlobalImpl.kt
|
wuxianqiang
| 508,329,768
| false
|
{"Kotlin": 1447881, "Vue": 237479, "TypeScript": 106023, "JavaScript": 93869, "HTML": 17163, "Assembly": 12226, "Lex": 11227, "Java": 2846, "Shell": 1917, "Pug": 338}
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.hxz.mpxjs.model
import com.intellij.javascript.nodejs.PackageJsonData
import com.intellij.javascript.web.webTypes.nodejs.PackageJsonWebTypesRegistryManager
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.lang.javascript.buildTools.npm.PackageJsonUtil
import com.intellij.lang.javascript.library.JSLibraryUtil.NODE_MODULES
import com.intellij.model.Pointer
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.MultiMap
import com.hxz.mpxjs.model.source.VueSourceGlobal
import com.hxz.mpxjs.model.source.VueSourcePlugin
import java.util.concurrent.ConcurrentHashMap
internal class VueGlobalImpl(override val project: Project, override val packageJsonUrl: String)
: VueDelegatedEntitiesContainer<VueGlobal>(), VueGlobal {
override val source: PsiElement? = null
override val parents: List<VueEntitiesContainer> = emptyList()
override val global: VueGlobal get() = this
override val plugins: List<VuePlugin>
get() = CachedValuesManager.getManager(project).getCachedValue(this, this::buildPluginsList)
override val apps: List<VueApp> get() = delegate.apps
override val unregistered: VueEntitiesContainer get() = delegate.unregistered
private val mySourceGlobal = VueSourceGlobal(project, packageJsonUrl)
private val packageJson: VirtualFile? get() = findFileByUrl(packageJsonUrl)
override val delegate
get() = mySourceGlobal
override fun getParents(scopeElement: VueScopeElement): List<VueEntitiesContainer> =
getElementToParentMap().get(scopeElement).toList()
private fun getElementToParentMap(): MultiMap<VueScopeElement, VueEntitiesContainer> =
CachedValuesManager.getManager(project).getCachedValue(this) {
Result.create(buildElementToParentMap(),
PsiModificationTracker.MODIFICATION_COUNT,
VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS)
} ?: MultiMap.empty()
/**
* Because of VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS
* we don't support scenarios in which you modify the `Vue.use` calls in main.js file
* and go back to editing an already existing Vue component
*/
private fun buildPluginsList(): Result<List<VuePlugin>> {
val result = mutableListOf<VuePlugin>()
val dependencies = mutableListOf<Any>(VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS)
packageJson?.let { file ->
dependencies.add(PackageJsonWebTypesRegistryManager.getModificationTracker(project, file))
PackageJsonWebTypesRegistryManager.getNodeModulesWithoutWebTypes(project, file)
.asSequence()
.filter { isVueLibrary(it) }
.map { VueSourcePlugin(project, it.name, it.version?.toString(), it.packageJsonFile) }
// Make order of plugin symbol containers predictable
.sortedBy { it.moduleName ?: "" }
.toCollection(result)
}
return Result.create(result, dependencies)
}
private fun buildElementToParentMap(): MultiMap<VueScopeElement, VueEntitiesContainer> {
val result = MultiMap<VueScopeElement, VueEntitiesContainer>()
sequenceOf(this)
.plus(plugins)
.plus(apps)
.forEach { container ->
sequenceOf(container.components.values,
container.directives.values,
container.filters.values,
container.mixins)
.flatMap { it.asSequence() }
.let { sequence ->
if (container is VueApp)
container.rootComponent?.let { rootComponent -> sequence.plus(rootComponent) } ?: sequence
else
sequence
}
.mapNotNull { if (it is VueDelegatedContainer<*>) it.delegate else it }
.forEach { el -> result.putValue(el, container) }
}
return result
}
override fun equals(other: Any?): Boolean {
return (other as? VueGlobalImpl)?.let {
it.project == project && it.packageJsonUrl == packageJsonUrl
} ?: false
}
override fun hashCode(): Int {
return (project.hashCode()) * 31 + packageJsonUrl.hashCode()
}
override fun createPointer(): Pointer<out VueGlobal> = Pointer.hardPointer(this)
companion object {
fun findFileByUrl(packageJsonUrl: String?): VirtualFile? {
return if (packageJsonUrl != null)
// TODO consider refresh if not valid
VirtualFileManager.getInstance().findFileByUrl(packageJsonUrl)
?.takeIf { it.isValid }
else null
}
fun getParents(scopeElement: VueScopeElement): List<VueEntitiesContainer> =
scopeElement.global?.getParents(scopeElement) ?: emptyList()
fun get(context: PsiElement): VueGlobal {
val psiFile = InjectedLanguageManager.getInstance(context.project).getTopLevelFile(context)
return psiFile?.originalFile
?.virtualFile
?.let { locatePackageJson(it) }
?.let {
getGlobalsMap(context.project)
.computeIfAbsent(it.url) { url -> VueGlobalImpl(context.project, url) }
}
?: VueSourceGlobal(context.project, null)
}
private val GLOBALS_CACHE_KEY = Key<CachedValue<MutableMap<String, VueGlobalImpl>>>("vue.globals")
private fun getGlobalsMap(project: Project): MutableMap<String, VueGlobalImpl> =
CachedValuesManager.getManager(project).getCachedValue(project, GLOBALS_CACHE_KEY, {
Result.create(ConcurrentHashMap(), ModificationTracker.NEVER_CHANGED)
}, false)
private fun locatePackageJson(context: VirtualFile): VirtualFile? {
var result: VirtualFile? = null
PackageJsonUtil.processUpPackageJsonFilesInAllScope(context) { candidate ->
var level = 4
var parent = candidate.parent
while (parent != null && level-- >= 0) {
if (NODE_MODULES == parent.name) {
return@processUpPackageJsonFilesInAllScope true
}
parent = parent.parent
}
result = candidate
false
}
return result
}
private fun isVueLibrary(data: PackageJsonData): Boolean =
data.name != "@vue/cli-service"
&& (data.name == "vue"
|| data.containsOneOfDependencyOfAnyType("vue-loader", "vue-latest", "vue", "vue-template-compiler"))
}
}
| 2
|
Kotlin
|
0
| 4
|
e069e8b340ab04780ac13eab375d900f21bc7613
| 6,796
|
intellij-plugin-mpx
|
Apache License 2.0
|
common/core/src/main/java/com/him/sama/spotifycompose/common/core/data/repository/SearchRepositoryImpl.kt
|
arohim
| 762,735,266
| false
|
{"Kotlin": 223059}
|
package com.him.sama.spotifycompose.common.core.data.repository
import arrow.core.Either
import arrow.core.EitherNel
import arrow.core.getOrElse
import arrow.core.left
import arrow.core.leftWiden
import arrow.core.right
import com.him.sama.spotifycompose.common.core.base.Mapper
import com.him.sama.spotifycompose.common.core.base.dispatcher.AppCoroutineDispatchers
import com.him.sama.spotifycompose.common.core.base.retrySuspend
import com.him.sama.spotifycompose.common.core.data.remote.model.SearchPageResponse
import com.him.sama.spotifycompose.common.core.data.remote.service.ApiService
import com.him.sama.spotifycompose.common.core.domain.model.SearchPageDomainModel
import com.him.sama.spotifycompose.common.core.domain.model.UserError
import com.him.sama.spotifycompose.common.core.domain.repository.SearchRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.IOException
import javax.inject.Inject
import kotlin.time.DurationUnit
import kotlin.time.toDuration
class SearchRepositoryImpl @Inject constructor(
private val apiService: ApiService,
private val dispatchers: AppCoroutineDispatchers,
private val responseToDomain: Mapper<SearchPageResponse, EitherNel<Nothing, SearchPageDomainModel>>,
private val errorMapper: Mapper<Throwable, UserError>
) : SearchRepository {
private val responseToDomainThrows: (SearchPageResponse) -> SearchPageDomainModel =
{ response ->
responseToDomain(response).let { validated ->
validated.getOrElse {
val t = UserError.NetworkError
throw t
}
}
}
private suspend fun getSearchPageFromRemoteWithRetry(): SearchPageDomainModel {
return withContext(dispatchers.io) {
retrySuspend(
times = 3,
initialDelay = 500.toDuration(DurationUnit.MILLISECONDS),
factor = 2.0,
shouldRetry = { it is IOException }
) { times ->
Timber.d("[SEARCH_REPO] Retry times=$times")
val search = apiService.getSearch()
responseToDomainThrows(search)
}
}
}
override suspend fun fetchSearchPage(): Flow<Either<UserError, SearchPageDomainModel>> {
return flow {
emit(getSearchPageFromRemoteWithRetry())
}.map {
val right = it.right()
right.leftWiden<UserError, Nothing, SearchPageDomainModel>()
}.catch {
logError(it, "fetchSearchPage")
val value: Either<UserError, Nothing> = errorMapper(it).left()
emit(value)
}
}
private fun logError(t: Throwable, message: String) = Timber.tag(TAG).e(t, message)
private companion object {
private val TAG = SearchRepositoryImpl::class.java.simpleName
}
}
| 0
|
Kotlin
|
0
| 0
|
826694a8a38dc6f53b48e3a337c8bd15a0f8549c
| 3,031
|
SpotifyJetpackCompose
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/gamelift/CfnBuildPropsDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.gamelift
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.gamelift.CfnBuildProps
@Generated
public fun buildCfnBuildProps(initializer: @AwsCdkDsl CfnBuildProps.Builder.() -> Unit):
CfnBuildProps = CfnBuildProps.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
e9a0ff020b0db2b99e176059efdb124bf822d754
| 385
|
aws-cdk-kt
|
Apache License 2.0
|
composeApp/src/desktopMain/kotlin/org/example/rammultiplatform/HttpClientEngineModule.desktop.kt
|
vimi30
| 863,714,235
| false
|
{"Kotlin": 112838, "Swift": 667}
|
package org.example.rammultiplatform
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.cio.CIO
import org.koin.core.module.Module
import org.koin.dsl.module
actual val httpClientEngine: Module = module {
single<HttpClientEngine> {
CIO.create()
}
}
| 0
|
Kotlin
|
0
| 0
|
fee830a016b3a559f4dce2d8832cbe0f4ceb7b8c
| 290
|
RickAndMorty
|
MIT License
|
sample/src/main/java/ro/dobrescuandrei/roomdynamicdaosample/dao/querybuilder/DemoQueryBuilder.kt
|
andob
| 162,691,296
| false
| null |
package ro.dobrescuandrei.roomdynamicdaosample.dao.querybuilder
import com.yatatsu.fieldschema.FS
import ro.dobrescuandrei.roomdynamicdao.*
import ro.dobrescuandrei.roomdynamicdaosample.model.RestaurantFilter
class DemoQueryBuilder : QueryBuilder<RestaurantFilter>
{
constructor(filter: RestaurantFilter) : super(filter)
//used to specify table name
override fun tableName() = FS.Restaurant
//used to specify where conditions
override fun where(conditions : QueryWhereConditions) : String?
{
conditions.add("${FS.Restaurant_id} in ${intArrayOf(1, 5).sqlEscaped}")
conditions.add("${FS.Restaurant_id} = 1")
conditions.add("${FS.Restaurant_rating} = 5")
return conditions.mergeWithAnd()
}
//enable pagination. By default, pagination is disabled
override fun enablePagination() = true
//column projections
override fun projection(clauses : QueryProjectionClauses): String
{
clauses.addAllFieldsFromTable(FS.Restaurant)
clauses.addField(FS.City_name,
fromTable = FS.City,
projectAs = FS.RestaurantJoin_cityName)
clauses.addField(FS.Country_name,
fromTable = FS.Country,
projectAs = FS.RestaurantJoin_countryName)
return clauses.merge()
}
//use for joins
override fun join(clauses : QueryJoinClauses) : String?
{
clauses.addInnerJoin(
table = FS.Restaurant,
column = FS.Restaurant_cityId,
remoteTable = FS.City,
remoteColumn = FS.City_id)
clauses.addInnerJoin(
table = FS.City,
column = FS.City_countryId,
remoteTable = FS.Country,
remoteColumn = FS.Country_id)
return clauses.merge()
}
//specify order by
override fun orderBy(): String? = "${FS.Restaurant_id} asc"
}
| 0
|
Kotlin
|
3
| 21
|
76ad4139d62578c1bf0d391c98df2d4548ad6e28
| 1,883
|
ROOM-Dynamic-Dao
|
Apache License 2.0
|
src/test/kotlin/blocksworld/methods/Methods2.kt
|
axgdev
| 135,467,490
| false
|
{"Kotlin": 43219}
|
package blocksworld.methods
import blocksworld.operators.*
import blocksworld.*
import khop.Method
import khop.MethodGroup
import khop.NetworkElement
data class GetByUnstack(private val block: String): Method<BlocksState> {
override fun satisfiesPreconditions(state: BlocksState): Boolean {
return state.clear[block]!!
}
override fun decompose(state: BlocksState): List<NetworkElement<BlocksState>> {
return listOf(UnstackM(block))
}
}
data class GetByPickup(private val block: String): Method<BlocksState> {
override fun satisfiesPreconditions(state: BlocksState): Boolean {
return state.clear[block]!!
}
override fun decompose(state: BlocksState): List<NetworkElement<BlocksState>> {
return listOf(PickupM(block))
}
}
data class PickupM(private val block: String): Method<BlocksState> {
override fun satisfiesPreconditions(state: BlocksState): Boolean {
return state.clear[block]!!
}
override fun decompose(state: BlocksState): List<NetworkElement<BlocksState>> {
return listOf(Pickup(block))
}
}
data class UnstackM(private val block: String): Method<BlocksState> {
override fun satisfiesPreconditions(state: BlocksState): Boolean {
return state.clear[block]!!
}
override fun decompose(state: BlocksState): List<NetworkElement<BlocksState>> {
checkDictionaryEntries(state, block)
return listOf(Unstack(block, state.pos[block]!!))
}
}
data class GetMG(private val block1: String): MethodGroup<BlocksState> {
override val methods: List<Method<BlocksState>> = getTheMethods()
private fun getTheMethods(): List<Method<BlocksState>> {
return listOf(GetByPickup(block1), GetByUnstack(block1))
}
}
| 0
|
Kotlin
|
0
| 1
|
5876f84119cb294a155dc31a4dc1cc63e39aef4d
| 1,763
|
KHOP
|
MIT License
|
demo-core/src/main/java/com/adamkobus/compose/navigation/democore/model/DogsSource.kt
|
AdamKobus
| 453,682,860
| false
| null |
package com.adamkobus.compose.navigation.democore.model
import com.adamkobus.compose.navigation.democore.data.DogInfo
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DogsSource @Inject constructor() {
private val data = MutableStateFlow(createData())
suspend fun observeDogs(): Flow<List<DogInfo>> {
delay(MOCK_DELAY)
return data
}
suspend fun getDog(id: Int): DogInfo {
delay(MOCK_DELAY)
return data.value.find { it.id == id } ?: throw IllegalArgumentException("Dog with id $id does not exist")
}
private fun createData() =
generateSequence(0) { it + 1 }.take(MOCKED_DATA_SIZE).map { DogInfo(it, "Dog $it") }.toList()
companion object {
private const val MOCK_DELAY = 500L
private const val MOCKED_DATA_SIZE = 20
}
}
| 14
|
Kotlin
|
0
| 5
|
a7dae0f6e2254ad074206eeee1d971e9d82ae741
| 954
|
compose-navigation
|
MIT License
|
sample/src/main/java/com/lib/lokdroid/navigation/Screen.kt
|
NikolayKuts
| 831,630,647
| false
|
{"Kotlin": 46666}
|
package com.lib.lokdroid.navigation
sealed class Screen(open val route: String) {
operator fun invoke(): String = route
data object SingleLogging : Screen(route = "SingleLogging")
data object MultipleLogging : Screen(route = "MultipleLogging")
}
| 0
|
Kotlin
|
0
| 0
|
9fd6ef454f7cdedbb9e2920674bb1e95ab7ee5ff
| 261
|
LoKdroid
|
Apache License 2.0
|
kotlinova-gradle/src/main/kotlin/si/inova/kotlinova/gradle/sarifmerge/SarifMergeTask.kt
|
inovait
| 247,635,811
| false
|
{"Kotlin": 745833, "Shell": 2502}
|
/*
* Copyright 2024 INOVA IT d.o.o.
*
* 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 si.inova.kotlinova.gradle.sarifmerge
import io.github.detekt.sarif4k.Level
import io.github.detekt.sarif4k.PropertyBag
import io.github.detekt.sarif4k.ReportingConfiguration
import io.github.detekt.sarif4k.Run
import io.github.detekt.sarif4k.SarifSchema210
import io.github.detekt.sarif4k.SarifSerializer
import org.gradle.api.DefaultTask
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
/**
* A gradle task that merges sarif reports into one.
*
* Based on https://github.com/detekt/detekt/blob/ace6e4e5de07532416e89abf811ba37e0ea2b565/detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/report/ReportMergeTask.kt
*/
@CacheableTask
abstract class SarifMergeTask : DefaultTask() {
@get:InputFiles
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val input: ConfigurableFileCollection
@get:OutputFile
abstract val output: RegularFileProperty
@TaskAction
fun merge() {
val sarifFiles = input.files.filter { it.exists() }.map { SarifSerializer.fromJson(it.readText()) }
if (sarifFiles.isEmpty()) {
output.get().asFile.delete()
return
}
val merged = sarifFiles.reduce(SarifSchema210::merge)
val fixedSeverity = merged.copy(
runs = merged.runs.map { run ->
// Workaround for the https://github.com/security-alert/security-alert/issues/50
run.copy(
tool = run.tool.copy(
driver = run.tool.driver.copy(
rules = run.tool.driver.rules?.map { rule ->
if (rule.defaultConfiguration?.level == null) {
rule.copy(
defaultConfiguration = ReportingConfiguration(level = Level.Warning)
)
} else {
rule
}
}
)
)
)
}.sortedByDescending {
// Display runs with fewer errors last
// Workaround for https://github.com/security-alert/security-alert/issues/74
it.results?.size ?: 0
}
)
output.get().asFile.writeText(SarifSerializer.toJson(fixedSeverity))
}
}
private fun SarifSchema210.merge(other: SarifSchema210): SarifSchema210 {
require(schema == other.schema) {
"Cannot merge sarifs with different schemas: '${schema ?: "null"}' or '${other.schema ?: "null"}'"
}
require(version == other.version) {
"Cannot merge sarifs with different versions: '$version' or '${other.version}'"
}
val mergedExternalProperties = (inlineExternalProperties.orEmpty() + other.inlineExternalProperties.orEmpty())
.takeIf { it.isNotEmpty() }
val mergedProperties = properties.merge(other.properties)
val mergedRuns = runs.merge(other.runs)
return SarifSchema210(
schema,
version,
mergedExternalProperties,
mergedProperties,
mergedRuns
)
}
// Temporary copy from https://github.com/detekt/sarif4k/pull/87 until new version of sarif4k with that included is released
private fun PropertyBag?.merge(other: PropertyBag?): PropertyBag? {
return (this?.tags.orEmpty() + other?.tags.orEmpty())
.takeIf { it.isNotEmpty() }
?.let { PropertyBag(it) }
}
private fun List<Run>.merge(other: List<Run>): List<Run> {
val runsByTool = (this + other).groupBy { it.tool.driver.fullName }
return runsByTool.mapValues { (_, runs) ->
val baseRun = runs.firstOrNull() ?: return@mapValues null
val mergedResults = runs.flatMap { it.results.orEmpty() }
val mergedRules = runs.flatMap { it.tool.driver.rules.orEmpty() }.distinctBy { it.id }
baseRun.copy(
results = mergedResults,
tool = baseRun.tool.copy(
driver = baseRun.tool.driver.copy(
rules = mergedRules
)
)
)
}.values.filterNotNull().toList()
}
| 0
|
Kotlin
|
1
| 7
|
c779bb7dd8760fcc77a2e7e33a2c1603da155b50
| 5,353
|
kotlinova
|
MIT License
|
idea/tests/testData/multiModuleQuickFix/other/generateHashCodeInExpect/common/common.kt
|
JetBrains
| 278,369,660
| false
| null |
// "Generate 'hashCode()'" "true"
// TOOL: org.jetbrains.kotlin.idea.inspections.EqualsOrHashCodeInspection
expect class With<caret>Constructor(x: Int, s: String) {
val x: Int
val s: String
override fun equals(other: Any?): Boolean
}
| 284
| null |
5162
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 247
|
intellij-kotlin
|
Apache License 2.0
|
domain/src/main/kotlin/io/github/wykopmobilny/domain/profile/ProfileUtils.kt
|
otwarty-wykop-mobilny
| 374,160,630
| false
| null |
package io.github.wykopmobilny.domain.profile
import io.github.wykopmobilny.data.cache.api.GenderEntity
import io.github.wykopmobilny.data.cache.api.UserColorEntity
import io.github.wykopmobilny.storage.api.LoggedUserInfo
import io.github.wykopmobilny.ui.components.widgets.AvatarUi
import io.github.wykopmobilny.ui.components.widgets.Color
import io.github.wykopmobilny.ui.components.widgets.ColorConst
import io.github.wykopmobilny.ui.components.widgets.ColorReference
import io.github.wykopmobilny.ui.components.widgets.UserInfoUi
import kotlinx.datetime.DateTimePeriod
internal const val DEFAULT_PROFILE_BACKGROUND = "https://i.imgur.com/aSm6pSJ.jpg"
internal fun GenderEntity.toGenderDomain() = when (this) {
GenderEntity.Male -> UserInfo.Gender.Male
GenderEntity.Female -> UserInfo.Gender.Female
}
internal fun UserColorEntity.toColorDomain() = when (this) {
UserColorEntity.Green -> UserInfo.Color.Green
UserColorEntity.Orange -> UserInfo.Color.Orange
UserColorEntity.Claret -> UserInfo.Color.Claret
UserColorEntity.Admin -> UserInfo.Color.Admin
UserColorEntity.Banned -> UserInfo.Color.Banned
UserColorEntity.Deleted -> UserInfo.Color.Deleted
UserColorEntity.Client -> UserInfo.Color.Client
UserColorEntity.Unknown -> UserInfo.Color.Unknown
}
internal fun UserInfo.Gender?.toUi() = when (this) {
UserInfo.Gender.Male -> ColorConst.Male
UserInfo.Gender.Female -> ColorConst.Female
null -> ColorConst.Transparent
}
internal fun UserInfo.Color.toUi(): Color = when (this) {
UserInfo.Color.Green -> ColorConst.UserGreen
UserInfo.Color.Orange -> ColorConst.UserOrange
UserInfo.Color.Claret -> ColorConst.UserClaret
UserInfo.Color.Admin -> ColorReference.Admin
UserInfo.Color.Banned -> ColorConst.UserBanned
UserInfo.Color.Deleted -> ColorConst.UserDeleted
UserInfo.Color.Client -> ColorConst.UserClient
UserInfo.Color.Unknown -> ColorConst.UserUnknown
}
fun DateTimePeriod.toPrettyString(suffix: String = "", nowFallback: String = "przed chwilą"): String {
val yearsPart = when {
years == 0 -> ""
years == 1 -> "1 rok"
years in 5..21 -> "$years lat"
years % 10 in 2..4 -> "$years lata"
else -> "$years lat"
}
val monthsPart = if (months == 0) {
""
} else {
"$months mies."
}
val daysPart = when {
days == 0 || years != 0 -> ""
days == 1 -> "1 dzień"
else -> "$days dni"
}
@Suppress("ComplexCondition")
val hoursPart = if (hours == 0 || years != 0 || months != 0 || days != 0) {
""
} else {
"$hours godz."
}
val minutesPart = when {
years != 0 || months != 0 || days != 0 || hours != 0 -> ""
minutes > 0 -> "$minutes min"
else -> return nowFallback
}
return buildString {
yearsPart.takeIf(String::isNotEmpty)?.let(::append)
monthsPart.takeIf(String::isNotEmpty)?.let {
append(" ")
append(it)
}
daysPart.takeIf(String::isNotEmpty)?.let {
append(" ")
append(it)
}
hoursPart.takeIf(String::isNotEmpty)?.let {
append(" ")
append(it)
}
minutesPart.takeIf(String::isNotEmpty)?.let {
append(" ")
append(it)
}
append(" ")
append(suffix)
}.trim()
}
internal fun LoggedUserInfo.toUi(onClicked: (() -> Unit)?) = UserInfoUi(
avatar = AvatarUi(
avatarUrl = avatarUrl,
rank = null,
genderStrip = null,
onClicked = onClicked,
),
name = id,
color = null,
)
| 7
| null |
4
| 47
|
85b54b736f5fbcd6f62305779ed7ae2085c3b136
| 3,649
|
wykop-android
|
MIT License
|
marker/py-marker/src/main/kotlin/spp/jetbrains/marker/py/service/PythonArtifactCreationService.kt
|
sourceplusplus
| 173,253,271
| false
|
{"Kotlin": 1227211, "Java": 190403, "JavaScript": 3929, "Groovy": 3042, "Python": 2564}
|
/*
* Source++, the continuous feedback platform for developers.
* Copyright (C) 2022-2023 CodeBrig, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spp.jetbrains.marker.js.service
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import spp.jetbrains.marker.SourceMarkerUtils
import spp.jetbrains.marker.service.ArtifactNamingService
import spp.jetbrains.marker.service.define.IArtifactCreationService
import spp.jetbrains.marker.source.SourceFileMarker
import spp.jetbrains.marker.source.mark.api.SourceMark
import spp.jetbrains.marker.source.mark.guide.ExpressionGuideMark
import spp.jetbrains.marker.source.mark.gutter.ExpressionGutterMark
import spp.jetbrains.marker.source.mark.gutter.GutterMark
import spp.jetbrains.marker.source.mark.gutter.MethodGutterMark
import spp.jetbrains.marker.source.mark.inlay.ExpressionInlayMark
import spp.jetbrains.marker.source.mark.inlay.InlayMark
import spp.jetbrains.marker.source.mark.inlay.MethodInlayMark
import java.util.*
/**
* Used to create Javascript [SourceMark]s.
*
* @since 0.7.0
* @author [<NAME>](mailto:<EMAIL>)
*/
class JavascriptArtifactCreationService : IArtifactCreationService {
override fun getOrCreateExpressionGutterMark(
fileMarker: SourceFileMarker,
lineNumber: Int,
autoApply: Boolean
): Optional<ExpressionGutterMark> {
val element = SourceMarkerUtils.getElementAtLine(fileMarker.psiFile, lineNumber)
if (element != null) {
return Optional.ofNullable(getOrCreateExpressionGutterMark(fileMarker, element, autoApply))
}
return Optional.empty()
}
override fun getOrCreateMethodGutterMark(
fileMarker: SourceFileMarker,
element: PsiElement,
autoApply: Boolean
): MethodGutterMark? {
TODO()
}
fun getOrCreateExpressionGutterMark(
fileMarker: SourceFileMarker,
element: PsiElement,
autoApply: Boolean = false
): ExpressionGutterMark? {
var gutterMark = element.getUserData(GutterMark.KEY) as ExpressionGutterMark?
if (gutterMark == null) {
gutterMark = fileMarker.getExpressionSourceMark(
element,
SourceMark.Type.GUTTER
) as ExpressionGutterMark?
if (gutterMark != null) {
if (gutterMark.updatePsiExpression(element, ArtifactNamingService.getFullyQualifiedName(element))) {
element.putUserData(GutterMark.KEY, gutterMark)
} else {
gutterMark = null
}
}
}
return if (gutterMark == null) {
gutterMark = fileMarker.createExpressionSourceMark(
element,
SourceMark.Type.GUTTER
) as ExpressionGutterMark
return if (autoApply) {
gutterMark.apply(true)
gutterMark
} else {
gutterMark
}
} else {
if (fileMarker.removeIfInvalid(gutterMark)) {
element.putUserData(GutterMark.KEY, null)
null
} else {
gutterMark
}
}
}
override fun getOrCreateExpressionInlayMark(
fileMarker: SourceFileMarker,
lineNumber: Int,
autoApply: Boolean
): Optional<ExpressionInlayMark> {
val element = SourceMarkerUtils.getElementAtLine(fileMarker.psiFile, lineNumber)
if (element != null) {
return Optional.ofNullable(getOrCreateExpressionInlayMark(fileMarker, element, autoApply))
}
return Optional.empty()
}
override fun createMethodGutterMark(
fileMarker: SourceFileMarker,
element: PsiElement,
autoApply: Boolean
): MethodGutterMark {
return fileMarker.createMethodGutterMark(element.parent as PsiNameIdentifierOwner, autoApply)
}
override fun createMethodInlayMark(
fileMarker: SourceFileMarker,
element: PsiElement,
autoApply: Boolean
): MethodInlayMark {
return fileMarker.createMethodInlayMark(element.parent as PsiNameIdentifierOwner, autoApply)
}
override fun createExpressionGutterMark(
fileMarker: SourceFileMarker,
lineNumber: Int,
autoApply: Boolean
): ExpressionGutterMark {
val element = SourceMarkerUtils.getElementAtLine(fileMarker.psiFile, lineNumber) as PsiElement
return fileMarker.createExpressionGutterMark(element, autoApply)
}
override fun createExpressionInlayMark(
fileMarker: SourceFileMarker,
lineNumber: Int,
autoApply: Boolean
): ExpressionInlayMark {
val element = SourceMarkerUtils.getElementAtLine(fileMarker.psiFile, lineNumber)!!
val inlayMark = fileMarker.createExpressionSourceMark(
element,
SourceMark.Type.INLAY
) as ExpressionInlayMark
return if (autoApply) {
inlayMark.apply(true)
inlayMark
} else {
inlayMark
}
}
override fun createExpressionGuideMark(
fileMarker: SourceFileMarker,
lineNumber: Int,
autoApply: Boolean
): ExpressionGuideMark {
val element = SourceMarkerUtils.getElementAtLine(fileMarker.psiFile, lineNumber)!!
val guideMark = fileMarker.createExpressionSourceMark(
element,
SourceMark.Type.GUIDE
) as ExpressionGuideMark
return if (autoApply) {
guideMark.apply(true)
guideMark
} else {
guideMark
}
}
fun getOrCreateExpressionInlayMark(
fileMarker: SourceFileMarker,
element: PsiElement,
autoApply: Boolean = false
): ExpressionInlayMark? {
var inlayMark = element.getUserData(InlayMark.KEY)?.firstOrNull() as ExpressionInlayMark?
if (inlayMark == null) {
inlayMark = fileMarker.getExpressionSourceMark(
element,
SourceMark.Type.INLAY
) as ExpressionInlayMark?
if (inlayMark != null) {
if (inlayMark.updatePsiExpression(element, ArtifactNamingService.getFullyQualifiedName(element))) {
element.putUserData(
InlayMark.KEY,
element.getUserData(InlayMark.KEY)?.plus(inlayMark) ?: setOf(inlayMark)
)
} else {
inlayMark = null
}
}
}
return if (inlayMark == null) {
inlayMark = fileMarker.createExpressionSourceMark(
element,
SourceMark.Type.INLAY
) as ExpressionInlayMark
return if (autoApply) {
inlayMark.apply(true)
inlayMark
} else {
inlayMark
}
} else {
if (fileMarker.removeIfInvalid(inlayMark)) {
element.putUserData(InlayMark.KEY, null)
null
} else {
inlayMark
}
}
}
}
| 2
|
Kotlin
|
13
| 87
|
199006a410529d961dc184f0740a5d845bd87899
| 7,689
|
interface-jetbrains
|
Apache License 2.0
|
source-downloader-core/src/main/kotlin/xyz/shoaky/sourcedownloader/core/processor/SourceProcessor.kt
|
shoaky009
| 607,575,763
| false
| null |
package xyz.shoaky.sourcedownloader.core.processor
import org.slf4j.LoggerFactory
import org.springframework.retry.RetryCallback
import org.springframework.retry.RetryContext
import org.springframework.retry.listener.RetryListenerSupport
import org.springframework.retry.support.RetryTemplateBuilder
import org.springframework.util.StopWatch
import xyz.shoaky.sourcedownloader.component.provider.MetadataVariableProvider
import xyz.shoaky.sourcedownloader.core.*
import xyz.shoaky.sourcedownloader.core.file.CoreFileContent
import xyz.shoaky.sourcedownloader.core.file.FileContentStatus
import xyz.shoaky.sourcedownloader.core.file.PersistentSourceContent
import xyz.shoaky.sourcedownloader.sdk.*
import xyz.shoaky.sourcedownloader.sdk.component.*
import xyz.shoaky.sourcedownloader.sdk.util.Jackson
import xyz.shoaky.sourcedownloader.util.Events
import java.io.IOException
import java.nio.file.Path
import java.time.Duration
import java.time.LocalDateTime
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
import kotlin.io.path.exists
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
/**
* 拉在这里,后面看情况重构
*/
class SourceProcessor(
val name: String,
// 先这样传入 后面要改
private val sourceId: String,
private val source: Source<SourceItemPointer>,
variableProviders: List<VariableProvider>,
private val itemFileResolver: ItemFileResolver,
private val downloader: Downloader,
private val fileMover: FileMover,
private val sourceSavePath: Path,
private val options: ProcessorConfig.Options = ProcessorConfig.Options(),
private val processingStorage: ProcessingStorage,
) : Runnable {
private val sourceItemFilters: MutableList<SourceItemFilter> = mutableListOf()
private val sourceFileFilters: MutableList<SourceFileFilter> = mutableListOf()
private val variableProviders = variableProviders.toMutableList()
private val runAfterCompletion: MutableList<RunAfterCompletion> = mutableListOf()
private val taggers: MutableList<FileTagger> = mutableListOf()
private val downloadPath = downloader.defaultDownloadPath()
private val fileSavePathPattern: PathPattern = options.savePathPattern
private val filenamePattern: PathPattern = CorePathPattern(options.filenamePattern.pattern, options.replaceVariable)
private val tagFilenamePattern = options.tagFilenamePattern.mapValues {
CorePathPattern(it.value.pattern, options.replaceVariable)
}
private var renameTaskFuture: ScheduledFuture<*>? = null
private val safeRunner by lazy {
SafeRunner(this)
}
private val renameScheduledExecutor by lazy {
Executors.newSingleThreadScheduledExecutor()
}
init {
if (options.saveContent) {
addItemFilter(SourceHashingItemFilter(name, processingStorage))
}
if (options.provideMetadataVariables) {
if (this.variableProviders.map { it }.contains(MetadataVariableProvider).not()) {
this.variableProviders.add(MetadataVariableProvider)
}
}
}
fun info(): Map<String, Any> {
return mapOf(
"Processor" to name,
"Source" to source::class.java.simpleName,
"Providers" to variableProviders.map { it::class.simpleName },
"FileResolver" to itemFileResolver::class.java.simpleName,
"Downloader" to downloader::class.java.simpleName,
"FileMover" to fileMover::class.java.simpleName,
"SourceItemFilter" to sourceItemFilters.map { it::class.simpleName },
"RunAfterCompletion" to runAfterCompletion.map { it::class.simpleName },
"DownloadPath" to downloadPath,
"SourceSavePath" to sourceSavePath,
"SourceFileFilter" to sourceFileFilters.map { it::class.simpleName },
"Taggers" to taggers.map { it::class.simpleName },
"Options" to options,
)
}
@OptIn(ExperimentalTime::class)
fun scheduleRenameTask(interval: Duration) {
if (downloader !is AsyncDownloader) {
return
}
renameTaskFuture?.cancel(false)
renameTaskFuture = renameScheduledExecutor.scheduleAtFixedRate({
log.debug("Processor:${name} 开始重命名任务...")
var modified = false
val measureTime = measureTime {
try {
modified = runRename() > 0
} catch (e: Exception) {
log.error("Processor:${name} 重命名任务出错", e)
}
System.currentTimeMillis()
}
if (modified) {
log.info("Processor:${name} 重命名任务完成 took:${measureTime.inWholeMilliseconds}ms")
}
val renameCostTimeThreshold = 100L
if (modified.not() && measureTime.inWholeMilliseconds > renameCostTimeThreshold) {
log.warn("Processor:${name} 重命名任务没有修改 took:${measureTime.inWholeMilliseconds}ms")
}
}, 5L, interval.seconds, TimeUnit.SECONDS)
}
override fun run() {
process()
}
fun dryRun(): List<ProcessingContent> {
return process(true)
}
private fun process(dryRun: Boolean = false): List<ProcessingContent> {
val lastState = processingStorage.findProcessorSourceState(name, sourceId)
val itemIterator = retry.execute<Iterator<PointedItem<SourceItemPointer>>, IOException> {
it.setAttribute("stage", ProcessStage("FetchSourceItems", lastState))
val pointer = lastState?.resolvePointer(source::class)
val iterator = source.fetch(pointer).iterator()
iterator
}
val result = mutableListOf<ProcessingContent>()
var lastPointedItem: PointedItem<SourceItemPointer>? = null
val simpleStat = SimpleStat(name)
for (item in itemIterator) {
val filterBy = sourceItemFilters.firstOrNull { it.test(item.sourceItem).not() }
if (filterBy != null) {
log.debug("{} Filtered item:{}", filterBy::class.simpleName, item)
lastPointedItem = item
simpleStat.incFilterCounting()
continue
}
val processingContent = kotlin.runCatching {
retry.execute<ProcessingContent, Throwable> {
it.setAttribute("stage", ProcessStage("ProcessItem", item))
processItem(item.sourceItem, dryRun)
}
}.onFailure {
log.error("Processor:${name}处理失败, item:$item", it)
}.onSuccess {
if (dryRun) {
result.add(it)
}
// 也许有一直失败的会卡住整体,暂时先这样处理
lastPointedItem = item
}.getOrElse {
ProcessingContent(name, PersistentSourceContent(
item.sourceItem, emptyList(), MapPatternVariables()
)).copy(status = ProcessingContent.Status.FAILURE, failureReason = it.message)
}
if (options.saveContent && dryRun.not()) {
processingStorage.save(processingContent)
}
simpleStat.incProcessingCounting()
}
simpleStat.stopWatch.stop()
if (simpleStat.isChanged()) {
log.info("Processor:{}", simpleStat)
}
if (dryRun.not()) {
saveSourceState(lastPointedItem, lastState)
}
return result
}
private fun saveSourceState(lastPointedItem: PointedItem<SourceItemPointer>?, lastState: ProcessorSourceState?) {
// not first time but no items
if (lastState != null && lastPointedItem == null) {
processingStorage.save(
lastState.copy(lastActiveTime = LocalDateTime.now())
)
return
}
// first time and no items
if (lastPointedItem == null) {
log.info("Processor:${name} Source:${sourceId} no items to process")
return
}
log.info("Processor:$name update pointer Source:$sourceId lastPointedItem:$lastPointedItem")
val latestPointer = Jackson.convert(lastPointedItem.pointer, PersistentItemPointer::class)
val sourceState = lastState?.copy(
processorName = name,
sourceId = sourceId,
lastPointer = latestPointer,
lastActiveTime = LocalDateTime.now()
) ?: ProcessorSourceState(
processorName = name,
sourceId = sourceId,
lastPointer = latestPointer,
)
processingStorage.save(sourceState)
}
private fun processItem(sourceItem: SourceItem, dryRun: Boolean = false): ProcessingContent {
val variablesAggregation = VariableProvidersAggregation(
sourceItem,
variableProviders.filter { it.support(sourceItem) }.toList(),
options.variableConflictStrategy,
options.variableNameReplace
)
val sourceContent = createPersistentSourceContent(variablesAggregation, sourceItem)
val contentStatus = probeContent(sourceContent)
sourceContent.updateFileStatus(fileMover)
val downloadTask = createDownloadTask(sourceContent)
if (contentStatus.first && dryRun.not()) {
// NOTE 非异步下载会阻塞
this.downloader.submit(downloadTask)
log.info("提交下载任务成功, Processor:${name} sourceItem:${sourceItem.title}")
processingStorage.saveTargetPath(sourceContent.allTargetPaths())
Events.post(ProcessorSubmitDownloadEvent(name, sourceContent))
}
var status = ProcessingContent.Status.WAITING_TO_RENAME
if (downloader !is AsyncDownloader && dryRun.not()) {
rename(sourceContent)
status = ProcessingContent.Status.RENAMED
}
if (contentStatus.first.not() && downloader is AsyncDownloader) {
status = contentStatus.second
}
return ProcessingContent(name, sourceContent).copy(status = status)
}
private fun createPersistentSourceContent(sourceItemGroup: SourceItemGroup, sourceItem: SourceItem): PersistentSourceContent {
val resolveFiles = itemFileResolver.resolveFiles(sourceItem)
val filteredFiles = resolveFiles.filter { path ->
val res = sourceFileFilters.all { it.test(path) }
if (res.not()) {
log.debug("Filtered file:{}", path)
}
res
}
val sharedPatternVariables = sourceItemGroup.sharedPatternVariables()
val sourceFiles = sourceItemGroup.sourceFiles(filteredFiles)
.mapIndexed { index, sourceFile ->
val sourceFileContent = CoreFileContent(
downloadPath.resolve(filteredFiles[index]),
sourceSavePath,
downloadPath,
MapPatternVariables(sourceFile.patternVariables().variables()),
fileSavePathPattern,
filenamePattern,
)
// 这里坑,后面看怎么改
val tagged = tagFileAndReplaceFilenamePattern(sourceFileContent)
tagged.setVariableErrorStrategy(options.variableErrorStrategy)
tagged.addSharedVariables(sharedPatternVariables)
tagged
}
return PersistentSourceContent(sourceItem, sourceFiles, MapPatternVariables(sharedPatternVariables))
}
private fun tagFileAndReplaceFilenamePattern(fileContent: CoreFileContent): CoreFileContent {
val customTags = tagFilenamePattern.keys
if (customTags.isEmpty()) {
return fileContent
}
val tags = taggers.mapNotNull { it.tag(fileContent) }
fileContent.tag(tags)
val tagged = customTags.filter {
fileContent.isTagged(it)
}
log.debug("Processor:{} 文件:{} 标签:{}", name, fileContent.fileDownloadPath, tagged)
val pathPatterns = tagged.mapNotNull {
options.tagFilenamePattern[it]
}
if (pathPatterns.isEmpty()) {
return fileContent
}
val taggedFilePattern = pathPatterns.first()
log.debug("Processor:{} 文件:{} 使用自定义命名规则:{}", name, fileContent.fileDownloadPath, taggedFilePattern)
val copy = fileContent.copy(filenamePattern = taggedFilePattern)
// 考虑要不要存tag
copy.tag(fileContent.tags())
return copy
}
private fun probeContent(sc: PersistentSourceContent): Pair<Boolean, ProcessingContent.Status> {
val files = sc.sourceFiles
if (files.isEmpty()) {
return false to ProcessingContent.Status.NO_FILES
}
val targetPaths = files.map { it.targetPath() }
// 预防这一批次的Item有相同的目标,并且是AsyncDownloader的情况下会重复下载
if (processingStorage.targetPathExists(targetPaths)) {
return false to ProcessingContent.Status.TARGET_ALREADY_EXISTS
}
if (fileMover.exists(targetPaths)) {
return false to ProcessingContent.Status.TARGET_ALREADY_EXISTS
}
val current = files.map { it.fileDownloadPath.exists() }
if (current.all { it }) {
return false to ProcessingContent.Status.WAITING_TO_RENAME
}
val any = current.any { it.not() }
if (any) {
return true to ProcessingContent.Status.WAITING_TO_RENAME
}
return false to ProcessingContent.Status.DOWNLOADED
}
private fun runAfterCompletions(taskContent: SourceContent) {
for (task in runAfterCompletion) {
task.runCatching {
this.accept(taskContent)
}.onFailure {
log.error("${task::class.simpleName}发生错误", it)
}
}
}
fun runRename(): Int {
val asyncDownloader = downloader as? AsyncDownloader
if (asyncDownloader == null) {
log.debug("Processor:${name} 非异步下载器不执行重命名任务")
return 0
}
val contentGrouping = processingStorage.findRenameContent(name, options.renameTimesThreshold)
.groupBy(
{ pc ->
val downloadTask = createDownloadTask(pc.sourceContent)
DownloadStatus.from(asyncDownloader.isFinished(downloadTask))
}, { it }
)
contentGrouping[DownloadStatus.NOT_FOUND]?.forEach { pc ->
kotlin.runCatching {
log.info("Processing下载任务不存在, record:${Jackson.toJsonString(pc)}")
processingStorage.save(pc.copy(
status = ProcessingContent.Status.DOWNLOAD_FAILED,
modifyTime = LocalDateTime.now(),
))
}.onFailure {
log.error("Processing更新状态出错, record:${Jackson.toJsonString(pc)}", it)
}
}
contentGrouping[DownloadStatus.FINISHED]?.forEach { pc ->
kotlin.runCatching {
processRenameTask(pc)
}.onFailure {
log.error("Processing重命名任务出错, record:${Jackson.toJsonString(pc)}", it)
}
}
return contentGrouping[DownloadStatus.FINISHED]?.size ?: 0
}
private fun processRenameTask(pc: ProcessingContent) {
val sourceContent = pc.sourceContent
val sourceFiles = sourceContent.sourceFiles
sourceFiles.forEach {
// 这边设计不太好
it.addSharedVariables(sourceContent.sharedPatternVariables)
it.setVariableErrorStrategy(options.variableErrorStrategy)
}
val targetPaths = sourceFiles.map { it.targetPath() }
if (fileMover.exists(targetPaths)) {
val toUpdate = pc.copy(
renameTimes = pc.renameTimes.inc(),
status = ProcessingContent.Status.TARGET_ALREADY_EXISTS,
modifyTime = LocalDateTime.now(),
)
processingStorage.save(toUpdate)
log.info("全部目标文件已存在,无需重命名,record:${Jackson.toJsonString(pc)}")
return
}
val allSuccess = rename(sourceContent)
if (allSuccess) {
val paths = sourceContent.sourceFiles.map { it.targetPath() }
// 如果失败了, 一些成功一些失败??
processingStorage.saveTargetPath(paths)
runAfterCompletions(sourceContent)
} else {
log.warn("有部分文件重命名失败record:${Jackson.toJsonString(pc)}")
}
val renameTimesThreshold = options.renameTimesThreshold
if (pc.renameTimes == renameTimesThreshold) {
log.error("重命名${renameTimesThreshold}次重试失败record:${Jackson.toJsonString(pc)}")
}
val toUpdate = pc.copy(
renameTimes = pc.renameTimes.inc(),
status = ProcessingContent.Status.RENAMED,
modifyTime = LocalDateTime.now()
)
processingStorage.save(toUpdate)
}
fun addItemFilter(vararg filters: SourceItemFilter) {
sourceItemFilters.addAll(filters)
}
fun addFileFilter(vararg filters: SourceFileFilter) {
sourceFileFilters.addAll(filters)
}
fun safeTask(): Runnable {
return safeRunner
}
private fun createDownloadTask(content: PersistentSourceContent): DownloadTask {
val downloadFiles = content.sourceFiles
.filter { it.status != FileContentStatus.TARGET_EXISTS }
.map { it.fileDownloadPath }
if (log.isDebugEnabled) {
log.debug("{} 创建下载任务文件, files:{}", content.sourceItem.title, downloadFiles)
}
return DownloadTask(content.sourceItem, downloadFiles, downloadPath, options.downloadOptions)
}
private fun rename(content: PersistentSourceContent): Boolean {
val renameFiles = content.getRenameFiles(fileMover)
if (renameFiles.isEmpty()) {
return true
}
renameFiles.map { it.saveDirectoryPath() }
.distinct()
.forEach {
fileMover.createDirectories(it)
}
return fileMover.rename(
content.copy(sourceFiles = renameFiles)
)
}
fun addRunAfterCompletion(vararg completion: RunAfterCompletion) {
runAfterCompletion.addAll(completion)
}
override fun toString(): String {
return info().map {
"${it.key}: ${it.value}"
}.joinToString("\n")
}
fun addTagger(tagger: FileTagger) {
if (taggers.contains(tagger).not()) {
taggers.add(tagger)
}
}
companion object {
private val retry = RetryTemplateBuilder()
.maxAttempts(3)
.fixedBackoff(Duration.ofSeconds(5L).toMillis())
.withListener(LoggingRetryListener())
.build()
}
}
private val log = LoggerFactory.getLogger(SourceProcessor::class.java)
private class LoggingRetryListener : RetryListenerSupport() {
override fun <T : Any?, E : Throwable?> onError(
context: RetryContext,
callback: RetryCallback<T, E>?,
throwable: Throwable
) {
val stage = context.getAttribute("stage")
log.info("第{}次重试失败, message:{}, stage:{}", context.retryCount, "${throwable::class.simpleName}:${throwable.message}", stage)
}
override fun <T : Any?, E : Throwable?> open(context: RetryContext?, callback: RetryCallback<T, E>?): Boolean {
return super.open(context, callback)
}
override fun <T : Any?, E : Throwable?> close(
context: RetryContext?,
callback: RetryCallback<T, E>?,
throwable: Throwable?
) {
super.close(context, callback, throwable)
}
}
private class SimpleStat(
private val name: String,
var processingCounting: Int = 0,
var filterCounting: Int = 0,
) {
val stopWatch = StopWatch("$name:fetch")
init {
stopWatch.start()
}
fun incProcessingCounting() {
processingCounting = processingCounting.inc()
}
fun incFilterCounting() {
filterCounting = filterCounting.inc()
}
fun isChanged(): Boolean {
return processingCounting > 0 || filterCounting > 0
}
override fun toString(): String {
return "$name 处理了${processingCounting}个 过滤了${filterCounting}个, took:${stopWatch.totalTimeMillis}ms"
}
}
private class SafeRunner(
private val processor: SourceProcessor
) : Runnable {
@Volatile
private var running = false
override fun run() {
val name = processor.name
log.info("Processor:${name} 触发获取源信息")
if (running) {
log.info("Processor:${name} 上一次任务还未完成,跳过本次任务")
return
}
running = true
try {
processor.run()
} catch (e: Exception) {
log.error("Processor:${name} 执行失败", e)
} finally {
running = false
}
}
}
private class ProcessStage(
val stage: String,
val subject: Any?
) {
override fun toString(): String {
return "operation='$stage', subject=$subject"
}
}
private class SourceHashingItemFilter(
val sourceName: String,
val processingStorage: ProcessingStorage
) : SourceItemFilter {
override fun test(item: SourceItem): Boolean {
val processingContent = processingStorage.findByNameAndHash(sourceName, item.hashing())
if (processingContent != null) {
if (log.isDebugEnabled) {
log.debug("Source:${sourceName}已提交过下载不做处理,item:${Jackson.toJsonString(item)}")
}
}
return processingContent == null
}
}
| 1
|
Kotlin
|
0
| 7
|
5d1a3d0ed55f6f935aeee93e96033fd918eca14c
| 21,611
|
source-downloader
|
Apache License 2.0
|
VertxAnnoCore/src/main/kotlin/io/github/johnfg10/vertxanno/annotations/fieldannotations/ProducesMimeType.kt
|
johnfg2610
| 126,643,220
| false
|
{"Kotlin": 13739}
|
package io.github.johnfg10.vertxanno.annotations.fieldannotations
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class ProducesMimeType(val producesMimeType: String)
| 0
|
Kotlin
|
0
| 0
|
0f2122151b7851753db4186b6742b8c61a79a845
| 205
|
VertxAnnotation
|
The Unlicense
|
core/src/commonMain/kotlin/work/socialhub/kslack/api/methods/request/oauth/OAuthTokenRequest.kt
|
uakihir0
| 794,979,552
| false
|
{"Kotlin": 868677, "Ruby": 2164, "Shell": 2095, "Makefile": 316}
|
package work.socialhub.kslack.api.methods.request.oauth
import work.socialhub.kslack.api.methods.FormRequest
import work.socialhub.kslack.api.methods.SlackApiRequest
/**
* https://api.slack.com/docs/oauth
*/
class OAuthAccessRequest(
override val token: String?,
/** Issued when you created your application. */
var clientId: String?,
/** Issued when you created your application. */
var clientSecret: String?,
/** The `code` param returned via the OAuth callback. */
var code: String?,
/** This must match the originally submitted URI (if one was sent). */
var redirectUri: String?,
/** Request the user to add your app only to a single channel. */
var isSingleChannel: Boolean
) : SlackApiRequest, FormRequest {
override fun toMap(): Map<String, Any> {
return mutableMapOf<String, Any>().also {
it.addParam("client_id", clientId)
it.addParam("client_secret", clientSecret)
it.addParam("code", code)
it.addParam("redirect_uri", redirectUri)
it.addParam("single_channel", isSingleChannel)
}
}
}
| 5
|
Kotlin
|
0
| 0
|
3975e9de4fae5ef2ddc5b013c2a346536852f7b3
| 1,127
|
kslack
|
MIT License
|
app/src/main/java/com/endcodev/myinvoice/data/repository/CustomersRepository.kt
|
EndikaCo
| 693,000,667
| false
|
{"Kotlin": 227181}
|
package com.endcodev.myinvoice.data.repository
import com.endcodev.myinvoice.domain.models.customer.Customer
import com.endcodev.myinvoice.data.database.daos.CustomersDao
import com.endcodev.myinvoice.data.database.entities.CustomersEntity
import com.endcodev.myinvoice.data.database.entities.toDomain
import javax.inject.Inject
class CustomersRepository @Inject constructor(
private val customersDao: CustomersDao,
) {
suspend fun getAllCustomersFromDB(): List<Customer> {
val customersList: List<CustomersEntity> = customersDao.getAllCustomers()
return customersList.map { it.toDomain() }
}
fun getCustomerById(id: String): Customer {
val customer: CustomersEntity = customersDao.getCustomerById(id)
return customer.toDomain()
}
suspend fun insertAllCustomers(customersList: List<CustomersEntity>) {
customersDao.insertAllCustomers(customersList)
}
suspend fun insertCustomer(customer: CustomersEntity) {
customersDao.insertCustomer(customer)
}
fun deleteCustomer(id: String) {
customersDao.deleteCustomer(id)
}
}
| 0
|
Kotlin
|
0
| 0
|
022387a62e029804855808e5124bfa2fe6baba24
| 1,122
|
app_my_invoice
|
MIT License
|
app/src/main/java/ru/ltst/u2020mvp/util/EnumPreferences.kt
|
LiveTyping
| 69,892,571
| false
| null |
package ru.ltst.u2020mvp.util
import android.content.SharedPreferences
object EnumPreferences {
fun <T : Enum<T>> getEnumValue(preferences: SharedPreferences, type: Class<T>,
key: String, defaultValue: T?): T? {
val name = preferences.getString(key, null)
if (name != null) {
try {
return valueOf(type, name)
} catch (ignored: IllegalArgumentException) {
}
}
return defaultValue
}
fun saveEnumValue(preferences: SharedPreferences, key: String, value: Enum<*>) {
preferences.edit().putString(key, value.name).apply()
}
}
fun <T : Enum<T>> valueOf(enumType: Class<T>?, name: String?): T {
if (enumType == null) {
throw NullPointerException("enumType == null")
} else if (name == null) {
throw NullPointerException("name == null")
}
val values = enumType.enumConstants ?: throw IllegalArgumentException(enumType.canonicalName
+ " is not an enum type")
for (value in values) {
if (name == value.name) {
return value
}
}
throw IllegalArgumentException(name + " is not a constant in " + enumType.name)
}
| 0
|
Kotlin
|
4
| 5
|
a704da798d7f11ceb4a59cbdbac5c5d4f34e3500
| 1,232
|
u2020-mvp-kotlin
|
Apache License 2.0
|
app/src/main/java/jp/co/yumemi/droidtraining/presentation/components/ErrorAlertDialog.kt
|
darmadevZone
| 786,634,499
| false
|
{"Kotlin": 21809}
|
package jp.co.yumemi.droidtraining.presentation.components
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@Composable
fun ErrorAlertDialog(
onReloadClick: () -> Unit,
onCloseClick: () -> Unit
) {
AlertDialog(
onDismissRequest = { /*TODO*/ },
confirmButton = {
Row {
TextButton(onClick = onCloseClick) {
Text(text = "Close")
}
TextButton(onClick = onReloadClick) {
Text(text = "Reload")
}
}
},
title = {
Text(text = "Error")
},
text = {
Text(text = "エラーが発生しました")
},
)
}
| 26
|
Kotlin
|
0
| 0
|
92920c736b6523a2aa1003eb3073aa0adf8dbb66
| 867
|
android-practice
|
Apache License 2.0
|
kotlin-mui-icons/src/main/generated/mui/icons/material/Support.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/Support")
package mui.icons.material
@JsName("default")
external val Support: SvgIconComponent
| 12
| null |
5
| 983
|
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
| 178
|
kotlin-wrappers
|
Apache License 2.0
|
test-shared/src/main/java/com/yvkalume/test/MainCoroutineRule.kt
|
yveskalume
| 356,004,687
| false
| null |
package com.yvkalume.test
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.*
import org.junit.rules.TestWatcher
class MainCoroutineRule @OptIn(ExperimentalCoroutinesApi::class) constructor(
val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
) : TestWatcher() {
override fun starting(description: org.junit.runner.Description?) {
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: org.junit.runner.Description?) {
super.finished(description)
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
}
@OptIn(ExperimentalCoroutinesApi::class)
fun MainCoroutineRule.runBlockingTest(block: suspend TestCoroutineScope.() -> Unit) =
this.testDispatcher.runBlockingTest {
block()
}
/**
* Creates a new [CoroutineScope] with the rule's testDispatcher
*/
fun MainCoroutineRule.CoroutineScope(): CoroutineScope = CoroutineScope(testDispatcher)
| 3
|
Kotlin
|
0
| 2
|
b0911c5bd75172708c52d86d3540958236d2c25e
| 1,109
|
eventcademy-old
|
Apache License 2.0
|
ui-difficulty-selection/src/main/java/com/jayasuryat/difficultyselection/preview/ParamProvider.kt
|
jayasuryat
| 426,077,797
| false
|
{"Kotlin": 364205, "Ruby": 1611}
|
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayasuryat.difficultyselection.composable
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import com.jayasuryat.difficultyselection.logic.DifficultyItem
import com.jayasuryat.difficultyselection.logic.GameDifficulty
internal class GameDifficultyListParamProvider : PreviewParameterProvider<List<GameDifficulty>> {
override val values: Sequence<List<GameDifficulty>>
get() = sequenceOf(
listOf(
GameDifficulty.Easy,
GameDifficulty.Medium,
GameDifficulty.Hard,
)
)
}
internal class GameDifficultyParamProvider : PreviewParameterProvider<GameDifficulty> {
override val values: Sequence<GameDifficulty>
get() = sequenceOf(
GameDifficulty.Easy,
GameDifficulty.Medium,
GameDifficulty.Hard,
)
}
internal class DifficultyItemParamProvider : PreviewParameterProvider<DifficultyItem> {
override val values: Sequence<DifficultyItem>
get() = sequenceOf(
DifficultyItem(
title = "Easy",
gridMessage = "10 x 10",
difficulty = GameDifficulty.Easy,
isGameInProgress = true,
),
DifficultyItem(
title = "Medium",
gridMessage = "15 x 15",
difficulty = GameDifficulty.Medium,
isGameInProgress = false,
),
)
}
| 3
|
Kotlin
|
15
| 81
|
92ef8a0c17172c684af00c143fb72154aec0750c
| 2,062
|
minesweeper-j-compose
|
Apache License 2.0
|
dd-sdk-android/src/test/kotlin/com/datadog/android/utils/forge/FeatureStorageConfigurationForgeryFactory.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.utils.forge
import com.datadog.android.v2.api.FeatureStorageConfiguration
import fr.xgouchet.elmyr.Forge
import fr.xgouchet.elmyr.ForgeryFactory
internal class FeatureStorageConfigurationForgeryFactory :
ForgeryFactory<FeatureStorageConfiguration> {
override fun getForgery(forge: Forge): FeatureStorageConfiguration {
return FeatureStorageConfiguration(
maxBatchSize = forge.aPositiveLong(),
maxItemsPerBatch = forge.aBigInt(),
maxItemSize = forge.aPositiveLong(),
oldBatchThreshold = forge.aPositiveLong()
)
}
}
| 44
| null |
60
| 86
|
bcf0d12fd978df4e28848b007d5fcce9cb97df1c
| 871
|
dd-sdk-android
|
Apache License 2.0
|
src/main/kotlin/com/github/shatteredsuite/core/dispatch/argument/impl/primitive/IntArgument.kt
|
ShatteredSoftware
| 263,221,103
| false
| null |
package com.github.shatteredsuite.core.dispatch.argument.impl.primitive
import com.github.shatteredsuite.core.dispatch.argument.ArgumentValidationResult
import com.github.shatteredsuite.core.dispatch.argument.DispatchOptionalArgument
import com.github.shatteredsuite.core.dispatch.context.CommandContext
import org.bukkit.util.StringUtil
import kotlin.math.max
import kotlin.math.min
open class IntArgument(
override val name: String,
override val usageId: String,
private val min: Int = Int.MIN_VALUE,
private val max: Int = Int.MAX_VALUE,
private val default: Int = 0,
private val completeRange: List<String>
) : DispatchOptionalArgument<CommandContext, Int> {
override val expectedArgs: Int = 1
private val range = min..max
constructor(
name: String,
usageId: String,
min: Int = Int.MIN_VALUE,
max: Int = Int.MAX_VALUE,
default: Int = 0,
completeMin: Int = 0,
completeMax: Int = 10,
completeIncrement: Int = 1
) : this(name, usageId, min, max, default,
(max(min, completeMin)..min(completeMax, max) step completeIncrement).toList().map { it.toString() }
)
constructor(
name: String,
usageId: String,
min: Int = Int.MIN_VALUE,
max: Int = Int.MAX_VALUE,
default: Int = 0,
completeCount: Int = 5,
completeFn: (index: Int) -> Int
) : this(name, usageId, min, max, default,
(0..completeCount).map { completeFn(it).toString() }
)
override fun validate(arguments: List<String>, start: Int, state: CommandContext): ArgumentValidationResult<Int> {
return try {
val arg = arguments[start].toInt()
if (arg in range) {
ArgumentValidationResult(success = true, result = arg)
} else {
val result = ArgumentValidationResult<Int>(faliureMessageId = "invalid-integer-range")
result.data["offender"] = arguments[start]
result.data["max"] = max
result.data["min"] = min
result
}
} catch (ex: NumberFormatException) {
val result = ArgumentValidationResult<Int>(faliureMessageId = "invalid-integer")
result.data["offender"] = arguments[start]
result
}
}
override fun complete(partialArguments: List<String>, start: Int, state: CommandContext): List<String> {
if (partialArguments.size <= start) {
return StringUtil.copyPartialMatches("", completeRange, mutableListOf())
}
return StringUtil.copyPartialMatches(partialArguments[start], completeRange, mutableListOf())
}
override fun default(state: CommandContext): Int? {
return default
}
}
| 5
|
Kotlin
|
3
| 1
|
13a5bd2ff37028281eb9fcb16f8418ee5e1508ed
| 2,791
|
ShatteredCore
|
MIT License
|
app/src/main/java/com/murilodev/dogs/view/DetailFragment.kt
|
MuriloCampos
| 310,916,175
| false
| null |
package com.murilodev.dogs.view
import android.app.PendingIntent
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.telephony.SmsManager
import android.view.*
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.palette.graphics.Palette
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.murilodev.dogs.R
import com.murilodev.dogs.databinding.FragmentDetailBinding
import com.murilodev.dogs.databinding.SendSmsDialogBinding
import com.murilodev.dogs.model.DogBreed
import com.murilodev.dogs.model.DogPalette
import com.murilodev.dogs.model.SmsInfo
import com.murilodev.dogs.util.getProgressDrawable
import com.murilodev.dogs.util.loadImage
import com.murilodev.dogs.viewmodel.DetailsViewModel
import kotlinx.android.synthetic.main.fragment_detail.*
class DetailFragment : Fragment() {
private var dogUuid = 0
private lateinit var viewModel: DetailsViewModel
private lateinit var dataBinding: FragmentDetailBinding
private var sendSmsStarted = false
private var currentDog: DogBreed? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setHasOptionsMenu(true)
dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_detail, container, false)
return dataBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
dogUuid = DetailFragmentArgs.fromBundle(it).dogUuid
}
viewModel = ViewModelProviders.of(this).get(DetailsViewModel::class.java)
viewModel.fetch(dogUuid)
observeViewModel()
}
private fun observeViewModel() {
viewModel.dogLiveData.observe(this, Observer { dog ->
dog?.let {
currentDog = dog
dataBinding.dog = dog
it.imageUrl?.let { url ->
setupBackgroundColor(url)
}
}
})
}
private fun setupBackgroundColor(url: String) {
Glide.with(this)
.asBitmap()
.load(url)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
Palette.from(resource)
.generate { palette ->
val intColor = palette?.vibrantSwatch?.rgb ?: 0
val myPalette = DogPalette(intColor)
dataBinding.palette = myPalette
}
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.detail_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_send_sms -> {
sendSmsStarted = true
(activity as MainActivity).checkSmsPermission()
}
R.id.action_share -> {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_SUBJECT, "Check out this dog my dude")
intent.putExtra(Intent.EXTRA_TEXT, "${currentDog?.dogBreed} bred for ${currentDog?.bredFor}")
intent.putExtra(Intent.EXTRA_STREAM, currentDog?.imageUrl)
startActivity(Intent.createChooser(intent, "Share with"))
}
}
return super.onOptionsItemSelected(item)
}
fun onPermissionResult(permissionGranted: Boolean) {
if (sendSmsStarted && permissionGranted) {
context?.let {
val smsInfo = SmsInfo(
"",
"${currentDog?.dogBreed} bred for ${currentDog?.bredFor}",
currentDog?.imageUrl
)
val dialogBinding = DataBindingUtil.inflate<SendSmsDialogBinding>(
LayoutInflater.from(it),
R.layout.send_sms_dialog,
null,
false
)
AlertDialog.Builder(it)
.setView(dialogBinding.root)
.setPositiveButton("Send SMS") {dialog, which ->
if (!dialogBinding.smsDestination.text.isNullOrEmpty()) {
smsInfo.to = dialogBinding.smsDestination.text.toString()
sendSms(smsInfo)
}
}
.setNegativeButton("Cancel") {dialog, which -> }
.show()
dialogBinding.smsInfo = smsInfo
}
}
}
private fun sendSms(smsInfo: SmsInfo) {
val intent = Intent(context, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
val sms = SmsManager.getDefault()
sms.sendTextMessage(smsInfo.to, null, smsInfo.text, pendingIntent, null)
}
}
| 0
|
Kotlin
|
0
| 0
|
a46028abe06bf148c0bbdebfa5141d3019062f81
| 5,602
|
DogList
|
MIT License
|
convention-plugin/src/main/kotlin/org/metaborg/gradle/MavenPublishConventionPlugin.kt
|
metaborg
| 807,678,664
| false
|
{"Kotlin": 10344}
|
package org.metaborg.gradle
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.create
import org.gradle.kotlin.dsl.withType
import java.util.*
class MavenPublishConventionPlugin: Plugin<Project> {
override fun apply(project: Project): Unit = with(project) {
// Add the configuration extension
val extension = extensions.create<MavenPublishConventionExtension>("mavenPublishConvention")
extension.setConvention()
// Apply the Maven Publish plugin
plugins.apply("maven-publish")
configure<PublishingExtension> {
afterEvaluate {
publications {
withType<MavenPublication> {
pom {
description.set(project.description)
url.set(extension.httpUrlFormat.with(extension.repoOwner, extension.repoName) { format, owner, name ->
String.format(Locale.ROOT, format, owner, name)
})
inceptionYear.set(extension.inceptionYear)
licenses {
license {
name.set(extension.license.map { it.name })
url.set(extension.license.map { it.url })
distribution.set("repo")
}
}
developers {
extension.developers.map {
for (dev in it) {
developer {
id.set(dev.id)
name.set(dev.name)
email.set(dev.email)
}
}
}
}
scm {
connection.set(extension.scmUrlFormat.with(extension.repoOwner, extension.repoName) { format, owner, name ->
String.format(Locale.ROOT, format, owner, name)
})
developerConnection.set(extension.scmUrlFormat.with(extension.repoOwner, extension.repoName) { format, owner, name ->
String.format(Locale.ROOT, format, owner, name)
})
url.set(extension.scmUrlFormat.with(extension.repoOwner, extension.repoName) { format, owner, name ->
String.format(Locale.ROOT, format, owner, name)
})
}
}
}
}
}
}
// maven-publish plugin
// - Configure maven-publish
// configure SCM (GitHub by default, etc)
// configure owner
// configure name
// configure license (Apache 2.0 by default)
// configure developers
// configure inception year
// configure publish to GitHub packages (by default if SCM = GitHub)
// configure publish to Metaborg Artifacts (by default)
// configure publish to Maven Central (optional)
// - Configure signing (optional)
TODO("Not yet implemented")
}
}
| 0
|
Kotlin
|
0
| 0
|
97bf4079dc8770aa0cd216ae8d5cf2c23f53f201
| 3,694
|
metaborg-gradle
|
Apache License 2.0
|
CorePayments/src/main/java/com/paypal/android/corepayments/analytics/DeviceData.kt
|
paypal
| 390,097,712
| false
| null |
package com.paypal.android.corepayments.analytics
data class DeviceData(
val appId: String,
val appName: String,
val clientOS: String,
val clientSDKVersion: String,
val merchantAppVersion: String,
val deviceManufacturer: String,
val deviceModel: String,
val isSimulator: Boolean,
)
| 11
|
Kotlin
|
28
| 35
|
68d06e66a3bf6f68a981e04acb6af64f45e3a5a5
| 315
|
paypal-android
|
Apache License 2.0
|
plugins/kotlin/tests-common/test/org/jetbrains/kotlin/idea/test/util/jetTestUtils.kt
|
ingokegel
| 72,937,917
| false
| null |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("JetTestUtils")
package org.jetbrains.kotlin.test.util
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import com.intellij.util.SmartFMap
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
fun String.trimTrailingWhitespaces(): String =
this.split('\n').joinToString(separator = "\n") { it.trimEnd() }
fun String.trimTrailingWhitespacesAndAddNewlineAtEOF(): String =
this.trimTrailingWhitespaces().let {
result -> if (result.endsWith("\n")) result else result + "\n"
}
fun PsiFile.findElementByCommentPrefix(commentText: String): PsiElement? =
findElementsByCommentPrefix(commentText).keys.singleOrNull()
fun PsiFile.findElementsByCommentPrefix(prefix: String): Map<PsiElement, String> {
var result = SmartFMap.emptyMap<PsiElement, String>()
accept(
object : KtTreeVisitorVoid() {
override fun visitComment(comment: PsiComment) {
val commentText = comment.text
if (commentText.startsWith(prefix)) {
val parent = comment.parent
val elementToAdd = when (parent) {
is KtDeclaration -> parent
is PsiMember -> parent
else -> PsiTreeUtil.skipSiblingsForward(
comment,
PsiWhiteSpace::class.java, PsiComment::class.java, KtPackageDirective::class.java
)
} ?: return
result = result.plus(elementToAdd, commentText.substring(prefix.length).trim())
}
}
}
)
return result
}
val CodeInsightTestFixture.elementByOffset: PsiElement
get() {
return file.findElementAt(editor.caretModel.offset) ?: error("Can't find element at offset. Probably <caret> is missing.")
}
val File.slashedPath: String
get() = KotlinTestUtils.toSlashEndingDirPath(absolutePath)
| 284
| null |
5162
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 2,439
|
intellij-community
|
Apache License 2.0
|
geojson/src/main/kotlin/net/nmandery/keo/geojson/GeoJSON.kt
|
nmandery
| 214,281,236
| false
|
{"Kotlin": 50663}
|
package net.nmandery.keo.geojson
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.locationtech.jts.geom.*
internal enum class Identifier(val ident: String) {
Coordinates("coordinates"),
Geometries("geometries"),
Type("type")
}
internal enum class GeometryType(val ident: String) {
Point("Point"),
LineString("LineString"),
Polygon("Polygon"),
MultiPoint("MultiPoint"),
MultiLineString("MultiLineString"),
MultiPolygon("MultiPolygon"),
GeometryCollection("GeometryCollection"),
}
internal enum class EnvelopeKey(val key: String) {
maxx("maxx"),
minx("minx"),
maxy("maxy"),
miny("miny")
}
private val objectMapper: ObjectMapper by lazy {
val om = jacksonObjectMapper()
om.registerJTSGeoJSON()
om
}
fun Geometry.geojsonGeometry() = objectMapper.writeValueAsString(this)!!
data class JTSGeoJsonConfiguration(
/**
* serialize Envelope object to JSON objects.
*
* The default is using arrays int the openlayers-compatible value order
* [minx, miny, maxx, maxy]
*
* https://openlayers.org/en/latest/apidoc/module-ol_extent.html#~Extent
*/
val serializeEnvelopesAsObjects: Boolean = false
)
class JTSGeoJSON(
configuration: JTSGeoJsonConfiguration = JTSGeoJsonConfiguration(),
gf: GeometryFactory = GeometryFactory()
) : SimpleModule("JTSGeoJSON") {
init {
addSerializer(Geometry::class.java, GeometrySerializer())
addSerializer(Coordinate::class.java, CoordinateSerializer())
addSerializer(CoordinateSequence::class.java,
CoordinateSequenceSerializer()
)
addSerializer(Envelope::class.java, EnvelopeSerializer(configuration))
addDeserializer(Geometry::class.java,
GeometryDeserializer(
GenericGeometryParser(
gf
)
)
)
addDeserializer(Point::class.java,
GeometryDeserializer(PointParser(gf))
)
addDeserializer(LineString::class.java,
GeometryDeserializer(
LineStringParser(
gf
)
)
)
addDeserializer(Polygon::class.java,
GeometryDeserializer(
PolygonParser(
gf
)
)
)
addDeserializer(MultiPoint::class.java,
GeometryDeserializer(
MultiPointParser(
gf
)
)
)
addDeserializer(MultiLineString::class.java,
GeometryDeserializer(
MultiLineStringParser(
gf
)
)
)
addDeserializer(MultiPolygon::class.java,
GeometryDeserializer(
MultiPolygonParser(
gf
)
)
)
addDeserializer(GeometryCollection::class.java,
GeometryDeserializer(
GeometryCollectionParser(
gf
)
)
)
addDeserializer(Coordinate::class.java, CoordinateDeserializer())
addDeserializer(CoordinateSequence::class.java,
CoordinateSequenceDeserializer(gf.coordinateSequenceFactory)
)
addDeserializer(Envelope::class.java, EnvelopeDeserializer())
}
override fun setupModule(context: SetupContext) {
super.setupModule(context)
}
}
fun ObjectMapper.registerJTSGeoJSON(
configuration: JTSGeoJsonConfiguration = JTSGeoJsonConfiguration(),
gf: GeometryFactory = GeometryFactory()
) {
this.registerModule(JTSGeoJSON(configuration, gf))
}
| 1
|
Kotlin
|
0
| 1
|
e7816efecbc7cbc0b05b07d033445d68034bc5cd
| 3,839
|
keo
|
Apache License 2.0
|
sample/src/main/java/studio/opends/sample/Navhost.kt
|
open-design-systems
| 810,431,148
| false
|
{"Kotlin": 42547, "Shell": 2799, "Makefile": 121}
|
package studio.opends.sample
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.opends.sample.screens.main.ColorScreen
import com.opends.sample.screens.main.HomeScreen
import com.opends.sample.screens.main.TypographyScreen
@Composable
internal fun AppNavHost(
modifier: Modifier = Modifier,
navController: NavHostController,
startDestination: NavigationDestinations = NavigationDestinations.Start
) {
var title by rememberSaveable { mutableStateOf("OpenDS") }
var canPop by rememberSaveable { mutableStateOf(false) }
Scaffold(
topBar = {
TopBar(
title = title,
canPop = canPop,
navController = navController,
)
}
) { padding ->
NavHost(
modifier = modifier.padding(padding),
navController = navController,
startDestination = startDestination.route
) {
composable(
route = NavigationDestinations.Start.route
) {
canPop = false
title = NavigationDestinations.Start.route
HomeScreen(navController = navController)
}
composable(
route = NavigationDestinations.ColorScreen.route
) {
canPop = true
title = NavigationDestinations.ColorScreen.route
ColorScreen()
}
composable(
route = NavigationDestinations.TypographyScreen.route
) {
canPop = true
title = NavigationDestinations.TypographyScreen.route
TypographyScreen()
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TopBar(
title: String,
canPop: Boolean,
navController: NavHostController
) {
if (canPop) {
TopAppBar(
navigationIcon = {
IconButton(onClick = {
navController.popBackStack()
}) {
Icon(
imageVector = Icons.AutoMirrored.Rounded.ArrowBack,
contentDescription = null,
)
}
},
title = {
Text(text = title)
}
)
} else {
TopAppBar(
title = {
Text(text = title)
}
)
}
}
| 1
|
Kotlin
|
0
| 0
|
7f969b713beb7d472504c68520e0482243f593a1
| 3,240
|
OpenDSAndroid
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/me/zhengjin/common/customs/business/cbi/logistics/po/result/ILogisticsReturn.kt
|
zhengjin-me
| 522,433,935
| false
|
{"Kotlin": 485833, "Java": 67793}
|
/*
* MIT License
*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.zhengjin.common.customs.business.cbi.logistics.po.result
import com.fasterxml.jackson.annotation.JsonIgnore
import me.zhengjin.common.core.jpa.comment.annotation.JpaComment
import me.zhengjin.common.customs.business.cbi.logistics.po.declare.ILogistics
import me.zhengjin.common.customs.po.ReturnContentBaseEntity
import org.hibernate.annotations.Where
import javax.persistence.Column
import javax.persistence.ConstraintMode
import javax.persistence.Entity
import javax.persistence.FetchType
import javax.persistence.ForeignKey
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne
import javax.persistence.Table
import javax.xml.bind.annotation.XmlAccessType
import javax.xml.bind.annotation.XmlAccessorType
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlTransient
import javax.xml.bind.annotation.XmlType
/**
* 跨境进口运单回执
*/
@Entity
@Table(name = "cbi_logistics_return")
@JpaComment("跨境进口运单回执")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = ["logisticsCode", "logisticsNo"])
@XmlRootElement(name = "LogisticsReturn", namespace = "http://www.chinaport.gov.cn/ceb")
data class ILogisticsReturn(
/**
* 物流企业代码
*/
@field:[
JpaComment("物流企业代码")
Column
XmlElement(namespace = "http://www.chinaport.gov.cn/ceb", required = true)
]
var logisticsCode: String? = null,
/**
* 物流运单编号
*/
@field:[
JpaComment("物流运单编号")
Column
XmlElement(namespace = "http://www.chinaport.gov.cn/ceb", required = true)
]
var logisticsNo: String? = null
) : ReturnContentBaseEntity() {
@JsonIgnore
@XmlTransient
@Where(clause = "is_delete = 0")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "logistics_id", foreignKey = ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))
var logistics: ILogistics? = null
}
| 0
|
Kotlin
|
0
| 0
|
7577fb6993d608ab392c127eb0d715e6eceec768
| 3,086
|
common-customs-beans
|
MIT License
|
src/main/kotlin/org/cuongnv/subfinder/reactx/MainScheduler.kt
|
cuongnv126
| 386,142,000
| false
| null |
package org.cuongnv.subfinder.reactx
import io.reactivex.rxjava3.core.Scheduler
class MainScheduler : Scheduler() {
override fun createWorker(): Worker = MainWorker()
}
| 0
|
Kotlin
|
0
| 5
|
d0492b892ae880e0cac508bb26528232f0c78756
| 174
|
subfinderapp
|
Apache License 2.0
|
compose/ui/ui-text/src/desktopTest/kotlin/androidx/compose/ui/text/DesktopParagraphTest.kt
|
RikkaW
| 389,105,112
| false
| null |
/*
* Copyright 2020 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.ui.text
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.font.createFontFamilyResolver
import androidx.compose.ui.text.platform.Font
import androidx.compose.ui.text.style.TextDirection
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.sp
import com.google.common.truth.Truth
import org.junit.Assume.assumeTrue
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class DesktopParagraphTest {
@get:Rule
val rule = createComposeRule()
private val fontFamilyResolver = createFontFamilyResolver()
private val defaultDensity = Density(density = 1f)
private val fontFamilyMeasureFont =
FontFamily(
Font(
"font/sample_font.ttf",
weight = FontWeight.Normal,
style = FontStyle.Normal
)
)
@Test
@Ignore("b/271123970 Fails in AOSP. Will be fixed after upstreaming Compose for Desktop")
fun getBoundingBox_basic() {
with(defaultDensity) {
val text = "abc"
val fontSize = 50.sp
val fontSizeInPx = fontSize.toPx()
val paragraph = simpleParagraph(
text = text,
style = TextStyle(fontSize = fontSize)
)
for (i in 0..text.length - 1) {
val box = paragraph.getBoundingBox(i)
Truth.assertThat(box.left).isEqualTo(i * fontSizeInPx)
Truth.assertThat(box.right).isEqualTo((i + 1) * fontSizeInPx)
Truth.assertThat(box.top).isZero()
Truth.assertThat(box.bottom).isEqualTo(fontSizeInPx + 10)
}
}
}
@Test
@Ignore("b/271123970 Fails in AOSP. Will be fixed after upstreaming Compose for Desktop")
fun getBoundingBox_multicodepoints() {
assumeTrue(isLinux)
with(defaultDensity) {
val text = "h\uD83E\uDDD1\uD83C\uDFFF\u200D\uD83E\uDDB0"
val fontSize = 50.sp
val fontSizeInPx = fontSize.toPx()
val paragraph = simpleParagraph(
text = text,
style = TextStyle(fontSize = 50.sp)
)
Truth.assertThat(paragraph.getBoundingBox(0))
.isEqualTo(Rect(0f, 0f, fontSizeInPx, 60f))
Truth.assertThat(paragraph.getBoundingBox(1))
.isEqualTo(Rect(fontSizeInPx, 0f, fontSizeInPx * 2.5f, 60f))
Truth.assertThat(paragraph.getBoundingBox(5))
.isEqualTo(Rect(fontSizeInPx, 0f, fontSizeInPx * 2.5f, 60f))
}
}
@Test
fun getLineForOffset() {
val text = "ab\na"
val paragraph = simpleParagraph(
text = text,
style = TextStyle(fontSize = 50.sp)
)
Truth.assertThat(paragraph.getLineForOffset(2))
.isEqualTo(0)
Truth.assertThat(paragraph.getLineForOffset(3))
.isEqualTo(1)
}
@Test
fun getLineEnd() {
with(defaultDensity) {
val text = ""
val paragraph = simpleParagraph(
text = text,
style = TextStyle(fontSize = 50.sp)
)
Truth.assertThat(paragraph.getLineEnd(0, true))
.isEqualTo(0)
}
with(defaultDensity) {
val text = "ab\n\nc"
val paragraph = simpleParagraph(
text = text,
style = TextStyle(fontSize = 50.sp)
)
Truth.assertThat(paragraph.getLineEnd(0, true))
.isEqualTo(2)
Truth.assertThat(paragraph.getLineEnd(1, true))
.isEqualTo(3)
Truth.assertThat(paragraph.getLineEnd(2, true))
.isEqualTo(5)
}
with(defaultDensity) {
val text = "ab\n"
val paragraph = simpleParagraph(
text = text,
style = TextStyle(fontSize = 50.sp)
)
Truth.assertThat(paragraph.getLineEnd(0, true))
.isEqualTo(2)
Truth.assertThat(paragraph.getLineEnd(1, true))
.isEqualTo(3)
}
}
@Test
fun getLineBaseline() {
val text = "abc\nabc\nabc"
val paragraph = simpleParagraph(text = text)
Truth.assertThat(paragraph.getLineBaseline(0)).isEqualTo(paragraph.firstBaseline)
Truth.assertThat(paragraph.getLineBaseline(2)).isEqualTo(paragraph.lastBaseline)
}
@Test
fun getHorizontalPositionForOffset_primary_Bidi_singleLine_textDirectionDefault() {
with(defaultDensity) {
val ltrText = "abc"
val rtlText = "\u05D0\u05D1\u05D2"
val text = ltrText + rtlText
val fontSize = 50.sp
val fontSizeInPx = fontSize.toPx()
val width = text.length * fontSizeInPx
val paragraph = simpleParagraph(
text = text,
style = TextStyle(fontSize = fontSize),
width = width
)
for (i in 0..ltrText.length) {
Truth.assertThat(paragraph.getHorizontalPosition(i, true))
.isEqualTo(fontSizeInPx * i)
}
for (i in 1 until rtlText.length) {
Truth.assertThat(paragraph.getHorizontalPosition(i + ltrText.length, true))
.isEqualTo(width - fontSizeInPx * i)
}
}
}
@Test
fun getHorizontalPositionForOffset_notPrimary_Bidi_singleLine_textDirectionLtr() {
with(defaultDensity) {
val ltrText = "abc"
val rtlText = "\u05D0\u05D1\u05D2"
val text = ltrText + rtlText
val fontSize = 50.sp
val fontSizeInPx = fontSize.toPx()
val width = text.length * fontSizeInPx
val paragraph = simpleParagraph(
text = text,
style = TextStyle(
fontSize = fontSize,
textDirection = TextDirection.Ltr
),
width = width
)
for (i in ltrText.indices) {
Truth.assertThat(paragraph.getHorizontalPosition(i, false))
.isEqualTo(fontSizeInPx * i)
}
for (i in rtlText.indices) {
Truth.assertThat(paragraph.getHorizontalPosition(i + ltrText.length, false))
.isEqualTo(width - fontSizeInPx * i)
}
Truth.assertThat(paragraph.getHorizontalPosition(text.length, false))
.isEqualTo(width - rtlText.length * fontSizeInPx)
}
}
@Test
fun getWordBoundary_spaces() {
val text = "ab cd e"
val paragraph = simpleParagraph(
text = text,
style = TextStyle(
fontFamily = fontFamilyMeasureFont,
fontSize = 20.sp
)
)
val singleSpaceStartResult = paragraph.getWordBoundary(text.indexOf('b') + 1)
Truth.assertThat(singleSpaceStartResult.start).isEqualTo(text.indexOf('a'))
Truth.assertThat(singleSpaceStartResult.end).isEqualTo(text.indexOf('b') + 1)
val singleSpaceEndResult = paragraph.getWordBoundary(text.indexOf('c'))
Truth.assertThat(singleSpaceEndResult.start).isEqualTo(text.indexOf('c'))
Truth.assertThat(singleSpaceEndResult.end).isEqualTo(text.indexOf('d') + 1)
val doubleSpaceResult = paragraph.getWordBoundary(text.indexOf('d') + 2)
Truth.assertThat(doubleSpaceResult.start).isEqualTo(text.indexOf('d') + 2)
Truth.assertThat(doubleSpaceResult.end).isEqualTo(text.indexOf('d') + 2)
}
@Test
fun two_paragraphs_use_common_intrinsics() {
fun Paragraph.testOffset() = getOffsetForPosition(Offset(0f, 100000f))
fun Paragraph.paint() = paint(Canvas(ImageBitmap(100, 100)))
val intrinsics = simpleIntrinsics((1..1000).joinToString(" "))
val paragraph1 = simpleParagraph(intrinsics, width = 100f)
val offset1 = paragraph1.testOffset()
val paragraph2 = simpleParagraph(intrinsics, width = 100000f)
val offset2 = paragraph2.testOffset()
Truth.assertThat(paragraph1.testOffset()).isEqualTo(offset1)
Truth.assertThat(paragraph2.testOffset()).isEqualTo(offset2)
paragraph2.paint()
Truth.assertThat(paragraph1.testOffset()).isEqualTo(offset1)
Truth.assertThat(paragraph2.testOffset()).isEqualTo(offset2)
paragraph1.paint()
Truth.assertThat(paragraph1.testOffset()).isEqualTo(offset1)
Truth.assertThat(paragraph2.testOffset()).isEqualTo(offset2)
paragraph2.paint()
Truth.assertThat(paragraph1.testOffset()).isEqualTo(offset1)
Truth.assertThat(paragraph2.testOffset()).isEqualTo(offset2)
}
@Test
fun `line heights`() {
val paragraph = simpleParagraph(
text = "aaa\n\naaa\n\n\naaa\n \naaa",
style = TextStyle(fontSize = 50.sp)
)
val firstLineHeight = paragraph.getLineHeight(0)
for (i in 1 until paragraph.lineCount) {
Truth.assertThat(paragraph.getLineHeight(i)).isEqualTo(firstLineHeight)
}
}
private fun simpleParagraph(
text: String = "",
style: TextStyle? = null,
maxLines: Int = Int.MAX_VALUE,
ellipsis: Boolean = false,
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
density: Density? = null,
width: Float = 2000f
): Paragraph {
return Paragraph(
text = text,
spanStyles = spanStyles,
style = TextStyle(
fontFamily = fontFamilyMeasureFont
).merge(style),
maxLines = maxLines,
ellipsis = ellipsis,
constraints = Constraints(maxWidth = width.ceilToInt()),
density = density ?: defaultDensity,
fontFamilyResolver = fontFamilyResolver
)
}
private fun simpleIntrinsics(
text: String = "",
style: TextStyle? = null,
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
density: Density? = null
): ParagraphIntrinsics {
return ParagraphIntrinsics(
text = text,
spanStyles = spanStyles,
style = TextStyle(
fontFamily = fontFamilyMeasureFont
).merge(style),
density = density ?: defaultDensity,
fontFamilyResolver = fontFamilyResolver
)
}
private fun simpleParagraph(
intrinsics: ParagraphIntrinsics,
maxLines: Int = Int.MAX_VALUE,
ellipsis: Boolean = false,
width: Float = 2000f
): Paragraph {
return Paragraph(
paragraphIntrinsics = intrinsics,
maxLines = maxLines,
ellipsis = ellipsis,
constraints = Constraints(maxWidth = width.ceilToInt()),
)
}
}
| 6
| null |
950
| 7
|
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
| 12,077
|
androidx
|
Apache License 2.0
|
viewer/src/main/kotlin/li/doerf/feeder/viewer/config/JwtTokenFilterConfigurer.kt
|
doerfli
| 188,579,479
| false
|
{"Kotlin": 190694, "Vue": 48142, "JavaScript": 21033, "SCSS": 2537, "HTML": 616}
|
package li.doerf.feeder.viewer.config
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.config.annotation.SecurityConfigurerAdapter
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.DefaultSecurityFilterChain
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
class JwtTokenFilterConfigurer @Autowired constructor(
private val jwtTokenProvider: JwtTokenProvider
) : SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>() {
override fun configure(http: HttpSecurity) {
val customFilter = JwtTokenFilter(jwtTokenProvider)
http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter::class.java)
}
}
| 30
|
Kotlin
|
0
| 0
|
f0a7ab9a8367ba49a7171b594b64ae2dea5deb87
| 820
|
feedscraper
|
MIT License
|
app/src/main/java/volovyk/guerrillamail/ui/assigned/AssignedEmailViewModel.kt
|
oleksandrvolovyk
| 611,731,548
| false
| null |
package volovyk.guerrillamail.ui.assigned
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import timber.log.Timber
import volovyk.guerrillamail.R
import volovyk.guerrillamail.data.emails.EmailRepository
import volovyk.guerrillamail.data.emails.model.EmailRepositoryException
import volovyk.guerrillamail.ui.SideEffect
import volovyk.guerrillamail.ui.util.EmailValidator
import javax.inject.Inject
data class AssignedEmailUiState(
val emailUsername: String? = null,
val emailDomain: String? = null,
val isGetNewAddressButtonVisible: Boolean = false
)
@HiltViewModel
class AssignedEmailViewModel @Inject constructor(
private val emailRepository: EmailRepository,
private val emailValidator: EmailValidator
) : ViewModel() {
init {
Timber.d("init ${hashCode()}")
}
private val _uiState = MutableStateFlow(AssignedEmailUiState())
val uiState: StateFlow<AssignedEmailUiState> = _uiState.asStateFlow()
private val _sideEffectChannel = Channel<SideEffect>(capacity = Channel.BUFFERED)
val sideEffectFlow: Flow<SideEffect>
get() = _sideEffectChannel.receiveAsFlow()
private val assignedEmailFlow = emailRepository.observeAssignedEmail().stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000),
null
)
init {
assignedEmailFlow
.onEach { assignedEmail ->
_uiState.update {
it.copy(
emailUsername = assignedEmail?.emailUsernamePart(),
emailDomain = assignedEmail?.emailDomainPart()
)
}
}.launchIn(viewModelScope)
}
fun getNewEmailAddress() {
val newAddress = uiState.value.emailUsername?.let {
"${uiState.value.emailUsername}@${uiState.value.emailDomain}"
}
if (newAddress == null || !emailValidator.isValidEmailAddress(newAddress)) {
_sideEffectChannel.trySend(SideEffect.ShowToast(R.string.email_invalid))
return
}
_sideEffectChannel.trySend(
SideEffect.ConfirmAction(
R.string.confirm_getting_new_address,
newAddress
) {
viewModelScope.launch {
_uiState.update { it.copy(isGetNewAddressButtonVisible = false) }
try {
emailRepository.setEmailAddress(newAddress)
} catch (e: EmailRepositoryException.EmailAddressAssignmentException) {
// If the operation is unsuccessful, revert emailUsername to previous assigned email
_uiState.update { it.copy(emailUsername = assignedEmailFlow.value?.emailUsernamePart()) }
}
}
})
}
fun userChangedEmailUsername(newEmailUsername: String) {
_uiState.update {
it.copy(
emailUsername = newEmailUsername,
isGetNewAddressButtonVisible = newEmailUsername != assignedEmailFlow.value?.emailUsernamePart()
)
}
}
fun copyEmailAddressToClipboard() {
assignedEmailFlow.value?.let { assignedEmail ->
_sideEffectChannel.trySend(SideEffect.CopyTextToClipboard(text = assignedEmail))
_sideEffectChannel.trySend(SideEffect.ShowToast(R.string.email_in_clipboard))
}
}
private fun String.emailUsernamePart(): String = this.substringBefore("@")
private fun String.emailDomainPart(): String = this.substringAfter("@")
}
| 0
| null |
0
| 1
|
0e204bb437a6cfd837cd0bb911a29f0fc43164ce
| 4,138
|
guerrilla-mail-android-client
|
MIT License
|
dsalgo/src/commonMain/kotlin/com/nalin/datastructurealgorithm/Utils.kt
|
nalinchhajer1
| 534,780,196
| false
| null |
package com.nalin.datastructurealgorithm
object Utils {
}
| 0
|
Kotlin
|
0
| 0
|
50c40c5b804c88852c5ccb06e5da1b182fcb0c07
| 63
|
kotlin-ds-algo
|
MIT License
|
http4k-testing/tracerbullet/src/test/kotlin/org/http4k/tracing/renderer/MarkdownDocumentTest.kt
|
http4k
| 86,003,479
| false
| null |
package org.http4k.tracing.renderer
import org.http4k.tracing.TraceRender
import org.http4k.tracing.TraceRenderer
class MarkdownDocumentTest : TraceRendererContract(
"foobar", "MD", MarkdownDocument(
MarkdownTraceDepthTable,
MarkdownTraceStepCountsTable,
MermaidSequenceDiagram,
MermaidInteractionDiagram,
TraceRenderer { scenarioName, steps ->
TraceRender(scenarioName, "TXT", steps.joinToString("\n"))
}
)
)
| 34
| null |
249
| 2,615
|
7ad276aa9c48552a115a59178839477f34d486b1
| 480
|
http4k
|
Apache License 2.0
|
wallet-task/src/main/kotlin/com/wallet/task/handler/SynJobHandler.kt
|
GalaxySciTech
| 339,935,435
| false
|
{"Kotlin": 273747, "CSS": 210000, "HTML": 94074, "PLpgSQL": 76509, "Java": 56269, "JavaScript": 47624, "SCSS": 25514, "Dockerfile": 1104, "Shell": 1071}
|
package com.wallet.task.handler
import com.wallet.biz.handler.service.impl.SynServiceImpl
import com.wallet.biz.rpc.RpcClient
import com.xxl.job.core.biz.model.ReturnT
import com.xxl.job.core.handler.annotation.XxlJob
import org.consenlabs.tokencore.wallet.model.ChainType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
/**
* Created by pie on 2020/6/29 01: 49.
*/
@Component
class SynJobHandler {
@XxlJob("synTRX")
fun synTRX(param: String): ReturnT<String> {
synService.synTRX()
return ReturnT.SUCCESS
}
@XxlJob("synETH")
fun synETH(param: String): ReturnT<String> {
synService.synETH()
return ReturnT.SUCCESS
}
@XxlJob("synBTC")
fun synBTC(param: String): ReturnT<String> {
synService.synBTCOrFork(rpcClient.omniRpc(), ChainType.BITCOIN)
return ReturnT.SUCCESS
}
@XxlJob("synOMNI")
fun synOMNI(param: String): ReturnT<String> {
synService.synOMNI()
return ReturnT.SUCCESS
}
@XxlJob("synDASH")
fun synDASH(param: String): ReturnT<String> {
synService.synBTCOrFork(rpcClient.dashRpc(), ChainType.DASH)
return ReturnT.SUCCESS
}
@XxlJob("synLTC")
fun synLTC(param: String): ReturnT<String> {
synService.synBTCOrFork(rpcClient.ltcRpc(), ChainType.LITECOIN)
return ReturnT.SUCCESS
}
@XxlJob("synBCH")
fun synBCH(param: String): ReturnT<String> {
synService.synBTCOrFork(rpcClient.bchRpc(), ChainType.BITCOINCASH)
return ReturnT.SUCCESS
}
@XxlJob("synBSV")
fun synBSV(param: String): ReturnT<String> {
synService.synBTCOrFork(rpcClient.bsvRpc(), ChainType.BITCOINSV)
return ReturnT.SUCCESS
}
@XxlJob("synDOGE")
fun synDOGE(param: String): ReturnT<String> {
synService.synBTCOrFork(rpcClient.dogeRpc(), ChainType.DOGECOIN)
return ReturnT.SUCCESS
}
@XxlJob("synEOS")
fun synEOS(param: String): ReturnT<String> {
synService.synEOS()
return ReturnT.SUCCESS
}
@XxlJob("synDeposit")
fun synDeposit(param: String): ReturnT<String> {
synService.synDeposit()
return ReturnT.SUCCESS
}
@XxlJob("synImportAddress")
fun synImportAddress(param: String): ReturnT<String> {
synService.synImportAddress()
return ReturnT.SUCCESS
}
@Autowired
lateinit var synService: SynServiceImpl
@Autowired
lateinit var rpcClient: RpcClient
}
| 5
|
Kotlin
|
40
| 99
|
d52e8f7f4b151676be9b98dc2c85b912b06cf536
| 2,542
|
java-wallet
|
MIT License
|
gto-support-util/src/test/java/org/ccci/gto/android/common/util/LocaleUtilsFallbackTest.kt
|
CruGlobal
| 30,609,844
| false
| null |
package org.ccci.gto.android.common.util
import androidx.test.ext.junit.runners.AndroidJUnit4
import java.util.Locale
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
private val MALAY = Locale.forLanguageTag("ms")
private val BENGKULU = Locale.forLanguageTag("pse")
@RunWith(AndroidJUnit4::class)
@Config(sdk = [21, 24])
class LocaleUtilsFallbackTest {
@Test
fun verifyGetFallback() {
assertThat(LocaleUtils.getFallback(Locale.US), equalTo(Locale.ENGLISH))
assertThat(LocaleUtils.getFallback(BENGKULU), equalTo(MALAY))
}
@Test
fun verifyGetFallbackWithScript() {
assertThat(LocaleUtils.getFallback(Locale.forLanguageTag("zh-Hans")), equalTo(Locale.CHINESE))
}
@Test
fun verifyGetFallbackWithExtensions() {
assertThat(LocaleUtils.getFallback(Locale.forLanguageTag("en-x-private")), equalTo(Locale.ENGLISH))
}
@Test
fun verifyGetFallbacks() {
assertThat(LocaleUtils.getFallbacks(Locale.US), equalTo(arrayOf(Locale.US, Locale.ENGLISH)))
assertThat(LocaleUtils.getFallbacks(Locale.ENGLISH), equalTo(arrayOf(Locale.ENGLISH)))
assertThat(LocaleUtils.getFallbacks(BENGKULU), equalTo(arrayOf(BENGKULU, MALAY)))
}
@Test
fun verifyGetFallbacksWithScript() {
val locale = Locale.forLanguageTag("zh-Hans-CN")
assertThat(
LocaleUtils.getFallbacks(locale),
equalTo(arrayOf(locale, Locale.forLanguageTag("zh-Hans"), Locale.CHINESE))
)
}
@Test
fun verifyGetFallbacksMulti() {
assertThat(LocaleUtils.getFallbacks(Locale.US, Locale.ENGLISH), equalTo(arrayOf(Locale.US, Locale.ENGLISH)))
assertThat(LocaleUtils.getFallbacks(Locale.ENGLISH, Locale.US), equalTo(arrayOf(Locale.ENGLISH, Locale.US)))
assertThat(
LocaleUtils.getFallbacks(Locale.US, Locale.CANADA, Locale.CANADA_FRENCH),
equalTo(arrayOf(Locale.US, Locale.ENGLISH, Locale.CANADA, Locale.CANADA_FRENCH, Locale.FRENCH))
)
}
}
| 4
|
Kotlin
|
2
| 5
|
6a16d0eb432f76266d5c1fed440428f71762ba7c
| 2,139
|
android-gto-support
|
MIT License
|
app/src/main/java/com/mytest/composetest/util/LogUtils.kt
|
pionio2
| 409,655,599
| false
|
{"Kotlin": 199306}
|
package com.mytest.composetest.util
import android.util.Log
/**
* kotlin에서 사용하기 위한 utility functions
*/
const val APP_TAG = "MyTestApp"
inline fun LogDebug(TAG: String, printLog: () -> String) {
Log.d(APP_TAG, "[$TAG] ${printLog()}")
}
inline fun LogInfo(TAG: String, printLog: () -> String) {
Log.i(APP_TAG, "[$TAG] ${printLog()}")
}
inline fun LogWarn(TAG: String, e: Exception? = null, printLog: () -> String) {
if (e == null) {
Log.w(APP_TAG, "[$TAG] ${printLog()}")
} else {
Log.w(APP_TAG, "[$TAG] ${printLog()}", e)
}
}
inline fun LogError(TAG: String, e: Exception? = null, printLog: () -> String) {
if (e == null) {
Log.e(APP_TAG, "[$TAG] ${printLog()}")
} else {
Log.e(TAG, "[$TAG] ${printLog()}", e)
}
}
| 0
|
Kotlin
|
0
| 1
|
c303ea93f25e94d4aa08485d1f2ab965a6d54a37
| 787
|
composeTest
|
Apache License 2.0
|
src/zh/qinqin/src/eu/kanade/tachiyomi/extension/zh/qinqin/Qinqin.kt
|
komikku-app
| 720,497,299
| false
| null |
package eu.kanade.tachiyomi.revived.zh.qinqin
import android.util.Base64
import eu.kanade.tachiyomi.multisrc.sinmh.SinMH
import eu.kanade.tachiyomi.network.GET
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
class Qinqin : SinMH("亲亲漫画", "https://www.acgud.com") {
override fun popularMangaRequest(page: Int) = GET("$baseUrl/list/post/?page=$page", headers)
override fun mangaDetailsParse(document: Document) = mangaDetailsParseDMZJStyle(document, hasBreadcrumb = true)
override fun Elements.sectionsDescending() = this
// https://www.acgud.com/js/jmzz20191018.js
override fun parsePageImages(chapterImages: String): List<String> {
val key = SecretKeySpec("<KEY>(), "AES")
val iv = IvParameterSpec("opb4x7z21vg1f3gI".toByteArray())
val result = Cipher.getInstance("AES/CBC/PKCS7Padding").run {
init(Cipher.DECRYPT_MODE, key, iv)
doFinal(Base64.decode(chapterImages, Base64.DEFAULT))
}
return super.parsePageImages(String(result))
}
}
| 9
| null |
99
| 97
|
7fc1d11ee314376fe0daa87755a7590a03bc11c0
| 1,151
|
komikku-extensions
|
Apache License 2.0
|
src/commonTest/kotlin/com/jeffpdavidson/kotwords/model/SnakeCharmerTest.kt
|
jpd236
| 143,651,464
| false
| null |
package com.jeffpdavidson.kotwords.model
import com.jeffpdavidson.kotwords.formats.CrosswordCompilerApplet
import com.jeffpdavidson.kotwords.readStringResource
import io.github.pdvrieze.xmlutil.testutil.assertXmlEquals
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
class SnakeCharmerTest {
@Test
fun jpzGeneration() = runTest {
val snakeCharmer = SnakeCharmer(
title = "Test title",
creator = "Test creator",
copyright = "Test copyright",
description = "Test description",
answers = listOf("ABCD", "EFG", "HABCD", "EFGH"),
clues = listOf("Clue 1", "Clue 2", "Clue 3", "Clue 4"),
gridCoordinates = listOf(0 to 0, 1 to 0, 2 to 0, 2 to 1, 2 to 2, 1 to 2, 0 to 2, 0 to 1)
)
val puzzle = snakeCharmer.asPuzzle()
val expected = readStringResource(SnakeCharmerTest::class, "snake-charmer/snake-charmer.jpz")
assertXmlEquals(
expected, puzzle.asJpz(
appletSettings = CrosswordCompilerApplet.AppletSettings(
cursorColor = "#00b100",
selectedCellsColor = "#80ff80",
completion = CrosswordCompilerApplet.AppletSettings.Completion(message = "All done!"),
)
).toXmlString()
)
}
}
| 8
| null |
6
| 25
|
e18e9cf0bad7497da15b40f6c81ba4234ec83917
| 1,346
|
kotwords
|
Apache License 2.0
|
src/converter/openapi/src/commonTest/kotlin/community/flock/wirespec/openapi/v3/OpenApiV3ParserTest.kt
|
flock-community
| 506,356,849
| false
|
{"Kotlin": 656506, "Shell": 6544, "TypeScript": 5819, "Witcher Script": 4248, "Java": 4221, "Dockerfile": 625, "Makefile": 501, "JavaScript": 140}
|
package community.flock.wirespec.openapi.v3
import com.goncalossilva.resources.Resource
import community.flock.kotlinx.openapi.bindings.v3.OpenAPI
import community.flock.wirespec.compiler.core.parse.Endpoint
import community.flock.wirespec.compiler.core.parse.Enum
import community.flock.wirespec.compiler.core.parse.Field
import community.flock.wirespec.compiler.core.parse.Identifier
import community.flock.wirespec.compiler.core.parse.Reference
import community.flock.wirespec.compiler.core.parse.Reference.Primitive
import community.flock.wirespec.compiler.core.parse.Type
import community.flock.wirespec.compiler.core.parse.Type.Shape
import community.flock.wirespec.openapi.common.Expected
import community.flock.wirespec.openapi.v3.OpenApiV3Parser.parse
import kotlin.test.Test
import kotlin.test.assertEquals
class OpenApiV3ParserTest {
@Test
fun petstore() {
val json = Resource("src/commonTest/resources/v3/petstore.json").readText()
val openApi = OpenAPI.decodeFromString(json)
val ast = openApi.parse()
val expect = listOf(
Enum(
comment = null,
identifier = Identifier("FindPetsByStatusParameterStatus"),
entries = setOf("available", "pending", "sold")
),
Type(
comment = null,
identifier = Identifier("Order"),
shape = Shape(
value = listOf(
Field(
identifier = Identifier("id"),
reference = Primitive(
type = Primitive.Type.Integer,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("petId"),
reference = Primitive(
type = Primitive.Type.Integer,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("quantity"),
reference = Primitive(
type = Primitive.Type.Integer,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("shipDate"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("status"),
reference = Reference.Custom(
value = "OrderStatus",
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("complete"),
reference = Primitive(
type = Primitive.Type.Boolean,
isIterable = false,
isDictionary = false
),
isNullable = true
)
)
),
extends = emptyList(),
),
Enum(
comment = null,
identifier = Identifier("OrderStatus"),
entries = setOf("placed", "approved", "delivered"),
),
Type(
comment = null,
identifier = Identifier("Customer"),
shape = Shape(
value = listOf(
Field(
identifier = Identifier("id"),
reference = Primitive(
type = Primitive.Type.Integer,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("username"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("address"),
reference = Reference.Custom(value = "Address", isIterable = true, isDictionary = false),
isNullable = true
)
)
),
extends = emptyList(),
),
Type(
comment = null,
identifier = Identifier("Address"),
shape = Shape(
value = listOf(
Field(
identifier = Identifier("street"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("city"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("state"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("zip"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
)
)
),
extends = emptyList(),
),
Type(
comment = null,
identifier = Identifier("Category"),
shape = Shape(
value = listOf(
Field(
identifier = Identifier("id"),
reference = Primitive(
type = Primitive.Type.Integer,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("name"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
)
)
),
extends = emptyList(),
),
Type(
comment = null,
identifier = Identifier("User"),
shape = Shape(
value = listOf(
Field(
identifier = Identifier("id"),
reference = Primitive(
type = Primitive.Type.Integer,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("username"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("firstName"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("lastName"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("email"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("password"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("phone"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("userStatus"),
reference = Primitive(
type = Primitive.Type.Integer,
isIterable = false,
isDictionary = false
),
isNullable = true
)
)
),
extends = emptyList(),
),
Type(
comment = null,
identifier = Identifier("Tag"),
shape = Shape(
value = listOf(
Field(
identifier = Identifier("id"),
reference = Primitive(
type = Primitive.Type.Integer,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("name"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
)
)
),
extends = emptyList(),
),
Type(
comment = null,
identifier = Identifier("Pet"),
shape = Shape(
value = listOf(
Field(
identifier = Identifier("id"),
reference = Primitive(
type = Primitive.Type.Integer,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("name"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = false
),
Field(
identifier = Identifier("category"),
reference = Reference.Custom(
value = "Category",
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("photoUrls"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = true,
isDictionary = false
),
isNullable = false
),
Field(
identifier = Identifier("tags"),
reference = Reference.Custom(
value = "Tag",
isIterable = true,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("status"),
reference = Reference.Custom(
value = "PetStatus",
isIterable = false,
isDictionary = false
),
isNullable = true
)
)
),
extends = emptyList(),
),
Enum(
comment = null,
identifier = Identifier("PetStatus"),
entries = setOf("available", "pending", "sold"),
),
Type(
comment = null,
identifier = Identifier("ApiResponse"),
shape = Shape(
value = listOf(
Field(
identifier = Identifier("code"),
reference = Primitive(
type = Primitive.Type.Integer,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("type"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
),
Field(
identifier = Identifier("message"),
reference = Primitive(
type = Primitive.Type.String,
isIterable = false,
isDictionary = false
),
isNullable = true
)
)
),
extends = emptyList(),
)
)
assertEquals(expect.filterIsInstance<Type>(), ast.filterIsInstance<Type>())
assertEquals(expect.filterIsInstance<Enum>(), ast.filterIsInstance<Enum>())
val endpoint = ast.filterIsInstance<Endpoint>().find { it.identifier.value == "GetInventory" }
val expectedEndpoint = Endpoint(
comment = null,
identifier = Identifier("GetInventory"),
method = Endpoint.Method.GET,
path = listOf(Endpoint.Segment.Literal(value = "store"), Endpoint.Segment.Literal(value = "inventory")),
queries = emptyList(),
headers = emptyList(),
cookies = emptyList(),
requests = listOf(Endpoint.Request(content = null)),
responses = listOf(
Endpoint.Response(
status = "200",
headers = emptyList(),
content = Endpoint.Content(
type = "application/json",
reference = Primitive(type = Primitive.Type.Integer, isIterable = false, isDictionary = true),
isNullable = false
)
)
)
)
assertEquals(expectedEndpoint, endpoint)
}
@Test
fun pizza() {
val json = Resource("src/commonTest/resources/v3/pizza.json").readText()
val openApi = OpenAPI.decodeFromString(json)
val ast = openApi.parse()
val expect = listOf(
Endpoint(
comment = null,
identifier = Identifier("PizzasPizzaIdIngredientsGET"),
method = Endpoint.Method.GET,
path = listOf(
Endpoint.Segment.Literal("pizzas"),
Endpoint.Segment.Param(
Identifier("pizzaId"),
Primitive(type = Primitive.Type.String, isIterable = false)
),
Endpoint.Segment.Literal("ingredients"),
),
queries = listOf(),
headers = listOf(),
cookies = listOf(),
requests = listOf(
Endpoint.Request(null),
),
responses = listOf(
Endpoint.Response(
status = "200",
headers = emptyList(),
content = Endpoint.Content("application/json", Reference.Custom("Ingredient", true), false)
),
Endpoint.Response(
status = "404",
headers = emptyList(),
content = null
)
)
),
Type(
comment = null,
identifier = Identifier("Ingredient"),
shape = Shape(
listOf(
Field(Identifier("id"), Primitive(Primitive.Type.String, false), true),
Field(Identifier("name"), Primitive(Primitive.Type.String, false), true),
Field(Identifier("quantity"), Primitive(Primitive.Type.String, false), true),
)
),
extends = emptyList(),
),
)
assertEquals(expect, ast)
}
@Test
fun todo() {
val json = Resource("src/commonTest/resources/v3/todo.json").readText()
val openApi = OpenAPI.decodeFromString(json)
val ast = openApi.parse()
val expect = listOf(
Endpoint(
comment = null,
identifier = Identifier("TodosList"),
method = Endpoint.Method.GET,
path = listOf(
Endpoint.Segment.Literal("todos")
),
queries = listOf(
Field(Identifier("completed"), Primitive(type = Primitive.Type.Boolean, isIterable = false), true)
),
headers = listOf(
Field(Identifier("x-user"), Primitive(type = Primitive.Type.Boolean, isIterable = false), true)
),
cookies = listOf(),
requests = listOf(
Endpoint.Request(null),
),
responses = listOf(
Endpoint.Response(
status = "200",
headers = emptyList(),
content = Endpoint.Content("application/json", Reference.Custom("Todo", true), false)
),
Endpoint.Response(
status = "500",
headers = emptyList(),
content = Endpoint.Content("application/json", Reference.Custom("Error", false), false)
)
)
),
Endpoint(
comment = null,
identifier = Identifier("TodosPOST"),
method = Endpoint.Method.POST,
path = listOf(
Endpoint.Segment.Literal("todos"),
),
queries = listOf(),
headers = listOf(
Field(Identifier("x-user"), Primitive(type = Primitive.Type.Boolean, isIterable = false), true)
),
cookies = listOf(),
requests = listOf(
Endpoint.Request(
Endpoint.Content(
type = "application/json",
reference = Reference.Custom("Todo_input", false),
isNullable = true
)
),
Endpoint.Request(
Endpoint.Content(
type = "application/xml",
reference = Reference.Custom("Todo", false),
isNullable = true
)
)
),
responses = listOf(
Endpoint.Response(
status = "201",
headers = emptyList(),
content = null
),
Endpoint.Response(
status = "500",
headers = emptyList(),
content = Endpoint.Content(
type = "application/json",
reference = Reference.Custom("Error", false),
isNullable = false
)
)
)
),
Endpoint(
comment = null,
identifier = Identifier("TodosIdGET"),
method = Endpoint.Method.GET,
path = listOf(
Endpoint.Segment.Literal("todos"),
Endpoint.Segment.Param(Identifier("id"), Primitive(Primitive.Type.String, false))
),
queries = listOf(),
headers = listOf(),
cookies = listOf(),
requests = listOf(
Endpoint.Request(null),
),
responses = listOf(
Endpoint.Response(
status = "200",
headers = emptyList(),
content = Endpoint.Content(
type = "application/json",
reference = Reference.Custom("Todo", false),
isNullable = true
)
),
Endpoint.Response(
status = "500",
headers = emptyList(),
content = Endpoint.Content(
type = "application/json",
reference = Reference.Custom("Error", false),
isNullable = false
)
)
)
),
Type(
comment = null,
identifier = Identifier("Todo_input"),
shape = Shape(
listOf(
Field(Identifier("title"), Primitive(Primitive.Type.String, false), true),
Field(Identifier("completed"), Primitive(Primitive.Type.Boolean, false), true)
)
),
extends = emptyList(),
),
Type(
comment = null,
identifier = Identifier("Todo"),
shape = Shape(
listOf(
Field(Identifier("id"), Primitive(Primitive.Type.String, false), true),
Field(Identifier("title"), Primitive(Primitive.Type.String, false), true),
Field(Identifier("completed"), Primitive(Primitive.Type.Boolean, false), true),
Field(Identifier("alert"), Reference.Custom("TodoAlert", false), true),
)
),
extends = emptyList(),
),
Type(
comment = null,
identifier = Identifier("TodoAlert"),
shape = Shape(
listOf(
Field(Identifier("code"), Primitive(Primitive.Type.String, false), true),
Field(Identifier("message"), Reference.Custom("TodoAlertMessage", false), true),
)
),
extends = emptyList(),
),
Type(
comment = null,
identifier = Identifier("TodoAlertMessage"),
shape = Shape(
listOf(
Field(Identifier("key"), Primitive(Primitive.Type.String, false), true),
Field(Identifier("value"), Primitive(Primitive.Type.String, false), true),
)
),
extends = emptyList(),
),
Type(
comment = null,
identifier = Identifier("TodosnestedArray"),
shape = Shape(
listOf(
Field(Identifier("id"), Primitive(Primitive.Type.String, false), true),
Field(Identifier("title"), Primitive(Primitive.Type.String, false), true),
Field(Identifier("nested"), Primitive(Primitive.Type.Boolean, false), true),
)
),
extends = emptyList(),
),
Type(
comment = null,
identifier = Identifier("Error"),
shape = Shape(
listOf(
Field(Identifier("code"), Primitive(Primitive.Type.String, false), true),
Field(Identifier("message"), Primitive(Primitive.Type.String, false), true),
)
),
extends = emptyList(),
),
)
assertEquals(expect, ast)
}
@Test
fun objectInRequest() {
val json = Resource("src/commonTest/resources/v3/object-in-request.json").readText()
val openApi = OpenAPI.decodeFromString(json)
val ast = openApi.parse()
assertEquals(Expected.objectInRequest, ast)
println(ast)
}
@Test
fun objectInResponse() {
val json = Resource("src/commonTest/resources/v3/object-in-response.json").readText()
val openApi = OpenAPI.decodeFromString(json)
val ast = openApi.parse()
assertEquals(Expected.objectInResponse, ast)
println(ast)
}
@Test
fun additionalProperties() {
val json = Resource("src/commonTest/resources/v3/additionalproperties.json").readText()
val openApi = OpenAPI.decodeFromString(json)
val ast = openApi.parse()
assertEquals(Expected.additionalProperties, ast)
println(ast)
}
@Test
fun array() {
val json = Resource("src/commonTest/resources/v3/array.json").readText()
val openApi = OpenAPI.decodeFromString(json)
val ast = openApi.parse()
assertEquals(Expected.array, ast)
println(ast)
}
@Test
fun allOf() {
val json = Resource("src/commonTest/resources/v3/allof.json").readText()
val openApi = OpenAPI.decodeFromString(json)
val ast = openApi.parse()
assertEquals(Expected.allOf, ast)
}
@Test
fun oneOf() {
val json = Resource("src/commonTest/resources/v3/oneof.json").readText()
val openApi = OpenAPI.decodeFromString(json)
val ast = openApi.parse()
Expected.oneOf.zip(ast).forEach { (expected, actual) ->
println(expected.identifier)
assertEquals(expected, actual)
}
}
@Test
fun enum() {
val json = Resource("src/commonTest/resources/v3/enum.json").readText()
val openApi = OpenAPI.decodeFromString(json)
val ast = openApi.parse()
assertEquals(Expected.enum, ast)
}
}
| 18
|
Kotlin
|
2
| 17
|
50f8b9a1e341d6d79fdc86f6bff9fca9b32b7579
| 31,061
|
wirespec
|
Apache License 2.0
|
app/src/main/java/com/sofa/nerdrunning/navigation/MainNavHost.kt
|
SoFabian
| 500,733,949
| false
| null |
package com.sofa.nerdrunning.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.sofa.nerdrunning.finishedrun.FinishedRunView
import com.sofa.nerdrunning.finishedrun.ListFinishedRunsView
import com.sofa.nerdrunning.home.HomeView
import com.sofa.nerdrunning.liverun.LiveRunView
@Composable
fun MainNavHost(navController: NavHostController) {
val navigation = Navigation(navController)
NavHost(navController, startDestination = Routes.home) {
composable(Routes.home) {
HomeView(navigation)
}
composable(Routes.liveRun) {
LiveRunView(navigation)
}
composable(Routes.finishedRun,
arguments = listOf(navArgument(Routes.Args.runId) { type = NavType.LongType })
) {
val runId = it.arguments?.getLong(Routes.Args.runId)
if (runId != null) {
FinishedRunView(runId, navigation)
}
}
composable(Routes.listFinishedRuns) {
ListFinishedRunsView(navigation)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
1c15de0dc9b85dfcd4e383b598f196bf27197ac3
| 1,261
|
androidrunning
|
MIT License
|
app/src/main/java/com/project/bestladyapp/data/utils/EmailMobileData.kt
|
Alvinimbua
| 528,758,122
| false
| null |
package com.project.bestladyapp.data.utils
data class EmailMobileData(
val emails: ArrayList<String> = ArrayList(),
val mobiles: ArrayList<String> = ArrayList()
)
| 0
|
Kotlin
|
0
| 2
|
f08ba9f626fed5fe9f3da79dd9b41358f924b945
| 165
|
e-commerce-app
|
MIT License
|
src/main/kotlin/no/nav/familie/oppdrag/grensesnittavstemming/GrensesnittavstemmingMapper.kt
|
navikt
| 596,541,750
| false
|
{"Kotlin": 164387, "Dockerfile": 120}
|
package no.nav.familie.oppdrag.grensesnittavstemming
import no.nav.familie.kontrakter.felles.oppdrag.OppdragStatus
import no.nav.familie.oppdrag.avstemming.AvstemmingMapper
import no.nav.familie.oppdrag.avstemming.AvstemmingMapper.fagområdeTilAvleverendeKomponentKode
import no.nav.familie.oppdrag.avstemming.SystemKode
import no.nav.familie.oppdrag.repository.OppdragLager
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.AksjonType
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.Aksjonsdata
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.AvstemmingType
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.Avstemmingsdata
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.DetaljType
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.Detaljdata
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.Fortegn
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.Grunnlagsdata
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.KildeType
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.Periodedata
import no.nav.virksomhet.tjenester.avstemming.meldinger.v1.Totaldata
import java.math.BigDecimal
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID
class GrensesnittavstemmingMapper(
private val oppdragsliste: List<OppdragLager>,
private val fagområde: String,
private val fom: LocalDateTime,
private val tom: LocalDateTime,
) {
private val ANTALL_DETALJER_PER_MELDING = 70
private val tidspunktFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH.mm.ss.SSSSSS")
val avstemmingId = AvstemmingMapper.encodeUUIDBase64(UUID.randomUUID())
fun lagAvstemmingsmeldinger(): List<Avstemmingsdata> {
if (oppdragsliste.isEmpty()) {
return emptyList()
} else {
return (listOf(lagStartmelding()) + lagDatameldinger() + listOf(lagSluttmelding()))
}
}
private fun lagStartmelding() = lagMelding(AksjonType.START)
private fun lagSluttmelding() = lagMelding(AksjonType.AVSL)
private fun lagDatameldinger(): List<Avstemmingsdata> {
val detaljMeldinger = opprettAvstemmingsdataLister()
val avstemmingsDataLister = if (detaljMeldinger.isNotEmpty()) detaljMeldinger else listOf(lagMelding(AksjonType.DATA))
avstemmingsDataLister.first().apply {
this.total = opprettTotalData()
this.periode = opprettPeriodeData()
this.grunnlag = opprettGrunnlagsData()
}
return avstemmingsDataLister
}
private fun lagMelding(aksjonType: AksjonType): Avstemmingsdata =
Avstemmingsdata().apply {
aksjon = opprettAksjonsdata(aksjonType)
}
private fun opprettAksjonsdata(aksjonType: AksjonType): Aksjonsdata {
return Aksjonsdata().apply {
this.aksjonType = aksjonType
this.kildeType = KildeType.AVLEV
this.avstemmingType = AvstemmingType.GRSN
this.avleverendeKomponentKode = fagområdeTilAvleverendeKomponentKode(fagområde)
this.mottakendeKomponentKode = SystemKode.OPPDRAGSSYSTEMET.kode
this.underkomponentKode = fagområde
this.nokkelFom = fom.format(tidspunktFormatter)
this.nokkelTom = tom.format(tidspunktFormatter)
this.avleverendeAvstemmingId = avstemmingId
this.brukerId = fagområde
}
}
private fun opprettAvstemmingsdataLister(): List<Avstemmingsdata> {
return opprettDetaljdata().chunked(ANTALL_DETALJER_PER_MELDING).map {
lagMelding(AksjonType.DATA).apply {
this.detalj.addAll(it)
}
}
}
private fun opprettDetaljdata(): List<Detaljdata> {
return oppdragsliste.mapNotNull { oppdrag ->
val detaljType = opprettDetaljType(oppdrag)
if (detaljType != null) {
val utbetalingsoppdrag = oppdrag.utbetalingsoppdrag
Detaljdata().apply {
this.detaljType = detaljType
this.offnr = utbetalingsoppdrag.aktoer
this.avleverendeTransaksjonNokkel = fagområde
this.tidspunkt = oppdrag.avstemmingTidspunkt.format(tidspunktFormatter)
if (detaljType in listOf(DetaljType.AVVI, DetaljType.VARS) && oppdrag.kvitteringsmelding != null) {
val kvitteringsmelding = oppdrag.kvitteringsmelding
this.meldingKode = kvitteringsmelding.kodeMelding
this.alvorlighetsgrad = kvitteringsmelding.alvorlighetsgrad
this.tekstMelding = kvitteringsmelding.beskrMelding
}
}
} else {
null
}
}
}
private fun opprettDetaljType(oppdrag: OppdragLager): DetaljType? =
when (oppdrag.status) {
OppdragStatus.LAGT_PÅ_KØ -> DetaljType.MANG
OppdragStatus.KVITTERT_MED_MANGLER -> DetaljType.VARS
OppdragStatus.KVITTERT_FUNKSJONELL_FEIL -> DetaljType.AVVI
OppdragStatus.KVITTERT_TEKNISK_FEIL -> DetaljType.AVVI
OppdragStatus.KVITTERT_OK -> null
OppdragStatus.KVITTERT_UKJENT -> null
}
private fun opprettTotalData(): Totaldata {
val totalBeløp = oppdragsliste.map { getSatsBeløp(it) }.sum()
return Totaldata().apply {
this.totalAntall = oppdragsliste.size
this.totalBelop = BigDecimal.valueOf(totalBeløp)
this.fortegn = getFortegn(totalBeløp)
}
}
private fun opprettPeriodeData(): Periodedata {
return Periodedata().apply {
this.datoAvstemtFom = formaterTilPeriodedataFormat(getLavesteAvstemmingstidspunkt().format(tidspunktFormatter))
this.datoAvstemtTom = formaterTilPeriodedataFormat(getHøyesteAvstemmingstidspunkt().format(tidspunktFormatter))
}
}
private fun opprettGrunnlagsData(): Grunnlagsdata {
var godkjentAntall = 0
var godkjentBelop = 0L
var varselAntall = 0
var varselBelop = 0L
var avvistAntall = 0
var avvistBelop = 0L
var manglerAntall = 0
var manglerBelop = 0L
for (oppdrag in oppdragsliste) {
val satsbeløp = getSatsBeløp(oppdrag)
when (oppdrag.status) {
OppdragStatus.LAGT_PÅ_KØ -> {
manglerBelop += satsbeløp
manglerAntall++
}
OppdragStatus.KVITTERT_OK -> {
godkjentBelop += satsbeløp
godkjentAntall++
}
OppdragStatus.KVITTERT_MED_MANGLER -> {
varselBelop += satsbeløp
varselAntall++
}
else -> {
avvistBelop += satsbeløp
avvistAntall++
}
}
}
return Grunnlagsdata().apply {
this.godkjentAntall = godkjentAntall
this.godkjentBelop = BigDecimal.valueOf(godkjentBelop)
this.godkjentFortegn = getFortegn(godkjentBelop)
this.varselAntall = varselAntall
this.varselBelop = BigDecimal.valueOf(varselBelop)
this.varselFortegn = getFortegn(varselBelop)
this.manglerAntall = manglerAntall
this.manglerBelop = BigDecimal.valueOf(manglerBelop)
this.manglerFortegn = getFortegn(manglerBelop)
this.avvistAntall = avvistAntall
this.avvistBelop = BigDecimal.valueOf(avvistBelop)
this.avvistFortegn = getFortegn(avvistBelop)
}
}
private fun getSatsBeløp(oppdrag: OppdragLager): Long =
oppdrag.utbetalingsoppdrag.utbetalingsperiode.map { it.sats }.reduce(BigDecimal::add).toLong()
private fun getFortegn(satsbeløp: Long): Fortegn {
return if (satsbeløp >= 0) Fortegn.T else Fortegn.F
}
private fun getHøyesteAvstemmingstidspunkt(): LocalDateTime {
return sortertAvstemmingstidspunkt().first()
}
private fun getLavesteAvstemmingstidspunkt(): LocalDateTime {
return sortertAvstemmingstidspunkt().last()
}
private fun sortertAvstemmingstidspunkt() =
oppdragsliste.map(OppdragLager::avstemmingTidspunkt).sortedDescending()
private fun formaterTilPeriodedataFormat(stringTimestamp: String): String =
LocalDateTime.parse(stringTimestamp, tidspunktFormatter)
.format(DateTimeFormatter.ofPattern("yyyyMMddHH"))
}
| 17
|
Kotlin
|
0
| 0
|
e9eb27715404d42a4cb6f95c9b08811c76f11174
| 8,618
|
familie-oppdrag
|
MIT License
|
calendarview/src/main/java/com/chahine/calendarview/delegates/EmptyDayDelegate.kt
|
chahine
| 130,400,266
| false
|
{"Gradle": 4, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 15, "Kotlin": 10, "Java": 2}
|
package com.chahine.calendarview.delegates
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import android.view.ViewGroup
import com.chahine.calendarview.CalendarAdapter
import com.chahine.calendarview.R
import org.threeten.bp.LocalDate
class EmptyDayDelegate {
class Delegate : CalendarAdapter.Delegate {
override fun layoutId() = R.layout.item_day_empty
override fun create(parent: ViewGroup) = Holder(itemView(parent))
}
class Holder(itemView: View) : ViewHolder(itemView)
data class Item(val date: LocalDate) : CalendarAdapter.Item {
override fun itemViewType() = CalendarAdapter.EMPTY_DAY
}
}
| 0
|
Kotlin
|
0
| 0
|
953c8544a627d974ab408285cf0f88a722ec48d9
| 658
|
calendarview
|
MIT License
|
domain/src/main/java/ru/sportivityteam/vucmirea/assistant/domain/repository/auth/AuthRepository.kt
|
SportivityTeam
| 753,183,017
| false
|
{"Kotlin": 46772, "Swift": 532}
|
package ru.sportivityteam.vucmirea.assistant.domain.repository.auth
import kotlinx.coroutines.flow.Flow
import ru.sportivityteam.vucmirea.assistant.domain.util.State
interface AuthRepository {
val isUserLogin: Flow<State<Boolean>>
suspend fun authUser(name: String, group: String): Flow<State<Unit>>
suspend fun logout(): Flow<State<Unit>>
}
| 0
|
Kotlin
|
0
| 2
|
a45c1129bb1cfc56c784778ef3b28afff302ec63
| 356
|
assistant-vuc-mirea
|
MIT License
|
libraries/tools/kotlin-stdlib-gen/src/templates/Snapshots.kt
|
qq451682583
| 46,259,824
| true
|
{"Java": 15970906, "Kotlin": 11444005, "JavaScript": 176060, "Protocol Buffer": 42992, "HTML": 26497, "Lex": 16515, "ANTLR": 9689, "CSS": 9358, "Groovy": 5204, "Shell": 4638, "Batchfile": 3703, "IDL": 3441}
|
package templates
import templates.Family.*
import templates.DocExtensions.element
import templates.DocExtensions.collection
fun snapshots(): List<GenericFunction> {
val templates = arrayListOf<GenericFunction>()
templates add f("toCollection(collection: C)") {
deprecate(Strings) { forBinaryCompatibility }
include(CharSequences, Strings)
doc { f -> "Appends all ${f.element}s to the given [collection]." }
returns("C")
typeParam("C : MutableCollection<in T>")
body {
"""
for (item in this) {
collection.add(item)
}
return collection
"""
}
}
templates add f("toSet()") {
doc { f -> "Returns a [Set] of all ${f.element}s." }
returns("Set<T>")
body { "return toCollection(LinkedHashSet<T>(mapCapacity(collectionSizeOrDefault(12))))" }
body(Sequences) { "return toCollection(LinkedHashSet<T>())" }
deprecate(Strings) { forBinaryCompatibility }
body(CharSequences, Strings) { "return toCollection(LinkedHashSet<T>(mapCapacity(length())))" }
body(ArraysOfObjects, ArraysOfPrimitives) { "return toCollection(LinkedHashSet<T>(mapCapacity(size())))" }
}
templates add f("toHashSet()") {
doc { f -> "Returns a [HashSet] of all ${f.element}s." }
returns("HashSet<T>")
body { "return toCollection(HashSet<T>(mapCapacity(collectionSizeOrDefault(12))))" }
body(Sequences) { "return toCollection(HashSet<T>())" }
deprecate(Strings) { forBinaryCompatibility }
body(CharSequences, Strings) { "return toCollection(HashSet<T>(mapCapacity(length())))" }
body(ArraysOfObjects, ArraysOfPrimitives) { "return toCollection(HashSet<T>(mapCapacity(size())))" }
}
templates add f("toSortedSet()") {
deprecate(Strings) { forBinaryCompatibility }
include(CharSequences, Strings)
doc { f -> "Returns a [SortedSet] of all ${f.element}s." }
returns("SortedSet<T>")
body { "return toCollection(TreeSet<T>())" }
}
templates add f("toArrayList()") {
doc { f -> "Returns an [ArrayList] of all ${f.element}s." }
returns("ArrayList<T>")
body { "return toCollection(ArrayList<T>())" }
body(Iterables) {
"""
if (this is Collection<T>)
return this.toArrayList()
return toCollection(ArrayList<T>())
"""
}
body(Collections) { "return ArrayList(this)" }
deprecate(Strings) { forBinaryCompatibility }
body(CharSequences, Strings) { "return toCollection(ArrayList<T>(length()))" }
body(ArraysOfObjects) { "return ArrayList(this.asCollection())" }
body(ArraysOfPrimitives) {
"""
val list = ArrayList<T>(size())
for (item in this) list.add(item)
return list
"""
}
}
templates add f("toList()") {
only(Maps)
doc { "Returns a [List] containing all key-value pairs." }
returns("List<Pair<K, V>>")
body {
"""
val result = ArrayList<Pair<K, V>>(size())
for (item in this)
result.add(item.key to item.value)
return result
"""
}
}
templates add f("toList()") {
deprecate(Strings) { forBinaryCompatibility }
include(CharSequences, Strings)
doc { f -> "Returns a [List] containing all ${f.element}s." }
returns("List<T>")
body { "return this.toArrayList()" }
}
templates add f("toLinkedList()") {
include(Strings)
doc { "Returns a [LinkedList] containing all elements." }
returns("LinkedList<T>")
deprecate { Deprecation("Use toCollection(LinkedList()) instead.", replaceWith = "toCollection(LinkedList())") }
}
templates add f("toMap(selector: (T) -> K)") {
inline(true)
deprecate(Strings) { forBinaryCompatibility }
body(Strings) { "return toMapBy(selector)" }
include(CharSequences, Strings)
typeParam("K")
returns("Map<K, T>")
deprecate(Deprecation("Use toMapBy instead.", replaceWith = "toMapBy(selector)"))
}
templates add f("toMapBy(selector: (T) -> K)") {
inline(true)
typeParam("K")
doc { f ->
"""
Returns Map containing the ${f.element}s from the given ${f.collection} indexed by the key
returned from [selector] function applied to each ${f.element}.
If any two ${f.element}s would have the same key returned by [selector] the last one gets added to the map.
"""
}
returns("Map<K, T>")
/**
* Collection size helper methods are private, so we fall back to the calculation from HashSet's Collection
* constructor.
*/
body {
"""
val capacity = (collectionSizeOrDefault(10)/.75f) + 1
val result = LinkedHashMap<K, T>(Math.max(capacity.toInt(), 16))
for (element in this) {
result.put(selector(element), element)
}
return result
"""
}
body(Sequences) {
"""
val result = LinkedHashMap<K, T>()
for (element in this) {
result.put(selector(element), element)
}
return result
"""
}
deprecate(Strings) { forBinaryCompatibility }
body(CharSequences, Strings) {
"""
val capacity = (length()/.75f) + 1
val result = LinkedHashMap<K, T>(Math.max(capacity.toInt(), 16))
for (element in this) {
result.put(selector(element), element)
}
return result
"""
}
body(ArraysOfObjects, ArraysOfPrimitives) {
"""
val capacity = (size()/.75f) + 1
val result = LinkedHashMap<K, T>(Math.max(capacity.toInt(), 16))
for (element in this) {
result.put(selector(element), element)
}
return result
"""
}
}
templates add f("toMap(selector: (T) -> K, transform: (T) -> V)") {
inline(true)
typeParam("K")
typeParam("V")
doc { f ->
"""
Returns Map containing the values provided by [transform] and indexed by [selector] functions applied to ${f.element}s of the given ${f.collection}.
If any two ${f.element}s would have the same key returned by [selector] the last one gets added to the map.
"""
}
returns("Map<K, V>")
/**
* Collection size helper methods are private, so we fall back to the calculation from HashSet's Collection
* constructor.
*/
body {
"""
val capacity = (collectionSizeOrDefault(10)/.75f) + 1
val result = LinkedHashMap<K, V>(Math.max(capacity.toInt(), 16))
for (element in this) {
result.put(selector(element), transform(element))
}
return result
"""
}
body(Sequences) {
"""
val result = LinkedHashMap<K, V>()
for (element in this) {
result.put(selector(element), transform(element))
}
return result
"""
}
deprecate(Strings) { forBinaryCompatibility }
body(CharSequences, Strings) {
"""
val capacity = (length()/.75f) + 1
val result = LinkedHashMap<K, V>(Math.max(capacity.toInt(), 16))
for (element in this) {
result.put(selector(element), transform(element))
}
return result
"""
}
body(ArraysOfObjects, ArraysOfPrimitives) {
"""
val capacity = (size()/.75f) + 1
val result = LinkedHashMap<K, V>(Math.max(capacity.toInt(), 16))
for (element in this) {
result.put(selector(element), transform(element))
}
return result
"""
}
}
return templates
}
| 0
|
Java
|
0
| 0
|
f105329fb432c92a859733f45c80c83725eb2f1f
| 8,324
|
kotlin
|
Apache License 2.0
|
cinescout/trending/data/remote/src/commonMain/kotlin/cinescout/trending/data/remote/service/TrendingService.kt
|
fardavide
| 280,630,732
| false
| null |
package cinescout.trending.data.remote.service
import arrow.core.Either
import cinescout.error.NetworkError
import cinescout.network.Try
import cinescout.network.trakt.TraktClient
import cinescout.network.trakt.model.withLimit
import cinescout.screenplay.domain.model.ScreenplayTypeFilter
import cinescout.trending.data.remote.model.TraktMoviesTrendingMetadataResponse
import cinescout.trending.data.remote.model.TraktScreenplaysTrendingMetadataResponse
import cinescout.trending.data.remote.model.TraktTvShowsTrendingMetadataResponse
import cinescout.utils.kotlin.plus
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.http.path
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import org.koin.core.annotation.Factory
import org.koin.core.annotation.Named
@Factory
internal class TrendingService(
@Named(TraktClient) private val client: HttpClient
) {
suspend fun getMostTrendingIds(
type: ScreenplayTypeFilter,
limit: Int = DefaultLimit
): Either<NetworkError, TraktScreenplaysTrendingMetadataResponse> = when (type) {
ScreenplayTypeFilter.All -> {
coroutineScope {
val movies = async { getMostTrendingMovieIds(limit) }
val tvShows = async { getMostTrendingTvShowIds(limit) }
movies.await() + tvShows.await()
}
}
ScreenplayTypeFilter.Movies -> getMostTrendingMovieIds(limit)
ScreenplayTypeFilter.TvShows -> getMostTrendingTvShowIds(limit)
}
private suspend fun getMostTrendingMovieIds(
limit: Int
): Either<NetworkError, TraktMoviesTrendingMetadataResponse> = Either.Try {
client.get {
url {
path("movies", "trending")
withLimit(limit)
}
}.body()
}
private suspend fun getMostTrendingTvShowIds(
limit: Int
): Either<NetworkError, TraktTvShowsTrendingMetadataResponse> = Either.Try {
client.get {
url {
path("shows", "trending")
withLimit(limit)
}
}.body()
}
companion object {
private const val DefaultLimit = 20
}
}
| 10
|
Kotlin
|
2
| 6
|
4c1b7baa4270e2b786982b2fd435a7128be9a70e
| 2,252
|
CineScout
|
Apache License 2.0
|
app/src/main/java/com/example/mycarrierapp/data/remote/dto/Gold.kt
|
Garguy
| 603,900,657
| false
| null |
package com.example.mycarrierapp.data.remote.dto
data class Gold(
val back_default: String,
val back_shiny: String,
val front_default: String,
val front_shiny: String,
val front_transparent: String
)
| 0
|
Kotlin
|
0
| 1
|
fe402995d9a5ba40593cea3134ebba8db870f14c
| 220
|
My-Playground-App
|
Apache License 2.0
|
src/commonMain/kotlin/io/github/koalaplot/sample/StackedVerticalBarSample.kt
|
KoalaPlot
| 518,289,194
| false
| null |
package io.github.koalaplot.sample
import androidx.compose.foundation.layout.absolutePadding
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.unit.dp
import io.github.koalaplot.core.ChartLayout
import io.github.koalaplot.core.Symbol
import io.github.koalaplot.core.bar.BarChartEntry
import io.github.koalaplot.core.bar.DefaultVerticalBar
import io.github.koalaplot.core.bar.VerticalBarChart
import io.github.koalaplot.core.legend.FlowLegend
import io.github.koalaplot.core.legend.LegendLocation
import io.github.koalaplot.core.theme.KoalaPlotTheme
import io.github.koalaplot.core.util.ExperimentalKoalaPlotApi
import io.github.koalaplot.core.util.VerticalRotation
import io.github.koalaplot.core.util.generateHueColorPalette
import io.github.koalaplot.core.util.rotateVertically
import io.github.koalaplot.core.util.toString
import io.github.koalaplot.core.xychart.CategoryAxisModel
import io.github.koalaplot.core.xychart.LineStyle
import io.github.koalaplot.core.xychart.LinearAxisModel
import io.github.koalaplot.core.xychart.XYChart
import io.github.koalaplot.core.xychart.rememberAxisStyle
import kotlin.math.ceil
import kotlin.math.max
private val colors = generateHueColorPalette(PopulationData.Categories.values().size)
private const val BarWidth = 0.8f
internal data class PopulationBarChartEntry<X, Y>(
override val xValue: X,
override val yMin: Y,
override val yMax: Y,
val borough: PopulationData.Categories,
val population: Int
) : BarChartEntry<X, Y>
private fun barChartEntries(): Pair<List<List<PopulationBarChartEntry<Int, Float>>>, Float> {
val series =
Array<MutableList<PopulationBarChartEntry<Int, Float>>>(PopulationData.Categories.values().size) {
ArrayList(PopulationData.years.size)
}
var maxPopulation = 0f
PopulationData.years.forEachIndexed { yearIndex, year ->
var yearTotal = 0f
PopulationData.Categories.values().forEachIndexed { bIndex, borough ->
series[bIndex] += PopulationBarChartEntry(
xValue = year,
yMin = yearTotal,
yMax = yearTotal + PopulationData.data[borough]!![yearIndex].toFloat(),
borough,
PopulationData.data[borough]!![yearIndex]
)
yearTotal += PopulationData.data[borough]!![yearIndex].toFloat()
}
maxPopulation = max(maxPopulation, yearTotal)
}
return series.toList() to maxPopulation
}
@OptIn(ExperimentalKoalaPlotApi::class)
@Composable
private fun Legend(thumbnail: Boolean = false) {
if (!thumbnail) {
Surface(shadowElevation = 2.dp) {
FlowLegend(
itemCount = PopulationData.Categories.values().size,
symbol = { i ->
Symbol(modifier = Modifier.size(padding), fillBrush = SolidColor(colors[i]))
},
label = { i ->
Text(PopulationData.Categories.values()[i].toString())
},
modifier = paddingMod
)
}
}
}
val stackedVerticalBarSampleView = object : SampleView {
override val name: String = "Stacked Vertical Bar"
override val thumbnail = @Composable {
ThumbnailTheme {
StackedBarSamplePlot(true, name)
}
}
override val content: @Composable () -> Unit = @Composable {
KoalaPlotTheme(axis = KoalaPlotTheme.axis.copy(minorGridlineStyle = minorGridLineStyle)) {
StackedBarSamplePlot(false, "New York City Population")
}
}
}
private const val PopulationScale = 1E6
@OptIn(ExperimentalKoalaPlotApi::class)
@Composable
private fun StackedBarSamplePlot(thumbnail: Boolean = false, title: String) {
val (barChartEntries, maxPopulation) = remember { barChartEntries() }
ChartLayout(
modifier = paddingMod,
title = { ChartTitle(title) },
legend = { Legend(thumbnail) },
legendLocation = LegendLocation.BOTTOM
) {
XYChart(
xAxisModel = CategoryAxisModel(PopulationData.years),
yAxisModel = LinearAxisModel(
0f..(ceil(maxPopulation / PopulationScale) * PopulationScale).toFloat(),
),
xAxisLabels = {
if (!thumbnail) AxisLabel("$it", Modifier.padding(top = 2.dp))
},
xAxisTitle = {
if (!thumbnail) AxisTitle("Year", modifier = paddingMod)
},
yAxisStyle = rememberAxisStyle(minorTickSize = 0.dp),
yAxisLabels = {
if (!thumbnail) {
AxisLabel(
(it / PopulationScale).toString(2),
Modifier.absolutePadding(right = 2.dp)
)
}
},
yAxisTitle = {
if (!thumbnail) {
AxisTitle(
"Population (Millions)",
modifier = Modifier.rotateVertically(VerticalRotation.COUNTER_CLOCKWISE)
.padding(bottom = padding)
)
}
},
verticalMajorGridLineStyle = null
) {
VerticalBarChart(
series = barChartEntries,
stacked = true,
bar = { series, _, value ->
DefaultVerticalBar(
brush = SolidColor(colors[series]),
modifier = Modifier.fillMaxWidth(BarWidth)
) {
if (!thumbnail) {
HoverSurface {
Text("${value.borough}: ${value.population}")
}
}
}
}
)
}
}
}
private val minorGridLineStyle = LineStyle(
brush = SolidColor(Color.LightGray),
pathEffect = PathEffect.dashPathEffect(floatArrayOf(2f, 2f))
)
| 0
|
Kotlin
|
0
| 9
|
216dde667c7122fffa44d791234dc0aa8e2eaa1c
| 6,449
|
koalaplot-samples
|
MIT License
|
src/main/kotlin/org/rust/lang/core/stubs/RsStubElementType.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.lang.core.stubs
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.stubs.IndexSink
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.tree.IStubFileElementType
import org.rust.lang.RsLanguage
import org.rust.lang.core.psi.ext.RsElement
abstract class RsStubElementType<StubT : StubElement<*>, PsiT : RsElement>(
debugName: String
) : IStubElementType<StubT, PsiT>(debugName, RsLanguage) {
final override fun getExternalId(): String = "rust.${super.toString()}"
override fun indexStub(stub: StubT, sink: IndexSink) {}
protected fun createStubIfParentIsStub(node: ASTNode): Boolean {
val parent = node.treeParent
val parentType = parent.elementType
return (parentType is IStubElementType<*, *> && parentType.shouldCreateStub(parent)) ||
parentType is IStubFileElementType<*>
}
}
| 1,841
| null |
380
| 4,528
|
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
| 1,031
|
intellij-rust
|
MIT License
|
android/src/main/kotlin/br/com/capyensina/gamestudies/main/android/AndroidLauncher.kt
|
Capy-Ensina
| 876,220,588
| false
|
{"Kotlin": 2257}
|
package br.com.capyensina.gamestudies.main.android
import android.os.Bundle
import com.badlogic.gdx.backends.android.AndroidApplication
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration
import br.com.capyensina.gamestudies.main.Main
/** Launches the Android application. */
class AndroidLauncher : AndroidApplication() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initialize(Main(), AndroidApplicationConfiguration().apply {
// Configure your application here.
useImmersiveMode = false // Recommended, but not required.
})
}
}
| 0
|
Kotlin
|
0
| 0
|
cfb0aadac91f14feaf59d0027e8230aea94a0fcf
| 655
|
game-android-studies
|
MIT License
|
core/domain/src/main/java/com/eshc/goonersapp/core/domain/model/match/MatchLineup.kt
|
eshc123
| 640,451,475
| false
|
{"Kotlin": 436450}
|
package com.eshc.goonersapp.core.domain.model.match
data class MatchLineup(
val homeLineup : TeamLineup,
val awayLineup : TeamLineup
)
data class TeamLineup(
val teamId : Int,
val formation : String,
val playerLineup : List<PlayerLineup>
)
data class PlayerLineup(
val lineUpId: Long,
val matchId: Int,
val playerId: Int,
val teamId: Int,
val playerName: String,
val playerImageUrl : String,
val playerBackNumber: Int,
val formationField: String?,
val formationPosition: Int?,
val positionId: Int,
val positionCategory: String,
val positionInitial: String
)
| 2
|
Kotlin
|
1
| 1
|
ee4b02379bc9b870895a5fedc7ca6b92f2936567
| 628
|
GoonersApp
|
Apache License 2.0
|
wiremock-graphql-extension/src/test/kotlin/io/github/nilwurtz/integration/ContainerTest.kt
|
wiremock
| 624,935,468
| false
|
{"Kotlin": 31766, "Makefile": 637, "Dockerfile": 386}
|
package io.github.nilwurtz.integration
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class ContainerTest : BaseContainerTest() {
@Test
fun `should start wiremock container`() {
Assertions.assertTrue(wireMockContainer.isRunning)
}
}
| 5
|
Kotlin
|
2
| 17
|
62c766da4d702e2891fdf9e5cc0cab125f9f40c0
| 282
|
wiremock-graphql-extension
|
MIT License
|
Projects/Test/app/src/main/java/ademar/study/test/presenter/detail/DetailView.kt
|
ademar111190
| 76,153,266
| false
| null |
package ademar.study.test.presenter.detail
import ademar.study.test.model.DetailViewModel
import ademar.study.test.model.HelloWorldViewModel
import ademar.study.test.presenter.LoadDataView
interface DetailView : LoadDataView {
fun bindFocus(viewModel: HelloWorldViewModel)
fun bindDetail(viewModel: DetailViewModel)
}
| 0
|
Kotlin
|
1
| 1
|
65466ea1c6e4f75ae9791826a428c7dd8e101f98
| 331
|
Studies
|
MIT License
|
src/app/src/main/java/com/example/dummyjson_products/data/remote/Product.kt
|
Hasuk1
| 768,593,694
| false
|
{"Kotlin": 42997}
|
package com.example.dummyjson_products.data.remote
data class Product(
val id: Int = 0,
val title: String = "",
val description: String = "",
val price: Int = 0,
val discountPercentage: Double = 0.0,
val rating: Double = 0.0,
val stock: Int = 0,
val brand: String = "",
val category: String = "",
val thumbnail: String = "",
val images: List<String> = emptyList()
)
| 0
|
Kotlin
|
0
| 1
|
161648d72d1b609453428ffbbea97e023f0639c7
| 389
|
dummyjson_products
|
MIT License
|
app/src/main/java/com/moegirlviewer/util/checkIsLoggedIn.kt
|
koharubiyori
| 449,942,456
| false
| null |
package com.moegirlviewer.util
import com.moegirlviewer.component.commonDialog.ButtonConfig
import com.moegirlviewer.component.commonDialog.CommonAlertDialogProps
import com.moegirlviewer.component.styled.StyledText
import com.moegirlviewer.store.AccountStore
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.flow.first
/**
* @throws [NotLoggedInException] 未登录
*/
suspend fun checkIsLoggedIn(message: String) {
val isLoggedIn = AccountStore.isLoggedIn.first()
if (!isLoggedIn) {
val deferred = CompletableDeferred<Boolean>()
Globals.commonAlertDialog.show(CommonAlertDialogProps(
content = {
StyledText(message)
},
secondaryButton = ButtonConfig.cancelButton {
deferred.complete(false)
},
onPrimaryButtonClick = {
Globals.navController.navigate("login")
deferred.complete(true)
}
))
throw NotLoggedInException(deferred.await())
}
}
class NotLoggedInException(
val gotoLoginClicked: Boolean
) : Exception("未登录拦截:${if (gotoLoginClicked) "点击前往登录" else "取消前往登录"}")
| 1
|
Kotlin
|
2
| 16
|
e09753e76c11932d6f7344302d48f7a214cccf3a
| 1,081
|
Moegirl-plus-native
|
MIT License
|
src/test/kotlin/com/rickbusarow/ktrules/EditorConfigPropertiesTest.kt
|
RBusarow
| 619,004,546
| false
| null |
/*
* Copyright (C) 2023 Rick Busarow
* 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.rickbusarow.ktrules
import com.rickbusarow.ktrules.rules.ALL_PROPERTIES
import com.rickbusarow.ktrules.rules.Tests
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class EditorConfigPropertiesTest : Tests {
class Environment {
val systemProp: String? by lazy { System.setProperty("ktrules.project_version", "0.0.1") }
val ruleProviders by lazy {
systemProp
KtRulesRuleSetProvider().getRuleProviders()
}
val ruleIds by lazy {
ruleProviders.map { it.createNewRuleInstance().ruleId.value }.sorted()
}
val propertyIds by lazy { ALL_PROPERTIES.map { it.name } }
@Suppress("EditorConfigEmptySection")
val defaultConfig =
//language=editorconfig
"""
# KtLint specific settings
# noinspection EditorConfigKeyCorrectness
[{*.kt,*.kts}]
ktlint_kt-rules_kdoc-blank-lines = enabled
ktlint_kt-rules_kdoc-collapse = enabled
ktlint_kt-rules_kdoc-content-wrapping = enabled
ktlint_kt-rules_kdoc-indent-after-leading-asterisk = enabled
ktlint_kt-rules_kdoc-leading-asterisk = enabled
ktlint_kt-rules_kdoc-tag-order = enabled
ktlint_kt-rules_kdoc-tag-param-or-property = enabled
ktlint_kt-rules_no-duplicate-copyright-header = enabled
ktlint_kt-rules_no-gradle-with-type-with-lambda = enabled
ktlint_kt-rules_no-leading-blank-lines = enabled
ktlint_kt-rules_no-since-in-kdoc = enabled
ktlint_kt-rules_no-space-in-annotation-with-target = enabled
ktlint_kt-rules_no-trailing-space-in-raw-string-literal = enabled
ktlint_kt-rules_no-useless-constructor-keyword = enabled
ktlint_kt-rules_project_version = 1.0.0
ktlint_kt-rules_wrapping_style = equal
[{*.kt,*.kts}]
# actual kotlin settings go here
""".trimIndent()
}
@Test
fun `defaultConfig property matches all defined rule IDs`() = test {
val ruleReg = """ktlint_(kt-rules_.*?) ?=.*""".toRegex()
val parsedRuleIds = defaultConfig
.lines()
.takeWhile { it.isNotBlank() }
.mapNotNull {
ruleReg.find(it)?.destructured?.component1()?.replace("_", ":")
}
parsedRuleIds shouldBe ruleIds
}
@Test
fun `defaultConfig property matches all defined config property IDs`() = test {
val ruleReg = """(ktlint_kt-rules_.*?) ?=.*""".toRegex()
val parsedPropertyIds = defaultConfig
.lines()
.dropWhile { it.isNotBlank() }
.mapNotNull {
ruleReg.find(it)?.destructured?.component1()
}
parsedPropertyIds shouldBe propertyIds
}
fun test(action: Environment.() -> Unit) {
Environment().action()
}
}
| 4
|
Kotlin
|
0
| 1
|
8268fde67e15511792da3f0bbed8e67957030432
| 3,266
|
ktrules
|
Apache License 2.0
|
app/src/main/java/com/apaluk/wsplayer/data/stream_cinema/remote/dto/tv_show/seasons/InfoLabelsDto.kt
|
apaluk
| 651,545,506
| false
| null |
package com.apaluk.streamtheater.data.stream_cinema.remote.dto.media
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class InfoLabelsDto(
@Json(name = "dateadded")
val dateadded: String,
@Json(name = "director")
val director: List<String>,
@Json(name = "duration")
val duration: Int,
@Json(name = "genre")
val genre: List<String>,
@Json(name = "mediatype")
val mediatype: MediaTypeDto,
@Json(name = "mpaa")
val mpaa: String?,
@Json(name = "originaltitle")
val originaltitle: String?,
@Json(name = "premiered")
val premiered: String?,
@Json(name = "studio")
val studio: List<String>?,
@Json(name = "writer")
val writer: List<String>,
@Json(name = "year")
val year: Int?,
@Json(name = "season")
val season: Int?,
@Json(name = "episode")
val episode: Int?
)
| 0
|
Kotlin
|
0
| 0
|
a431523e40b1d975fc3e4a264dedaa8744c6649e
| 920
|
ws-player-android
|
MIT License
|
pathshapeview/src/main/java/shape/path/view/PathProvider.kt
|
gleb8k
| 118,509,977
| false
| null |
package shape.path.view
import android.annotation.TargetApi
import android.graphics.Matrix
import android.graphics.Path
import android.graphics.PointF
import android.graphics.RectF
import android.os.Build
import shape.path.view.graph.function.CustomLinesBuilder
import shape.path.view.point.converter.PointConverter
/**
* Created by root on 1/9/18.
*/
class PathProvider {
private val path: Path = Path()
internal var shapePath: Path? = null
enum class PathOperation {
ADD,
SUB,
SUB_REVERSE,
JOIN,
INTERSECT,
XOR;
companion object {
fun fromString(type: String?): PathOperation? {
if (type.isNullOrEmpty()) return null
PathOperation.values().forEach {
if (it.toString() == type) {
return it
}
}
return null
}
}
}
fun putLines(list: List<PointF>, isClosed:Boolean, operation: PathOperation) {
if (list.isNotEmpty()) {
val p = Path()
p.moveTo(list[0].x, list[0].y)
for (i in 1 until list.size) {
p.lineTo(list[i].x, list[i].y)
}
if (isClosed) {
p.close()
}
putPath(p, operation)
}
}
fun putCustomShape(customLinesBuilder: CustomLinesBuilder, operation: PathOperation) {
putPath(customLinesBuilder.getPath(), operation)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun putArc(centerPoint: PointF, width:Float, height:Float, startAngle: Float, sweepAngle: Float, operation: PathOperation) {
val p = Path()
val left = centerPoint.x - width / 2
val top = centerPoint.y - height / 2
val right = centerPoint.x + width / 2
val bottom = centerPoint.y + height / 2
val start = PointF(left, top)
val end = PointF(right, bottom)
p.addArc(start.x, start.y, end.x, end.y, startAngle, sweepAngle)
putPath(p, operation)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun putOval(centerPoint: PointF, width:Float, height:Float, operation: PathOperation) {
val p = Path()
val left = centerPoint.x - width / 2
val top = centerPoint.y - height / 2
val right = centerPoint.x + width / 2
val bottom = centerPoint.y + height / 2
val start = PointF(left, top)
val end = PointF(right, bottom)
p.addOval(start.x, start.y, end.x, end.y, Path.Direction.CCW)
putPath(p, operation)
}
fun putCircle(centerPoint: PointF, radius:Float, operation: PathOperation) {
val p = Path()
p.addCircle(centerPoint.x, centerPoint.y, radius, Path.Direction.CCW)
putPath(p, operation)
}
fun putPoly(centerPoint: PointF, radius:Float, angleRotation: Float, sidesCount:Int, operation: PathOperation) {
if (sidesCount < 3) {
return
}
val p = Path()
val a = Math.toRadians(angleRotation.toDouble())
for (i in 0 until sidesCount) {
val x = (Math.sin( i.toDouble() / sidesCount * 2 * Math.PI + a) * radius).toFloat() + centerPoint.x
val y = (Math.cos( i.toDouble() / sidesCount * 2 * Math.PI + a) * radius).toFloat() + centerPoint.y
if (i == 0) {
p.moveTo(x, y)
}
else {
p.lineTo(x, y)
}
}
p.close()
putPath(p, operation)
}
fun putStar(centerPoint: PointF, outerRadius:Float, innerRadius: Float, angleRotation: Float, sidesCount:Int, operation: PathOperation) {
if (sidesCount < 3) {
return
}
val p = Path()
val rotation = Math.toRadians(angleRotation.toDouble())
val angle = (2 * Math.PI) / sidesCount
val n = 2 * sidesCount
var innerStep = 0
var outerStep = 0
for(i in 0 until n) {
val k = i % 2
var omega: Double
var r: Float
if (k == 0) {
omega = angle * outerStep + rotation
r = outerRadius
outerStep++
}
else {
omega = angle * innerStep + angle / 2 + rotation
r = innerRadius
innerStep++
}
val x = r * Math.sin(omega).toFloat() + centerPoint.x
val y = r * Math.cos(omega).toFloat() + centerPoint.y
if (i == 0) {
p.moveTo(x, y)
}
else {
p.lineTo(x, y)
}
}
p.close()
putPath(p, operation)
}
fun putText(centerPoint: PointF, width: Float, height: Float, text: String, textConfigurator: TextConfigurator, operation: PathOperation) {
val p = textConfigurator.getPath(text, centerPoint, width, height)
putPath(p, operation)
}
fun putRect(centerPoint: PointF, width:Float, height:Float, operation: PathOperation) {
val p = Path()
val left = centerPoint.x - width / 2
val top = centerPoint.y - height / 2
val right = centerPoint.x + width / 2
val bottom = centerPoint.y + height / 2
val start = PointF(left, top)
val end = PointF(right, bottom)
p.addRect(start.x, start.y, end.x, end.y, Path.Direction.CCW)
putPath(p, operation)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun putRoundRect(centerPoint: PointF, width:Float, height:Float, cornerRadius: Float, operation: PathOperation) {
val p = Path()
val left = centerPoint.x - width / 2
val top = centerPoint.y - height / 2
val right = centerPoint.x + width / 2
val bottom = centerPoint.y + height / 2
val start = PointF(left, top)
val end = PointF(right, bottom)
p.addRoundRect(start.x, start.y, end.x, end.y, cornerRadius * 1.5f, cornerRadius, Path.Direction.CCW)
putPath(p, operation)
}
fun reset() {
path.reset()
shapePath = null
}
private fun putPath(p: Path, operation: PathOperation) {
when (operation) {
PathOperation.ADD -> path.addPath(p)
PathOperation.INTERSECT -> path.op(p, Path.Op.INTERSECT)
PathOperation.SUB -> path.op(p, Path.Op.DIFFERENCE)
PathOperation.SUB_REVERSE -> path.op(p, Path.Op.REVERSE_DIFFERENCE)
PathOperation.JOIN -> path.op(p, Path.Op.UNION)
PathOperation.XOR -> path.op(p, Path.Op.XOR)
}
}
internal fun build(converter: PointConverter) {
this.build(converter, 0f)
}
internal fun build(converter: PointConverter, contourWidth: Float) {
val m = converter.getMatrix()
shapePath = Path(path)
if (!m.isIdentity) {
shapePath!!.transform(m)
}
fitContourPath(converter.screenWidth, converter.screenHeight, contourWidth)
}
private fun fitContourPath(screenWidth: Float, screenHeight: Float, contourWidth: Float) {
if (contourWidth >= 0f) {
val d = contourWidth / 2
val r1 = RectF(0f, 0f, screenWidth, screenHeight)
val r2 = RectF(d, d, screenWidth - d, screenHeight - d)
val matrix = Matrix()
matrix.setRectToRect(r1, r2, Matrix.ScaleToFit.FILL)
shapePath?.transform(matrix)
}
}
internal fun hasPath(): Boolean {
return shapePath != null
}
}
| 1
| null |
7
| 21
|
54433597c277191df263586884242140a5e665cd
| 7,548
|
Android-PathShapeView
|
Apache License 2.0
|
game/src/main/kotlin/gg/rsmod/game/message/handler/OpHeld5Handler.kt
|
2011Scape
| 578,880,245
| false
| null |
package gg.rsmod.game.message.handler
import gg.rsmod.game.message.MessageHandler
import gg.rsmod.game.message.impl.OpHeld5Message
import gg.rsmod.game.model.World
import gg.rsmod.game.model.attr.INTERACTING_ITEM
import gg.rsmod.game.model.attr.INTERACTING_ITEM_ID
import gg.rsmod.game.model.attr.INTERACTING_ITEM_SLOT
import gg.rsmod.game.model.entity.Client
import gg.rsmod.game.model.entity.GroundItem
import gg.rsmod.game.model.item.Item
import gg.rsmod.game.service.log.LoggerService
import java.lang.ref.WeakReference
/**
* @author Tom <<EMAIL>>
*/
class OpHeld5Handler : MessageHandler<OpHeld5Message> {
override fun handle(client: Client, world: World, message: OpHeld5Message) {
if (!client.lock.canDropItems()) {
return
}
val hash = message.hash
val slot = message.slot
val item = client.inventory[slot] ?: return
log(client, "Drop item: item=[%d, %d], slot=%d, interfaceId=%d, component=%d", item.id, item.amount, slot, hash shr 16, hash and 0xFFFF)
client.attr[INTERACTING_ITEM] = WeakReference(item)
client.attr[INTERACTING_ITEM_ID] = item.id
client.attr[INTERACTING_ITEM_SLOT] = slot
client.resetFacePawn()
if (world.plugins.canDropItem(client, item.id)) {
val remove = client.inventory.remove(item, assureFullRemoval = false, beginSlot = slot)
if (remove.completed > 0) {
val floor = GroundItem(item.id, remove.completed, client.tile, client)
remove.firstOrNull()?.let { removed ->
floor.copyAttr(removed.item.attr)
}
world.spawn(floor)
world.getService(LoggerService::class.java, searchSubclasses = true)?.logItemDrop(client, Item(item.id, remove.completed), slot)
}
}
}
}
| 39
| null |
22
| 34
|
e5400cc71bfa087164153d468979c5a3abc24841
| 1,850
|
game
|
Apache License 2.0
|
game/src/main/kotlin/gg/rsmod/game/message/handler/OpHeld5Handler.kt
|
2011Scape
| 578,880,245
| false
| null |
package gg.rsmod.game.message.handler
import gg.rsmod.game.message.MessageHandler
import gg.rsmod.game.message.impl.OpHeld5Message
import gg.rsmod.game.model.World
import gg.rsmod.game.model.attr.INTERACTING_ITEM
import gg.rsmod.game.model.attr.INTERACTING_ITEM_ID
import gg.rsmod.game.model.attr.INTERACTING_ITEM_SLOT
import gg.rsmod.game.model.entity.Client
import gg.rsmod.game.model.entity.GroundItem
import gg.rsmod.game.model.item.Item
import gg.rsmod.game.service.log.LoggerService
import java.lang.ref.WeakReference
/**
* @author Tom <<EMAIL>>
*/
class OpHeld5Handler : MessageHandler<OpHeld5Message> {
override fun handle(client: Client, world: World, message: OpHeld5Message) {
if (!client.lock.canDropItems()) {
return
}
val hash = message.hash
val slot = message.slot
val item = client.inventory[slot] ?: return
log(client, "Drop item: item=[%d, %d], slot=%d, interfaceId=%d, component=%d", item.id, item.amount, slot, hash shr 16, hash and 0xFFFF)
client.attr[INTERACTING_ITEM] = WeakReference(item)
client.attr[INTERACTING_ITEM_ID] = item.id
client.attr[INTERACTING_ITEM_SLOT] = slot
client.resetFacePawn()
if (world.plugins.canDropItem(client, item.id)) {
val remove = client.inventory.remove(item, assureFullRemoval = false, beginSlot = slot)
if (remove.completed > 0) {
val floor = GroundItem(item.id, remove.completed, client.tile, client)
remove.firstOrNull()?.let { removed ->
floor.copyAttr(removed.item.attr)
}
world.spawn(floor)
world.getService(LoggerService::class.java, searchSubclasses = true)?.logItemDrop(client, Item(item.id, remove.completed), slot)
}
}
}
}
| 39
| null |
22
| 34
|
e5400cc71bfa087164153d468979c5a3abc24841
| 1,850
|
game
|
Apache License 2.0
|
src/main/kotlin/com/objectpartners/plummer/kotlin/calendar/entry/Appointment.kt
|
mike-plummer
| 51,262,029
| false
| null |
package com.objectpartners.plummer.kotlin.calendar.entry
import java.time.LocalDateTime
import com.objectpartners.plummer.kotlin.calendar.*
/**
* Represents a single-person [CalendarEntry] with an optional 'private' indicator
*/
data class Appointment( override var start: LocalDateTime? = LocalDateTime.now(),
override var duration: java.time.Duration? = java.time.Duration.ZERO,
var privateAppointment: Boolean = false): CalendarEntry {
override val id: String by IdDelegate()
override fun toString(): String {
return """[
Appointment: $id
Start: $start
Duration: ${duration?.prettyPrint()}
Private: $privateAppointment
]"""
}
}
| 0
|
Kotlin
|
0
| 6
|
fdb9f57ee12100f1f02b6288237d152aef1447c3
| 719
|
KotlinCalendar
|
MIT License
|
screenshot-test/feature/home/src/test/java/com/yml/healthcare/home/ui/view/LoadedHomeKtTest.kt
|
codeandtheory
| 516,391,220
| false
|
{"Kotlin": 166320, "Java": 4188, "Shell": 954}
|
package com.yml.healthcare.home.ui.view
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import app.cash.paparazzi.Paparazzi
import com.yml.healthcare.home.domain.model.Article
import com.yml.healthcare.home.domain.model.Blog
import com.yml.healthcare.home.domain.model.HomeDataModel
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class LoadedHomeKtTest {
@get:Rule
val paparazzi = Paparazzi()
@Before
fun before() {
}
@Test
fun `verify home screen with only articles`() {
paparazzi.snapshot("home_articles") {
LoadedHomeScreen(
modifier = Modifier
.fillMaxSize()
.background(Color.White),
data = HomeDataModel(displayArticles = mockArticleList()),
userIntent = {}
)
}
}
@Test
fun `verify home screen with only blogs`() {
paparazzi.snapshot("home_blogs") {
LoadedHomeScreen(
modifier = Modifier
.fillMaxSize()
.background(Color.White),
data = HomeDataModel(displayBlogs = mockBlogList()),
userIntent = {}
)
}
}
@Test
fun `verify home screen with articles and blogs`() {
paparazzi.snapshot("home_fully_loaded") {
LoadedHomeScreen(
modifier = Modifier
.fillMaxSize()
.background(Color.White),
data = HomeDataModel(
displayArticles = mockArticleList(),
displayBlogs = mockBlogList()
),
userIntent = {}
)
}
}
@After
fun after() {
}
}
private fun mockBlogList(): List<Blog> {
val mock = mutableListOf<Blog>()
for (i in 0..4) {
mock.add(
Blog(
title = "Lower Costs on market place coverage $i",
description = "Still need Hearlh Insurance?\nYou can get health coverage for the rest of the year if....",
url = "",
tags = listOf("Blog", "Insurance")
)
)
}
return mock
}
private fun mockArticleList(): List<Article> {
val mock = mutableListOf<Article>()
for (i in 0..10) {
mock.add(
Article(
title = "Lower Costs on market place coverage $i",
description = "Still need Hearlh Insurance?\nYou can get health coverage for the rest of the year if....",
url = "",
tags =/* if (i % 2 == 0) listOf("Blog", "Insurance") else*/ listOf()
)
)
}
return mock
}
| 3
|
Kotlin
|
2
| 4
|
f96dd4e04996aa2e2660de2055548aef8157d734
| 2,871
|
compose-testing-samples
|
Apache License 2.0
|
src/main/kotlin/org/geepawhill/jltkv/ViewerMain.kt
|
GeePawHill
| 661,747,103
| false
|
{"Kotlin": 56637}
|
package org.geepawhill.jltkv
import org.geepawhill.jltkv.ui.ViewerFrame
import tornadofx.App
import tornadofx.launch
import za.co.wethinkcode.flow.Recorder
public class ViewerMain : App(ViewerFrame::class) {
companion object {
val wtc = Recorder().logRun()
}
}
fun main(args: Array<String>) {
launch<ViewerMain>(args)
}
| 0
|
Kotlin
|
0
| 0
|
9c0c2c597dd42b4013933b8e951d419058d79572
| 344
|
jltk-viewer
|
MIT License
|
library/src/main/java/com/kdownloader/internal/DownloadDispatchers.kt
|
varungulatii
| 628,881,033
| false
|
{"Kotlin": 57465}
|
package com.kdownloader.internal
import com.kdownloader.Status
import com.kdownloader.database.DbHelper
import com.kdownloader.database.DownloadModel
import com.kdownloader.utils.getTempPath
import kotlinx.coroutines.*
import java.io.File
class DownloadDispatchers(private val dbHelper: DbHelper) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main +
CoroutineExceptionHandler { _, _ ->
})
private val dbScope = CoroutineScope(SupervisorJob() + Dispatchers.IO +
CoroutineExceptionHandler { _, _ ->
})
fun enqueue(req: DownloadRequest): Int {
val job = scope.launch {
execute(req)
}
req.job = job
return req.downloadId
}
private suspend fun execute(request: DownloadRequest) {
DownloadTask(request, dbHelper).run(
onStart = {
executeOnMainThread { request.listener?.onStart() }
},
onProgress = {
executeOnMainThread { request.listener?.onProgress(it) }
},
onPause = {
executeOnMainThread { request.listener?.onPause() }
},
onCompleted = {
executeOnMainThread { request.listener?.onCompleted() }
},
onError = {
executeOnMainThread { request.listener?.onError(it) }
}
)
}
private fun executeOnMainThread(block: () -> Unit) {
scope.launch {
block()
}
}
fun cancel(req: DownloadRequest) {
if (req.status == Status.PAUSED) {
val tempPath = getTempPath(req.dirPath, req.fileName)
val file = File(tempPath)
if (file.exists()) {
file.delete()
}
req.reset()
}
req.status = Status.CANCELLED
req.job.cancel()
req.listener?.onError("Cancelled")
dbScope.launch {
dbHelper.remove(req.downloadId)
}
}
fun cancelAll() {
scope.cancel()
dbScope.launch {
dbHelper.empty()
}
}
fun cleanup(days: Int) {
dbScope.launch {
val models: List<DownloadModel>? = dbHelper.getUnwantedModels(days)
if (models != null) {
for (model in models) {
val tempPath: String = getTempPath(
model.dirPath,
model.fileName
)
dbHelper.remove(model.id)
val file = File(tempPath)
if (file.exists()) {
file.delete()
}
}
}
}
}
}
| 3
|
Kotlin
|
11
| 55
|
7c63ca35d2780af3f000506fd0848fdf8e714b07
| 2,762
|
Kdownloader
|
Apache License 2.0
|
src/main/kotlin/com/teamclicker/gameservice/models/dao/InventoryItemSlotDAO.kt
|
Humberd
| 140,150,771
| false
|
{"Kotlin": 153182, "Dockerfile": 346}
|
package com.teamclicker.gameservice.models.dao
import com.teamclicker.gameservice.game.spring.TemplatesStore
import com.teamclicker.gameservice.game.templates.ItemTemplate
import javax.persistence.*
@Entity
@Table(name = "InventoryItemSlot")
class InventoryItemSlotDAO {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0
@Column(name = "count", nullable = false)
var count: Int = 1
@Column(name = "itemId")
var itemId: Long? = null
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "playerInventoryId", insertable = false, updatable = false)
lateinit var playerInventory: PlayerInventoryDAO
@Transient
var item: ItemTemplate? = null
@PrePersist
fun saveItemId() {
itemId = item?.templateId
}
@PostLoad
fun loadItemObject() {
itemId?.let {
item = TemplatesStore.instance.getItemTemplate(it)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
dfe3c64168e1ff62edd1cc93d86d1b85dabc5eeb
| 964
|
TeamClicker-GameService
|
Apache License 2.0
|
demo/src/main/java/de/brueggenthies/compose/video/demo/ui/VideoPlaybackDemo.kt
|
timbrueggenthies
| 481,628,632
| false
|
{"Kotlin": 53879}
|
package de.brueggenthies.compose.video.demo.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.RadioButton
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.scope.DestinationScope
import de.brueggenthies.compose.video.demo.R
import de.brueggenthies.leinwand.core.PauseWithLifecycle
import de.brueggenthies.leinwand.core.RepeatMode
import de.brueggenthies.leinwand.core.rememberVideoPlayerState
import de.brueggenthies.leinwand.ui.core.FullScreenMode
import de.brueggenthies.leinwand.ui.core.ResizeMode
import de.brueggenthies.leinwand.ui.core.VideoPlayback
@Destination
@Composable
fun DestinationScope<Unit>.VideoPlaybackDemo() {
val context = LocalContext.current
val videoUrl = stringResource(id = R.string.stock_video_16_9)
val player = remember {
val player = ExoPlayer.Builder(context).build()
player.setMediaItem(MediaItem.fromUri(videoUrl))
player
}
VideoDemo(player = player)
}
@Composable
private fun VideoDemo(player: Player) {
val playerState = rememberVideoPlayerState(player = player) {
playWhenReady = true
repeatMode = RepeatMode.One
prepare()
}
PauseWithLifecycle(playerState, restart = true)
var fullscreenMode: FullScreenMode by remember { mutableStateOf(FullScreenMode.Off) }
var resizeMode: ResizeMode by remember { mutableStateOf(ResizeMode.Fit) }
Box(
modifier = Modifier
.systemBarsPadding()
.padding(16.dp)
.fillMaxWidth()
) {
Column {
Row(modifier = Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
Switch(
checked = fullscreenMode == FullScreenMode.On,
onCheckedChange = { checked -> fullscreenMode = if (checked) FullScreenMode.On else FullScreenMode.Off }
)
Text(text = "Toggle fullscreen mode")
}
ResizeModeRadioButton(resizeMode, ResizeMode.Fit) { resizeMode = it }
ResizeModeRadioButton(resizeMode, ResizeMode.Fill) { resizeMode = it }
ResizeModeRadioButton(resizeMode, ResizeMode.Zoom) { resizeMode = it }
ResizeModeRadioButton(resizeMode, ResizeMode.FillHeight) { resizeMode = it }
ResizeModeRadioButton(resizeMode, ResizeMode.FillWidth) { resizeMode = it }
VideoPlayback(
playerState = playerState,
resizeMode = resizeMode,
fullScreenMode = fullscreenMode,
modifier = Modifier
.fillMaxSize()
.clip(RoundedCornerShape(8.dp))
.background(Color.LightGray)
)
}
}
}
@Composable
fun ResizeModeRadioButton(current: ResizeMode, use: ResizeMode, choose: (ResizeMode) -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically) {
val text = when (use) {
ResizeMode.Fit -> "Fit"
ResizeMode.FillWidth -> "FillWidth"
ResizeMode.FillHeight -> "FillHeight"
ResizeMode.Fill -> "Fill"
ResizeMode.Zoom -> "Zoom"
}
RadioButton(selected = current == use, onClick = { choose(use) })
Text(text)
}
}
| 0
|
Kotlin
|
0
| 4
|
9e97292e776153134f94f395d08895aee864ed86
| 4,423
|
leinwand
|
Apache License 2.0
|
hilt-binder-compiler/src/main/java/com/paulrybitskyi/hiltbinder/processor/generator/ModuleFileGenerator.kt
|
mars885
| 332,237,059
| false
| null |
/*
* Copyright 2021 <NAME>, <EMAIL>
*
* 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.paulrybitskyi.hiltbinder.processor.generator
import com.paulrybitskyi.hiltbinder.compiler.processing.XFiler
import com.paulrybitskyi.hiltbinder.compiler.processing.XOriginatingElement
import com.paulrybitskyi.hiltbinder.processor.generator.content.ModuleFileContentGenerator
import com.paulrybitskyi.hiltbinder.processor.model.ContributionType
import com.paulrybitskyi.hiltbinder.processor.model.HiltComponent
import com.paulrybitskyi.hiltbinder.processor.model.ModuleSchema
internal class ModuleFileGenerator(
private val outputLanguage: Language,
private val moduleFileContentGenerator: ModuleFileContentGenerator,
private val filer: XFiler
) {
fun generateModuleFile(moduleSchema: ModuleSchema) {
val fileContent = moduleFileContentGenerator.generateFileContent(moduleSchema)
val file = XFiler.File(
packageName = moduleSchema.packageName,
name = moduleSchema.interfaceName,
extension = outputLanguage.fileExtension,
content = fileContent,
originatingElements = moduleSchema.getOriginatingElements()
)
filer.createSourceFile(file)
}
private fun ModuleSchema.getOriginatingElements(): List<XOriginatingElement> {
val elements = mutableListOf<XOriginatingElement?>()
elements.add(componentType.originatingElement)
for (binding in bindings) {
if (binding.component is HiltComponent.Custom) {
elements.add(binding.component.element.originatingElement)
}
if (binding.contributionType is ContributionType.Map) {
elements.add(binding.contributionType.mapKeyAnnotation.type.element.originatingElement)
}
if (binding.qualifierAnnotation != null) {
elements.add(binding.qualifierAnnotation.type.element.originatingElement)
}
elements.add(binding.paramType.originatingElement)
elements.add(binding.returnType.type.element.originatingElement)
}
return elements.filterNotNull()
}
}
internal fun ModuleFileGenerator.generateModuleFiles(moduleSchemas: List<ModuleSchema>) {
moduleSchemas.forEach(::generateModuleFile)
}
| 4
| null |
4
| 69
|
cbd813dcfb1ec7f770258405347b5496ccc9d94a
| 2,840
|
hilt-binder
|
Apache License 2.0
|
app/src/main/java/com/example/app/ui/AppActivity.kt
|
fpadilha90
| 200,267,301
| false
| null |
package com.example.app.ui
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.Navigation.findNavController
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.app.R
import kotlinx.android.synthetic.main.activity_main.*
class AppActivity : AppCompatActivity() {
private lateinit var appBarConfiguration : AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
appBarConfiguration = AppBarConfiguration(getNavHostFragment().navController.graph)
setupActionBarWithNavController(getNavHostFragment().navController, appBarConfiguration)
bottom_nav_view.setupWithNavController(getNavHostFragment().navController)
}
override fun onSupportNavigateUp() = findNavController(R.id.my_nav_host_fragment).navigateUp(appBarConfiguration)
private fun getNavHostFragment() = (my_nav_host_fragment as NavHostFragment)
}
| 1
|
Kotlin
|
1
| 1
|
e1897c09ef1bc7f8d3620de073e76c2751148eca
| 1,318
|
feature-oriented-architecture
|
Apache License 2.0
|
features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/UserPreferences.kt
|
vector-im
| 546,522,002
| false
| null |
/*
* Copyright (c) 2022 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.features.preferences.impl.user
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import io.element.android.libraries.designsystem.preview.ElementPreviewDark
import io.element.android.libraries.designsystem.preview.ElementPreviewLight
import io.element.android.libraries.matrix.api.user.MatrixUser
import io.element.android.libraries.matrix.ui.components.MatrixUserHeader
import io.element.android.libraries.matrix.ui.components.MatrixUserWithNullProvider
@Composable
fun UserPreferences(
user: MatrixUser?,
modifier: Modifier = Modifier,
) {
MatrixUserHeader(
modifier = modifier,
matrixUser = user
)
}
@Preview
@Composable
internal fun UserPreferencesLightPreview(@PreviewParameter(MatrixUserWithNullProvider::class) matrixUser: MatrixUser?) =
ElementPreviewLight { ContentToPreview(matrixUser) }
@Preview
@Composable
internal fun UserPreferencesDarkPreview(@PreviewParameter(MatrixUserWithNullProvider::class) matrixUser: MatrixUser?) =
ElementPreviewDark { ContentToPreview(matrixUser) }
@Composable
private fun ContentToPreview(matrixUser: MatrixUser?) {
UserPreferences(matrixUser)
}
| 105
|
Kotlin
|
32
| 287
|
4587b51bd33e8b5a2e2c81c79f3aa70a3ac52923
| 1,908
|
element-x-android
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.