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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
baselibrary/src/main/java/ruolan/com/baselibrary/ui/activity/BaseMvpActivity.kt | wuyinlei | 117,832,134 | false | null | package ruolan.com.baselibrary.ui.activity
import android.os.Bundle
import com.alibaba.android.arouter.launcher.ARouter
import org.jetbrains.anko.toast
import ruolan.com.baselibrary.common.BaseApplication
import ruolan.com.baselibrary.injection.component.ActivityComponent
import ruolan.com.baselibrary.injection.component.DaggerActivityComponent
import ruolan.com.baselibrary.injection.module.ActivityModule
import ruolan.com.baselibrary.injection.module.LifecycleProviderModule
import ruolan.com.baselibrary.presenter.BasePresenter
import ruolan.com.baselibrary.presenter.view.BaseView
import javax.inject.Inject
/**
* Created by wuyinlei on 2018/1/19.
*
* @function mvp activity基类
*
*/
abstract class BaseMvpActivity<T : BasePresenter<*>> : BaseActivity(), BaseView {
override fun hideLoading() {
}
override fun onError(message: String) {
toast(message)
}
override fun showLoading() {
}
lateinit var mActivityComponent: ActivityComponent
@Inject
lateinit var mPresenter: T
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initActivityComponent()
injectComponent()
}
abstract fun injectComponent()
private fun initActivityComponent() {
mActivityComponent = DaggerActivityComponent.builder().appComponent((application as BaseApplication).appComponent)
.activityModule(ActivityModule(this))
.lifecycleProviderModule(LifecycleProviderModule(this))
.build()
}
} | 1 | Kotlin | 1 | 2 | 2b388a915760c6f85dc1523b42cf11446c3ff63f | 1,565 | CNMarket4Kotlin | Apache License 2.0 |
proto-actor/src/test/kotlin/actor/proto/tests/PIDTests.kt | asynkron | 96,669,281 | false | null | package actor.proto.tests
import actor.proto.PID
import actor.proto.ProcessRegistry
import actor.proto.cachedProcess
import actor.proto.fixture.EmptyReceive
import actor.proto.fixture.TestMailbox
import actor.proto.fixture.TestProcess
import actor.proto.fromFunc
import actor.proto.spawn
import actor.proto.stop
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertSame
import org.junit.jupiter.api.Test
import java.util.*
class PIDTests {
@Test
fun `given actor not dead, cachedProcess should return it`() {
val pid: PID = spawn(fromFunc(EmptyReceive))
val p = pid.cachedProcess()
assertNotNull(p)
}
@Test
fun `given actor died, cachedProcess should not return it`() {
val pid: PID = spawn(fromFunc(EmptyReceive).withMailbox { TestMailbox() })
stop(pid)
val p = pid.cachedProcess()
assertNotNull(p)
}
@Test
fun `given other process, cachedProcess should return it`() {
val id = UUID.randomUUID().toString()
val p = TestProcess()
val pid = ProcessRegistry.put(id, p)
val p2 = pid.cachedProcess()
assertSame(p, p2)
}
}
| 8 | Kotlin | 21 | 211 | 5d42177ff79969000b64a150ac4433dee3209b45 | 1,202 | protoactor-kotlin | Apache License 2.0 |
libraries/csm.cloud.project.avro/src/test/kotlin/com/bosch/pt/csm/cloud/projectmanagement/project/event/TopicAttachmentEventGenerator.kt | boschglobal | 805,348,245 | false | {"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344} | /*
* ************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2018 - 2021
*
* ************************************************************************
*/
package com.bosch.pt.csm.cloud.projectmanagement.project.event
import com.bosch.pt.csm.cloud.common.extensions.toUUID
import com.bosch.pt.csm.cloud.common.messages.buildAggregateIdentifier
import com.bosch.pt.csm.cloud.common.model.key.AggregateEventMessageKey
import com.bosch.pt.csm.cloud.common.test.event.EventStreamGenerator
import com.bosch.pt.csm.cloud.common.test.event.EventStreamGenerator.Companion.DEFAULT_USER
import com.bosch.pt.csm.cloud.common.test.event.EventStreamGenerator.Companion.newAggregateIdentifier
import com.bosch.pt.csm.cloud.common.test.event.EventStreamGenerator.Companion.newAuditingInformation
import com.bosch.pt.csm.cloud.projectmanagement.common.ProjectmanagementAggregateTypeEnum
import com.bosch.pt.csm.cloud.projectmanagement.common.ProjectmanagementAggregateTypeEnum.PROJECT
import com.bosch.pt.csm.cloud.projectmanagement.common.ProjectmanagementAggregateTypeEnum.TOPIC
import com.bosch.pt.csm.cloud.projectmanagement.common.messages.AttachmentAvro
import com.bosch.pt.csm.cloud.projectmanagement.topic.messages.TopicAttachmentAggregateAvro
import com.bosch.pt.csm.cloud.projectmanagement.topic.messages.TopicAttachmentEventAvro
import com.bosch.pt.csm.cloud.projectmanagement.topic.messages.TopicAttachmentEventEnumAvro
import com.bosch.pt.csm.cloud.projectmanagement.topic.messages.TopicAttachmentEventEnumAvro.CREATED
import java.time.Instant
import java.util.UUID
import kotlin.collections.set
@JvmOverloads
fun EventStreamGenerator.submitTopicAttachment(
asReference: String = "topicAttachment",
rootContextIdentifier: UUID =
getContext().lastIdentifierPerType[PROJECT.value]!!.getIdentifier().toUUID(),
auditUserReference: String = DEFAULT_USER,
eventType: TopicAttachmentEventEnumAvro = CREATED,
time: Instant = getContext().timeLineGenerator.next(),
businessTransactionReference: String? = getContext().lastBusinessTransactionReference,
aggregateModifications: ((TopicAttachmentAggregateAvro.Builder) -> Unit)? = null
): EventStreamGenerator {
val existingAttachment = get<TopicAttachmentAggregateAvro?>(asReference)
val defaultAggregateModifications: ((TopicAttachmentAggregateAvro.Builder) -> Unit) = {
setAuditingInformation(it.auditingInformationBuilder, eventType.name, auditUserReference, time)
it.aggregateIdentifierBuilder.increase(eventType.name)
}
val referenceModifications: ((TopicAttachmentAggregateAvro.Builder) -> Unit) = {
it.topic = it.topic ?: getContext().lastIdentifierPerType[TOPIC.value]
}
val attachmentEvent =
existingAttachment.buildEventAvro(
eventType, defaultAggregateModifications, aggregateModifications, referenceModifications)
val messageKey =
AggregateEventMessageKey(
attachmentEvent.getAggregate().getAggregateIdentifier().buildAggregateIdentifier(),
rootContextIdentifier)
val sentEvent =
send(
"project",
asReference,
messageKey,
attachmentEvent,
time.toEpochMilli(),
businessTransactionReference)
as TopicAttachmentEventAvro
getContext().events[asReference] = sentEvent.getAggregate()
return this
}
private fun TopicAttachmentAggregateAvro?.buildEventAvro(
eventType: TopicAttachmentEventEnumAvro,
vararg blocks: ((TopicAttachmentAggregateAvro.Builder) -> Unit)?
) =
(this?.let { TopicAttachmentEventAvro.newBuilder().setName(eventType).setAggregate(this) }
?: newAttachment(eventType))
.apply { for (block in blocks) block?.invoke(aggregateBuilder) }
.build()
private fun newAttachment(
event: TopicAttachmentEventEnumAvro = CREATED
): TopicAttachmentEventAvro.Builder {
val attachment =
TopicAttachmentAggregateAvro.newBuilder()
.setAggregateIdentifierBuilder(
newAggregateIdentifier(ProjectmanagementAggregateTypeEnum.TOPICATTACHMENT.value))
.setAuditingInformationBuilder(newAuditingInformation())
.setAttachmentBuilder(
AttachmentAvro.newBuilder()
.setCaptureDate(Instant.now().toEpochMilli())
.setFileName("myPicture.jpg")
.setFileSize(1000)
.setFullAvailable(false)
.setSmallAvailable(false)
.setWidth(768)
.setHeight(1024))
return TopicAttachmentEventAvro.newBuilder().setAggregateBuilder(attachment).setName(event)
}
| 0 | Kotlin | 3 | 9 | 9f3e7c4b53821bdfc876531727e21961d2a4513d | 4,671 | bosch-pt-refinemysite-backend | Apache License 2.0 |
compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/DeclarationProviderFactoryService.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.resolve.lazy.declarations
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.psi.search.DelegatingGlobalSearchScope
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.storage.StorageManager
import com.intellij.openapi.vfs.VirtualFile
import java.util.HashSet
abstract class DeclarationProviderFactoryService {
abstract fun create(
project: Project,
storageManager: StorageManager,
syntheticFiles: Collection<KtFile>,
filesScope: GlobalSearchScope
): DeclarationProviderFactory
companion object {
@JvmStatic fun createDeclarationProviderFactory(
project: Project,
storageManager: StorageManager,
syntheticFiles: Collection<KtFile>,
filesScope: GlobalSearchScope
): DeclarationProviderFactory {
return ServiceManager.getService(project, DeclarationProviderFactoryService::class.java)!!
.create(project, storageManager, syntheticFiles, filteringScope(syntheticFiles, filesScope))
}
private fun filteringScope(syntheticFiles: Collection<KtFile>, baseScope: GlobalSearchScope): GlobalSearchScope {
if (syntheticFiles.isEmpty()) {
return baseScope
}
return SyntheticFilesFilteringScope(syntheticFiles, baseScope)
}
}
private class SyntheticFilesFilteringScope(syntheticFiles: Collection<KtFile>, baseScope: GlobalSearchScope)
: DelegatingGlobalSearchScope(baseScope) {
private val originals = syntheticFiles.mapNotNullTo(HashSet<VirtualFile>()) { it.originalFile.virtualFile }
override fun contains(file: VirtualFile) = super.contains(file) && file !in originals
}
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 2,517 | kotlin | Apache License 2.0 |
arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/memoization.kt | arrow-kt | 86,057,409 | false | null | @file:JvmName("Memoization")
package arrow.core
import arrow.core.continuations.AtomicRef
import arrow.core.continuations.loop
import kotlin.jvm.JvmName
/**
* Memoizes the given **pure** function so that invocations with the same arguments will only execute the function once.
*
* ```kotlin
* import arrow.core.memoize
* fun someWorkIntensiveFunction(someParam: Int): String = "$someParam"
*
* fun main() {
* //sampleStart
* val memoizedF = ::someWorkIntensiveFunction.memoize()
*
* // The first invocation will store the argument and result in a cache inside the `memoizedF` reference.
* val value1 = memoizedF(42)
* // This second invocation won't really call the `someWorkIntensiveFunction` function
* //but retrieve the result from the previous invocation instead.
* val value2 = memoizedF(42)
*
* //sampleEnd
* println("$value1 $value2")
* }
* ```
* <!--- KNIT example-memoization-01.kt -->
*
* Note that calling this function with the same parameters in parallel might cause the function to be executed twice.
*/
public fun <R> (() -> R).memoize(): () -> R {
val m = MemoizedHandler<() -> R, MemoizeKey0<R>, R>(this@memoize)
return { m(MemoizeKey0(0)) }
}
/**
* @see memoize
*/
public fun <P1, R> ((P1) -> R).memoize(): (P1) -> R {
val m = MemoizedHandler<((P1) -> R), MemoizeKey1<P1, R>, R>(this@memoize)
return { p1 -> m(MemoizeKey1(p1)) }
}
/**
* @see memoize
*/
public fun <P1, P2, R> ((P1, P2) -> R).memoize(): (P1, P2) -> R {
val m = MemoizedHandler<((P1, P2) -> R), MemoizeKey2<P1, P2, R>, R>(this@memoize)
return { p1: P1, p2: P2 -> m(MemoizeKey2(p1, p2)) }
}
/**
* @see memoize
*/
public fun <P1, P2, P3, R> ((P1, P2, P3) -> R).memoize(): (P1, P2, P3) -> R {
val m = MemoizedHandler<((P1, P2, P3) -> R), MemoizeKey3<P1, P2, P3, R>, R>(this@memoize)
return { p1: P1, p2: P2, p3: P3 -> m(MemoizeKey3(p1, p2, p3)) }
}
/**
* @see memoize
*/
public fun <P1, P2, P3, P4, R> ((P1, P2, P3, P4) -> R).memoize(): (P1, P2, P3, P4) -> R {
val m = MemoizedHandler<((P1, P2, P3, P4) -> R), MemoizeKey4<P1, P2, P3, P4, R>, R>(this@memoize)
return { p1: P1, p2: P2, p3: P3, p4: P4 -> m(MemoizeKey4(p1, p2, p3, p4)) }
}
/**
* @see memoize
*/
public fun <P1, P2, P3, P4, P5, R> ((P1, P2, P3, P4, P5) -> R).memoize(): (P1, P2, P3, P4, P5) -> R {
val m = MemoizedHandler<((P1, P2, P3, P4, P5) -> R), MemoizeKey5<P1, P2, P3, P4, P5, R>, R>(this@memoize)
return { p1: P1, p2: P2, p3: P3, p4: P4, p5: P5 -> m(MemoizeKey5(p1, p2, p3, p4, p5)) }
}
private interface MemoizedCall<in F, out R> {
operator fun invoke(f: F): R
}
private data class MemoizeKey0<R>(val p1: Byte) : MemoizedCall<() -> R, R> {
override fun invoke(f: () -> R): R = f()
}
private data class MemoizeKey1<out P1, R>(val p1: P1) : MemoizedCall<(P1) -> R, R> {
override fun invoke(f: (P1) -> R) = f(p1)
}
private data class MemoizeKey2<out P1, out P2, R>(val p1: P1, val p2: P2) : MemoizedCall<(P1, P2) -> R, R> {
override fun invoke(f: (P1, P2) -> R) = f(p1, p2)
}
private data class MemoizeKey3<out P1, out P2, out P3, R>(val p1: P1, val p2: P2, val p3: P3) :
MemoizedCall<(P1, P2, P3) -> R, R> {
override fun invoke(f: (P1, P2, P3) -> R) = f(p1, p2, p3)
}
private data class MemoizeKey4<out P1, out P2, out P3, out P4, R>(val p1: P1, val p2: P2, val p3: P3, val p4: P4) :
MemoizedCall<(P1, P2, P3, P4) -> R, R> {
override fun invoke(f: (P1, P2, P3, P4) -> R) = f(p1, p2, p3, p4)
}
private data class MemoizeKey5<out P1, out P2, out P3, out P4, out P5, R>(
val p1: P1,
val p2: P2,
val p3: P3,
val p4: P4,
val p5: P5
) : MemoizedCall<(P1, P2, P3, P4, P5) -> R, R> {
override fun invoke(f: (P1, P2, P3, P4, P5) -> R) = f(p1, p2, p3, p4, p5)
}
private class MemoizedHandler<F, in K : MemoizedCall<F, R>, out R>(val f: F) {
private val cache = AtomicRef(emptyMap<K, R>())
operator fun invoke(k: K): R = when (k) {
in cache.get() -> cache.get().getValue(k)
else -> {
val b = k(f)
cache.loop { old ->
when (k) {
in old ->
return@invoke old.getValue(k)
else -> {
if (cache.compareAndSet(old, old + Pair(k, b)))
return@invoke b
}
}
}
}
}
}
| 38 | null | 436 | 5,958 | 5f0da6334b834bad481c7e3c906bee5a34c1237b | 4,234 | arrow | Apache License 2.0 |
livemap/src/commonMain/kotlin/jetbrains/livemap/api/Bars.kt | JetBrains | 176,771,727 | false | null | package jetbrains.livemap.api
import jetbrains.datalore.base.typedGeometry.explicitVec
import jetbrains.livemap.chart.BarChart
import jetbrains.livemap.chart.ChartElementComponent
import jetbrains.livemap.chart.SymbolComponent
import jetbrains.livemap.core.ecs.EcsEntity
import jetbrains.livemap.core.ecs.addComponents
import jetbrains.livemap.core.layers.LayerGroup
import jetbrains.livemap.mapengine.LayerEntitiesComponent
import jetbrains.livemap.mapengine.RenderableComponent
import jetbrains.livemap.mapengine.placement.ScreenDimensionComponent
import jetbrains.livemap.mapengine.placement.ScreenLoopComponent
import jetbrains.livemap.mapengine.placement.ScreenOriginComponent
import jetbrains.livemap.mapengine.placement.WorldOriginComponent
import jetbrains.livemap.searching.IndexComponent
import jetbrains.livemap.searching.LocatorComponent
import kotlin.math.abs
import kotlin.math.sign
@LiveMapDsl
class Bars(factory: MapEntityFactory) {
val barsFactory = BarsFactory(factory)
}
fun LayersBuilder.bars(block: Bars.() -> Unit) {
val layerEntity = myComponentManager
.createEntity("map_layer_bar")
.addComponents {
+ layerManager.addLayer("livemap_bar", LayerGroup.FEATURES)
+ LayerEntitiesComponent()
}
Bars(MapEntityFactory(layerEntity)).apply {
block()
barsFactory.produce()
}
}
fun Bars.bar(block: Symbol.() -> Unit) {
barsFactory.add(Symbol().apply(block))
}
@LiveMapDsl
class BarsFactory(
private val myFactory: MapEntityFactory
) {
private val mySymbols = ArrayList<Symbol>()
fun add(source: Symbol) {
mySymbols.add(source)
}
fun produce(): List<EcsEntity> {
val maxAbsValue = mySymbols
.asSequence()
.mapNotNull(Symbol::values)
.flatten()
.map(::abs)
.maxOrNull()
?: error("Failed to calculate maxAbsValue.")
return mySymbols.map {
val heights = it.values.map { value ->
val height = when (maxAbsValue) {
0.0 -> 0.0
else -> value / maxAbsValue
}
when {
abs(height) >= MIN_HEIGHT -> height //
else -> height.sign * MIN_HEIGHT
}
}
when {
it.point != null -> this.myFactory.createStaticEntityWithLocation("map_ent_s_bar_sector", it.point!!)
else -> error("Can't create barSector entity. Coord is null.")
}.setInitializer { worldPoint ->
if (it.layerIndex != null) {
+ IndexComponent(it.layerIndex!!, 0)
}
+ LocatorComponent(BarChart.Locator())
+ RenderableComponent().apply {
renderer = BarChart.Renderer()
}
+ ChartElementComponent().apply {
sizeScalingRange = it.sizeScalingRange
alphaScalingEnabled = it.alphaScalingEnabled
strokeColor = it.strokeColor
strokeWidth = it.strokeWidth
}
+ SymbolComponent().apply {
size = explicitVec(2 * it.radius, it.radius)
values = heights
colors = it.colors
indices = it.indices
}
+ WorldOriginComponent(worldPoint)
+ ScreenDimensionComponent()
+ ScreenLoopComponent()
+ ScreenOriginComponent()
}
}
}
}
private const val MIN_HEIGHT = 0.05
| 67 | Kotlin | 37 | 771 | ffa5728a09b348fae441a96aba27e5812a22c18c | 3,660 | lets-plot | MIT License |
app/src/main/java/com/coldfier/currencyobserver/data/sources/shared_prefs/models/SortSettings.kt | Dmitriy1892 | 536,910,669 | false | null | package com.coldfier.currencyobserver.data.sources.shared_prefs.models
enum class SortSettings {
NONE,
ALPHABET_ASC,
ALPHABET_DESC,
VALUE_ASC,
VALUE_DESC
} | 0 | Kotlin | 0 | 0 | 6282730747dc05e348fc0f6bf3fc7927ee889730 | 176 | CurrencyObserver | Apache License 2.0 |
compiler/testData/codegen/bytecodeListing/annotations/internalPropertyOrTypealias.kt | JetBrains | 3,432,266 | false | null | @Target(AnnotationTarget.PROPERTY, AnnotationTarget.TYPEALIAS)
annotation class Anno
class C {
@Anno
internal val property: Int get() = 0
}
@Anno
internal val property: Int get() = 0
@Anno
internal typealias Typealias = Any
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 235 | kotlin | Apache License 2.0 |
game_engine/src/main/java/com/wradchuk/game_engine/utils/HelpingTools.kt | wRadchuk | 784,185,757 | false | {"Kotlin": 47665} | package com.wradchuk.game_engine.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import androidx.core.content.ContextCompat
import com.wradchuk.game_engine.R
import com.wradchuk.game_engine.common.Vector2
import com.wradchuk.game_engine.map.MapData
import org.json.JSONObject
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Получает ширину экрана в пикселях.
*
* @return Ширина экрана в пикселях.
*/
fun Context.getDisplayWidthInPixels(): Int = this.resources.displayMetrics.widthPixels
/**
* Получает высоту экрана в пикселях.
*
* @return Высота экрана в пикселях.
*/
fun Context.getDisplayHeightInPixels(): Int = this.resources.displayMetrics.heightPixels
/**
* Получает битмап из ресурсов.
*
* @param resId Идентификатор ресурса изображения.
* @return Битмап изображения.
*/
fun Context.getBitmap(resId: Int): Bitmap {
val bitmapOptions = BitmapFactory.Options()
bitmapOptions.inScaled = false
return BitmapFactory.decodeResource(this.resources, resId, bitmapOptions)
}
/**
* Рисует текст на холсте с заданными параметрами.
*
* @param color Цвет текста.
* @param textSizeF Размер текста.
* @param message Текст для отображения.
* @param position Позиция текста на холсте.
* @param visible Флаг видимости текста.
*/
fun Canvas.drawText(
color: Int,
textSizeF: Float = 30f,
message: String?,
position: Vector2<Float>,
visible: Boolean = true,
) {
if(visible) {
val paint = Paint().apply {
this.color = color
this.textSize = textSizeF
}
this.drawText(message ?: "", position.x, position.y, paint)
}
}
/**
* Функция для вычисления расстояния между двумя точками в двумерном пространстве.
*
* @param point1 Первая точка в формате Vector2<Int>.
* @param point2 Вторая точка в формате Vector2<Double>.
* @return Расстояние между двумя точками в формате Double.
*/
fun calculateDistance(point1: Vector2<Int>, point2: Vector2<Double>): Double {
return sqrt(
(point1.x - point2.x).pow(2.0) +
(point1.y - point2.y).pow(2.0)
)
}
/**
* Загружает данные карты из ресурсов raw и возвращает объект MapData.
*
* @param rawResourceId Идентификатор ресурса raw с данными карты.
* @return Объект MapData, представляющий данные карты, или null, если загрузка не удалась.
*/
fun Context.loadMapDataFromRaw(rawResourceId: Int): MapData? {
val inputStream = this.resources.openRawResource(rawResourceId)
val jsonString = inputStream.bufferedReader().use { it.readText() }
val jsonObject = JSONObject(jsonString)
val maxRowIndex = jsonObject.getInt("width")
val maxColumnIndex = jsonObject.getInt("height")
val tileSize = jsonObject.getInt("tilewidth")
val orientation = jsonObject.getString("orientation")
val layersArray = jsonObject.getJSONArray("layers").getJSONObject(0).getJSONArray("data")
if (maxRowIndex * maxColumnIndex != layersArray.length()) {
// Проверка на корректность размеров массива
return null
}
val layersData = Array(maxColumnIndex) { IntArray(maxRowIndex) }
var dataIndex = 0
for (row in 0 until maxColumnIndex) {
for (col in 0 until maxRowIndex) {
layersData[row][col] = layersArray.getInt(dataIndex)
dataIndex++
}
}
return MapData(
maxRowIndex = maxRowIndex,
maxColumnIndex = maxColumnIndex,
tileSize = tileSize,
orientation = orientation,
layersData = layersData
)
} | 0 | Kotlin | 0 | 0 | 8da25655744992e4ccd778a2ecf0456320682094 | 3,623 | Kotlin-Game-Engine-2D-by-wRadchuk | Apache License 2.0 |
app/src/main/java/com/vitorpamplona/amethyst/ui/note/ZapUserSetCompose.kt | vitorpamplona | 587,850,619 | false | null | package com.vitorpamplona.amethyst.ui.note
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.google.accompanist.flowlayout.FlowRow
import com.vitorpamplona.amethyst.NotificationCache
import com.vitorpamplona.amethyst.R
import com.vitorpamplona.amethyst.ui.screen.ZapUserSetCard
import com.vitorpamplona.amethyst.ui.screen.loggedIn.AccountViewModel
import com.vitorpamplona.amethyst.ui.theme.BitcoinOrange
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ZapUserSetCompose(zapSetCard: ZapUserSetCard, isInnerNote: Boolean = false, routeForLastRead: String, accountViewModel: AccountViewModel, navController: NavController) {
val accountState by accountViewModel.accountLiveData.observeAsState()
val account = accountState?.account ?: return
var isNew by remember { mutableStateOf<Boolean>(false) }
LaunchedEffect(key1 = zapSetCard.createdAt()) {
withContext(Dispatchers.IO) {
isNew = zapSetCard.createdAt > NotificationCache.load(routeForLastRead)
NotificationCache.markAsRead(routeForLastRead, zapSetCard.createdAt)
}
}
var backgroundColor = if (isNew) {
MaterialTheme.colors.primary.copy(0.12f).compositeOver(MaterialTheme.colors.background)
} else {
MaterialTheme.colors.background
}
Column(
modifier = Modifier
.background(backgroundColor)
.clickable {
navController.navigate("User/${zapSetCard.user.pubkeyHex}")
}
) {
Row(
modifier = Modifier
.padding(
start = if (!isInnerNote) 12.dp else 0.dp,
end = if (!isInnerNote) 12.dp else 0.dp,
top = 10.dp
)
) {
// Draws the like picture outside the boosted card.
if (!isInnerNote) {
Box(
modifier = Modifier
.width(55.dp)
.padding(0.dp)
) {
Icon(
imageVector = Icons.Default.Bolt,
contentDescription = stringResource(id = R.string.zaps),
tint = BitcoinOrange,
modifier = Modifier
.size(25.dp)
.align(Alignment.TopEnd)
)
}
}
Column(modifier = Modifier.padding(start = if (!isInnerNote) 10.dp else 0.dp)) {
FlowRow() {
zapSetCard.zapEvents.forEach {
NoteAuthorPicture(
note = it.key,
navController = navController,
userAccount = account.userProfile(),
size = 35.dp
)
}
}
UserCompose(baseUser = zapSetCard.user, accountViewModel = accountViewModel, navController = navController)
}
}
}
}
| 120 | Kotlin | 88 | 686 | 24d722cdb72a7b52986e488b66a5540682be18f6 | 4,271 | amethyst | MIT License |
app/src/main/java/com/abanapps/videoplayer/ui_layer/Screens/Folder.kt | Aban3049 | 838,005,943 | false | {"Kotlin": 122882} | package com.abanapps.videoplayer.ui_layer.Screens
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
@Composable
fun Folders(navHostController: NavHostController) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = "Folder Content")
}
} | 0 | Kotlin | 0 | 0 | d8c0bd004b4c1d18650ecd323c09b0db04d64ad9 | 565 | MediaPlayerCompose | MIT License |
compiler/daemon/daemon-common/src/org/jetbrains/kotlin/daemon/common/CompilerCallbackServicesFacadeAsync.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.daemon.common
import org.jetbrains.kotlin.incremental.components.LookupInfo
import org.jetbrains.kotlin.load.kotlin.incremental.components.JvmPackagePartProto
import org.jetbrains.kotlin.modules.TargetId
interface CompilerCallbackServicesFacadeAsync : CompilerServicesFacadeBaseAsync {
suspend fun hasIncrementalCaches(): Boolean
suspend fun hasLookupTracker(): Boolean
suspend fun hasCompilationCanceledStatus(): Boolean
// ----------------------------------------------------
// IncrementalCache
suspend fun incrementalCache_getObsoletePackageParts(target: TargetId): Collection<String>
suspend fun incrementalCache_getObsoleteMultifileClassFacades(target: TargetId): Collection<String>
suspend fun incrementalCache_getPackagePartData(target: TargetId, partInternalName: String): JvmPackagePartProto?
suspend fun incrementalCache_getModuleMappingData(target: TargetId): ByteArray?
suspend fun incrementalCache_registerInline(target: TargetId, fromPath: String, jvmSignature: String, toPath: String)
suspend fun incrementalCache_getClassFilePath(target: TargetId, internalClassName: String): String
suspend fun incrementalCache_close(target: TargetId)
suspend fun incrementalCache_getMultifileFacadeParts(target: TargetId, internalName: String): Collection<String>?
// ----------------------------------------------------
// LookupTracker
suspend fun lookupTracker_requiresPosition(): Boolean
fun lookupTracker_record(lookups: Collection<LookupInfo>)
suspend fun lookupTracker_isDoNothing(): Boolean
// ----------------------------------------------------
// CompilationCanceledStatus
suspend fun compilationCanceledStatus_checkCanceled(): Void?
} | 157 | Kotlin | 5209 | 42,102 | 65f712ab2d54e34c5b02ffa3ca8c659740277133 | 1,942 | kotlin | Apache License 2.0 |
shared/src/commonMain/kotlin/dev/vengateshm/petcareapp/data/remote/models/response/ServicesOfferedResponse.kt | vengateshm | 675,750,819 | false | null | package dev.vengateshm.petcareapp.data.remote.models.response
import dev.vengateshm.petcareapp.data.remote.models.ServicesOfferedDto
import kotlinx.serialization.Serializable
@Serializable
data class ServicesOfferedResponse(
val data: List<ServicesOfferedDto>,
) | 0 | Kotlin | 0 | 0 | 3193fe08530930bb4a0f09f2691de66f1d91ace0 | 268 | pet-care-app | Apache License 2.0 |
compiler/testData/diagnostics/tests/annotations/cycleAnnotationOnPropertyFieldInsideLocalClass.kt | JetBrains | 3,432,266 | false | null | package myPack
annotation class Anno(val number: String)
fun topLevelFun() {
class LocalClass {
@Anno(<!ANNOTATION_ARGUMENT_MUST_BE_CONST!>variableToResolve<!>)
@field:Anno(<!ANNOTATION_ARGUMENT_MUST_BE_CONST!>variableToResolve<!>)
var variableToResolve = "${42}"
@Anno(<!ANNOTATION_ARGUMENT_MUST_BE_CONST!>variableToResolve<!>)
get() = field + "str"
@Anno(<!ANNOTATION_ARGUMENT_MUST_BE_CONST!>variableToResolve<!>)
set(@Anno(<!ANNOTATION_ARGUMENT_MUST_BE_CONST!>variableToResolve<!>) value) = Unit
}
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 585 | kotlin | Apache License 2.0 |
enro-core/src/main/java/dev/enro/core/controller/lifecycle/FragmentLifecycleCallbacksForEnro.kt | isaac-udy | 256,179,010 | false | {"Kotlin": 1135982} | package dev.enro.core.controller.lifecycle
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.activity.ComponentDialog
import androidx.activity.OnBackPressedCallback
import androidx.core.view.ViewCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.findViewTreeViewModelStoreOwner
import dev.enro.core.*
import dev.enro.core.controller.usecase.OnNavigationContextCreated
import dev.enro.core.controller.usecase.OnNavigationContextSaved
import dev.enro.core.internal.handle.getNavigationHandleViewModel
internal class FragmentLifecycleCallbacksForEnro(
private val onNavigationContextCreated: OnNavigationContextCreated,
private val onNavigationContextSaved: OnNavigationContextSaved,
) : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentPreCreated(
fm: FragmentManager,
fragment: Fragment,
savedInstanceState: Bundle?
) {
// TODO throw exception if fragment is opened into an Enro registered NavigationContainer without
// being opened through Enro
onNavigationContextCreated(FragmentContext(fragment), savedInstanceState)
}
override fun onFragmentSaveInstanceState(
fm: FragmentManager,
fragment: Fragment,
outState: Bundle
) {
onNavigationContextSaved(fragment.navigationContext, outState)
}
override fun onFragmentViewCreated(
fm: FragmentManager,
fragment: Fragment,
view: View,
outState: Bundle?
) {
if (fragment is DialogFragment && fragment.showsDialog) {
val dialog = fragment.requireDialog()
if (dialog is ComponentDialog) {
dialog.onBackPressedDispatcher.addCallback(fragment.viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
fragment.navigationContext.leafContext().getNavigationHandle().requestClose()
}
})
}
else {
ViewCompat.addOnUnhandledKeyEventListener(view, DialogFragmentBackPressedListener)
}
}
}
}
private object DialogFragmentBackPressedListener : ViewCompat.OnUnhandledKeyEventListenerCompat {
override fun onUnhandledKeyEvent(view: View, event: KeyEvent): Boolean {
val isBackPressed =
event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP
if (!isBackPressed) return false
view.findViewTreeViewModelStoreOwner()
?.getNavigationHandleViewModel()
?.navigationContext
?.leafContext()
?.getNavigationHandle()
?.requestClose() ?: return false
return true
}
} | 13 | Kotlin | 13 | 226 | ffe0fedab54282083c0671f23e454d43df63b35f | 2,881 | Enro | Apache License 2.0 |
app/src/main/java/com/bruno13palhano/shopdanimanagement/ui/screens/financial/viewmodel/StockDebitsViewModel.kt | bruno13palhano | 670,001,130 | false | null | package com.bruno13palhano.shopdanimanagement.ui.screens.financial.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bruno13palhano.core.data.di.StockRep
import com.bruno13palhano.core.data.repository.stock.StockRepository
import com.bruno13palhano.core.model.StockItem
import com.bruno13palhano.shopdanimanagement.ui.screens.common.Stock
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted.Companion.WhileSubscribed
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class StockDebitsViewModel
@Inject
constructor(
@StockRep private val stockRepository: StockRepository
) : ViewModel() {
private val _debitItems = MutableStateFlow(emptyList<StockItem>())
val debitItems =
_debitItems
.map {
it.map { stockItem ->
Stock(
id = stockItem.id,
name = stockItem.name,
photo = stockItem.photo,
purchasePrice = stockItem.purchasePrice,
quantity = stockItem.quantity
)
}
}
.stateIn(
scope = viewModelScope,
started = WhileSubscribed(5_000),
initialValue = emptyList()
)
fun getDebitStock() {
viewModelScope.launch {
stockRepository.getDebitStock().collect {
_debitItems.value = it
}
}
}
fun getStockByPrice(isOrderedAsc: Boolean) {
viewModelScope.launch {
stockRepository.getDebitStockByPrice(isOrderedAsc = isOrderedAsc).collect {
_debitItems.value = it
}
}
}
fun getStockByName(isOrderedAsc: Boolean) {
viewModelScope.launch {
stockRepository.getDebitStockByName(isOrderedAsc = isOrderedAsc).collect {
_debitItems.value = it
}
}
}
} | 0 | null | 0 | 2 | c55b8f8f9fccb42ce9b5a99a309e41bd2ec0b5b2 | 2,350 | shop-dani-management | MIT License |
app/src/main/java/dev/arkbuilders/rate/presentation/portfolio/PortfolioViewModel.kt | ARK-Builders | 515,514,394 | false | {"Kotlin": 382616} | package dev.arkbuilders.rate.presentation.portfolio
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import dev.arkbuilders.rate.domain.model.Amount
import dev.arkbuilders.rate.domain.model.Asset
import dev.arkbuilders.rate.domain.model.CurrencyCode
import dev.arkbuilders.rate.domain.model.QuickPair
import dev.arkbuilders.rate.domain.repo.AnalyticsManager
import dev.arkbuilders.rate.domain.repo.CurrencyRepo
import dev.arkbuilders.rate.domain.repo.PortfolioRepo
import dev.arkbuilders.rate.domain.repo.PreferenceKey
import dev.arkbuilders.rate.domain.repo.Prefs
import dev.arkbuilders.rate.domain.usecase.ConvertWithRateUseCase
import dev.arkbuilders.rate.presentation.shared.AppSharedFlow
import dev.arkbuilders.rate.presentation.ui.NotifyAddedSnackbarVisuals
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.orbitmvi.orbit.Container
import org.orbitmvi.orbit.ContainerHost
import org.orbitmvi.orbit.syntax.simple.blockingIntent
import org.orbitmvi.orbit.syntax.simple.intent
import org.orbitmvi.orbit.syntax.simple.postSideEffect
import org.orbitmvi.orbit.syntax.simple.reduce
import org.orbitmvi.orbit.viewmodel.container
import javax.inject.Inject
import javax.inject.Singleton
data class PortfolioScreenState(
val filter: String = "",
val baseCode: CurrencyCode = "USD",
val pages: List<PortfolioScreenPage> = emptyList(),
val initialized: Boolean = false
)
data class PortfolioScreenPage(
val group: String?,
val assets: List<PortfolioDisplayAsset>
)
data class PortfolioDisplayAsset(
val asset: Asset,
val baseAmount: Amount,
val ratioToBase: Double
)
sealed class PortfolioScreenEffect {
class ShowSnackbarAdded(
val visuals: NotifyAddedSnackbarVisuals
) : PortfolioScreenEffect()
data class ShowRemovedSnackbar(val asset: Asset): PortfolioScreenEffect()
}
class PortfolioViewModel(
private val assetsRepo: PortfolioRepo,
private val currencyRepo: CurrencyRepo,
private val prefs: Prefs,
private val convertUseCase: ConvertWithRateUseCase,
private val analyticsManager: AnalyticsManager
) : ViewModel(), ContainerHost<PortfolioScreenState, PortfolioScreenEffect> {
override val container: Container<PortfolioScreenState, PortfolioScreenEffect> =
container(PortfolioScreenState())
init {
analyticsManager.trackScreen("PortfolioScreen")
intent {
if (isRatesAvailable().not())
return@intent
init()
AppSharedFlow.ShowAddedSnackbarQuick.flow.onEach { visuals ->
postSideEffect(PortfolioScreenEffect.ShowSnackbarAdded(visuals))
}.launchIn(viewModelScope)
prefs.flow(PreferenceKey.BaseCurrencyCode).drop(1).onEach {
init()
}.launchIn(viewModelScope)
assetsRepo.allAssetsFlow().drop(1).onEach {
init()
}.launchIn(viewModelScope)
}
}
fun onAssetRemove(asset: Asset) = intent {
val deleted = assetsRepo.removeAsset(asset.id)
if (deleted) {
postSideEffect(PortfolioScreenEffect.ShowRemovedSnackbar(asset))
}
}
fun undoDelete(asset: Asset) = intent {
assetsRepo.setAsset(asset)
}
fun onFilterChange(filter: String) = blockingIntent {
reduce { state.copy(filter = filter) }
}
private fun init() = intent {
val baseCode = prefs.get(PreferenceKey.BaseCurrencyCode)
val assets = assetsRepo.allAssets().reversed()
val groups = assets.groupBy(keySelector = { it.group })
val pages = groups.map { (group, assets) ->
val displayAssets = assetToPortfolioDisplayAmount(
baseCode,
assets
)
PortfolioScreenPage(group, displayAssets)
}
reduce {
state.copy(baseCode = baseCode, pages = pages, initialized = true)
}
}
private suspend fun assetToPortfolioDisplayAmount(
baseCode: CurrencyCode,
list: List<Asset>
): List<PortfolioDisplayAsset> {
val rates = currencyRepo.getCodeToCurrencyRate().getOrNull()!!
return list.map { asset ->
val (baseAmount, rate) = convertUseCase(
asset.code,
asset.value,
toCode = baseCode,
rates
)
PortfolioDisplayAsset(asset, baseAmount, rate)
}
}
private suspend fun isRatesAvailable() = currencyRepo.getCurrencyRate().isRight()
}
@Singleton
class PortfolioViewModelFactory @Inject constructor(
private val assetsRepo: PortfolioRepo,
private val currencyRepo: CurrencyRepo,
private val prefs: Prefs,
private val convertUseCase: ConvertWithRateUseCase,
private val analyticsManager: AnalyticsManager
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return PortfolioViewModel(
assetsRepo,
currencyRepo,
prefs,
convertUseCase,
analyticsManager
) as T
}
} | 38 | Kotlin | 2 | 2 | 9edf1f8b0f1cf0be595ed18e278e532614b5e877 | 5,240 | ARK-Rate | MIT License |
app/src/main/java/net/kibotu/swipedirectionviewpager/demo/models/PageModel.kt | kibotu | 119,252,017 | false | null | package net.kibotu.swipedirectionviewpager.demo.models
/**
* Created by [<NAME>](https://about.me/janrabe).
*/
data class PageModel(
var text: String? = null,
var imageUrl: String? = null
) | 0 | Kotlin | 4 | 10 | b48701b6b251283eefdac58f2384b51eaac7b88f | 209 | SwipeDirectionViewPager | Apache License 2.0 |
plugins/kotlin/code-insight/inspections-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/inspections/expressions/KotlinDoubleNegationInspection.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.inspections.expressions
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.inspections.AbstractKotlinApplicableInspection
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicabilityRange
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtParenthesizedExpression
import org.jetbrains.kotlin.psi.KtPrefixExpression
import org.jetbrains.kotlin.psi.KtVisitorVoid
internal class KotlinDoubleNegationInspection : AbstractKotlinApplicableInspection<KtPrefixExpression>() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitPrefixExpression(expression: KtPrefixExpression) {
visitTargetElement(expression, holder, isOnTheFly)
}
}
}
override fun getProblemDescription(element: KtPrefixExpression): String =
KotlinBundle.message("inspection.kotlin.double.negation.display.name")
override fun getActionFamilyName(): String = KotlinBundle.message("inspection.kotlin.double.negation.action.name")
override fun getApplicabilityRange(): KotlinApplicabilityRange<KtPrefixExpression> = ApplicabilityRanges.SELF
override fun isApplicableByPsi(element: KtPrefixExpression): Boolean =
element.operationToken == KtTokens.EXCL
&& (element.parentThroughParenthesis as? KtPrefixExpression)?.operationToken == KtTokens.EXCL
context(KtAnalysisSession)
override fun isApplicableByAnalyze(element: KtPrefixExpression): Boolean = element.getKtType()?.isBoolean == true
override fun apply(element: KtPrefixExpression, project: Project, editor: Editor?) {
element.baseExpression?.let { element.parentThroughParenthesis.replace(it) }
}
}
private val PsiElement.parentThroughParenthesis: PsiElement
get() {
var result = parent
while (result is KtParenthesizedExpression) {
result = result.parent
}
return result
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 2,713 | intellij-community | Apache License 2.0 |
analyzer/src/main/kotlin/managers/Bundler.kt | codeakki | 354,880,826 | false | null | /*
* Copyright (C) 2017-2019 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.ossreviewtoolkit.analyzer.managers
import com.fasterxml.jackson.module.kotlin.readValue
import com.vdurmont.semver4j.Requirement
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.util.SortedSet
import org.ossreviewtoolkit.analyzer.AbstractPackageManagerFactory
import org.ossreviewtoolkit.analyzer.PackageManager
import org.ossreviewtoolkit.downloader.VcsHost
import org.ossreviewtoolkit.downloader.VersionControlSystem
import org.ossreviewtoolkit.model.Hash
import org.ossreviewtoolkit.model.Identifier
import org.ossreviewtoolkit.model.OrtIssue
import org.ossreviewtoolkit.model.Package
import org.ossreviewtoolkit.model.PackageReference
import org.ossreviewtoolkit.model.Project
import org.ossreviewtoolkit.model.ProjectAnalyzerResult
import org.ossreviewtoolkit.model.RemoteArtifact
import org.ossreviewtoolkit.model.Scope
import org.ossreviewtoolkit.model.VcsInfo
import org.ossreviewtoolkit.model.config.AnalyzerConfiguration
import org.ossreviewtoolkit.model.config.RepositoryConfiguration
import org.ossreviewtoolkit.model.createAndLogIssue
import org.ossreviewtoolkit.model.jsonMapper
import org.ossreviewtoolkit.model.yamlMapper
import org.ossreviewtoolkit.utils.CommandLineTool
import org.ossreviewtoolkit.utils.HttpDownloadError
import org.ossreviewtoolkit.utils.OkHttpClientHelper
import org.ossreviewtoolkit.utils.Os
import org.ossreviewtoolkit.utils.collectMessagesAsString
import org.ossreviewtoolkit.utils.log
import org.ossreviewtoolkit.utils.showStackTrace
import org.ossreviewtoolkit.utils.stashDirectories
import org.ossreviewtoolkit.utils.textValueOrEmpty
/**
* The [Bundler](https://bundler.io/) package manager for Ruby. Also see
* [Clarifying the Roles of the .gemspec and Gemfile][1].
*
* [1]: http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/
*/
class Bundler(
name: String,
analysisRoot: File,
analyzerConfig: AnalyzerConfiguration,
repoConfig: RepositoryConfiguration
) : PackageManager(name, analysisRoot, analyzerConfig, repoConfig), CommandLineTool {
class Factory : AbstractPackageManagerFactory<Bundler>("Bundler") {
override val globsForDefinitionFiles = listOf("Gemfile")
override fun create(
analysisRoot: File,
analyzerConfig: AnalyzerConfiguration,
repoConfig: RepositoryConfiguration
) = Bundler(managerName, analysisRoot, analyzerConfig, repoConfig)
}
override fun command(workingDir: File?) = if (Os.isWindows) "bundle.bat" else "bundle"
override fun transformVersion(output: String) = output.removePrefix("Bundler version ")
override fun getVersionRequirement(): Requirement = Requirement.buildIvy("[1.16,)")
override fun beforeResolution(definitionFiles: List<File>) =
// We do not actually depend on any features specific to a version of Bundler, but we still want to stick to
// fixed versions to be sure to get consistent results.
checkVersion(analyzerConfig.ignoreToolVersions)
override fun resolveDependencies(definitionFile: File): List<ProjectAnalyzerResult> {
val workingDir = definitionFile.parentFile
stashDirectories(workingDir.resolve("vendor")).use {
val scopes = mutableSetOf<Scope>()
val packages = sortedSetOf<Package>()
val issues = mutableListOf<OrtIssue>()
installDependencies(workingDir)
val (projectName, version, homepageUrl, authors, declaredLicenses) = parseProject(workingDir)
val projectId = Identifier(managerName, "", projectName, version)
val groupedDeps = getDependencyGroups(workingDir)
for ((groupName, dependencyList) in groupedDeps) {
parseScope(workingDir, projectId, groupName, dependencyList, scopes, packages, issues)
}
val project = Project(
id = projectId,
definitionFilePath = VersionControlSystem.getPathInfo(definitionFile).path,
authors = authors,
declaredLicenses = declaredLicenses.toSortedSet(),
vcs = VcsInfo.EMPTY,
vcsProcessed = processProjectVcs(workingDir, VcsInfo.EMPTY, homepageUrl),
homepageUrl = homepageUrl,
scopeDependencies = scopes.toSortedSet()
)
return listOf(ProjectAnalyzerResult(project, packages, issues))
}
}
private fun parseScope(
workingDir: File, projectId: Identifier, groupName: String, dependencyList: List<String>,
scopes: MutableSet<Scope>, packages: MutableSet<Package>, issues: MutableList<OrtIssue>
) {
log.debug { "Parsing scope: $groupName\nscope top level deps list=$dependencyList" }
val scopeDependencies = mutableSetOf<PackageReference>()
dependencyList.forEach {
parseDependency(workingDir, projectId, it, packages, scopeDependencies, issues)
}
scopes += Scope(groupName, scopeDependencies.toSortedSet())
}
private fun parseDependency(
workingDir: File, projectId: Identifier, gemName: String, packages: MutableSet<Package>,
scopeDependencies: MutableSet<PackageReference>, issues: MutableList<OrtIssue>
) {
log.debug { "Parsing dependency '$gemName'." }
try {
var gemSpec = getGemspec(gemName, workingDir)
val gemId = Identifier("Gem", "", gemSpec.name, gemSpec.version)
// The project itself can be listed as a dependency if the project is a gem (i.e. there is a .gemspec file
// for it, and the Gemfile refers to it). In that case, skip querying Rubygems and adding Package and
// PackageReference objects and continue with the projects dependencies.
if (gemId == projectId) {
gemSpec.runtimeDependencies.forEach {
parseDependency(workingDir, projectId, it, packages, scopeDependencies, issues)
}
} else {
queryRubygems(gemId.name, gemId.version)?.apply {
gemSpec = merge(gemSpec)
}
packages += Package(
id = gemId,
authors = gemSpec.authors,
declaredLicenses = gemSpec.declaredLicenses,
description = gemSpec.description,
homepageUrl = gemSpec.homepageUrl,
binaryArtifact = RemoteArtifact.EMPTY,
sourceArtifact = gemSpec.artifact,
vcs = gemSpec.vcs,
vcsProcessed = processPackageVcs(gemSpec.vcs, gemSpec.homepageUrl)
)
val transitiveDependencies = mutableSetOf<PackageReference>()
gemSpec.runtimeDependencies.forEach {
parseDependency(workingDir, projectId, it, packages, transitiveDependencies, issues)
}
scopeDependencies += PackageReference(gemId, dependencies = transitiveDependencies.toSortedSet())
}
} catch (e: IOException) {
e.showStackTrace()
issues += createAndLogIssue(
source = managerName,
message = "Failed to parse spec for gem '$gemName': ${e.collectMessagesAsString()}"
)
}
}
private fun getDependencyGroups(workingDir: File): Map<String, List<String>> {
val scriptFile = File.createTempFile("bundler_dependencies", ".rb")
scriptFile.writeBytes(javaClass.getResource("/scripts/bundler_dependencies.rb").readBytes())
try {
val scriptCmd = run(
"exec", "ruby", scriptFile.path,
workingDir = workingDir,
environment = mapOf("BUNDLE_PATH" to "vendor/bundle")
)
return jsonMapper.readValue(scriptCmd.stdout)
} finally {
if (!scriptFile.delete()) {
log.warn { "Helper script file '$scriptFile' could not be deleted." }
}
}
}
private fun parseProject(workingDir: File) =
getGemspecFile(workingDir)?.let { gemspecFile ->
// Project is a Gem, i.e. a library.
getGemspec(gemspecFile.nameWithoutExtension, workingDir)
} ?: GemSpec(
workingDir.name,
"",
"",
sortedSetOf(),
sortedSetOf(),
"",
emptySet(),
VcsInfo.EMPTY,
RemoteArtifact.EMPTY
)
private fun getGemspec(gemName: String, workingDir: File): GemSpec {
val spec = run(
"exec", "gem", "specification", gemName,
workingDir = workingDir,
environment = mapOf("BUNDLE_PATH" to "vendor/bundle")
).stdout
return GemSpec.createFromYaml(spec)
}
private fun getGemspecFile(workingDir: File) =
workingDir.walk().maxDepth(1).filter { it.isFile && it.extension == "gemspec" }.firstOrNull()
private fun installDependencies(workingDir: File) {
requireLockfile(workingDir) { workingDir.resolve("Gemfile.lock").isFile }
// Work around "--path" being deprecated since Bundler 2.1 and avoid tampering with the ".bundle/config" file at
// all by using the "BUNDLER_PATH" environment variable to specify where to install the Gems to.
run("install", workingDir = workingDir, environment = mapOf("BUNDLE_PATH" to "vendor/bundle"))
}
private fun queryRubygems(name: String, version: String, retryCount: Int = 3): GemSpec? {
// See http://guides.rubygems.org/rubygems-org-api-v2/.
val url = "https://rubygems.org/api/v2/rubygems/$name/versions/$version.json"
return OkHttpClientHelper.downloadText(url).mapCatching {
GemSpec.createFromJson(it)
}.onFailure {
val error = (it as? HttpDownloadError) ?: run {
log.warn { "Unable to retrieve meta-data for gem '$name' from RubyGems: ${it.message}" }
return null
}
when (error.code) {
HttpURLConnection.HTTP_NOT_FOUND -> log.info { "Gem '$name' was not found on RubyGems." }
OkHttpClientHelper.HTTP_TOO_MANY_REQUESTS -> {
throw IOException(
"RubyGems reported too many requests when requesting meta-data for gem '$name', see " +
"https://guides.rubygems.org/rubygems-org-api/#rate-limits."
)
}
HttpURLConnection.HTTP_BAD_GATEWAY -> {
if (retryCount > 0) {
// We see a lot of sporadic "bad gateway" responses that disappear when trying again.
Thread.sleep(100)
return queryRubygems(name, version, retryCount - 1)
}
throw IOException(
"RubyGems reported too many bad gateway errors when requesting meta-data for gem '$name'."
)
}
else -> {
throw IOException(
"RubyGems reported unhandled HTTP code ${error.code} when requesting meta-data for gem '$name'."
)
}
}
}.getOrNull()
}
}
data class GemSpec(
val name: String,
val version: String,
val homepageUrl: String,
val authors: SortedSet<String>,
val declaredLicenses: SortedSet<String>,
val description: String,
val runtimeDependencies: Set<String>,
val vcs: VcsInfo,
val artifact: RemoteArtifact
) {
companion object Factory {
fun createFromYaml(spec: String): GemSpec {
val yaml = yamlMapper.readTree(spec)
val runtimeDependencies = yaml["dependencies"]?.asIterable()?.mapNotNull { dependency ->
dependency["name"]?.textValue()?.takeIf { dependency["type"]?.textValue() == ":runtime" }
}?.toSet()
val homepage = yaml["homepage"].textValueOrEmpty()
return GemSpec(
yaml["name"].textValue(),
yaml["version"]["version"].textValue(),
homepage,
yaml["authors"]?.asIterable()?.mapTo(sortedSetOf()) { it.textValue() } ?: sortedSetOf(),
yaml["licenses"]?.asIterable()?.mapTo(sortedSetOf()) { it.textValue() } ?: sortedSetOf(),
yaml["description"].textValueOrEmpty(),
runtimeDependencies.orEmpty(),
VcsHost.toVcsInfo(homepage),
RemoteArtifact.EMPTY
)
}
fun createFromJson(spec: String): GemSpec {
val json = jsonMapper.readTree(spec)
val runtimeDependencies = json["dependencies"]?.get("runtime")?.mapNotNull { dependency ->
dependency["name"]?.textValue()
}?.toSet()
val vcs = if (json.hasNonNull("source_code_uri")) {
VcsHost.toVcsInfo(json["source_code_uri"].textValue())
} else {
VcsInfo.EMPTY
}
val artifact = if (json.hasNonNull("gem_uri") && json.hasNonNull("sha")) {
val sha = json["sha"].textValue()
RemoteArtifact(json["gem_uri"].textValue(), Hash.create(sha))
} else {
RemoteArtifact.EMPTY
}
val authors = json["authors"]
.textValueOrEmpty()
.split(',')
.mapNotNullTo(sortedSetOf()) { author ->
author.trim().takeIf {
it.isNotEmpty()
}
}
return GemSpec(
json["name"].textValue(),
json["version"].textValue(),
json["homepage_uri"].textValueOrEmpty(),
authors,
json["licenses"]?.asIterable()?.mapTo(sortedSetOf()) { it.textValue() } ?: sortedSetOf(),
json["description"].textValueOrEmpty(),
runtimeDependencies.orEmpty(),
vcs,
artifact
)
}
}
fun merge(other: GemSpec): GemSpec {
require(name == other.name && version == other.version) {
"Cannot merge specs for different gems."
}
return GemSpec(name, version,
homepageUrl.takeUnless { it.isEmpty() } ?: other.homepageUrl,
authors.takeUnless { it.isEmpty() } ?: other.authors,
declaredLicenses.takeUnless { it.isEmpty() } ?: other.declaredLicenses,
description.takeUnless { it.isEmpty() } ?: other.description,
runtimeDependencies.takeUnless { it.isEmpty() } ?: other.runtimeDependencies,
vcs.takeUnless { it == VcsInfo.EMPTY } ?: other.vcs,
artifact.takeUnless { it == RemoteArtifact.EMPTY } ?: other.artifact
)
}
}
| 0 | null | 0 | 2 | edbb46cb1dab1529d5ffb81cba18d365b98ef23e | 15,704 | ort | Apache License 2.0 |
cotta-core/src/main/kotlin/com/mgtriffid/games/cotta/core/entities/Entities.kt | mgtriffid | 524,701,185 | false | {"Kotlin": 478306, "Java": 9323} | package com.mgtriffid.games.cotta.core.entities
import com.mgtriffid.games.cotta.core.entities.id.EntityId
import com.mgtriffid.games.cotta.core.exceptions.EntityNotExistsException
/**
* Represents all Entities in game world in a current tick.
*/
interface Entities {
/**
* Creates a new Entity owned by the given owner (defaults to System).
*
* @param ownedBy the owner of the entity - means this entity will be
* processed during prediction on the client side if the owner is a Player,
* otherwise it's a regular Entity not processed by prediction.
*/
fun create(ownedBy: Entity.OwnedBy = Entity.OwnedBy.System): Entity
/**
* Retrieves an Entity by its id.
*/
fun get(id: EntityId): Entity?
fun getOrNotFound(id: EntityId): Entity = get(id) ?: throw EntityNotExistsException("Could not find entity $id")
/**
* Returns all Entities existing in the current tick.
*/
fun all(): Collection<Entity>
/**
* Returns all Entities that are dynamic (i.e. not static). Static entities
* are those created in the
* [com.mgtriffid.games.cotta.core.CottaGame.initializeStaticState] method.
*/
fun dynamic(): Collection<Entity>
/**
* Removes an Entity. Happens immediately, removals are not postponed until
* the end of the tick (this behavior may change).
*/
fun remove(id: EntityId)
}
| 2 | Kotlin | 0 | 6 | ee0bd897c67451b31f68a3a31a6ee8de756b2b52 | 1,410 | cotta | MIT License |
magellan-sample-advanced/src/main/java/com/wealthfront/magellan/sample/advanced/suggestexhibit/SuggestExhibitStartStep.kt | wealthfront | 82,854,849 | false | null | package com.wealthfront.magellan.sample.advanced.suggestexhibit
import android.content.Context
import com.wealthfront.magellan.core.Step
import com.wealthfront.magellan.sample.advanced.databinding.SuggestExhibitStartBinding
class SuggestExhibitStartStep(private val goToSuggestExhibitJourney: () -> Unit) :
Step<SuggestExhibitStartBinding>(SuggestExhibitStartBinding::inflate) {
override fun onShow(context: Context, binding: SuggestExhibitStartBinding) {
binding.suggestExhibitStart.setOnClickListener { goToSuggestExhibitJourney() }
}
}
| 36 | Kotlin | 66 | 685 | dceeeb25a502c8bd143a769858169c86a099c5e7 | 552 | magellan | Apache License 2.0 |
magellan-sample-advanced/src/main/java/com/wealthfront/magellan/sample/advanced/suggestexhibit/SuggestExhibitStartStep.kt | wealthfront | 82,854,849 | false | null | package com.wealthfront.magellan.sample.advanced.suggestexhibit
import android.content.Context
import com.wealthfront.magellan.core.Step
import com.wealthfront.magellan.sample.advanced.databinding.SuggestExhibitStartBinding
class SuggestExhibitStartStep(private val goToSuggestExhibitJourney: () -> Unit) :
Step<SuggestExhibitStartBinding>(SuggestExhibitStartBinding::inflate) {
override fun onShow(context: Context, binding: SuggestExhibitStartBinding) {
binding.suggestExhibitStart.setOnClickListener { goToSuggestExhibitJourney() }
}
}
| 36 | Kotlin | 66 | 685 | dceeeb25a502c8bd143a769858169c86a099c5e7 | 552 | magellan | Apache License 2.0 |
app/src/main/java/com/brouken/player/activity/BuySubscriptionActivity.kt | mahsak01 | 596,924,815 | false | null | package com.brouken.player.activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.brouken.player.Fragment.LoadingFragment
import com.brouken.player.R
import com.brouken.player.adapter.BuySubscriptionPlanItemAdapter
import com.brouken.player.common.MainContainer.isMobile
import com.brouken.player.data.model.Plan
import com.brouken.player.data.model.enum.ToastStatus
import com.brouken.player.databinding.ActivityBuySubscriptionBinding
import com.brouken.player.viewModel.UserSettingViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
import showCustomToast
class BuySubscriptionActivity : AppCompatActivity() {
private lateinit var binding: ActivityBuySubscriptionBinding
private var loadingFragment: LoadingFragment? = null
private val userSettingViewModel: UserSettingViewModel by viewModel()
private var showError: Boolean = true
private var selectGetWay: Int = -1
private var selectPlan = -1
private var selectPlanId = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_buy_subscription)
if (supportActionBar != null) {
supportActionBar?.hide()
}
setObserver()
userSettingViewModel.getAllPlans()
loadingFragment = LoadingFragment()
loadingFragment?.show(supportFragmentManager, null)
Handler(mainLooper)
.postDelayed({
if (loadingFragment != null && loadingFragment!!.showsDialog)
loadingFragment!!.dismiss()
}, (30000))
setListener()
}
override fun onResume() {
super.onResume()
if (!isMobile) {
this.binding.ActivityBuySubscriptionBackBtn.focusable = 1
this.binding.ActivityBuySubscriptionBackBtn.isFocusableInTouchMode = true
setFocus()
this.binding.ActivityBuySubscriptionBackBtn.requestFocus(1)
}
}
private fun setObserver() {
userSettingViewModel.errorHandlingLiveData.observe(this) {
if (it.message != null && showError) {
showError = false
Toast.makeText(
this,
it.message,
Toast.LENGTH_LONG
)
.showCustomToast(
it.message!!,
this,
ToastStatus.ERROR
)
}
Handler()
.postDelayed({
showError = true
}, (15000))
}
this.userSettingViewModel.getAllPlansInformationLiveData.observe(this) {
if (!it.results!!.isNullOrEmpty()) {
binding.ActivityBuySubscriptionItemsRv.layoutManager =
LinearLayoutManager(this, RecyclerView.VERTICAL, false)
val adapter = BuySubscriptionPlanItemAdapter(
it.results as List<Plan>,
this,
object : BuySubscriptionPlanItemAdapter.EventListener {
override fun click(plan: Plan, position: Int) {
selectPlan = position
selectPlanId = plan.id
}
}, selectPlan
)
binding.ActivityBuySubscriptionItemsRv.adapter = adapter
if (loadingFragment != null && loadingFragment!!.showsDialog)
loadingFragment!!.dismiss()
} else {
this.binding.ActivityBuySubscriptionItemsRv.visibility = View.GONE
if (loadingFragment != null && loadingFragment!!.showsDialog)
loadingFragment!!.dismiss()
}
}
this.userSettingViewModel.getAllGetAllGateWaysLiveData.observe(this) {
if (it != null && !it.results.isNullOrEmpty()) {
selectGetWay = it.results[0].id;
this.userSettingViewModel.getPaymentLink(selectPlanId, selectGetWay)
} else {
Toast.makeText(this, "درگاه پرداختی وجود ندارد", Toast.LENGTH_LONG)
.showCustomToast(
"درگاه پرداختی وجود ندارد",
this,
ToastStatus.ERROR
)
}
}
this.userSettingViewModel.getPaymentLinkLiveData.observe(this) {
if (!it.toString().contains("\"message\"") && it != null) {
this.onBackPressed()
val openURL = Intent(Intent.ACTION_VIEW)
openURL.data = Uri.parse(it.toString())
startActivity(openURL)
} else {
Toast.makeText(this, "درگاه پرداختی با مشکل مواجه شده است ", Toast.LENGTH_LONG)
.showCustomToast(
"درگاه پرداختی با مشکل مواجه شده است ",
this,
ToastStatus.ERROR
)
}
}
}
private fun setFocus() {
this.binding.ActivityBuySubscriptionBackBtn.setOnFocusChangeListener { view, isFocused ->
// add focus handling logic
if (isFocused) {
this.binding.ActivityBuySubscriptionBackBtn.background =
resources.getDrawable(
R.drawable.background_select_icon_android_tv
)
} else {
this.binding.ActivityBuySubscriptionBackBtn.background =
resources.getDrawable(
R.drawable.background_select_text_no_color_android_tv
)
}
}
this.binding.ActivityBuySubscriptionAcceptBtn.setOnFocusChangeListener { view, isFocused ->
// add focus handling logic
if (isFocused) {
this.binding.ActivityBuySubscriptionAcceptBtn.background =
resources.getDrawable(
R.drawable.background_select_text_red__android_tv
)
} else {
this.binding.ActivityBuySubscriptionAcceptBtn.background =
resources.getDrawable(
R.drawable.background_red_button_setting
)
}
}
}
private fun setListener() {
this.binding.ActivityBuySubscriptionBackBtn.setOnClickListener {
this.onBackPressed()
}
this.binding.ActivityBuySubscriptionAcceptBtn.setOnClickListener {
if (selectPlanId != -1)
this.userSettingViewModel.getAllGateWay()
else
Toast.makeText(this, "ابتدا یک پلن را انتخاب کنید", Toast.LENGTH_LONG)
.showCustomToast(
"ابتدا یک پلن را انتخاب کنید",
this,
ToastStatus.ERROR
)
}
}
} | 0 | Kotlin | 0 | 0 | e1ef9a8a316f76446718489f458e3a088ae55d15 | 7,361 | ArianaFilm | The Unlicense |
app/src/main/java/com/lonard/camerlangproject/db/homepage/NotificationCatEntity.kt | lonard2 | 490,593,898 | false | null | package com.lonard.camerlangproject.db.homepage
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
@Parcelize
@Entity(tableName = "notification_categories")
data class NotificationCatEntity (
@PrimaryKey(autoGenerate = false)
@ColumnInfo(name = "id")
var id: Int?,
@ColumnInfo(name = "notification_cat_name")
var name: String? = null,
@ColumnInfo(name = "notification_cat_desc")
var description: String? = null,
): Parcelable | 0 | Kotlin | 2 | 2 | 52f69ed3312071307b5c8c9221a45ccdde6c7351 | 563 | CAMerlang-Mobile-Development | MIT License |
appcompat/appcompat/src/androidTest/java/androidx/appcompat/testutils/NightModeActivityTestRule.kt | RikkaW | 389,105,112 | true | {"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343} | /*
* Copyright 2019 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.appcompat.testutils
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
@Suppress("DEPRECATION")
class NightModeActivityTestRule<T : AppCompatActivity>(
activityClazz: Class<T>,
initialTouchMode: Boolean = false,
launchActivity: Boolean = true
) : androidx.test.rule.ActivityTestRule<T>(activityClazz, initialTouchMode, launchActivity) {
override fun beforeActivityLaunched() {
// By default we'll set the night mode to NO, which allows us to make better
// assumptions in the test below
runOnUiThread {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
}
override fun afterActivityFinished() {
// Reset the default night mode
runOnUiThread {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
}
}
| 28 | Java | 937 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 1,532 | androidx | Apache License 2.0 |
android/src/test/kotlin/uk/co/objectivity/beacon_monitoring/plugin/service/BluetoothServiceTest.kt | VinniciusJesus | 442,466,273 | false | {"Swift": 77863, "Kotlin": 76055, "Dart": 13707, "Ruby": 2323, "Objective-C": 38} | // Copyright (c) 2020 Objectivity. All rights reserved.
// Use of this source code is governed by The MIT License (MIT) that can be
// found in the LICENSE file.
package uk.co.objectivity.beacon_monitoring.plugin.service
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import org.hamcrest.CoreMatchers.`is`
import org.junit.Assert.assertThat
import org.junit.Test
import org.mockito.Mockito.*
private const val REQUEST_CODE_BLUETOOTH = 6607
class BluetoothServiceTest {
private val context = mock(Context::class.java)
private val bluetoothService = BluetoothService(context)
@Test
fun shouldCheckIfBluetoothIsEnabled() {
val bluetoothManager = mock(BluetoothManager::class.java)
val bluetoothAdapter = mock(BluetoothAdapter::class.java)
`when`(context.getSystemService(Context.BLUETOOTH_SERVICE)).thenReturn(bluetoothManager)
`when`(bluetoothManager.adapter).thenReturn(bluetoothAdapter)
`when`(bluetoothAdapter.isEnabled).thenReturn(true)
val result = bluetoothService.isEnabled()
assertThat(result, `is`(true))
}
@Test
fun shouldBindServiceToActivity() {
val activityPluginBinding = mock(ActivityPluginBinding::class.java)
bluetoothService.bind(activityPluginBinding)
verify(activityPluginBinding).addActivityResultListener(bluetoothService)
}
@Test
fun shouldUnbindServiceFromActivity() {
val activityPluginBinding = mock(ActivityPluginBinding::class.java)
bluetoothService.bind(activityPluginBinding)
bluetoothService.unbind()
verify(activityPluginBinding).removeActivityResultListener(bluetoothService)
}
@Test
fun shouldOpenBluetoothSettings() {
val activityPluginBinding = mock(ActivityPluginBinding::class.java)
val activity = mock(Activity::class.java)
bluetoothService.bind(activityPluginBinding)
`when`(activityPluginBinding.activity).thenReturn(activity)
`when`(activity.startActivityForResult(any(), eq(REQUEST_CODE_BLUETOOTH))).then {
bluetoothService.onActivityResult(REQUEST_CODE_BLUETOOTH, Activity.RESULT_OK, null)
}
var callbackCalled = false
bluetoothService.openSettings { callbackCalled = true }
assertThat(callbackCalled, `is`(true))
}
}
| 0 | Swift | 0 | 0 | 361b91e4084851dc015663788a21051e9eb3a314 | 2,499 | beacon_monitoring | MIT License |
src/test/kotlin/no/nav/familie/baks/mottak/søknad/SøknadTest.kt | navikt | 221,166,975 | false | null | package no.nav.familie.baks.mottak.søknad
import no.nav.familie.baks.mottak.DevLauncherPostgres
import no.nav.familie.baks.mottak.søknad.barnetrygd.BarnetrygdSøknadService
import no.nav.familie.baks.mottak.søknad.barnetrygd.domene.DBBarnetrygdSøknad
import no.nav.familie.baks.mottak.søknad.barnetrygd.domene.SøknadV8
import no.nav.familie.baks.mottak.søknad.barnetrygd.domene.tilDBSøknad
import no.nav.familie.baks.mottak.util.DbContainerInitializer
import no.nav.familie.kontrakter.felles.objectMapper
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
import kotlin.test.assertEquals
@ExtendWith(SpringExtension::class)
@ContextConfiguration(initializers = [DbContainerInitializer::class])
@ActiveProfiles("postgres")
@Tag("integration")
@SpringBootTest(classes = [DevLauncherPostgres::class])
class SøknadTest(
@Autowired val barnetrygdSøknadService: BarnetrygdSøknadService,
) {
val søknadV8 = SøknadTestData.søknadV8()
@Test
fun `Lagring av søknad`() {
val dbSøknadFraMapper = søknadV8.tilDBSøknad()
assertThat(dbSøknadFraMapper.hentVersjonertSøknad() is SøknadV8).isTrue
val dbSøknadFraDB = barnetrygdSøknadService.lagreDBSøknad(dbSøknadFraMapper)
val hentetSøknad = barnetrygdSøknadService.hentDBSøknad(dbSøknadFraDB.id)
assertEquals(dbSøknadFraDB.id, hentetSøknad!!.id)
assertThat(hentetSøknad.hentVersjonertSøknad() is SøknadV8)
}
@Test
fun `Få riktig versjon v8 ved mapping fra DBSøknad`() {
val dbSøknadFraMapper = søknadV8.tilDBSøknad()
val versjon: Int? =
when (val versjonertSøknad = dbSøknadFraMapper.hentVersjonertSøknad()) {
is SøknadV8 -> versjonertSøknad.søknad.kontraktVersjon
else -> {
null
}
}
assertEquals(søknadV8.kontraktVersjon, versjon)
val dbSøknadFraDB = barnetrygdSøknadService.lagreDBSøknad(dbSøknadFraMapper)
val hentetSøknad = barnetrygdSøknadService.hentDBSøknad(dbSøknadFraDB.id)
assertEquals(dbSøknadFraDB.id, hentetSøknad!!.id)
assertThat(hentetSøknad.hentVersjonertSøknad() is SøknadV8).isTrue
}
@Test
fun `Version detection ved henting av søknad fra database`() {
val lagraV8SøknadData = objectMapper.writeValueAsString(SøknadTestData.søknadV8())
val v8DbBarnetrygdSøknad =
DBBarnetrygdSøknad(
id = 2L,
søknadJson = lagraV8SøknadData,
fnr = "1234123412",
)
assertThat(v8DbBarnetrygdSøknad.hentVersjonertSøknad() is SøknadV8).isTrue
}
}
| 5 | null | 0 | 2 | c01ed56945453f13b9fb959cb0a57d0231c64050 | 3,043 | familie-baks-mottak | MIT License |
app/src/main/java/com/vultisig/wallet/ui/screens/vault_settings/VaultSettingsViewModel.kt | vultisig | 789,965,982 | false | {"Kotlin": 678690} | package com.vultisig.wallet.ui.screens.vault_settings
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.vultisig.wallet.common.Utils
import com.vultisig.wallet.data.on_board.db.VaultDB
import com.vultisig.wallet.data.on_board.db.VaultDB.Companion.FILE_POSTFIX
import com.vultisig.wallet.models.Vault
import com.vultisig.wallet.ui.navigation.Destination
import com.vultisig.wallet.ui.navigation.Navigator
import com.vultisig.wallet.ui.screens.vault_settings.VaultSettingsEvent.Backup
import com.vultisig.wallet.ui.screens.vault_settings.VaultSettingsEvent.Delete
import com.vultisig.wallet.ui.screens.vault_settings.VaultSettingsEvent.ErrorDownloadFile
import com.vultisig.wallet.ui.screens.vault_settings.VaultSettingsEvent.SuccessBackup
import com.vultisig.wallet.ui.screens.vault_settings.VaultSettingsUiEvent.BackupFailed
import com.vultisig.wallet.ui.screens.vault_settings.VaultSettingsUiEvent.BackupFile
import com.vultisig.wallet.ui.screens.vault_settings.VaultSettingsUiEvent.BackupSuccess
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import javax.inject.Inject
@HiltViewModel
internal open class VaultSettingsViewModel @Inject constructor(
private val vaultDB: VaultDB,
savedStateHandle: SavedStateHandle,
private val navigator: Navigator<Destination>,
) : ViewModel() {
private val vaultId: String =
savedStateHandle.get<String>(Destination.VaultSettings.ARG_VAULT_ID)!!
val vault: Vault? = vaultDB.select(vaultId)
private val channel = Channel<VaultSettingsUiEvent>()
val channelFlow = channel.receiveAsFlow()
fun onEvent(event: VaultSettingsEvent) {
when (event) {
Backup -> backupVault()
Delete -> deleteVault()
ErrorDownloadFile -> errorBackUp()
is SuccessBackup -> successBackup(event.fileName)
}
}
private fun successBackup(fileName: String) {
viewModelScope.launch {
channel.send(BackupSuccess(fileName + FILE_POSTFIX))
}
}
private fun errorBackUp() {
viewModelScope.launch {
channel.send(BackupFailed)
}
}
private fun backupVault() {
viewModelScope.launch {
vault?.let {
val thresholds = Utils.getThreshold(it.signers.count())
val date = Date()
val format = SimpleDateFormat("yyyy-MM")
val formattedDate = format.format(date)
val fileName =
"vultisig-${it.name}-$formattedDate-${thresholds + 1}of${it.signers.count()}-${
it.pubKeyECDSA.takeLast(4)
}-${it.localPartyID}.dat"
channel.send(BackupFile(it.name, fileName))
}
}
}
private fun deleteVault() {
viewModelScope.launch {
vaultDB.delete(vaultId)
navigator.navigate(Destination.Home)
}
}
} | 13 | Kotlin | 0 | 2 | 75d1359a25f8eec8f855cc27787ef05cd0e3cbc6 | 3,172 | vultisig-android | Apache License 2.0 |
java/idea-ui/src/com/intellij/ide/projectWizard/generators/IntelliJJavaBuildSystemType.kt | baimuchengling | 402,478,098 | true | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.projectWizard.generators
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.ide.util.projectWizard.JavaModuleBuilder
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.UIBundle
import com.intellij.ui.layout.*
import java.nio.file.Paths
class IntelliJJavaBuildSystemType : JavaBuildSystemType {
override val name = "IntelliJ"
override fun createStep(context: WizardContext) = Step(context)
class Step(context: WizardContext) : NewProjectWizardStep(context) {
var moduleName: String = ""
var contentRoot: String = ""
var moduleFileLocation: String = ""
override fun setupUI(builder: RowBuilder) {
with(builder) {
hideableRow(UIBundle.message("label.project.wizard.new.project.advanced.settings")) {
row(UIBundle.message("label.project.wizard.new.project.module.name")) {
textField(::moduleName)
}
row(UIBundle.message("label.project.wizard.new.project.content.root")) {
textFieldWithBrowseButton(::contentRoot,
UIBundle.message("label.project.wizard.new.project.content.root.title"), context.project,
FileChooserDescriptorFactory.createSingleFolderDescriptor())
}
row(UIBundle.message("label.project.wizard.new.project.module.file.location")) {
textFieldWithBrowseButton(::moduleFileLocation,
UIBundle.message("label.project.wizard.new.project.module.file.location.title"), context.project,
FileChooserDescriptorFactory.createSingleFolderDescriptor())
}
}
}
}
override fun setupProject(project: Project) {
val builder = JavaModuleBuilder()
val moduleFile = Paths.get(moduleFileLocation, moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION)
builder.name = moduleName
builder.moduleFilePath = FileUtil.toSystemDependentName(moduleFile.toString())
builder.contentEntryPath = FileUtil.toSystemDependentName(contentRoot)
builder.moduleJdk = JavaNewProjectWizard.SdkStep.getSdk(context)
builder.commit(project)
}
}
} | 0 | null | 0 | 0 | de611590e0fbe93d47a6ce4d87318838e188af8c | 2,515 | intellij-community | Apache License 2.0 |
src/main/kotlin/venus/simulator/impls/SBImpl.kt | hiporox | 98,627,941 | true | {"Kotlin": 124095, "HTML": 9018, "JavaScript": 2502, "CSS": 840} | package venus.simulator.impls
import venus.simulator.impls.types.STypeImpl
import venus.simulator.Simulator
object SBImpl : STypeImpl() {
override fun evaluate(sim: Simulator, addr: Int, vrs2: Int) {
sim.storeByte(addr, vrs2)
}
}
| 0 | Kotlin | 0 | 0 | 606d6f8185b1646b5f5f9f512a1c702994e355b7 | 248 | venus | MIT License |
plugins/jvm-abi-gen/testData/compare/inlineFunUsageMakesAbiUnstable/sameAbi/test.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | package test
private fun main() {
//comment should not break ABI
inlineFun()
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 88 | kotlin | Apache License 2.0 |
project_versions/14_ImplementandoHATEOAS/rest-with-spring-boot-and-kotlin-aws-miagui/src/main/kotlin/br/com/miagui/exceptions/handler/CustomizedResponseEntityExceptionHandler.kt | thiagotsartore | 584,764,151 | false | null | package br.com.miagui.exceptions.handler
import br.com.miagui.exceptions.ExceptionResponse
import br.com.miagui.exceptions.RequiredObjectsIsNullException
import br.com.miagui.exceptions.ResourceNotFoundException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.context.request.WebRequest
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
import java.lang.Exception
import java.util.*
@ControllerAdvice
@RestController
class CustomizedResponseEntityExceptionHandler: ResponseEntityExceptionHandler() {
@ExceptionHandler(Exception::class)
fun handleAllExceptions (ex: Exception, request: WebRequest):
ResponseEntity<ExceptionResponse> {
val exceptionResponse = ExceptionResponse(
Date(),
ex.message,
request.getDescription(false)
)
return ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR)
}
@ExceptionHandler(ResourceNotFoundException::class)
fun handleResourceNotFoundExceptions (ex: Exception, request: WebRequest):
ResponseEntity<ExceptionResponse> {
val exceptionResponse = ExceptionResponse(
Date(),
ex.message,
request.getDescription(false)
)
return ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_FOUND)
}
@ExceptionHandler(RequiredObjectsIsNullException::class)
fun handleBadRequestExceptions (ex: Exception, request: WebRequest):
ResponseEntity<ExceptionResponse> {
val exceptionResponse = ExceptionResponse(
Date(),
ex.message,
request.getDescription(false)
)
return ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.BAD_REQUEST)
}
} | 0 | Kotlin | 0 | 0 | cc6498141980a0118edc5daffa9242573eb290a3 | 2,073 | rest-with-spring-boot-and-kotlin-aws-miagui | Apache License 2.0 |
feature-account-impl/src/main/java/io/novafoundation/nova/feature_account_impl/domain/account/export/json/validations/ExportJsonPasswordValidationPayload.kt | novasamatech | 415,834,480 | false | null | package com.edgeverse.wallet.feature_account_impl.domain.account.export.json.validations
class ExportJsonPasswordValidationPayload(
val password: String,
val passwordConfirmation: String,
)
| 11 | null | 6 | 9 | b39307cb56302ce7298582dbd03f33f6b2e2a807 | 199 | nova-wallet-android | Apache License 2.0 |
app/src/main/java/com/cozo/cozomvp/userprofile/ProfileServiceModel.kt | joaophellip | 146,646,270 | false | null | package com.cozo.cozomvp.userprofile
import com.cozo.cozomvp.helpers.IdleResourceInterceptor
import com.cozo.cozomvp.paymentactivity.PaymentActivity
import io.reactivex.Observable
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import java.io.File
class ProfileServiceModel {
constructor(baseUrl: String? = null) {
if (baseUrl == null) {
profileServiceAPI = ProfileServiceAPI.create()
} else {
profileServiceAPI = ProfileServiceAPI.create(baseUrl)
}
}
private val profileServiceAPI: ProfileServiceAPI
fun uploadUserProfileToBackEnd(userModel: UserModel): Observable<ResponseBody> {
return profileServiceAPI.createUserProfile(userModel)
}
fun uploadUserAvatarToStorage(userId: String, image: File): Observable<String> {
val reqFile = RequestBody.create(MediaType.parse("image/*"), image)
val body = MultipartBody.Part.createFormData("upload", userId, reqFile)
return profileServiceAPI.saveUserAvatar(userId, body)
}
fun updateUserPaymentExternalIdToBackEnd(userId: String, externalId: String){
profileServiceAPI.saveUserExternalId(userId, externalId)
}
fun addUserFundingInstrumentToBackEnd(userId: String, fundingInstrument: PaymentActivity.CardData){
profileServiceAPI.saveUserCreditCard(userId, fundingInstrument)
}
fun setFavoriteUserFundingInstrumentToBackEnd(userId: String, cardId: String){
profileServiceAPI.saveFavoriteCreditCard(userId, cardId)
}
fun getFavoriteUserFundingInstrumentFromBackEnd(userId: String) : Observable<String?> {
return profileServiceAPI.getUserFavoriteCreditCard(userId)
}
fun loadUserProfileFromBackEnd(token: String): Observable<UserModel>{
IdleResourceInterceptor.getInstance().stackCall("ProfileServiceModel - loadUserProfileFromBackEnd")
return profileServiceAPI.loadUserProfile(token)
}
} | 5 | Kotlin | 0 | 2 | 8a5f1b18875ccde6e742be9909a39419a27cfaaf | 1,994 | MVP | Apache License 2.0 |
app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksAdapter.kt | jasper55 | 192,397,303 | false | null | package com.example.android.architecture.blueprints.todoapp.tasks
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import androidx.databinding.DataBindingUtil
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.databinding.TaskItemBinding
class TasksAdapter(
private var tasks: List<Task>,
private val tasksViewModel: TasksViewModel
) : BaseAdapter() {
fun replaceData(tasks: List<Task>) {
setList(tasks)
}
override fun getCount() = tasks.size
override fun getItem(position: Int) = tasks[position]
override fun getItemId(position: Int) = position.toLong()
override fun getView(position: Int, view: View?, viewGroup: ViewGroup): View {
val binding: TaskItemBinding
binding = if (view == null) {
// Inflate
val inflater = LayoutInflater.from(viewGroup.context)
// Create the binding
TaskItemBinding.inflate(inflater, viewGroup, false)
} else {
// Recycling view
DataBindingUtil.getBinding(view) ?: throw IllegalStateException()
}
val userActionsListener = object : TaskItemUserActionsListener {
override fun onFavoriteChanged(task: Task, v: View) {
val checked = (v as CheckBox).isChecked
tasksViewModel.favorTask(task, checked)
}
override fun onCompleteChanged(task: Task, v: View) {
val checked = (v as CheckBox).isChecked
tasksViewModel.completeTask(task, checked)
}
override fun onTaskClicked(task: Task) {
tasksViewModel.openTask(task.id)
}
}
with(binding) {
task = tasks[position]
listener = userActionsListener
executePendingBindings()
}
return binding.root
}
private fun setList(tasks: List<Task>) {
this.tasks = tasks
notifyDataSetChanged()
}
}
| 0 | Kotlin | 0 | 0 | adbb376fc080449128162c4ae7ac8dad93f193d6 | 2,157 | Todo_MVVM_Kotlin | Apache License 2.0 |
src/main/kotlin/no/nav/bidrag/arbeidsflyt/model/OppgaverForHendelse.kt | navikt | 295,692,779 | false | null | package no.nav.bidrag.arbeidsflyt.model
data class OppgaverForHendelse(val dataForHendelse: List<OppgaveDataForHendelse>) {
fun erEndringAvTildeltEnhetsnummer(journalpostHendelse: JournalpostHendelse): Boolean {
return journalpostHendelse.harEnhet() && dataForHendelse.stream()
.filter { journalpostHendelse.enhet != it.tildeltEnhetsnr }
.findAny().isPresent
}
fun erEndringAvAktoerId(journalpostHendelse: JournalpostHendelse): Boolean {
return journalpostHendelse.harAktorId() && dataForHendelse.stream()
.filter { journalpostHendelse.aktorId != it.aktorId }
.findAny().isPresent
}
fun harIkkeJournalforingsoppgaveForJournalpost(journalpostHendelse: JournalpostHendelse): Boolean {
return dataForHendelse.isEmpty() || dataForHendelse.stream()
.filter { it.oppgavetype == JOURNALFORINGSOPPGAVE }
.filter { it.journalpostId == journalpostHendelse.hentJournalpostIdUtenPrefix() || it.journalpostId == journalpostHendelse.journalpostId }
.findAny().isEmpty
}
fun harJournalforingsoppgaver() = dataForHendelse
.find { it.oppgavetype == JOURNALFORINGSOPPGAVE } != null
fun hentJournalforingsOppgaver() = dataForHendelse.filter { it.oppgavetype == JOURNALFORINGSOPPGAVE }
}
| 2 | Kotlin | 0 | 1 | 8a550416c3994108318d153a7c071c022df44a36 | 1,322 | bidrag-arbeidsflyt | MIT License |
local/local/src/main/java/com/nimbusframework/nimbuslocal/deployment/webserver/WebServerHandler.kt | thomasjallerton | 163,180,980 | false | {"YAML": 3, "Ignore List": 2, "XML": 4, "Maven POM": 9, "Dockerfile": 1, "Text": 1, "Markdown": 35, "Kotlin": 570, "Java": 167, "JSON": 2, "JavaScript": 4, "SVG": 4, "CSS": 1} | package com.nimbusframework.nimbuslocal.deployment.webserver
import com.nimbusframework.nimbuscore.annotations.function.HttpMethod
import com.nimbusframework.nimbuslocal.deployment.http.HttpMethodIdentifier
import org.eclipse.jetty.server.Request
import org.eclipse.jetty.server.handler.AbstractHandler
import com.nimbusframework.nimbuslocal.deployment.http.LocalHttpMethod
import com.nimbusframework.nimbuslocal.deployment.webserver.resources.FileResource
import com.nimbusframework.nimbuslocal.deployment.webserver.resources.FunctionResource
import com.nimbusframework.nimbuslocal.deployment.webserver.resources.WebResource
import java.io.File
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
open class WebServerHandler(private val indexFile: String,
private val errorFile: String,
private val basePath: String
): AbstractHandler() {
private val resources: MutableMap<HttpMethodIdentifier, WebResource> = mutableMapOf()
private var errorResource: WebResource? = null
override fun handle(
target: String,
baseRequest: Request,
request: HttpServletRequest,
response: HttpServletResponse
) {
val httpMethod = HttpMethod.valueOf(request.method)
var webResource: WebResource? = null
for ((identifier, resource) in resources) {
if (identifier.matches(target, httpMethod)) {
webResource = resource
break
}
}
if (webResource != null) {
if (passesCors(webResource, request)) {
webResource.writeResponse(request, response, target)
} else {
response.status = HttpServletResponse.SC_UNAUTHORIZED
response.writer.println("CORS prevented access to this resource ($target). Check logs for more details.")
response.writer.close()
}
} else {
if (errorResource != null) {
errorResource!!.writeResponse(request, response, target)
} else {
response.status = HttpServletResponse.SC_NOT_FOUND
response.writer.close()
}
}
baseRequest.isHandled = true
}
fun addWebResource(path: String, file: File, contentType: String, allowedOrigins: List<String>) {
addNewResource(path, HttpMethod.GET, FileResource(file, contentType, allowedOrigins, combinePaths(path)))
}
fun addWebResource(path: String, httpMethod: HttpMethod, method: LocalHttpMethod, allowedOrigin: String, allowedHeaders: Array<String>) {
addNewResource(path, httpMethod, FunctionResource(path, httpMethod, method, allowedHeaders, allowedOrigin, combinePaths(path)))
}
private fun addNewResource(path: String, httpMethod: HttpMethod, webResource: WebResource) {
val fixedPath = if (path.isNotEmpty()) "/$path" else path
resources[HttpMethodIdentifier(fixedPath, httpMethod)] = webResource
if (path == indexFile) {
resources[HttpMethodIdentifier("/", HttpMethod.GET)] = webResource
}
if (path == errorFile) {
errorResource = webResource
}
}
fun addRedirectResource(path: String, httpMethod: HttpMethod, webResource: WebResource) {
val fixedPath = if (path.isNotEmpty()) "/$path" else path
resources[HttpMethodIdentifier(fixedPath, httpMethod)] = webResource
}
private fun passesCors(webResource: WebResource, request: HttpServletRequest): Boolean {
val headersToCheck = request.getHeader("Access-Control-Request-Headers")?.split(",")
//Check Access-Control-Request-Headers headers
if (headersToCheck != null) {
if (!webResource.checkCorsHeaders(headersToCheck)) return false
}
//Check origin
val referer = request.getHeader("Referer")
if (referer != null) {
return webResource.checkCorsOrigin(referer)
}
return true
}
private fun combinePaths(path: String): String {
return when {
basePath.endsWith("/") and !path.startsWith("/") -> basePath + path
!basePath.endsWith("/") and path.startsWith("/") -> basePath + path
else -> "$basePath/$path"
}
}
} | 6 | Kotlin | 5 | 39 | 5c3325caaf3fe9de9ffad130fd1e773c6f680e89 | 4,370 | nimbus-framework | MIT License |
PhoenixPenNG/libgame/src/main/java/com/phoenixpen/game/simulation/System.kt | nshcat | 182,317,693 | false | {"Text": 2, "Ignore List": 4, "Markdown": 1, "Gradle": 5, "INI": 1, "Shell": 6, "Batchfile": 1, "GLSL": 12, "JSON": 28, "Java Properties": 1, "XML": 15, "Kotlin": 213, "Java": 6, "C": 2} | package com.phoenixpen.game.simulation
import com.phoenixpen.game.core.Updateable
/**
* An abstract base class for all simulation systems
*
* @property simulation The current simulation state
*/
abstract class System(val simulation: Simulation): Updateable
{
/**
* The current resource provider
*/
protected val resources = this.simulation.resources
} | 0 | Kotlin | 0 | 1 | 8e29e78b8f3d1ff7bdfedfd7c872b1ac69dd665d | 375 | phoenixpen_ng | MIT License |
sdk/src/androidTest/java/com/minapp/android/sdk/test/table/GeoTest.kt | ifanrx | 178,979,868 | false | null | package com.minapp.android.sdk.test.table
import com.minapp.android.sdk.database.GeoPoint
import com.minapp.android.sdk.database.GeoPolygon
import com.minapp.android.sdk.database.query.Query
import com.minapp.android.sdk.database.query.Where
import org.junit.Assert.*
import org.junit.Test
class GeoTest: BaseTableTest() {
/**
* 腾讯地图
* 复杂查询测试: withinCircle, withIn
*/
@Test
fun queryTest() {
val zoo = table.createRecord().apply {
put(TableContract.NAME, "动物园")
put(TableContract.LOCATION, GeoPoint(113.3072f, 23.1347f))
save()
}
val martyrsPark = table.createRecord().apply {
put(TableContract.NAME, "烈士陵园")
put(TableContract.LOCATION, GeoPoint(113.2855f, 23.1264f))
save()
}
val cantonTower = table.createRecord().apply {
put(TableContract.NAME, "广州塔")
put(TableContract.LOCATION, GeoPoint(113.3232f, 23.1065f))
save()
}
val sysu = table.createRecord().apply {
put(TableContract.NAME, "中大")
put(TableContract.LOCATION, GeoPoint(113.2931f, 23.0921f))
save()
}
// 东山口附近 2km 内包含「烈士陵园」,「动物园」
var result = table.query(Query().apply {
put(Where().apply {
withinCircle(TableContract.LOCATION, GeoPoint(113.2953f, 23.1239f), 2f)
})
})
assertTrue(result.objects!!.all { it in arrayOf(martyrsPark, zoo) })
// 五羊邨附近 (2, 5) 内包含「无」
result = table.query(Query().apply {
put(Where().apply {
withinRegion(TableContract.LOCATION, GeoPoint(113.3144f, 23.1199f), 5f, 2f)
})
})
assertTrue(result.objects.isNullOrEmpty())
// 晓港 - 江泰路 - 鹭江 之间包含「中大」
result = table.query(Query().apply {
put(Where().apply {
// 晓港 - 江泰路 - 鹭江
withIn(
TableContract.LOCATION, GeoPolygon(listOf(
GeoPoint(113.2817f, 23.0927f),
GeoPoint(113.2806f, 23.0825f),
GeoPoint(113.3080f, 23.0949f),
GeoPoint(113.2817f, 23.0927f)
)))
})
})
assertTrue(result.objects!!.all { it == sysu })
}
/**
* 复杂查询测试: include
* 腾讯地图
*/
@Test
fun includeTest() {
table.batchDelete(Query())
// 广州塔 - 客村 - 赤岗
val tit = table.createRecord().apply {
put(TableContract.NAME, "T.I.T")
put(
TableContract.LOCATION, GeoPolygon(listOf(
GeoPoint(113.3236f, 23.1063f),
GeoPoint(113.3201f, 23.0964f),
GeoPoint(113.3347f, 23.0966f),
GeoPoint(113.3236f, 23.1063f)
))
)
save()
}
// 黄埔大道 - 五羊邨 - 海心沙 - 猎德
val cbd = table.createRecord().apply {
put(TableContract.NAME, "CBD")
put(
TableContract.LOCATION, GeoPolygon(listOf(
GeoPoint(113.3244f, 23.1273f),
GeoPoint(113.3143f, 23.1201f),
GeoPoint(113.3242f, 23.1113f),
GeoPoint(113.3326f, 23.1188f),
GeoPoint(113.3244f, 23.1273f)
))
)
save()
}
// 丽园雅庭
val housing = GeoPoint(113.3261f, 23.0977f)
// 花城大道
val centerStreet = GeoPoint(113.3247f, 23.1193f)
var result = table.query(Query().apply {
put(Where().apply {
include(TableContract.LOCATION, housing)
})
})
assertEquals(result.objects.size, 1)
assertEquals(result.objects.first().id, tit.id)
result = table.query(Query().apply {
put(Where().apply {
include(TableContract.LOCATION, centerStreet)
})
})
assertEquals(result.objects.size, 1)
assertEquals(result.objects.first().id, cbd.id)
}
} | 1 | null | 1 | 1 | 6e4a222ae69e2e26e981f1a4345c20caece49520 | 4,068 | hydrogen-android-sdk | Apache License 2.0 |
app/src/main/java/fr/azhot/weatherapp/presentation/MainViewModel.kt | Azhot | 353,679,211 | false | null | package fr.azhot.weatherapp.presentation
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import fr.azhot.weatherapp.domain.model.City
import java.util.*
import javax.inject.Inject
import kotlin.Comparator
@HiltViewModel
class MainViewModel @Inject constructor(
application: Application,
) : AndroidViewModel(application) {
// todo : this viewModel should hold a LiveData of cities coming from Room database.
// addCity and removeCity should then perform relevant actions on the database, changes applied
// being then observe through the LiveData.
private val _cities: MutableLiveData<SortedSet<City>> = MutableLiveData()
val cities: LiveData<SortedSet<City>>
get() = _cities
init {
_cities.value = sortedSetOf(Comparator<City> { o1, o2 ->
o1?.name.toString().compareTo(o2?.name.toString())
})
}
fun addCity(city: City) {
_cities.value?.add(city)
_cities.value = _cities.value
}
fun removeCity(city: City) {
_cities.value?.remove(city)
_cities.value = _cities.value
}
} | 0 | Kotlin | 0 | 0 | d21a1f4fb91a9e402d664f18001c4111b2bf6d34 | 1,249 | WeatherApp | MIT License |
app/src/main/java/com/forestmouse/samples/streaming/api/ApiResult.kt | mortenskovhus | 268,904,126 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Text": 1, "Proguard": 1, "Java": 2, "XML": 22, "Kotlin": 23} | package com.forestmouse.samples.streaming.api
sealed class ApiResult<out T : Any> {
data class Success<out T : Any>(val output: T) : ApiResult<T>()
data class Error(val exception: Exception) : ApiResult<Nothing>()
}
| 1 | null | 1 | 1 | 9e45e58dafcbc20ea3d16944c6f959ae55e10d7b | 226 | TestStreamingApp | Apache License 2.0 |
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/PaletteSolid.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36756847} | package compose.icons.lineawesomeicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.PaletteSolid: ImageVector
get() {
if (_paletteSolid != null) {
return _paletteSolid!!
}
_paletteSolid = Builder(name = "PaletteSolid", defaultWidth = 32.0.dp, defaultHeight =
32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.5938f, 2.9688f)
curveTo(15.0625f, 2.9844f, 14.5156f, 3.043f, 13.9688f, 3.125f)
lineTo(13.9375f, 3.125f)
curveTo(8.6133f, 3.9961f, 4.3008f, 8.1914f, 3.2188f, 13.5f)
curveTo(2.8945f, 15.0117f, 2.9141f, 16.4219f, 3.125f, 17.8125f)
curveTo(3.1328f, 17.8164f, 3.125f, 17.8359f, 3.125f, 17.8438f)
curveTo(3.4531f, 20.1914f, 6.5f, 21.2188f, 8.2188f, 19.5f)
curveTo(9.4492f, 18.2695f, 11.2695f, 18.2695f, 12.5f, 19.5f)
curveTo(13.7305f, 20.7305f, 13.7305f, 22.5508f, 12.5f, 23.7813f)
curveTo(10.7813f, 25.5f, 11.8086f, 28.5469f, 14.1563f, 28.875f)
curveTo(14.1641f, 28.875f, 14.1836f, 28.8672f, 14.1875f, 28.875f)
curveTo(15.5664f, 29.0859f, 16.9688f, 29.0977f, 18.4688f, 28.7813f)
curveTo(18.4805f, 28.7813f, 18.4883f, 28.7813f, 18.5f, 28.7813f)
curveTo(23.8242f, 27.7891f, 28.0078f, 23.375f, 28.875f, 18.0625f)
lineTo(28.875f, 18.0313f)
curveTo(30.0078f, 10.3906f, 24.4219f, 3.7188f, 17.1563f, 3.0313f)
curveTo(16.6367f, 2.9805f, 16.125f, 2.9531f, 15.5938f, 2.9688f)
close()
moveTo(15.625f, 4.9688f)
curveTo(16.0781f, 4.9531f, 16.5273f, 4.9609f, 16.9688f, 5.0f)
curveTo(23.1641f, 5.5664f, 27.875f, 11.2148f, 26.9063f, 17.75f)
curveTo(26.1758f, 22.2266f, 22.5859f, 25.9922f, 18.125f, 26.8125f)
lineTo(18.0938f, 26.8125f)
curveTo(16.8164f, 27.0859f, 15.6367f, 27.0898f, 14.4375f, 26.9063f)
curveTo(13.6172f, 26.8047f, 13.2383f, 25.8867f, 13.9063f, 25.2188f)
curveTo(15.875f, 23.25f, 15.875f, 20.0625f, 13.9063f, 18.0938f)
curveTo(11.9375f, 16.125f, 8.75f, 16.125f, 6.7813f, 18.0938f)
curveTo(6.1133f, 18.7617f, 5.1953f, 18.3828f, 5.0938f, 17.5625f)
curveTo(4.9102f, 16.3633f, 4.9141f, 15.1836f, 5.1875f, 13.9063f)
curveTo(6.1055f, 9.418f, 9.7734f, 5.8242f, 14.25f, 5.0938f)
curveTo(14.7188f, 5.0234f, 15.1719f, 4.9844f, 15.625f, 4.9688f)
close()
moveTo(14.0f, 7.0f)
curveTo(12.8945f, 7.0f, 12.0f, 7.8945f, 12.0f, 9.0f)
curveTo(12.0f, 10.1055f, 12.8945f, 11.0f, 14.0f, 11.0f)
curveTo(15.1055f, 11.0f, 16.0f, 10.1055f, 16.0f, 9.0f)
curveTo(16.0f, 7.8945f, 15.1055f, 7.0f, 14.0f, 7.0f)
close()
moveTo(21.0f, 9.0f)
curveTo(19.8945f, 9.0f, 19.0f, 9.8945f, 19.0f, 11.0f)
curveTo(19.0f, 12.1055f, 19.8945f, 13.0f, 21.0f, 13.0f)
curveTo(22.1055f, 13.0f, 23.0f, 12.1055f, 23.0f, 11.0f)
curveTo(23.0f, 9.8945f, 22.1055f, 9.0f, 21.0f, 9.0f)
close()
moveTo(9.0f, 11.0f)
curveTo(7.8945f, 11.0f, 7.0f, 11.8945f, 7.0f, 13.0f)
curveTo(7.0f, 14.1055f, 7.8945f, 15.0f, 9.0f, 15.0f)
curveTo(10.1055f, 15.0f, 11.0f, 14.1055f, 11.0f, 13.0f)
curveTo(11.0f, 11.8945f, 10.1055f, 11.0f, 9.0f, 11.0f)
close()
moveTo(23.0f, 16.0f)
curveTo(21.8945f, 16.0f, 21.0f, 16.8945f, 21.0f, 18.0f)
curveTo(21.0f, 19.1055f, 21.8945f, 20.0f, 23.0f, 20.0f)
curveTo(24.1055f, 20.0f, 25.0f, 19.1055f, 25.0f, 18.0f)
curveTo(25.0f, 16.8945f, 24.1055f, 16.0f, 23.0f, 16.0f)
close()
moveTo(19.0f, 21.0f)
curveTo(17.8945f, 21.0f, 17.0f, 21.8945f, 17.0f, 23.0f)
curveTo(17.0f, 24.1055f, 17.8945f, 25.0f, 19.0f, 25.0f)
curveTo(20.1055f, 25.0f, 21.0f, 24.1055f, 21.0f, 23.0f)
curveTo(21.0f, 21.8945f, 20.1055f, 21.0f, 19.0f, 21.0f)
close()
}
}
.build()
return _paletteSolid!!
}
private var _paletteSolid: ImageVector? = null
| 15 | Kotlin | 20 | 460 | 651badc4ace0137c5541f859f61ffa91e5242b83 | 5,222 | compose-icons | MIT License |
src/main/kotlin/chart/difficulty/_obstacleCustomData.kt | TheRedKorsar | 303,352,689 | true | {"Kotlin": 197222} | package chart.difficulty
import com.google.gson.annotations.SerializedName
@Suppress("ClassName")
data class _obstacleCustomData(
@SerializedName("_position") val _position: List<Double>? = null,
@SerializedName("_scale") val _scale: List<Double>? = null,
@SerializedName("_color") val _color: List<Double>? = null,
@SerializedName("_rotation") val _rotation: List<Double>? = null,
@SerializedName("_localRotation") val _localRotation: List<Double>? = null,
@SerializedName("_track") var _track: String? = null,
@SerializedName("_noteJumpMovementSpeed") var _noteJumpMovementSpeed: Double? = null,
@SerializedName("_noteJumpStartBeatOffset ") var _noteJumpStartBeatOffset: Double? = null
)
| 0 | Kotlin | 0 | 0 | 430fc367d07104542904489960bd8602c160ceee | 725 | beatwalls | MIT License |
model/src/commonMain/kotlin/io/github/droidkaigi/feeder/TimetableCategory.kt | DroidKaigi | 283,062,475 | false | null | package io.github.droidkaigi.feeder
data class TimetableCategory(
val id: Int,
val title: MultiLangText,
)
| 45 | Kotlin | 189 | 633 | 3fb47a7b7b245e5a7c7c66d6c18cb7d2a7b295f2 | 116 | conference-app-2021 | Apache License 2.0 |
model/src/commonMain/kotlin/io/github/droidkaigi/feeder/TimetableCategory.kt | DroidKaigi | 283,062,475 | false | null | package io.github.droidkaigi.feeder
data class TimetableCategory(
val id: Int,
val title: MultiLangText,
)
| 45 | Kotlin | 189 | 633 | 3fb47a7b7b245e5a7c7c66d6c18cb7d2a7b295f2 | 116 | conference-app-2021 | Apache License 2.0 |
phoenix-android/src/main/kotlin/fr/acinq/phoenix/android/utils/datastore/InternalData.kt | ACINQ | 192,964,514 | false | {"C": 8424033, "Kotlin": 2181997, "Swift": 1451684, "Java": 39996, "HTML": 11266, "Dockerfile": 3570, "CMake": 2276, "CSS": 504} | /*
* Copyright 2022 ACINQ SAS
*
* 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 fr.acinq.phoenix.android.utils.datastore
import android.content.Context
import androidx.datastore.preferences.core.*
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.lightning.LiquidityEvents
import fr.acinq.lightning.MilliSatoshi
import fr.acinq.lightning.utils.currentTimestampMillis
import fr.acinq.lightning.utils.msat
import fr.acinq.phoenix.android.service.ChannelsWatcher
import fr.acinq.phoenix.legacy.internalData
import fr.acinq.phoenix.legacy.userPrefs
import fr.acinq.phoenix.legacy.utils.Prefs as LegacyPrefs
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.slf4j.LoggerFactory
import java.io.IOException
object InternalData {
private val log = LoggerFactory.getLogger(this::class.java)
private val json = Json { ignoreUnknownKeys = true }
// -- Firebase Cloud Messaging token.
private val FCM_TOKEN = stringPreferencesKey("FCM_TOKEN")
fun getFcmToken(context: Context): Flow<String?> = prefs(context).map { it[FCM_TOKEN] }
suspend fun saveFcmToken(context: Context, token: String) = context.internalData.edit { it[FCM_TOKEN] = token }
// -- Build code of the last Phoenix instance that has been run on the device. Used for migration purposes.
private val LAST_USED_APP_CODE = intPreferencesKey("LAST_USED_APP_CODE")
fun getLastUsedAppCode(context: Context): Flow<Int?> = prefs(context).map { it[LAST_USED_APP_CODE] }
suspend fun saveLastUsedAppCode(context: Context, code: Int) = context.internalData.edit { it[LAST_USED_APP_CODE] = code }
// -- When the user states that he made a manual backup of the seed
private val SEED_MANUAL_BACKUP_DONE = booleanPreferencesKey("SEED_MANUAL_BACKUP_DONE")
fun isManualSeedBackupDone(context: Context): Flow<Boolean> = prefs(context).map { it[SEED_MANUAL_BACKUP_DONE] ?: false }
suspend fun saveManualSeedBackupDone(context: Context, isDone: Boolean) = context.internalData.edit { it[SEED_MANUAL_BACKUP_DONE] = isDone }
// -- When the user has read the seed loss disclaimer
private val SEED_LOSS_DISCLAIMER_READ = booleanPreferencesKey("SEED_LOSS_DISCLAIMER_READ")
fun isSeedLossDisclaimerRead(context: Context): Flow<Boolean> = prefs(context).map { it[SEED_LOSS_DISCLAIMER_READ] ?: false }
suspend fun saveSeedLossDisclaimerRead(context: Context, isRead: Boolean) = context.internalData.edit { it[SEED_LOSS_DISCLAIMER_READ] = isRead }
// -- Whether a seed backup warning should be displayed - computed from SEED_MANUAL_BACKUP_DONE & SEED_LOSS_DISCLAIMER_READ
fun showSeedBackupNotice(context: Context) = prefs(context).map { it[SEED_MANUAL_BACKUP_DONE] != true || it[SEED_LOSS_DISCLAIMER_READ] != true }
// -- Show a notice when the migration has been done.
private val LEGACY_MIGRATION_MESSSAGE_SHOWN = booleanPreferencesKey("LEGACY_MIGRATION_MESSSAGE_SHOWN")
fun getLegacyMigrationMessageShown(context: Context): Flow<Boolean> = prefs(context).map { it[LEGACY_MIGRATION_MESSSAGE_SHOWN] ?: false }
suspend fun saveLegacyMigrationMessageShown(context: Context, isShown: Boolean) = context.internalData.edit { it[LEGACY_MIGRATION_MESSSAGE_SHOWN] = isShown }
// -- Show a dialog about the swap-in address change when the migration has been done.
private val LEGACY_MIGRATION_ADDRESS_WARNING_SHOWN = booleanPreferencesKey("LEGACY_MIGRATION_ADDRESS_WARNING_SHOWN")
fun getLegacyMigrationAddressWarningShown(context: Context): Flow<Boolean> = prefs(context).map { it[LEGACY_MIGRATION_ADDRESS_WARNING_SHOWN] ?: false }
suspend fun saveLegacyMigrationAddressWarningShown(context: Context, isShown: Boolean) = context.internalData.edit { it[LEGACY_MIGRATION_ADDRESS_WARNING_SHOWN] = isShown }
// -- Show introduction screen at startup. True by default.
private val SHOW_INTRO = booleanPreferencesKey("SHOW_INTRO")
fun getShowIntro(context: Context): Flow<Boolean> = prefs(context).map { it[SHOW_INTRO] ?: LegacyPrefs.showFTUE(context) }
suspend fun saveShowIntro(context: Context, showIntro: Boolean) = context.internalData.edit { it[SHOW_INTRO] = showIntro }
// -- Channels-watcher job result
private val CHANNELS_WATCHER_OUTCOME = stringPreferencesKey("CHANNELS_WATCHER_RESULT")
fun getChannelsWatcherOutcome(context: Context): Flow<ChannelsWatcher.Outcome?> = prefs(context).map {
it[CHANNELS_WATCHER_OUTCOME]?.let { json.decodeFromString(it) }
}
suspend fun saveChannelsWatcherOutcome(context: Context, outcome: ChannelsWatcher.Outcome) = context.internalData.edit {
it[CHANNELS_WATCHER_OUTCOME] = json.encodeToString(outcome)
}
// -- system notifications
/** Do not spam user with duplicate notifications for the same on-chain deposit. */
private val LAST_REJECTED_ONCHAIN_SWAP_AMOUNT = longPreferencesKey("LAST_REJECTED_ONCHAIN_SWAP_AMOUNT")
private val LAST_REJECTED_ONCHAIN_SWAP_TIMESTAMP = longPreferencesKey("LAST_REJECTED_ONCHAIN_SWAP_TIMESTAMP")
fun getLastRejectedOnchainSwap(context: Context): Flow<Pair<MilliSatoshi, Long>?> = prefs(context).map {
val amount = it[LAST_REJECTED_ONCHAIN_SWAP_AMOUNT]
val timestamp = it[LAST_REJECTED_ONCHAIN_SWAP_TIMESTAMP]
if (amount != null && timestamp != null) amount.msat to timestamp else null
}
suspend fun saveLastRejectedOnchainSwap(context: Context, liquidityEvent: LiquidityEvents.Rejected) = context.internalData.edit {
it[LAST_REJECTED_ONCHAIN_SWAP_AMOUNT] = liquidityEvent.amount.msat
it[LAST_REJECTED_ONCHAIN_SWAP_TIMESTAMP] = currentTimestampMillis()
}
private fun prefs(context: Context): Flow<Preferences> {
return context.internalData.data.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
}
} | 86 | C | 85 | 476 | 72bfce196c454065ecde403439c3fbc915966485 | 6,566 | phoenix | Apache License 2.0 |
src/commonTest/kotlin/baaahs/gl/ToolchainSpec.kt | baaahs | 174,897,412 | false | {"Kotlin": 3453815, "C": 1529197, "C++": 661364, "GLSL": 404582, "HTML": 55183, "JavaScript": 53132, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450} | package baaahs.gl
import baaahs.describe
import baaahs.only
import baaahs.show.Shader
import ch.tutteli.atrium.api.fluent.en_GB.startsWith
import ch.tutteli.atrium.api.verbs.expect
import org.spekframework.spek2.Spek
object ToolchainSpec : Spek({
describe<Toolchain> {
val toolchain by value { RootToolchain(testPlugins()) }
context("analyze") {
val shaderText by value {
Shader(
"Title",
"""
struct Whatever {
float a;
float b;
}
void main() { ... };
""".trimIndent()
)
}
it("catches analyzer exceptions") {
val analysis = toolchain.analyze(shaderText)
expect(analysis.errors.only().message)
.startsWith("huh? couldn't find a struct")
}
}
}
}) | 107 | Kotlin | 12 | 40 | 2aca7de985798cd222b8427841052742cf0fe453 | 999 | sparklemotion | MIT License |
ui-lib/src/main/java/co/electriccoin/zcash/ui/screen/home/AndroidHome.kt | Electric-Coin-Company | 390,808,594 | false | {"Kotlin": 983647} | @file:Suppress("ktlint:standard:filename")
package co.electriccoin.zcash.ui.screen.home
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.viewModels
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.res.stringResource
import cash.z.ecc.android.sdk.model.ZecSend
import co.electriccoin.zcash.ui.MainActivity
import co.electriccoin.zcash.ui.R
import co.electriccoin.zcash.ui.common.viewmodel.HomeViewModel
import co.electriccoin.zcash.ui.screen.account.WrapAccount
import co.electriccoin.zcash.ui.screen.balances.WrapBalances
import co.electriccoin.zcash.ui.screen.home.model.TabItem
import co.electriccoin.zcash.ui.screen.home.view.Home
import co.electriccoin.zcash.ui.screen.receive.WrapReceive
import co.electriccoin.zcash.ui.screen.send.WrapSend
import co.electriccoin.zcash.ui.screen.send.model.SendArguments
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
@Composable
@Suppress("LongParameterList")
internal fun MainActivity.WrapHome(
onPageChange: (HomeScreenIndex) -> Unit,
goBack: () -> Unit,
goSettings: () -> Unit,
goMultiTrxSubmissionFailure: () -> Unit,
goScan: () -> Unit,
goSendConfirmation: (ZecSend) -> Unit,
sendArguments: SendArguments
) {
WrapHome(
this,
onPageChange = onPageChange,
goBack = goBack,
goScan = goScan,
goSendConfirmation = goSendConfirmation,
goSettings = goSettings,
goMultiTrxSubmissionFailure = goMultiTrxSubmissionFailure,
sendArguments = sendArguments
)
}
@Suppress("LongParameterList", "LongMethod")
@Composable
internal fun WrapHome(
activity: ComponentActivity,
goBack: () -> Unit,
goSettings: () -> Unit,
goMultiTrxSubmissionFailure: () -> Unit,
goScan: () -> Unit,
goSendConfirmation: (ZecSend) -> Unit,
onPageChange: (HomeScreenIndex) -> Unit,
sendArguments: SendArguments
) {
val homeViewModel by activity.viewModels<HomeViewModel>()
// Flow for propagating the new page index to the pager in the view layer
val forceHomePageIndexFlow: MutableSharedFlow<ForcePage?> =
MutableSharedFlow(
Int.MAX_VALUE,
Int.MAX_VALUE,
BufferOverflow.SUSPEND
)
val forceIndex = forceHomePageIndexFlow.collectAsState(initial = null).value
val homeGoBack: () -> Unit = {
when (homeViewModel.screenIndex.value) {
HomeScreenIndex.ACCOUNT -> goBack()
HomeScreenIndex.SEND,
HomeScreenIndex.RECEIVE,
HomeScreenIndex.BALANCES -> forceHomePageIndexFlow.tryEmit(ForcePage(HomeScreenIndex.ACCOUNT))
}
}
BackHandler {
homeGoBack()
}
val tabs =
persistentListOf(
TabItem(
index = HomeScreenIndex.ACCOUNT,
title = stringResource(id = R.string.home_tab_account),
testTag = HomeTag.TAB_ACCOUNT,
screenContent = {
WrapAccount(
activity = activity,
goBalances = { forceHomePageIndexFlow.tryEmit(ForcePage(HomeScreenIndex.BALANCES)) },
goSettings = goSettings,
)
}
),
TabItem(
index = HomeScreenIndex.SEND,
title = stringResource(id = R.string.home_tab_send),
testTag = HomeTag.TAB_SEND,
screenContent = {
WrapSend(
activity = activity,
goToQrScanner = goScan,
goBack = homeGoBack,
goBalances = { forceHomePageIndexFlow.tryEmit(ForcePage(HomeScreenIndex.BALANCES)) },
goSendConfirmation = goSendConfirmation,
goSettings = goSettings,
sendArguments = sendArguments
)
}
),
TabItem(
index = HomeScreenIndex.RECEIVE,
title = stringResource(id = R.string.home_tab_receive),
testTag = HomeTag.TAB_RECEIVE,
screenContent = {
WrapReceive(
activity = activity,
onSettings = goSettings,
)
}
),
TabItem(
index = HomeScreenIndex.BALANCES,
title = stringResource(id = R.string.home_tab_balances),
testTag = HomeTag.TAB_BALANCES,
screenContent = {
WrapBalances(
activity = activity,
goSettings = goSettings,
goMultiTrxSubmissionFailure = goMultiTrxSubmissionFailure
)
}
)
)
Home(
subScreens = tabs,
forcePage = forceIndex,
onPageChange = onPageChange
)
}
/**
* Wrapper class used to pass forced pages index into the view layer
*/
class ForcePage(
val currentPage: HomeScreenIndex,
)
/**
* Enum of the Home screen sub-screens
*/
enum class HomeScreenIndex {
// WARN: Be careful when re-ordering these, as the ordinal number states for their order
ACCOUNT,
SEND,
RECEIVE,
BALANCES, ;
companion object {
fun fromIndex(index: Int) = entries[index]
}
}
| 183 | Kotlin | 11 | 19 | a8ad649ef8fdbc49a5c8be3a266dad64444f41d8 | 5,609 | zashi-android | MIT License |
app/src/main/java/com/tais/listadetarefascompose/datasource/DataSource.kt | TaisPorto | 689,840,754 | false | {"Kotlin": 29559} | package com.tais.listadetarefascompose.datasource
import com.google.firebase.firestore.FirebaseFirestore
import com.tais.listadetarefascompose.model.Tarefa
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class DataSource {
private val db = FirebaseFirestore.getInstance()
private val _todastarefas = MutableStateFlow< MutableList<Tarefa>>(mutableListOf())
private val todastarefas : StateFlow<MutableList<Tarefa>> = _todastarefas
fun salvarTarefa(tarefa: String, descricao: String, prioridade: Int) {
val tarefaMap = hashMapOf(
"tarefa" to tarefa,
"descricao" to descricao,
"prioridade" to prioridade
)
db.collection("tarefas").document(tarefa).set(tarefaMap).addOnCompleteListener {
}.addOnFailureListener {
}
}
fun recuperarTarefas() : Flow<MutableList <Tarefa>>{
val listadeTarefas: MutableList<Tarefa> = mutableListOf()
db.collection("tarefas").get().addOnCompleteListener { querySnapshot ->
if (querySnapshot.isSuccessful) {
for (documento in querySnapshot.result) {
val tarefa = documento.toObject(Tarefa:: class.java)
listadeTarefas.add(tarefa)
_todastarefas.value = listadeTarefas
}
}
}
return todastarefas
}
fun deletarTarefa( tarefa: String){
db.collection("tarefas").document(tarefa).delete().addOnCompleteListener {
}.addOnFailureListener {
}
}
}
| 0 | Kotlin | 0 | 0 | aa94095549fe4cdb046c52cbe40ed97eb6300f63 | 1,635 | ListadeTarefasCompose | MIT License |
telekt/src/main/kotlin/telekt/network/requests/edit/editMessageLiveLocation.kt | telekt | 173,566,083 | false | null | package rocks.waffle.telekt.network.requests.edit
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import rocks.waffle.telekt.network.TelegramMethod
import rocks.waffle.telekt.network.requests.abstracts.SimpleRequest
import rocks.waffle.telekt.types.Message
import rocks.waffle.telekt.types.replymarkup.ReplyMarkup
import rocks.waffle.telekt.util.Recipient
import rocks.waffle.telekt.util.serializer
/**
* [EditMessageLiveLocation] inline request.
* Use this method to edit live location messages sent via the bot (for inline bots).
* A location can be edited until its live_period expires or
* editing is explicitly disabled by a call to [StopMessageLiveLocationInline].
* More: https://core.telegram.org/bots/api#editmessagelivelocation
*/
@Serializable data class EditMessageLiveLocationInline(
/** Identifier of the inline message */
@SerialName("inline_message_id") val inlineMessageId: String,
/** Latitude of new location */
val latitude: Float,
/** Longitude of new location */
val longitude: Float,
/** A JSON-serialized object for a new inline keyboard. */
@SerialName("reply_markup") val replyMarkup: ReplyMarkup? = null
) : SimpleRequest<Unit>() {
@Transient override val method = TelegramMethod.editMessageLiveLocation
@Transient override val resultDeserializer: KSerializer<out Unit> = Unit.serializer()
override fun stringify(json: Json): String = json.stringify(EditMessageLiveLocationInline.serializer(), this)
}
/**
* [EditMessageLiveLocation] request.
* Use this method to edit live location messages sent by the bot.
* A location can be edited until its live_period expires or
* editing is explicitly disabled by a call to [StopMessageLiveLocation].
* On success, the edited Message is returned.
* More: https://core.telegram.org/bots/api#editmessagelivelocation
*/
@Serializable data class EditMessageLiveLocation(
/** Unique identifier for the target chat or username of the target channel (in the format @channelusername) */
@SerialName("chat_id") val chatId: Recipient,
/** Identifier of the sent message */
@SerialName("message_id") val messageId: Int,
/** Latitude of new location */
val latitude: Float,
/** Longitude of new location */
val longitude: Float,
/** A JSON-serialized object for a new inline keyboard. */
@SerialName("reply_markup") val replyMarkup: ReplyMarkup? = null
) : SimpleRequest<Message>() {
@Transient override val method = TelegramMethod.editMessageLiveLocation
@Transient override val resultDeserializer: KSerializer<out Message> = Message.serializer()
override fun stringify(json: Json): String = json.stringify(EditMessageLiveLocation.serializer(), this)
}
| 0 | Kotlin | 3 | 12 | 6e337e863884c875f3032fd60bbdf4bf537bb17e | 2,840 | telekt | MIT License |
slack_data_layer/src/commonMain/kotlin/dev/baseio/slackdata/datasources/local/messages/IMessageDecrypterImpl.kt | oianmol | 528,898,439 | false | {"Kotlin": 752408, "Swift": 113141, "Ruby": 11800, "Shell": 587, "Objective-C": 486, "C": 1} | package dev.baseio.slackdata.datasources.local.messages
import dev.baseio.security.*
import dev.baseio.slackdata.datasources.local.channels.loggedInUser
import dev.baseio.slackdomain.datasources.IDataDecryptor
import dev.baseio.slackdomain.datasources.local.SKLocalKeyValueSource
import dev.baseio.slackdomain.datasources.local.channels.SKLocalDataSourceChannelMembers
import dev.baseio.slackdomain.datasources.local.messages.IMessageDecrypter
import dev.baseio.slackdomain.model.message.DomainLayerMessages
class IMessageDecrypterImpl(
private val skKeyValueData: SKLocalKeyValueSource,
private val iDataDecrypter: IDataDecryptor,
private val skLocalDataSourceChannelMembers: SKLocalDataSourceChannelMembers,
) : IMessageDecrypter {
override suspend fun decrypted(message: DomainLayerMessages.SKMessage): Result<DomainLayerMessages.SKMessage> {
return kotlin.runCatching {
val privateKey = usersDecryptedPrivateKey(
message.workspaceId,
message.channelId,
)
val decodedMessage = privateKey?.let {
iDataDecrypter.decrypt(
Pair(
message.messageFirst,
message.messageSecond
),
privateKeyBytes = it
).decodeToString()
} ?: throw Exception("Private key not available for channel member ?")
message.copy(decodedMessage = decodedMessage)
}
}
private suspend fun usersDecryptedPrivateKey(
workspaceId: String,
channelId: String,
): ByteArray? {
val user = skKeyValueData.loggedInUser(workspaceId)
//TODO the user should always have uuid and email, fix this!
val capillary = user?.email?.let { CapillaryInstances.getInstance(it) }
val safeChannelEncryptedPrivateKey =
user?.uuid?.let {
skLocalDataSourceChannelMembers.getChannelPrivateKeyForMe(
workspaceId,
channelId,
it
)?.channelEncryptedPrivateKey
}
return capillary?.decrypt(
EncryptedData(
safeChannelEncryptedPrivateKey!!.first,
safeChannelEncryptedPrivateKey.second
),
capillary.privateKey()
)
}
}
| 3 | Kotlin | 21 | 235 | 143f06c11b757641fd3e67809f57dee9f2ffd04b | 2,379 | SlackComposeMultiplatform | Apache License 2.0 |
Application/app/src/main/java/com/droid/code/runnable/RunnableActivity.kt | devrath | 537,447,474 | false | {"Kotlin": 26395} | package com.droid.code.runnable
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.droid.code.databinding.ActivityRunnableBinding
import com.droid.code.runnable.workers.CustomRunnableOne
import com.droid.code.runnable.workers.CustomRunnableThree
import com.droid.code.runnable.workers.CustomRunnableTwo
val TAG_NARUTO = "Naruto"
class RunnableActivity : AppCompatActivity() {
private lateinit var binding: ActivityRunnableBinding
lateinit var thread1 : Thread
lateinit var thread2 : Thread
lateinit var thread3 : Thread
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRunnableBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnPublishOneId.setOnClickListener {
val runnable = CustomRunnableOne()
thread1 = Thread(runnable)
thread1.name = CustomRunnableOne::javaClass.name
thread1.start()
}
binding.btnPublishTwoId.setOnClickListener {
val runnable = CustomRunnableTwo()
thread2 = Thread(runnable)
thread2.name = CustomRunnableTwo::javaClass.name
thread2.start()
}
binding.btnPublishThreeId.setOnClickListener {
val runnable = CustomRunnableThree()
thread3 = Thread(runnable)
thread3.name = CustomRunnableThree::javaClass.name
thread3.start()
}
binding.btnStopThreadId.setOnClickListener {
stopThreads()
}
}
private fun stopThreads() {
if(::thread1.isInitialized){
thread1.interrupt()
}
if(::thread2.isInitialized){
thread2.interrupt()
}
if(::thread3.isInitialized){
thread3.interrupt()
}
}
} | 0 | Kotlin | 0 | 0 | cf3fe590145a34c57c241a2001a8d596c1c82914 | 1,882 | android-handler-thread | Apache License 2.0 |
compiler/testData/codegen/boxInline/defaultValues/lambdaInlining/jvmStaticDefault.kt | JakeWharton | 99,388,807 | false | null | // IGNORE_BACKEND: JS_IR
// FILE: 1.kt
// LANGUAGE_VERSION: 1.2
// SKIP_INLINE_CHECK_IN: inlineFun$default
// IGNORE_BACKEND: JS, NATIVE
//WITH_RUNTIME
package test
object X {
@JvmStatic
inline fun inlineFun(capturedParam: String, lambda: () -> String = { capturedParam }): String {
return lambda()
}
}
// FILE: 2.kt
import test.*
fun box(): String {
return X.inlineFun("OK")
} | 12 | null | 37 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 405 | kotlin | Apache License 2.0 |
shortlink-lib/src/main/kotlin/util/Encoding.kt | prashantjois | 734,920,429 | false | {"Kotlin": 46737, "Shell": 1884} | package ca.jois.shortlink.util
import java.nio.ByteBuffer
import java.util.*
object Encoding {
fun UUID.toBase64(): String {
val byteBuffer = ByteBuffer.wrap(ByteArray(16))
byteBuffer.putLong(this.mostSignificantBits)
byteBuffer.putLong(this.leastSignificantBits)
return Base64.getUrlEncoder().encodeToString(byteBuffer.array())
}
}
| 0 | Kotlin | 0 | 0 | b81ee1b0b8fd9ed1aba8ca0b12b5b3e958f9b37f | 375 | shortlink | MIT License |
sample/src/main/java/io/noties/adapt/sample/samples/recyclerview/RecyclerViewDiffSample.kt | noties | 138,477,077 | false | {"Kotlin": 739989, "Java": 214837, "JavaScript": 2125} | package io.noties.adapt.sample.samples.recyclerview
import android.annotation.SuppressLint
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.noties.adapt.recyclerview.AdaptRecyclerView
import io.noties.adapt.recyclerview.DiffUtilDataSetChangedHandler
import io.noties.adapt.sample.R
import io.noties.adapt.sample.SampleView
import io.noties.adapt.sample.annotation.AdaptSample
@AdaptSample(
id = "20210122143122",
title = "DiffUtil",
description = "<b>DiffUtil</b> with the <b><tt>RecyclerView</tt></b>",
tags = ["recyclerview"]
)
class RecyclerViewDiffSample : SampleView() {
override val layoutResId: Int = R.layout.view_sample_recycler_view
// Suppress because it is triggered mistakenly
@SuppressLint("InvalidSetHasFixedSize")
override fun render(view: View) {
val recyclerView: RecyclerView = view.findViewById(R.id.recycler_view)
recyclerView.layoutManager = LinearLayoutManager(view.context)
recyclerView.itemAnimator = DefaultItemAnimator()
recyclerView.setHasFixedSize(true)
val adapt = AdaptRecyclerView.init(recyclerView) {
it.dataSetChangeHandler(DiffUtilDataSetChangedHandler.create(true))
}
initSampleItems(adapt)
}
} | 0 | Kotlin | 2 | 4 | 7a440d50e6dd2ba327851d8ccee369eab1a842f8 | 1,387 | Adapt | Apache License 2.0 |
data/local/images/src/main/java/com/alexnechet/local/images/model/ImageDb.kt | alex-nechet | 634,167,292 | false | null | package com.alexnechet.local.images.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "images")
data class ImageDb(
@PrimaryKey(autoGenerate = true)
val databaseId : Long = 0,
val id: Long,
val tags: String? = null,
val previewUrl: String? = null,
val largeImageUrl: String? = null,
val views: Int? = null,
val comments: Int? = null,
val downloads: Int? = null,
val collections: Int? = null,
val likes: Int? = null,
val userName: String? = null,
val userImageUrl: String? = null
) | 0 | Kotlin | 0 | 0 | 6adf90e68f20d413a4a20a960339ae5c26840fb6 | 570 | PixabayApp | MIT License |
src/main/kotlin/org/linguamachina/klinguamachina/interpreter/block/impl/PrimitiveBlock.kt | Lingua-Machina | 254,106,597 | false | {"Java": 165058, "Kotlin": 118787, "ANTLR": 3004, "Makefile": 1404} | package org.linguamachina.klinguamachina.interpreter.block.impl
import org.linguamachina.klinguamachina.interpreter.block.Block
class PrimitiveBlock(
val name: String,
arity: Int
): Block(arity)
| 6 | Java | 1 | 1 | 267c1c73b39ec57f235cb4ce3374b6f283b31eb7 | 205 | KLinguaMachina | MIT License |
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/ConfigurationCacheReport.kt | kakenovna | 369,340,712 | true | {"Groovy": 28297477, "Java": 27157632, "Kotlin": 3618364, "C++": 1805886, "JavaScript": 207598, "CSS": 182117, "C": 98580, "HTML": 66407, "XSLT": 42845, "Perl": 37849, "Scala": 19901, "Shell": 7675, "Swift": 2040, "Objective-C": 840, "Objective-C++": 441, "GAP": 424, "CoffeeScript": 421, "Assembly": 277, "Gherkin": 191, "Python": 57, "Brainfuck": 54, "Ruby": 16} | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache
import groovy.json.JsonOutput
import org.gradle.api.internal.DocumentationRegistry
import org.gradle.configurationcache.problems.PropertyKind
import org.gradle.configurationcache.problems.PropertyProblem
import org.gradle.configurationcache.problems.PropertyTrace
import org.gradle.configurationcache.problems.buildConsoleSummary
import org.gradle.configurationcache.problems.firstTypeFrom
import org.gradle.configurationcache.problems.taskPathFrom
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
import java.net.URL
class ConfigurationCacheReport {
companion object {
private
const val reportHtmlFileName = "configuration-cache-report.html"
}
internal
fun consoleSummaryFor(cacheAction: String, problems: List<PropertyProblem>, htmlReportFile: File) =
buildConsoleSummary(cacheAction, problems, htmlReportFile)
/**
* Writes the report file to [outputDirectory].
*
* The file is laid out in such a way as to allow extracting the pure JSON model,
* see [writeJsReportData].
*/
internal
fun writeReportFileTo(outputDirectory: File, cacheAction: String, problems: List<PropertyProblem>): File {
require(outputDirectory.mkdirs()) {
"Could not create configuration cache report directory '$outputDirectory'"
}
// Groovy JSON uses the context classloader to locate various components, so use this class's classloader as the context classloader
return withContextClassLoader {
outputDirectory.resolve(reportHtmlFileName).also { htmlReportFile ->
val html = javaClass.requireResource(reportHtmlFileName)
htmlReportFile.bufferedWriter().use { writer ->
html.openStream().bufferedReader().use { reader ->
writer.writeReportFileText(reader, cacheAction, problems)
}
}
}
}
}
private
fun <T> withContextClassLoader(action: () -> T): T {
val currentThread = Thread.currentThread()
val previous = currentThread.contextClassLoader
currentThread.contextClassLoader = javaClass.classLoader
try {
return action()
} finally {
currentThread.contextClassLoader = previous
}
}
private
fun BufferedWriter.writeReportFileText(htmlReader: BufferedReader, cacheAction: String, problems: List<PropertyProblem>) {
var dataWritten = false
htmlReader.forEachLine { line ->
if (!dataWritten && line.contains("configuration-cache-report-data.js")) {
appendLine("""<script type="text/javascript">""")
writeJsReportData(cacheAction, problems)
appendLine("</script>")
dataWritten = true
} else {
appendLine(line)
}
}
require(dataWritten) { "Didn't write report data, placeholder not found!" }
}
/**
* Writes the report data function.
*
* The text is laid out in such a way as to allow extracting the pure JSON model
* by looking for `// begin-report-data` and `// end-report-data`.
*/
private
fun BufferedWriter.writeJsReportData(cacheAction: String, problems: List<PropertyProblem>) {
appendLine("function configurationCacheProblems() { return (")
appendLine("// begin-report-data")
writeJsonModelFor(cacheAction, problems)
appendLine("// end-report-data")
appendLine(");}")
}
private
fun BufferedWriter.writeJsonModelFor(cacheAction: String, problems: List<PropertyProblem>) {
val documentationRegistry = DocumentationRegistry()
appendLine("{") // begin JSON
appendLine("\"cacheAction\": \"$cacheAction\",")
appendLine("\"documentationLink\": \"${documentationRegistry.getDocumentationFor("configuration_cache")}\",")
appendLine("\"problems\": [") // begin problems
problems.forEachIndexed { index, problem ->
if (index > 0) append(',')
append(
JsonOutput.toJson(
mapOf(
"trace" to traceListOf(problem),
"message" to problem.message.fragments,
"documentationLink" to problem.documentationSection?.let { documentationRegistry.getDocumentationFor("configuration_cache", it.anchor) },
"error" to stackTraceStringOf(problem)
)
)
)
}
appendLine("]") // end problems
appendLine("}") // end JSON
}
private
fun Class<*>.requireResource(path: String): URL = getResource(path).also {
require(it != null) { "Resource `$path` could not be found!" }
}
private
fun stackTraceStringOf(problem: PropertyProblem): String? =
problem.exception?.let {
stackTraceStringFor(it)
}
private
fun stackTraceStringFor(error: Throwable): String =
StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
private
fun traceListOf(problem: PropertyProblem): List<Map<String, Any>> =
problem.trace.sequence.map(::traceToMap).toList()
private
fun traceToMap(trace: PropertyTrace): Map<String, Any> = when (trace) {
is PropertyTrace.Property -> {
when (trace.kind) {
PropertyKind.Field -> mapOf(
"kind" to trace.kind.name,
"name" to trace.name,
"declaringType" to firstTypeFrom(trace.trace).name
)
else -> mapOf(
"kind" to trace.kind.name,
"name" to trace.name,
"task" to taskPathFrom(trace.trace)
)
}
}
is PropertyTrace.Task -> mapOf(
"kind" to "Task",
"path" to trace.path,
"type" to trace.type.name
)
is PropertyTrace.Bean -> mapOf(
"kind" to "Bean",
"type" to trace.type.name
)
is PropertyTrace.BuildLogic -> mapOf(
"kind" to "BuildLogic",
"location" to trace.displayName.displayName
)
is PropertyTrace.BuildLogicClass -> mapOf(
"kind" to "BuildLogicClass",
"type" to trace.name
)
PropertyTrace.Gradle -> mapOf(
"kind" to "Gradle"
)
PropertyTrace.Unknown -> mapOf(
"kind" to "Unknown"
)
}
}
| 1 | null | 1 | 1 | f48c633d6e577c3d95c1eaa3f965d35d3abdd0b3 | 7,337 | java_course_barancev | Apache License 2.0 |
src/main/kotlin/com/saltynote/service/domain/transfer/TokenPair.kt | SaltyNote | 694,892,361 | false | {"Kotlin": 91667} | package com.saltynote.service.domain.transfer
import com.fasterxml.jackson.annotation.JsonProperty
data class TokenPair(
@JsonProperty("access_token")
val accessToken: String,
@JsonProperty("refresh_token")
val refreshToken: String = ""
)
| 2 | Kotlin | 0 | 0 | aa736919198795a486cc26a13728288ad81aff15 | 257 | saltynote-service-kotlin | MIT License |
app/src/main/java/cn/nekocode/caka/di/module/FragmentModule.kt | nekocode | 41,577,702 | false | null | /*
* Copyright 2019. nekocode (<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 cn.nekocode.caka.di.module
import androidx.fragment.app.Fragment
import cn.nekocode.caka.di.FragmentScope
import dagger.Module
import dagger.Provides
/**
* @author nekocode (<EMAIL>)
*/
@Module
class FragmentModule(private val fragment: Fragment) {
@Provides
@FragmentScope
fun provideFragment(): Fragment = fragment
} | 2 | Kotlin | 215 | 1,595 | 7f7db5e441d1493949284af3609724b8571e0453 | 946 | create-android-kotlin-app | Apache License 2.0 |
app/src/main/java/cz/marvincz/rssnotifier/fragment/ItemsFragment.kt | marvincz-cz | 403,626,281 | false | {"Kotlin": 79439} | package cz.marvincz.rssnotifier.fragment
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.*
import androidx.recyclerview.widget.DefaultItemAnimator
import cz.marvincz.rssnotifier.R
import cz.marvincz.rssnotifier.adapter.ItemAdapter
import cz.marvincz.rssnotifier.databinding.FragmentItemsBinding
import cz.marvincz.rssnotifier.fragment.base.BaseFragment
import cz.marvincz.rssnotifier.model.RssItem
import cz.marvincz.rssnotifier.viewmodel.ItemsViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
class ItemsFragment : BaseFragment<ItemsViewModel>() {
val channelUrl: String by lazy { requireArguments().getString(ARG_CHANNEL)!! }
override val viewModel: ItemsViewModel by viewModel { parametersOf(channelUrl) }
private var _binding: FragmentItemsBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
_binding = FragmentItemsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.list.adapter = ItemAdapter(viewLifecycleOwner, viewModel.items, object : ItemAdapter.ItemListCallBack {
override fun toggle(item: RssItem) {
viewModel.toggle(item)
}
override fun open(item: RssItem) {
viewModel.read(item)
item.link?.let { goToLink(it) }
}
})
binding.list.itemAnimator = DefaultItemAnimator()
handleEmptyState()
}
private fun handleEmptyState() {
viewModel.items.observe(this.viewLifecycleOwner) {
if (it.isEmpty())
binding.flipper.displayedChild = FLIP_EMPTY
else
binding.flipper.displayedChild = FLIP_LIST
}
viewModel.showSeen.observe(this.viewLifecycleOwner) { showSeen ->
if (showSeen)
binding.emptyMessage.setText(R.string.empty_no_items)
else
binding.emptyMessage.setText(R.string.empty_no_unseen)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_items, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_all_seen -> {
viewModel.markAllRead()
return true
}
R.id.action_show_seen -> {
viewModel.toggleShowSeen()
return true
}
}
return false
}
private fun goToLink(link: String) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
companion object {
private const val ARG_CHANNEL = "channel_param"
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param channelUrl RSS Channel ID
* @return A new instance of fragment ItemsFragment.
*/
fun newInstance(channelUrl: String) = ItemsFragment().apply {
arguments = Bundle().apply {
putString(ARG_CHANNEL, channelUrl)
}
}
private const val FLIP_LIST = 0
private const val FLIP_EMPTY = 1
}
}
| 0 | Kotlin | 0 | 0 | afcd91647dc84c1ae400ffd63693c5d9101a5c55 | 4,000 | rss-notifier | MIT License |
src/main/kotlin/io/github/gunkim/application/RoomService.kt | gunkim | 374,385,822 | false | null | package io.github.gunkim.application
import io.github.gunkim.domain.exception.LeaveHostException
import io.github.gunkim.domain.game.Board
import io.github.gunkim.domain.game.Gamer
import io.github.gunkim.domain.game.event.GameStopEvent
import io.github.gunkim.domain.game.event.ScheduledGameStopNotifier
import io.github.gunkim.domain.room.Room
import io.github.gunkim.domain.room.RoomRepository
import io.github.gunkim.domain.user.UserRepository
import org.springframework.stereotype.Service
import java.util.UUID
@Service
class RoomService(
private val userRepository: UserRepository,
private val roomRepository: RoomRepository,
private val scheduledGameStopNotifier: ScheduledGameStopNotifier
) {
fun find() = roomRepository.find()
fun find(userId: UUID, roomId: UUID) = roomRepository.find(roomId)
.also { validate(it, userId, roomId) }
fun find(roomId: UUID) = roomRepository.find(roomId)
fun join(roomId: UUID, userId: UUID) {
val (user, room) = load(userId, roomId)
require(!roomRepository.existByUserId(user.id)) { "이미 방에 참여중입니다." }
roomRepository.save(room.join(user))
}
fun start(roomId: UUID, userId: UUID) {
val room = roomRepository.find(roomId)
roomRepository.save(room.start(userId))
scheduledGameStopNotifier.notify(GameStopEvent(room.id))
}
fun leave(roomId: UUID, userId: UUID): Boolean {
val room = roomRepository.find(roomId)
return try {
roomRepository.save(room.leave(userId))
true
} catch (e: LeaveHostException) {
roomRepository.delete(room)
false
}
}
fun create(title: String, userId: UUID): Room {
val user = userRepository.find(userId)
require(!roomRepository.existByUserId(user.id)) { "이미 방에 참여중입니다." }
val hostGamer = Gamer(user = user, board = Board.create(), isHost = true)
val room = Room(title = title, gamers = listOf(hostGamer), isStart = false)
return roomRepository.save(room)
}
fun ready(userId: UUID, roomId: UUID) {
val room = roomRepository.find(roomId)
roomRepository.save(room.ready(userId))
}
fun kick(roomId: UUID, managerId: UUID, gamerId: UUID) {
val room = roomRepository.find(roomId)
roomRepository.save(room.kick(managerId, gamerId))
}
private fun load(userId: UUID, roomId: UUID) = userRepository.find(userId) to roomRepository.find(roomId)
private fun validate(
room: Room,
userId: UUID,
roomId: UUID
) {
require(room.hasUserId(userId)) { "해당 플레이어는 방에 참여하지 않았습니다. (gamer_id : $userId, room_id : $roomId)" }
}
}
| 1 | null | 1 | 3 | fadf78225d3da7e038990cbb40e365f0eb3f45c8 | 2,713 | 2048-online | MIT License |
libChat/messagePage/emoji/adapter/HorizontalRecyclerviewAdapter.kt | Gianzhou | 308,232,822 | false | null | package com.somoplay.wefungame.libChat.messagePage.emoji.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.RecyclerView
import com.somoplay.wefungame.R
import com.somoplay.wefungame.libChat.messagePage.emoji.ImageModel
import com.somoplay.wefungame.libChat.messagePage.emoji.utils.ScreenUtils
class HorizontalRecyclerviewAdapter:
RecyclerView.Adapter<HorizontalRecyclerviewAdapter.ViewHolder> {
private var datas: ArrayList<ImageModel>
private var mInflater: LayoutInflater
private var context: Context
private lateinit var onClickItemListener: OnClickItemListener
constructor(context: Context, datas: ArrayList<ImageModel>){
this.datas = datas
this.context = context
mInflater = LayoutInflater.from(context)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
var view: View = mInflater.inflate(R.layout.recyclerview_horizontal_item, parent, false)
view.setBackgroundColor(ContextCompat.getColor(context, R.color.white))
return ViewHolder(view)
}
override fun getItemCount(): Int {
return datas.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var model: ImageModel = datas[position]
holder.itemView.setPadding(8, 2, 8, 2)
if(onClickItemListener != null){
holder.itemView.setOnClickListener(View.OnClickListener {
var pos: Int = holder.layoutPosition
onClickItemListener.onItemClick(holder.itemView, pos, datas)
})
holder.itemView.setOnLongClickListener(View.OnLongClickListener {
var pos: Int = holder.layoutPosition
onClickItemListener.onItemLongClick(holder.itemView, pos, datas)
return@OnLongClickListener false
})
}
/**
* 动态计算底部tab的宽度。
*/
var width: Int=ScreenUtils.getScreenWidth(context)
var itemW: Float = width/10f
var lp : ViewGroup.LayoutParams = holder.imageBtn.layoutParams
lp.width = itemW.toInt()
lp.height = itemW.toInt()
holder.imageBtn.setImageDrawable(model.icon)
/* if(model.isSelected){
holder.imageBtn.setBackgroundColor(ContextCompat.getColor(context,R.color.bg_horizontal_btn_selected))
}else{
// holder.imageBtn.setBackgroundColor(R.color.bg_horizontal_btn_normal)
// holder.imageBtn.setBackgroundColor(ContextCompat.getColor(context,R.color.bg_horizontal_btn_normal))
}*/
}
class ViewHolder : RecyclerView.ViewHolder{
var imageBtn: ImageView
constructor(itemView: View):super(itemView){
imageBtn = itemView.findViewById(R.id.image_btn) as ImageView
}
}
fun setOnClickItemListener(listener: OnClickItemListener){
this.onClickItemListener = listener
}
public interface OnClickItemListener {
fun onItemClick(view:View, position: Int, datas: ArrayList<ImageModel>)
fun onItemLongClick(view:View, position:Int, datas: ArrayList<ImageModel>)
}
} | 0 | Kotlin | 0 | 0 | 48e7d1dfc279b5ae203d88824615fc6ba074d528 | 3,469 | AndroidChatFunction | MIT License |
src/main/kotlin/io/github/oxisto/reticulated/ast/expression/booleanops/NotTest.kt | AndHager | 244,382,209 | true | {"Kotlin": 276598, "ANTLR": 26984, "Python": 2008} | /*
* Copyright (c) 2020, <NAME> and <NAME>. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.github.oxisto.reticulated.ast.expression.booleanops
import io.github.oxisto.reticulated.ast.CouldNotParseException
import io.github.oxisto.reticulated.ast.expression.comparison.Comparison
/**
* This class represents a not_test.
* It´s EBNF definition is:
* not_test ::= comparison | "not" not_test
* [see: {@linktourl https://docs.python.org/3/reference/expressions.html#boolean-operations}]
*/
class NotTest(val comparison: Comparison?, val notTest:NotTest? ): BaseBooleanOp() {
init {
if(comparison == null){
if(notTest == null){
throw CouldNotParseException(
"In a NotTest should not be boat, the comparison ant the notTest, null."
)
}
}else {
if(notTest != null){
throw CouldNotParseException(
"In a NotTest should be ether the comparison or the notTes, null."
)
}
}
}
override fun toString(): String {
var result = "NotTest(" + System.lineSeparator() + "\t"
result += if(comparison == null){
"not notTest=$notTest"
}else {
"comparison=$comparison"
}
result += System.lineSeparator() + ")"
return result
}
} | 0 | Kotlin | 0 | 0 | 95b24f52e1c2e37c004048e1e8274885b3fa08ed | 1,950 | reticulated-python | Apache License 2.0 |
app/src/main/java/tk/pokatomnik/mrakopediareader2/ui/components/FavoriteItem.kt | pokatomnik | 551,521,498 | false | {"Kotlin": 187257} | package tk.pokatomnik.mrakopediareader2.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
private const val HEIGHT = 64
@Composable
fun ListItemWithClickableIcon(
title: String,
description: String?,
icon: ImageVector,
contentDescription: String,
onItemClick: () -> Unit,
onIconClick: () -> Unit
) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(HEIGHT.dp)
.clickable(
onClick = onItemClick,
indication = rememberRipple(bounded = true),
interactionSource = remember { MutableInteractionSource() }
)
.padding(horizontal = LIST_ITEM_PADDING.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier
.fillMaxWidth()
.weight(1f)
) {
Text(
text = title,
maxLines = 1,
style = MaterialTheme.typography.h6,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.alpha(0.8f)
)
if (description != null) {
Text(
text = description,
modifier = Modifier.alpha(0.54f),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.body2,
)
}
}
Column(
modifier = Modifier
.requiredHeight(HEIGHT.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
imageVector = icon,
contentDescription = contentDescription,
modifier = Modifier.clickable (
onClick = onIconClick,
indication = rememberRipple(
bounded = false,
radius = (HEIGHT / 2).dp
),
interactionSource = remember { MutableInteractionSource() }
)
)
}
}
}
| 7 | Kotlin | 0 | 0 | 16c4135887d08d5b966f1061cf4652b5523f09d7 | 2,799 | MrakopediaReader2 | MIT License |
app/src/main/java/id/asmith/bajalangclean/ui/main/fragment/FragmentMainPlace.kt | bakode | 116,363,403 | false | null | package id.asmith.bajalangclean.ui.main.fragment
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.*
import id.asmith.bajalangclean.R
import id.asmith.bajalangclean.ui.main.MainViewModel
import kotlinx.android.synthetic.main.fragment_main_place.view.*
/**
* Created by <NAME> on 10/01/2018.
* https://asmith.my.id
* <EMAIL>
*/
class FragmentMainPlace : Fragment(){
private val mViewModel: MainViewModel by lazy {
ViewModelProviders.of(activity!!).get(MainViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_main_place, container, false)
setHasOptionsMenu(true)
onClickedListener(view)
return view
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater){
super.onCreateOptionsMenu(menu, inflater)
menu!!.findItem(R.id.action_search).isVisible = false
}
private fun onClickedListener(view: View){
view.layout_main_restaurant.setOnClickListener {
mViewModel.replaceWithListPlace()
mViewModel.setPassingCategory("restaurant")
}
view.layout_main_school.setOnClickListener {
mViewModel.replaceWithListPlace()
mViewModel.setPassingCategory("school")
}
}
} | 0 | Kotlin | 0 | 0 | cfd0f59669333a93227841499ad189ebd6120f47 | 1,492 | bajalang-cc | Apache License 2.0 |
src/commonTest/kotlin/com/jeffpdavidson/kotwords/formats/RowsGardenTest.kt | jpd236 | 143,651,464 | false | {"Kotlin": 4427197, "HTML": 41941, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618} | package com.jeffpdavidson.kotwords.formats
import com.jeffpdavidson.kotwords.readBinaryResource
import com.jeffpdavidson.kotwords.readStringResource
import io.github.pdvrieze.xmlutil.testutil.assertXmlEquals
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
class RowsGardenTest {
@Test
fun convertToJpz() = runTest {
val puzzle = Rgz.fromRgzFile(readBinaryResource(RowsGardenTest::class, "rows-garden/test.rgz")).asRowsGarden(
lightBloomColor = "#FFFFFF",
mediumBloomColor = "#C3C8FA",
darkBloomColor = "#5765F7",
addWordCount = true,
addHyphenated = true
).asPuzzle()
val expected = readStringResource(RowsGardenTest::class, "rows-garden/rows-garden.jpz")
assertXmlEquals(
expected, puzzle.asJpz(
appletSettings = CrosswordCompilerApplet.AppletSettings(
cursorColor = "#00b100",
selectedCellsColor = "#80ff80",
completion = CrosswordCompilerApplet.AppletSettings.Completion(message = "All done!")
)
).toXmlString()
)
}
@Test
fun convertToJpz_mini() = runTest {
val puzzle = Rgz.fromRgzFile(readBinaryResource(RowsGardenTest::class, "rows-garden/test-mini.rg"))
.asRowsGarden(
lightBloomColor = "#FFFFFF",
mediumBloomColor = "#C3C8FA",
darkBloomColor = "#5765F7",
addWordCount = true,
addHyphenated = true,
).asPuzzle()
val expected = readStringResource(RowsGardenTest::class, "rows-garden/rows-garden-mini.jpz")
assertXmlEquals(
expected, puzzle.asJpz(
appletSettings = CrosswordCompilerApplet.AppletSettings(
cursorColor = "#00b100",
selectedCellsColor = "#80ff80",
completion = CrosswordCompilerApplet.AppletSettings.Completion(message = "All done!")
)
).toXmlString()
)
}
} | 8 | Kotlin | 6 | 25 | e18e9cf0bad7497da15b40f6c81ba4234ec83917 | 2,089 | kotwords | Apache License 2.0 |
app/src/main/java/study/me/please/data/io/QuestionAnswerIO.kt | JacobCube | 683,485,839 | false | {"Kotlin": 3640147} | package study.me.please.data.io
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
import study.me.please.data.room.AppRoomDatabase
import java.io.Serializable
import java.util.UUID
@Entity(tableName = AppRoomDatabase.ROOM_QUESTION_ANSWER_TABLE)
data class QuestionAnswerIO (
/** Answer text to be displayed */
var text: String = "",
/** list of texts */
var textList: List<String> = listOf(),
/** What is the reasoniung behind this answer being wrong/correct */
@SerializedName("explanation_message")
var explanationMessage: String = "",
/** unique identifier */
@PrimaryKey
val uid: String = UUID.randomUUID().toString(),
/** explanation image */
@SerializedName("image_explanation")
var imageExplanation: LargePathAsset? = null,
/** whether this answer is the correct one to a parent prompt */
@SerializedName("is_correct")
var isCorrect: Boolean = false,
/** Whether the prompt is list mode */
var isListAnswer: Boolean = textList.isNotEmpty()
): Serializable {
/** whether this object has no important data */
@get:Ignore
val isEmpty: Boolean
get() = text.isEmpty()
&& explanationMessage.isEmpty()
&& imageExplanation?.isEmpty != false
/** Updates this object with new question */
fun updateTO(answer: QuestionAnswerIO) {
this.text = answer.text
this.explanationMessage = answer.explanationMessage
this.imageExplanation = answer.imageExplanation
this.isCorrect = answer.isCorrect
}
} | 0 | Kotlin | 0 | 0 | a696f216e1a7b72d7ac370318b4a37512d8cd10d | 1,646 | Study-me-please | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Musicplaylist.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup
public val OutlineGroup.Musicplaylist: ImageVector
get() {
if (_musicplaylist != null) {
return _musicplaylist!!
}
_musicplaylist = Builder(name = "Musicplaylist", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.0f, 22.75f)
horizontalLineTo(7.0f)
curveTo(3.35f, 22.75f, 1.25f, 20.65f, 1.25f, 17.0f)
verticalLineTo(12.0f)
curveTo(1.25f, 8.35f, 3.35f, 6.25f, 7.0f, 6.25f)
horizontalLineTo(17.0f)
curveTo(20.65f, 6.25f, 22.75f, 8.35f, 22.75f, 12.0f)
verticalLineTo(17.0f)
curveTo(22.75f, 20.65f, 20.65f, 22.75f, 17.0f, 22.75f)
close()
moveTo(7.0f, 7.75f)
curveTo(4.14f, 7.75f, 2.75f, 9.14f, 2.75f, 12.0f)
verticalLineTo(17.0f)
curveTo(2.75f, 19.86f, 4.14f, 21.25f, 7.0f, 21.25f)
horizontalLineTo(17.0f)
curveTo(19.86f, 21.25f, 21.25f, 19.86f, 21.25f, 17.0f)
verticalLineTo(12.0f)
curveTo(21.25f, 9.14f, 19.86f, 7.75f, 17.0f, 7.75f)
horizontalLineTo(7.0f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.0f, 5.25f)
horizontalLineTo(6.0f)
curveTo(5.59f, 5.25f, 5.25f, 4.91f, 5.25f, 4.5f)
curveTo(5.25f, 4.09f, 5.59f, 3.75f, 6.0f, 3.75f)
horizontalLineTo(18.0f)
curveTo(18.41f, 3.75f, 18.75f, 4.09f, 18.75f, 4.5f)
curveTo(18.75f, 4.91f, 18.41f, 5.25f, 18.0f, 5.25f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.0f, 2.75f)
horizontalLineTo(9.0f)
curveTo(8.59f, 2.75f, 8.25f, 2.41f, 8.25f, 2.0f)
curveTo(8.25f, 1.59f, 8.59f, 1.25f, 9.0f, 1.25f)
horizontalLineTo(15.0f)
curveTo(15.41f, 1.25f, 15.75f, 1.59f, 15.75f, 2.0f)
curveTo(15.75f, 2.41f, 15.41f, 2.75f, 15.0f, 2.75f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(8.8895f, 19.8601f)
curveTo(7.7195f, 19.8601f, 6.7695f, 18.9101f, 6.7695f, 17.7401f)
curveTo(6.7695f, 16.5701f, 7.7195f, 15.6201f, 8.8895f, 15.6201f)
curveTo(10.0595f, 15.6201f, 11.0095f, 16.5701f, 11.0095f, 17.7401f)
curveTo(11.0095f, 18.9101f, 10.0595f, 19.8601f, 8.8895f, 19.8601f)
close()
moveTo(8.8895f, 17.1201f)
curveTo(8.5495f, 17.1201f, 8.2695f, 17.4001f, 8.2695f, 17.7401f)
curveTo(8.2695f, 18.0801f, 8.5495f, 18.3601f, 8.8895f, 18.3601f)
curveTo(9.2295f, 18.3601f, 9.5095f, 18.0801f, 9.5095f, 17.7401f)
curveTo(9.5095f, 17.4001f, 9.2295f, 17.1201f, 8.8895f, 17.1201f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.2598f, 18.4901f)
curveTo(9.8498f, 18.4901f, 9.5098f, 18.1501f, 9.5098f, 17.7401f)
verticalLineTo(12.2301f)
curveTo(9.5098f, 11.3501f, 10.0598f, 10.6401f, 10.8998f, 10.4101f)
lineTo(13.6398f, 9.6601f)
curveTo(14.5098f, 9.4201f, 15.0597f, 9.6502f, 15.3597f, 9.8902f)
curveTo(15.6597f, 10.1201f, 16.0198f, 10.5901f, 16.0198f, 11.4801f)
verticalLineTo(16.8301f)
curveTo(16.0198f, 17.2401f, 15.6798f, 17.5801f, 15.2698f, 17.5801f)
curveTo(14.8598f, 17.5801f, 14.5198f, 17.2401f, 14.5198f, 16.8301f)
verticalLineTo(11.4801f)
curveTo(14.5198f, 11.2001f, 14.4598f, 11.0901f, 14.4398f, 11.0801f)
curveTo(14.4198f, 11.0701f, 14.2998f, 11.0301f, 14.0198f, 11.1101f)
lineTo(11.2897f, 11.8601f)
curveTo(11.0397f, 11.9301f, 10.9998f, 12.1001f, 10.9998f, 12.2401f)
verticalLineTo(17.7501f)
curveTo(11.0098f, 18.1501f, 10.6698f, 18.4901f, 10.2598f, 18.4901f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(13.9091f, 18.95f)
curveTo(12.7391f, 18.95f, 11.7891f, 18.0f, 11.7891f, 16.83f)
curveTo(11.7891f, 15.66f, 12.7391f, 14.71f, 13.9091f, 14.71f)
curveTo(15.0791f, 14.71f, 16.0291f, 15.66f, 16.0291f, 16.83f)
curveTo(16.0291f, 18.0f, 15.0791f, 18.95f, 13.9091f, 18.95f)
close()
moveTo(13.9091f, 16.21f)
curveTo(13.5691f, 16.21f, 13.2891f, 16.49f, 13.2891f, 16.83f)
curveTo(13.2891f, 17.17f, 13.5691f, 17.45f, 13.9091f, 17.45f)
curveTo(14.2491f, 17.45f, 14.5291f, 17.17f, 14.5291f, 16.83f)
curveTo(14.5291f, 16.49f, 14.2491f, 16.21f, 13.9091f, 16.21f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.2604f, 14.5801f)
curveTo(9.9304f, 14.5801f, 9.6304f, 14.3601f, 9.5404f, 14.0301f)
curveTo(9.4304f, 13.6301f, 9.6704f, 13.2201f, 10.0704f, 13.1101f)
lineTo(15.0804f, 11.7401f)
curveTo(15.4904f, 11.6301f, 15.8904f, 11.8701f, 16.0004f, 12.2701f)
curveTo(16.1104f, 12.6701f, 15.8704f, 13.0801f, 15.4704f, 13.1901f)
lineTo(10.4604f, 14.5601f)
curveTo(10.3904f, 14.5701f, 10.3304f, 14.5801f, 10.2604f, 14.5801f)
close()
}
}
.build()
return _musicplaylist!!
}
private var _musicplaylist: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 7,925 | VuesaxIcons | MIT License |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Musicplaylist.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup
public val OutlineGroup.Musicplaylist: ImageVector
get() {
if (_musicplaylist != null) {
return _musicplaylist!!
}
_musicplaylist = Builder(name = "Musicplaylist", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.0f, 22.75f)
horizontalLineTo(7.0f)
curveTo(3.35f, 22.75f, 1.25f, 20.65f, 1.25f, 17.0f)
verticalLineTo(12.0f)
curveTo(1.25f, 8.35f, 3.35f, 6.25f, 7.0f, 6.25f)
horizontalLineTo(17.0f)
curveTo(20.65f, 6.25f, 22.75f, 8.35f, 22.75f, 12.0f)
verticalLineTo(17.0f)
curveTo(22.75f, 20.65f, 20.65f, 22.75f, 17.0f, 22.75f)
close()
moveTo(7.0f, 7.75f)
curveTo(4.14f, 7.75f, 2.75f, 9.14f, 2.75f, 12.0f)
verticalLineTo(17.0f)
curveTo(2.75f, 19.86f, 4.14f, 21.25f, 7.0f, 21.25f)
horizontalLineTo(17.0f)
curveTo(19.86f, 21.25f, 21.25f, 19.86f, 21.25f, 17.0f)
verticalLineTo(12.0f)
curveTo(21.25f, 9.14f, 19.86f, 7.75f, 17.0f, 7.75f)
horizontalLineTo(7.0f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.0f, 5.25f)
horizontalLineTo(6.0f)
curveTo(5.59f, 5.25f, 5.25f, 4.91f, 5.25f, 4.5f)
curveTo(5.25f, 4.09f, 5.59f, 3.75f, 6.0f, 3.75f)
horizontalLineTo(18.0f)
curveTo(18.41f, 3.75f, 18.75f, 4.09f, 18.75f, 4.5f)
curveTo(18.75f, 4.91f, 18.41f, 5.25f, 18.0f, 5.25f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.0f, 2.75f)
horizontalLineTo(9.0f)
curveTo(8.59f, 2.75f, 8.25f, 2.41f, 8.25f, 2.0f)
curveTo(8.25f, 1.59f, 8.59f, 1.25f, 9.0f, 1.25f)
horizontalLineTo(15.0f)
curveTo(15.41f, 1.25f, 15.75f, 1.59f, 15.75f, 2.0f)
curveTo(15.75f, 2.41f, 15.41f, 2.75f, 15.0f, 2.75f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(8.8895f, 19.8601f)
curveTo(7.7195f, 19.8601f, 6.7695f, 18.9101f, 6.7695f, 17.7401f)
curveTo(6.7695f, 16.5701f, 7.7195f, 15.6201f, 8.8895f, 15.6201f)
curveTo(10.0595f, 15.6201f, 11.0095f, 16.5701f, 11.0095f, 17.7401f)
curveTo(11.0095f, 18.9101f, 10.0595f, 19.8601f, 8.8895f, 19.8601f)
close()
moveTo(8.8895f, 17.1201f)
curveTo(8.5495f, 17.1201f, 8.2695f, 17.4001f, 8.2695f, 17.7401f)
curveTo(8.2695f, 18.0801f, 8.5495f, 18.3601f, 8.8895f, 18.3601f)
curveTo(9.2295f, 18.3601f, 9.5095f, 18.0801f, 9.5095f, 17.7401f)
curveTo(9.5095f, 17.4001f, 9.2295f, 17.1201f, 8.8895f, 17.1201f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.2598f, 18.4901f)
curveTo(9.8498f, 18.4901f, 9.5098f, 18.1501f, 9.5098f, 17.7401f)
verticalLineTo(12.2301f)
curveTo(9.5098f, 11.3501f, 10.0598f, 10.6401f, 10.8998f, 10.4101f)
lineTo(13.6398f, 9.6601f)
curveTo(14.5098f, 9.4201f, 15.0597f, 9.6502f, 15.3597f, 9.8902f)
curveTo(15.6597f, 10.1201f, 16.0198f, 10.5901f, 16.0198f, 11.4801f)
verticalLineTo(16.8301f)
curveTo(16.0198f, 17.2401f, 15.6798f, 17.5801f, 15.2698f, 17.5801f)
curveTo(14.8598f, 17.5801f, 14.5198f, 17.2401f, 14.5198f, 16.8301f)
verticalLineTo(11.4801f)
curveTo(14.5198f, 11.2001f, 14.4598f, 11.0901f, 14.4398f, 11.0801f)
curveTo(14.4198f, 11.0701f, 14.2998f, 11.0301f, 14.0198f, 11.1101f)
lineTo(11.2897f, 11.8601f)
curveTo(11.0397f, 11.9301f, 10.9998f, 12.1001f, 10.9998f, 12.2401f)
verticalLineTo(17.7501f)
curveTo(11.0098f, 18.1501f, 10.6698f, 18.4901f, 10.2598f, 18.4901f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(13.9091f, 18.95f)
curveTo(12.7391f, 18.95f, 11.7891f, 18.0f, 11.7891f, 16.83f)
curveTo(11.7891f, 15.66f, 12.7391f, 14.71f, 13.9091f, 14.71f)
curveTo(15.0791f, 14.71f, 16.0291f, 15.66f, 16.0291f, 16.83f)
curveTo(16.0291f, 18.0f, 15.0791f, 18.95f, 13.9091f, 18.95f)
close()
moveTo(13.9091f, 16.21f)
curveTo(13.5691f, 16.21f, 13.2891f, 16.49f, 13.2891f, 16.83f)
curveTo(13.2891f, 17.17f, 13.5691f, 17.45f, 13.9091f, 17.45f)
curveTo(14.2491f, 17.45f, 14.5291f, 17.17f, 14.5291f, 16.83f)
curveTo(14.5291f, 16.49f, 14.2491f, 16.21f, 13.9091f, 16.21f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.2604f, 14.5801f)
curveTo(9.9304f, 14.5801f, 9.6304f, 14.3601f, 9.5404f, 14.0301f)
curveTo(9.4304f, 13.6301f, 9.6704f, 13.2201f, 10.0704f, 13.1101f)
lineTo(15.0804f, 11.7401f)
curveTo(15.4904f, 11.6301f, 15.8904f, 11.8701f, 16.0004f, 12.2701f)
curveTo(16.1104f, 12.6701f, 15.8704f, 13.0801f, 15.4704f, 13.1901f)
lineTo(10.4604f, 14.5601f)
curveTo(10.3904f, 14.5701f, 10.3304f, 14.5801f, 10.2604f, 14.5801f)
close()
}
}
.build()
return _musicplaylist!!
}
private var _musicplaylist: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 7,925 | VuesaxIcons | MIT License |
app/src/main/java/com/rjvjha/android/employee/di/components/ActivityComponent.kt | rjvjha | 292,233,162 | false | {"Kotlin": 57195} | package com.rjvjha.android.employee.di.components
import com.rjvjha.android.employee.di.ActivityScope
import com.rjvjha.android.employee.di.module.ActivityModule
import com.rjvjha.android.employee.ui.main.MainActivity
import dagger.Component
@ActivityScope
@Component(dependencies = [ApplicationComponent::class], modules = [ActivityModule::class])
interface ActivityComponent {
fun inject(activity: MainActivity)
}
| 0 | Kotlin | 0 | 0 | 477db017158bc1e30be5a25c0b8a71f5a6328a6f | 424 | EmployeeApp | Apache License 2.0 |
app/src/test/kotlin/no/nav/navnosearchadminapi/utils/testData.kt | navikt | 710,261,054 | false | {"Kotlin": 57636, "Dockerfile": 226} | package no.nav.navnosearchadminapi.utils
import no.nav.navnosearchadminapi.common.constants.ENGLISH
import no.nav.navnosearchadminapi.common.constants.NORWEGIAN_BOKMAAL
import no.nav.navnosearchadminapi.common.enums.ValidTypes
import no.nav.navnosearchadminapi.common.model.ContentDao
import no.nav.navnosearchadminapi.common.model.MultiLangFieldLong
import no.nav.navnosearchadminapi.common.model.MultiLangFieldShort
import no.nav.navnosearchadminapi.consumer.kodeverk.dto.KodeverkResponse
import no.nav.navnosearchadminapi.dto.inbound.ContentDto
import no.nav.navnosearchadminapi.dto.inbound.ContentMetadata
import org.springframework.data.elasticsearch.core.suggest.Completion
import java.time.ZonedDateTime
const val TEAM_NAME = "test-team"
const val PRIVATPERSON = "privatperson"
const val ARBEIDSGIVER = "arbeidsgiver"
const val SAMARBEIDSPARTNER = "samarbeidspartner"
const val AGDER = "agder"
const val STATISTIKK = "statistikk"
const val HINDI = "hi"
val mockedKodeverkResponse = KodeverkResponse(listOf("NB", "NN", "EN", "SE", "PL", "UK", "RU"))
val now: ZonedDateTime = ZonedDateTime.now()
val nowMinusTwoYears: ZonedDateTime = ZonedDateTime.now().minusYears(2)
val nowMinus10Days: ZonedDateTime = ZonedDateTime.now().minusDays(10)
val nowMinus50Days: ZonedDateTime = ZonedDateTime.now().minusDays(50)
val initialTestData = listOf(
dummyContentDao(
externalId = "1",
textPrefix = "First",
audience = listOf(PRIVATPERSON, ARBEIDSGIVER, SAMARBEIDSPARTNER),
fylke = AGDER,
metatags = listOf(STATISTIKK)
),
dummyContentDao(
externalId = "2",
textPrefix = "Second",
fylke = AGDER,
metatags = listOf(STATISTIKK)
),
dummyContentDao(
externalId = "3",
textPrefix = "Third",
timestamp = nowMinusTwoYears,
fylke = AGDER,
metatags = listOf(STATISTIKK)
),
dummyContentDao(
externalId = "4",
textPrefix = "Fourth",
timestamp = nowMinusTwoYears,
language = ENGLISH
),
dummyContentDao(
externalId = "5",
textPrefix = "Fifth",
timestamp = nowMinus10Days,
audience = listOf(ARBEIDSGIVER),
language = ENGLISH,
),
dummyContentDao(
externalId = "6",
textPrefix = "Sixth",
timestamp = nowMinus10Days,
audience = listOf(ARBEIDSGIVER),
language = ENGLISH,
),
dummyContentDao(
externalId = "7",
textPrefix = "Seventh",
timestamp = nowMinus50Days,
audience = listOf(ARBEIDSGIVER),
language = HINDI,
),
dummyContentDao(
externalId = "8",
textPrefix = "Eighth",
timestamp = nowMinus50Days,
audience = listOf(SAMARBEIDSPARTNER),
language = HINDI,
),
dummyContentDao(
externalId = "9",
textPrefix = "Ninth",
timestamp = nowMinus50Days,
audience = listOf(SAMARBEIDSPARTNER),
language = HINDI,
),
dummyContentDao(
externalId = "10",
textPrefix = "Tenth",
timestamp = nowMinus50Days,
audience = listOf(SAMARBEIDSPARTNER),
language = HINDI,
),
)
fun dummyContentDao(
teamName: String = TEAM_NAME,
externalId: String,
textPrefix: String = "",
timestamp: ZonedDateTime = now,
audience: List<String> = listOf(PRIVATPERSON),
language: String = NORWEGIAN_BOKMAAL,
fylke: String? = null,
metatags: List<String> = emptyList()
): ContentDao {
val title = "$textPrefix title"
val ingress = "$textPrefix ingress"
val text = "$textPrefix text"
return ContentDao(
id = "$teamName-$externalId",
autocomplete = Completion(listOf("$textPrefix title")),
teamOwnedBy = teamName,
href = "https://$textPrefix.com",
title = MultiLangFieldShort(value = title, language = language),
ingress = MultiLangFieldShort(value = ingress, language = language),
text = MultiLangFieldLong(value = text, language = language),
//allText = MultiLangFieldLong(value = text, language = language), todo: fix
type = ValidTypes.ANDRE.descriptor,
createdAt = timestamp,
lastUpdated = timestamp,
audience = audience,
language = language,
fylke = fylke,
metatags = metatags
)
}
fun dummyContentDto(
id: String? = "11",
href: String? = "https://eleventh.com",
title: String? = "Eleventh title",
ingress: String? = "Eleventh ingress",
text: String? = "Eleventh text",
type: String = ValidTypes.ANDRE.descriptor,
createdAt: ZonedDateTime? = now,
lastUpdated: ZonedDateTime? = now,
audience: List<String>? = listOf(SAMARBEIDSPARTNER),
language: String? = ENGLISH,
fylke: String? = null,
metatags: List<String> = emptyList(),
languageRefs: List<String> = emptyList(),
) = ContentDto(
id,
href,
title,
ingress,
text,
ContentMetadata(
type,
createdAt,
lastUpdated,
audience,
language,
fylke,
metatags,
languageRefs,
)
)
| 2 | Kotlin | 0 | 0 | fec2608cc31ddfa2a2d71a48bd43c45d5c15ec78 | 5,134 | navno-search-admin-api | MIT License |
presentation/src/main/java/hiennguyen/me/weatherapp/common/injection/qualifiers/ForAddressModel.kt | hiennguyen1001 | 123,107,985 | false | null | package hiennguyen.me.weatherapp.common.injection.qualifiers
import javax.inject.Qualifier
@Qualifier
@MustBeDocumented
@Retention
annotation class ForAddressModel
| 1 | null | 1 | 2 | a1d782792ccfabcad5710097b4132fc69883ec71 | 168 | weather-app-kotlin | MIT License |
app/shared/f8e-client/impl/src/commonMain/kotlin/build/wallet/f8e/partnerships/GetPurchaseRedirectServiceImpl.kt | proto-at-block | 761,306,853 | false | {"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.f8e.partnerships
import build.wallet.bitcoin.address.BitcoinAddress
import build.wallet.bitkey.f8e.FullAccountId
import build.wallet.f8e.F8eEnvironment
import build.wallet.f8e.client.F8eHttpClient
import build.wallet.f8e.partnerships.GetPurchaseRedirectF8eClient.Success
import build.wallet.ktor.result.NetworkingError
import build.wallet.ktor.result.RedactedRequestBody
import build.wallet.ktor.result.RedactedResponseBody
import build.wallet.ktor.result.bodyResult
import build.wallet.ktor.result.setRedactedBody
import build.wallet.money.FiatMoney
import build.wallet.partnerships.PartnershipTransactionId
import com.github.michaelbull.result.Result
import com.github.michaelbull.result.map
import io.ktor.client.request.post
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
class GetPurchaseRedirectF8eClientImpl(
private val f8eHttpClient: F8eHttpClient,
) : GetPurchaseRedirectF8eClient {
override suspend fun purchaseRedirect(
fullAccountId: FullAccountId,
address: BitcoinAddress,
f8eEnvironment: F8eEnvironment,
fiatAmount: FiatMoney,
partner: String,
paymentMethod: String,
quoteId: String?,
partnerTransactionId: PartnershipTransactionId?,
): Result<Success, NetworkingError> {
return f8eHttpClient
.authenticated(
accountId = fullAccountId,
f8eEnvironment = f8eEnvironment
)
.bodyResult<ResponseBody> {
post("/api/partnerships/purchases/redirects") {
setRedactedBody(
RequestBody(
address = address.address,
fiatAmount = fiatAmount.value.doubleValue(exactRequired = false),
fiatCurrency = fiatAmount.currency.textCode.code.uppercase(),
partner = partner,
paymentMethod = paymentMethod,
quoteId = quoteId,
partnerTransactionId = partnerTransactionId
)
)
}
}
.map { body ->
Success(
body.redirectInfo
)
}
}
@Serializable
private data class RequestBody(
val address: String,
@SerialName("fiat_amount")
val fiatAmount: Double,
@SerialName("fiat_currency")
val fiatCurrency: String,
val partner: String,
@SerialName("payment_method")
val paymentMethod: String,
@SerialName("quote_id")
val quoteId: String?,
@SerialName("partner_transaction_id")
val partnerTransactionId: PartnershipTransactionId?,
) : RedactedRequestBody
@Serializable
private data class ResponseBody(
@SerialName("redirect_info")
val redirectInfo: RedirectInfo,
) : RedactedResponseBody
}
| 3 | C | 16 | 98 | 1f9f2298919dac77e6791aa3f1dbfd67efe7f83c | 2,670 | bitkey | MIT License |
core/database/src/main/java/com/vproject/texttoimage/core/database/TextToImageDatabase.kt | viethua99 | 652,124,255 | false | {"Kotlin": 240107} | package com.vproject.texttoimage.core.database
import androidx.room.Database
import androidx.room.RoomDatabase
import com.vproject.texttoimage.core.database.dao.PromptDao
import com.vproject.texttoimage.core.database.entity.PromptEntity
@Database(entities = [PromptEntity::class], version = 1)
abstract class TextToImageDatabase : RoomDatabase() {
abstract fun promptDao(): PromptDao
} | 1 | Kotlin | 2 | 16 | fe9363cf032e9d3b32df8da026c39e9823aecb36 | 391 | Android-Text-to-Image | Apache License 2.0 |
app/src/main/java/com/nullpointer/dogedex/inject/OthersModule.kt | Hcnc100 | 523,932,808 | false | {"Kotlin": 233643} | package com.nullpointer.dogedex.inject
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.preferencesDataStoreFile
import androidx.room.Room
import androidx.security.crypto.EncryptedFile
import androidx.security.crypto.MasterKeys
import com.nullpointer.dogedex.database.DogeDexDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import io.github.osipxd.security.crypto.createEncrypted
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object OthersModule {
private const val NAME_DB = "DOGE_DEX_DB"
private const val NAME_SETTINGS = "DOGS_SETTINGS"
@Provides
@Singleton
fun provideDatabase(
@ApplicationContext context: Context
): DogeDexDatabase = Room.databaseBuilder(
context,
DogeDexDatabase::class.java,
NAME_DB
).fallbackToDestructiveMigration().build()
@Singleton
@Provides
fun providePreferencesDataStore(
@ApplicationContext appContext: Context
): DataStore<Preferences> {
return PreferenceDataStoreFactory.createEncrypted(
corruptionHandler = ReplaceFileCorruptionHandler(
produceNewData = { emptyPreferences() }
),
produceFile = {
val file = appContext.preferencesDataStoreFile(NAME_SETTINGS)
EncryptedFile.Builder(
file,
appContext,
MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build()
},
)
}
} | 0 | Kotlin | 0 | 0 | d518a4c462552b0f4744987b8e2363f1534dfe33 | 2,049 | DogeDexCompose | MIT License |
features/grind/domain/src/main/java/com/mctech/pokergrinder/grind/domain/usecase/CreateNewSessionUseCase.kt | MayconCardoso | 539,349,342 | false | {"Kotlin": 630714} | package com.mctech.pokergrinder.grind.domain.usecase
import com.mctech.pokergrinder.grind.domain.GrindRepository
import com.mctech.pokergrinder.grind.domain.entities.Session
import java.util.Calendar
import javax.inject.Inject
/**
* Responsible for creating a new grind session.
*
* @property repository grind data repository.
* @property generateUniqueIdUseCase use case responsible for generating a unique id.
*/
class CreateNewSessionUseCase @Inject constructor(
private val repository: GrindRepository,
private val generateUniqueIdUseCase: GenerateUniqueIdUseCase,
) {
suspend operator fun invoke(title: String) {
// Gets current session.
val currentSession = repository.loadCurrentSession()
// Close session if it's opened.
if (currentSession != null) {
repository.saveGrind(currentSession.copy(isOpened = false))
}
// Create session
val session = Session(
id = generateUniqueIdUseCase.invoke(),
cash = 0.0,
buyIn = 0.0,
title = title,
isOpened = true,
tournamentsPlayed = 0,
avgBuyIn = 0.0,
startTimeInMs = Calendar.getInstance().timeInMillis,
)
// Saves it
repository.saveGrind(session)
}
} | 7 | Kotlin | 1 | 7 | ecb4278d82b5e055b3dd1d08080ebbf8a17d2915 | 1,209 | poker-grinder | Apache License 2.0 |
client-api/src/test/kotlin/org/ostelco/prime/client/api/resources/SubscriptionsResourceTest.kt | sami-alajrami | 145,691,257 | false | {"Gradle": 25, "YAML": 32, "Markdown": 33, "Shell": 31, "Text": 1, "Ignore List": 11, "Batchfile": 1, "Dockerfile": 9, "Kotlin": 146, "XML": 27, "Java": 24, "Java Properties": 2, "OASv2-yaml": 2, "INI": 1, "Protocol Buffer": 2, "JSON": 3, "PlantUML": 19, "SVG": 13, "Cypher": 1} | package org.ostelco.prime.client.api.resources
import arrow.core.Either
import com.nhaarman.mockito_kotlin.argumentCaptor
import io.dropwizard.auth.AuthDynamicFeature
import io.dropwizard.auth.AuthValueFactoryProvider
import io.dropwizard.auth.oauth.OAuthCredentialAuthFilter
import io.dropwizard.testing.junit.ResourceTestRule
import org.assertj.core.api.Assertions.assertThat
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory
import org.junit.Before
import org.junit.ClassRule
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.ostelco.prime.client.api.auth.AccessTokenPrincipal
import org.ostelco.prime.client.api.auth.OAuthAuthenticator
import org.ostelco.prime.core.ApiError
import org.ostelco.prime.client.api.store.SubscriberDAO
import org.ostelco.prime.client.api.util.AccessToken
import org.ostelco.prime.model.Subscription
import java.util.*
import javax.ws.rs.client.Invocation
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
/**
* Subscription API tests.
*
*/
class SubscriptionsResourceTest {
private val email = "<EMAIL>"
private val subscription = Subscription(MSISDN)
@Before
@Throws(Exception::class)
fun setUp() {
`when`(AUTHENTICATOR.authenticate(ArgumentMatchers.anyString()))
.thenReturn(Optional.of(AccessTokenPrincipal(email)))
}
@Test
@Throws(Exception::class)
fun getSubscriptions() {
val arg = argumentCaptor<String>()
`when`<Either<ApiError, Collection<Subscription>>>(DAO.getSubscriptions(arg.capture())).thenReturn(Either.right(listOf(subscription)))
val resp = RULE.target("/subscriptions")
.request()
.header("Authorization", "Bearer ${AccessToken.withEmail(email)}")
.get(Response::class.java)
assertThat(resp.status).isEqualTo(Response.Status.OK.statusCode)
assertThat(resp.mediaType.toString()).isEqualTo(MediaType.APPLICATION_JSON)
// assertThat and assertEquals is not working
assertThat(subscription).isEqualTo(resp.readEntity(Array<Subscription>::class.java)[0])
assertThat(arg.firstValue).isEqualTo(email)
}
companion object {
val MSISDN = "msisdn"
val DAO: SubscriberDAO = mock(SubscriberDAO::class.java)
val AUTHENTICATOR: OAuthAuthenticator = mock(OAuthAuthenticator::class.java)
val request: Invocation.Builder = mock(Invocation.Builder::class.java)
@JvmField
@ClassRule
val RULE: ResourceTestRule = ResourceTestRule.builder()
.addResource(AuthDynamicFeature(
OAuthCredentialAuthFilter.Builder<AccessTokenPrincipal>()
.setAuthenticator(AUTHENTICATOR)
.setPrefix("Bearer")
.buildAuthFilter()))
.addResource(AuthValueFactoryProvider.Binder(AccessTokenPrincipal::class.java))
.addResource(SubscriptionsResource(DAO))
.setTestContainerFactory(GrizzlyWebTestContainerFactory())
.build()
}
}
| 1 | null | 1 | 1 | b642713279f783ca8fa643713cc34f6c8b3560cb | 3,211 | ostelco-core | Apache License 2.0 |
visionforge-threejs/src/jsMain/kotlin/space/kscience/visionforge/solid/three/ThreePointLightFactory.kt | SciProgCentre | 174,502,624 | false | {"Kotlin": 968491, "CSS": 913} | package space.kscience.visionforge.solid.three
import space.kscience.dataforge.names.asName
import space.kscience.visionforge.onPropertyChange
import space.kscience.visionforge.solid.LightSource
import space.kscience.visionforge.solid.PointLightSource
import three.lights.PointLight
import three.math.Color
import kotlin.reflect.KClass
public object ThreePointLightFactory : ThreeFactory<PointLightSource> {
override val type: KClass<in PointLightSource> get() = PointLightSource::class
private val DEFAULT_COLOR = Color(0x404040)
override suspend fun build(three: ThreePlugin, vision: PointLightSource, observe: Boolean): PointLight {
val res = PointLight().apply {
matrixAutoUpdate = false
color = vision.color.threeColor() ?: DEFAULT_COLOR
intensity = vision.intensity.toDouble()
updatePosition(vision)
}
if(observe) {
vision.onPropertyChange(three.context) { name ->
when (name) {
LightSource::color.name.asName() -> res.color = vision.color.threeColor() ?: DEFAULT_COLOR
LightSource::intensity.name.asName() -> res.intensity = vision.intensity.toDouble()
else -> res.updateProperty(vision, name)
}
}
}
return res
}
} | 15 | Kotlin | 6 | 34 | 8e5503f0d8480b9f879a32885f66c3ae0f163b10 | 1,348 | visionforge | Apache License 2.0 |
idea/testData/quickfix/experimental/experimentalUnused2.kt | arrow-kt | 109,678,056 | true | null | // "Safe delete 'Marker'" "false"
// COMPILER_ARGUMENTS: -Xuse-experimental=kotlin.Experimental -Xexperimental=test.Marker
// WITH_RUNTIME
// ACTION: Rename file to Marker.kt
// TOOL: org.jetbrains.kotlin.idea.inspections.UnusedSymbolInspection
package test
@Experimental
annotation class <caret>Marker
| 12 | Kotlin | 1 | 43 | d2a24985b602e5f708e199aa58ece652a4b0ea48 | 305 | kotlin | Apache License 2.0 |
analysis/low-level-api-fir/testData/lazyResolve/annotationWithCycleInDefaults.kt | JetBrains | 3,432,266 | false | null | annotation class WithCycle cons<caret>tructor(val param: WithCycle = WithCycle())
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 82 | kotlin | Apache License 2.0 |
cocache-core/src/main/kotlin/me/ahoo/cache/Cache.kt | Ahoo-Wang | 461,189,010 | false | null | /*
* Copyright [2021-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)].
* 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 me.ahoo.cache
import me.ahoo.cache.CacheValue.Companion.forever
import me.ahoo.cache.CacheValue.Companion.missingGuard
import me.ahoo.cache.CacheValue.Companion.missingGuardValue
/**
* Cache api.
*
* @author ahoo wang
*/
interface Cache<K, V> : CacheGetter<K, V> {
/**
* Get the real cache value.
*
* @param key cache key
* @return real cache value
*/
@Suppress("ReturnCount")
override fun get(key: K): V? {
val cacheValue = getCache(key) ?: return null
if (cacheValue.isMissingGuard || cacheValue.isExpired) {
return null
}
return cacheValue.value
}
fun getCache(key: K): CacheValue<V>?
/**
* get cache expire at time.
*
* @param key cache key
* @return when return null:cache not exist.
*/
@Suppress("ReturnCount")
fun getTtlAt(key: K): Long? {
val cacheValue = getCache(key) ?: return null
if (cacheValue.isMissingGuard) {
return null
}
return cacheValue.ttlAt
}
operator fun set(key: K, ttlAt: Long, value: V) {
setCache(key, CacheValue(value, ttlAt))
}
operator fun set(key: K, value: V) {
val cacheValue = if (missingGuardValue<Any>() == value) missingGuard() else forever(value)
setCache(key, cacheValue)
}
fun setCache(key: K, value: CacheValue<V>)
/**
* evict cache.
*
* @param key cache key
*/
fun evict(key: K)
}
| 3 | Kotlin | 0 | 7 | 4244f12425a48d30cdc0b35d21ed2905d19da7d1 | 2,138 | CoCache | Apache License 2.0 |
features/app-widgets/src/main/java/app/ss/widgets/glance/BaseGlanceAppWidgetReceiver.kt | Adventech | 65,243,816 | false | null | /*
* Copyright (c) 2023. Adventech <<EMAIL>>
*
* 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 NON-INFRINGEMENT. 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 app.ss.widgets.glance
import android.content.Context
import android.content.Intent
import androidx.glance.ExperimentalGlanceApi
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.updateAll
import app.ss.widgets.BaseWidgetProvider
import app.ss.widgets.WidgetDataProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import ss.foundation.coroutines.Scopable
import javax.inject.Inject
abstract class BaseGlanceAppWidgetReceiver<T : GlanceAppWidget> :
GlanceAppWidgetReceiver(),
Scopable {
@Inject
internal lateinit var widgetDataProvider: WidgetDataProvider
override val glanceAppWidget: GlanceAppWidget
get() = createWidget()
abstract fun createWidget(): T
@OptIn(ExperimentalGlanceApi::class)
override val scope: CoroutineScope get() = CoroutineScope(SupervisorJob() + coroutineContext)
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
if (intent.action == BaseWidgetProvider.REFRESH_ACTION) {
scope.launch { glanceAppWidget.updateAll(context) }
}
}
}
| 8 | null | 45 | 163 | 63bcdbf9420d98f318d2b1654e9e1b194e1d6c68 | 2,380 | sabbath-school-android | MIT License |
composeApp/src/commonMain/kotlin/com/rwmobi/kunigami/ui/previewsampledata/InsightsSamples.kt | ryanw-mobile | 794,752,204 | false | {"Kotlin": 1440473, "Ruby": 2466, "Swift": 693} | /*
* Copyright (c) 2024. RW MobiMedia UK Limited
*
* Contributions made by other developers remain the property of their respective authors but are licensed
* to RW MobiMedia UK Limited and others under the same licence terms as the main project, as outlined in
* the LICENSE file.
*
* RW MobiMedia UK Limited reserves the exclusive right to distribute this application on app stores.
* Reuse of this source code, with or without modifications, requires proper attribution to
* RW MobiMedia UK Limited. Commercial distribution of this code or its derivatives without prior written
* permission from RW MobiMedia UK Limited is prohibited.
*
* Please refer to the LICENSE file for the full terms and conditions.
*/
package com.rwmobi.kunigami.ui.previewsampledata
import com.rwmobi.kunigami.ui.model.consumption.Insights
internal object InsightsSamples {
val trueCost = Insights(
consumptionAggregateRounded = 85.115,
consumptionTimeSpan = 303,
consumptionChargeRatio = 0.64,
costWithCharges = 90.988,
consumptionDailyAverage = 32.611,
costDailyAverage = 12.434,
consumptionAnnualProjection = 30.235,
costAnnualProjection = 11.487,
isTrueCost = true,
)
}
| 16 | Kotlin | 10 | 145 | 7f278204448e9c59ca028e520e9e5aca97fa1e13 | 1,250 | OctoMeter | Creative Commons Attribution 4.0 International |
swc-binding/src/main/kotlin/dev/yidafu/swc/dsl/PropBase.kt | yidafu | 745,507,915 | false | {"Kotlin": 1532978, "JavaScript": 1186983, "TypeScript": 52873, "Rust": 15241, "Shell": 2012} | package dev.yidafu.swc.dsl
import dev.yidafu.swc.types.*
/**
* subtype of PropBase
*/
fun PropBase.keyValueProperty(block: KeyValueProperty.() -> Unit): KeyValueProperty {
return KeyValuePropertyImpl().apply(block)
}
/**
* subtype of PropBase
*/
fun PropBase.getterProperty(block: GetterProperty.() -> Unit): GetterProperty {
return GetterPropertyImpl().apply(block)
}
/**
* subtype of PropBase
*/
fun PropBase.setterProperty(block: SetterProperty.() -> Unit): SetterProperty {
return SetterPropertyImpl().apply(block)
}
/**
* subtype of PropBase
*/
fun PropBase.methodProperty(block: MethodProperty.() -> Unit): MethodProperty {
return MethodPropertyImpl().apply(block)
}
/**
* PropBase#key: PropertyName
* extension function for create PropertyName -> IdentifierImpl
*/
fun PropBase.identifier(block: Identifier.() -> Unit): Identifier {
return IdentifierImpl().apply(block)
}
/**
* PropBase#key: PropertyName
* extension function for create PropertyName -> StringLiteralImpl
*/
fun PropBase.stringLiteral(block: StringLiteral.() -> Unit): StringLiteral {
return StringLiteralImpl().apply(block)
}
/**
* PropBase#key: PropertyName
* extension function for create PropertyName -> NumericLiteralImpl
*/
fun PropBase.numericLiteral(block: NumericLiteral.() -> Unit): NumericLiteral {
return NumericLiteralImpl().apply(block)
}
/**
* PropBase#key: PropertyName
* extension function for create PropertyName -> ComputedPropNameImpl
*/
fun PropBase.computedPropName(block: ComputedPropName.() -> Unit): ComputedPropName {
return ComputedPropNameImpl().apply(block)
}
/**
* PropBase#key: PropertyName
* extension function for create PropertyName -> BigIntLiteralImpl
*/
fun PropBase.bigIntLiteral(block: BigIntLiteral.() -> Unit): BigIntLiteral {
return BigIntLiteralImpl().apply(block)
} | 1 | Kotlin | 0 | 0 | fecf831e1b47f4693eba781e74d3cf7df22dfac7 | 1,851 | swc-binding | Apache License 2.0 |
app/src/main/kotlin/com/absinthe/libchecker/model/KotlinToolingMetadata.kt | LibChecker | 248,400,799 | false | {"Kotlin": 1060313, "Java": 56760, "AIDL": 1149} | package com.absinthe.libchecker.model
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class KotlinToolingMetadata(
val buildPlugin: String,
val buildPluginVersion: String
)
| 38 | Kotlin | 246 | 2,894 | 82c49ec6b5a1d3da3a60de6dcaf79332c7424f23 | 207 | LibChecker | Apache License 2.0 |
kandy-lets-plot/src/main/kotlin/org/jetbrains/kotlinx/kandy/letsplot/layers/vLine.kt | Kotlin | 502,039,936 | false | null | /*
* Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.kotlinx.kandy.letsplot.layers
import org.jetbrains.kotlinx.kandy.dsl.internal.LayerCollectorContext
import org.jetbrains.kotlinx.kandy.letsplot.internal.LetsPlotGeom
import org.jetbrains.kotlinx.kandy.letsplot.layers.context.VLineContext
// TODO
@PublishedApi
internal val V_LINE: LetsPlotGeom = LetsPlotGeom("vLine")
/**
* Adds a new vertical line layer.
*
* Creates a context in which you can configure layer. Within it, you can set mappings and settings
* on aesthetic attributes. Mappings allow you to set a relationship between data and attribute values,
* while settings allow you to assign a constant value to the attributes.
*
* Mapping can be performed via method with name of corresponding aes.
* Setting for non-positional attributes can be performed with simple assignment of variable with name of aes.
* Setting for positional attributes can be performed with `.constant()` method of special property with
* the same name as the attribute.
*
* Vertical ine aesthetics:
* * `x`
* * `color`
* * `type`
* * `width`
* * `alpha`
*
* Example:
*
* ```
* vLine {
* // positional mapping
* x(count) {
* ... // some mapping parameters
* }
* // even though the v-line have no "y" attribute we can adjust the `Y` axis
* y.limits = 0.0 to 5.0
* // non-positional setting
* width = 2.5
* // non-positional mapping
* color("count")
* }
* ```
*/
public inline fun LayerCollectorContext.vLine(block: VLineContext.() -> Unit) {
addLayer(VLineContext(this).apply(block), V_LINE)
} | 79 | Kotlin | 0 | 98 | fd613edc4dd37aac0d0ecdb4245a770e09617fc7 | 1,681 | kandy | Apache License 2.0 |
kotlin-csstype/src/main/generated/csstype/WordBreak.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package csstype
// language=JavaScript
@JsName("""(/*union*/{breakAll: 'break-all', breakWord: 'break-word', keepAll: 'keep-all', normal: 'normal'}/*union*/)""")
sealed external interface WordBreak {
companion object {
val breakAll: WordBreak
val breakWord: WordBreak
val keepAll: WordBreak
val normal: WordBreak
}
}
| 12 | Kotlin | 6 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 499 | kotlin-wrappers | Apache License 2.0 |
Project/library/analytic/src/main/java/com/singularityindonesia/analytic/Report.kt | SingularityIndonesia | 766,901,851 | false | {"Kotlin": 57383} | /*
* Copyright (c) 2024 <NAME> (<EMAIL>)
* Created on 04/03/2024 12:00
* You are not allowed to remove the copyright.
*/
package com.singularityindonesia.analytic
import android.util.Log
import com.singularityindonesia.exception.MException
import kotlinx.coroutines.*
@OptIn(DelicateCoroutinesApi::class)
fun MException.report() {
GlobalScope.launch {
withContext(Dispatchers.IO) {
// fixme: report the exception here
Log.d("MException", "report: $this")
}
}
} | 0 | Kotlin | 0 | 0 | bb560726e4f8269aff123e2075eb5896280b58ae | 514 | SingularityAndroidApp | Creative Commons Zero v1.0 Universal |
app/app/src/main/kotlin/tech/nagual/phoenix/tools/organizer/data/dao/OrganizerDao.kt | overphoenix | 621,371,055 | false | null | package tech.nagual.phoenix.tools.organizer.data.dao
import androidx.room.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import tech.nagual.phoenix.tools.organizer.data.model.Organizer
@Dao
interface OrganizerDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(organizer: Organizer): Long
@Query("SELECT MAX(ordinal) FROM organizers")
fun getMaxOrdinal(): Flow<Long?>
@Transaction
suspend fun insertWithOrdinal(organizer: Organizer): Long {
val maxOrdinal = getMaxOrdinal().first()
val nextOrdinal = if (maxOrdinal == null) 0 else maxOrdinal + 1L
return insert(
organizer.copy(
ordinal = nextOrdinal.toInt()
)
)
}
@Delete
suspend fun delete(organizer: Organizer)
@Transaction
suspend fun deleteAndFixOrdinals(organizer: Organizer) {
delete(organizer)
val organizers = getAllFromOrdinal(organizer.ordinal).first().toMutableList()
for (i in 0 until organizers.size) {
val organizer = organizers[i]
organizers[i] = organizer.copy(ordinal = organizer.ordinal - 1)
}
update(*organizers.toTypedArray())
}
@Update
suspend fun update(vararg organizers: Organizer)
@Query("SELECT * FROM organizers WHERE id = :organizerId")
fun getById(organizerId: Long): Flow<Organizer?>
@Query("SELECT * FROM organizers WHERE ordinal = :ordinal")
fun getByOrdinal(ordinal: Int): Flow<Organizer?>
@Query("SELECT * FROM organizers WHERE ordinal > :ordinal")
fun getAllFromOrdinal(ordinal: Int): Flow<List<Organizer>>
@Query("SELECT * FROM organizers ORDER BY ordinal ASC")
fun getAll(): Flow<List<Organizer>>
@Query("SELECT * FROM organizers WHERE name = :organizerName LIMIT 1")
fun getByName(organizerName: String): Flow<Organizer?>
}
| 0 | Kotlin | 0 | 0 | 64264f261c2138d5f1932789702661917bbfae28 | 1,906 | phoenix-android | Apache License 2.0 |
mobile-common-lib/src/commonMain/kotlin/fi/riista/common/domain/srva/sync/network/FetchSrvaEvents.kt | suomenriistakeskus | 78,840,058 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 2, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 4, "Gradle Kotlin DSL": 1, "Kotlin": 1344, "XML": 401, "Java": 161, "Protocol Buffer": 1, "JSON": 1} | package fi.riista.common.domain.srva.sync.network
import fi.riista.common.domain.constants.Constants
import fi.riista.common.domain.srva.sync.dto.SrvaEventPageDTO
import fi.riista.common.model.LocalDateTime
import fi.riista.common.network.NetworkClient
import fi.riista.common.network.calls.NetworkRequest
import fi.riista.common.network.calls.NetworkResponse
import io.ktor.client.request.*
import io.ktor.http.*
internal class FetchSrvaEvents(
private val modifiedAfter: LocalDateTime?,
) : NetworkRequest<SrvaEventPageDTO> {
override suspend fun request(client: NetworkClient): NetworkResponse<SrvaEventPageDTO> {
val baseUrl = "${client.serverBaseAddress}/api/mobile/v2/srva/srvaevents/page?srvaEventSpecVersion=${Constants.SRVA_SPEC_VERSION}"
val url = if (modifiedAfter != null) {
"$baseUrl&modifiedAfter=${modifiedAfter.toStringISO8601()}"
} else {
baseUrl
}
return client.request(
request = {
get(urlString = url) {
accept(ContentType.Application.Json)
}
},
configureResponseHandler = {
// nop, default response handling works just fine
}
)
}
}
| 0 | Kotlin | 0 | 3 | 23645d1abe61c68d649b6d0ca1d16556aa8ffa16 | 1,256 | oma-riista-android | MIT License |
temporal-kotlin/src/main/kotlin/io/temporal/workflow/ActivityStubExt.kt | imalao | 455,798,604 | true | {"Shell": 2, "Markdown": 10, "Batchfile": 1, "Kotlin": 41, "Java": 639, "Dockerfile": 2, "Java Properties": 2, "INI": 1} | /*
* Copyright (C) 2020 Temporal Technologies, Inc. All Rights Reserved.
*
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Modifications copyright (C) 2017 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.temporal.workflow
import kotlin.reflect.javaType
import kotlin.reflect.typeOf
/**
* Executes an activity by its type name and arguments. Blocks until the activity completion.
*
* @param activityName name of an activity type to execute.
* @param T the expected return class of the activity. Use `Void` for activities that return void
* type.
* @see ActivityStub.execute
*/
@OptIn(ExperimentalStdlibApi::class)
inline fun <reified T> ActivityStub.execute(activityName: String, vararg args: Any?): T {
return execute(activityName, T::class.java, typeOf<T>().javaType, args)
}
/**
* Executes an activity asynchronously by its type name and arguments.
*
* @param activityName name of an activity type to execute.
* @param T the expected return class of the activity. Use `Void` for activities that return void
* type.
* @see ActivityStub.executeAsync
*/
@OptIn(ExperimentalStdlibApi::class)
inline fun <reified T> ActivityStub.executeAsync(
activityName: String,
vararg args: Any?
): Promise<T> {
return executeAsync(activityName, T::class.java, typeOf<T>().javaType, args)
}
| 0 | null | 0 | 0 | d92db251b725c3aea4bc37337a27279232703437 | 1,840 | sdk-java | Apache License 2.0 |
framework/src/main/java/com/grarcht/shuttle/framework/content/bundle/DefaultBundleFactory.kt | grarcht | 330,873,493 | false | null | package com.grarcht.shuttle.framework.content.bundle
import android.os.Bundle
import android.os.PersistableBundle
/**
* This contractual interface is used to provide a factory that [Bundle] objects. Having this
* factory enables for unit testing of [Bundle] objects in the Shuttle Framework.
*
* For more information on the factory design pattern, refer to:
* <a href="https://www.tutorialspoint.com/design_pattern/factory_pattern.htm">Factory Design Pattern</a>
*/
open class DefaultBundleFactory : BundleFactory {
/**
* @return the newly created bundle reference
*/
override fun create(): Bundle {
return Bundle()
}
/**
* @param loader An explicit ClassLoader to use when instantiating objects inside of the Bundle.
* @return the newly created bundle reference
*/
override fun create(loader: ClassLoader?): Bundle {
return Bundle(loader)
}
/**
* @param capacity The initial capacity of the Bundle
* @return the newly created bundle reference
*/
override fun create(capacity: Int): Bundle {
return Bundle(capacity)
}
/**
* @param bundle A bundle to be shallow copied.
* @return the newly created bundle reference
*/
override fun create(bundle: Bundle): Bundle {
return Bundle(bundle)
}
/**
* @param bundle APersistableBundle to be shallow copied.
* @return the newly created bundle reference
*/
override fun create(bundle: PersistableBundle): Bundle {
return Bundle(bundle)
}
}
| 0 | Kotlin | 1 | 42 | e3b06ef6e06b7fd48e6d9cdfb09f2c6176812532 | 1,567 | Shuttle | MIT License |
vector/src/test/java/com/haroldadmin/vector/VectorStateFactoryTest.kt | haroldadmin | 190,186,711 | false | null | package com.haroldadmin.vector
import io.mockk.mockk
import org.junit.Before
import org.junit.Test
internal class VectorStateFactoryTest {
private lateinit var factory: VectorStateFactory
@Before
fun setup() {
factory = RealStateFactory()
}
@Test(expected = UnInstantiableStateClassException::class)
fun `should fail to create state when there's no ViewModel Companion Factory or Default params`() {
val state = factory.createInitialState(
TestViewModel::class,
TestStates.TestState::class,
mockk(),
mockk()
)
assert(state.count == 42)
}
@Test
fun `should create state using default parameters when there is no Companion Factory`() {
val state = factory.createInitialState(
TestViewModel::class,
TestStates.TestStateWithDefaults::class,
mockk(),
mockk()
)
assert(state.count == 42)
}
@Test
fun `should use companion factory to create state when it is present`() {
val state = factory.createInitialState(
TestViewModelWithFactory::class,
TestStates.TestState::class,
mockk(),
mockk()
)
assert(state.count == 0)
}
@Test
fun `should prefer companion factory over default params when creating state`() {
val state = factory.createInitialState(
TestViewModelWithFactoryAndDefaults::class,
TestStates.TestStateWithDefaults::class,
mockk(),
mockk()
)
assert(state.count == 0)
}
}
| 13 | Kotlin | 7 | 197 | 2f52fd2b42cfc516854c6ae534cdd9f73e982579 | 1,641 | Vector | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/s3/notifications/SqsDestination.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 142794926} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.s3.notifications
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.services.s3.BucketNotificationDestinationConfig
import io.cloudshiftdev.awscdk.services.s3.IBucket
import io.cloudshiftdev.awscdk.services.s3.IBucketNotificationDestination
import io.cloudshiftdev.awscdk.services.sqs.IQueue
import io.cloudshiftdev.constructs.Construct
/**
* Use an SQS queue as a bucket notification destination.
*
* Example:
*
* ```
* Queue myQueue;
* Bucket bucket = new Bucket(this, "MyBucket");
* bucket.addEventNotification(EventType.OBJECT_REMOVED, new SqsDestination(myQueue),
* NotificationKeyFilter.builder()
* .prefix("foo/")
* .suffix(".jpg")
* .build());
* ```
*/
public open class SqsDestination internal constructor(
internal override val cdkObject: software.amazon.awscdk.services.s3.notifications.SqsDestination,
) : CdkObject(cdkObject), IBucketNotificationDestination {
public constructor(queue: IQueue) :
this(software.amazon.awscdk.services.s3.notifications.SqsDestination(queue.let(IQueue::unwrap))
)
/**
* Allows using SQS queues as destinations for bucket notifications.
*
* Use `bucket.onEvent(event, queue)` to subscribe.
*
* @param _scope
* @param bucket
*/
public override fun bind(scope: Construct, bucket: IBucket): BucketNotificationDestinationConfig =
unwrap(this).bind(scope.let(Construct::unwrap),
bucket.let(IBucket::unwrap)).let(BucketNotificationDestinationConfig::wrap)
public companion object {
internal fun wrap(cdkObject: software.amazon.awscdk.services.s3.notifications.SqsDestination):
SqsDestination = SqsDestination(cdkObject)
internal fun unwrap(wrapped: SqsDestination):
software.amazon.awscdk.services.s3.notifications.SqsDestination = wrapped.cdkObject
}
}
| 1 | Kotlin | 0 | 4 | a18731816a3ec710bc89fb8767d2ab71cec558a6 | 2,034 | kotlin-cdk-wrapper | Apache License 2.0 |
common/data/src/main/java/tech/antee/products/data/repositories/ProductsRepositoryImpl.kt | AnteeOne | 567,392,451 | false | null | package tech.antee.products.data.repositories
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import tech.antee.products.data.local.sources.ProductsLocalSource
import tech.antee.products.data.mappers.ProductDomainMapper
import tech.antee.products.domain.models.Product
import tech.antee.products.domain.repositories.ProductsRepository
import javax.inject.Inject
class ProductsRepositoryImpl @Inject constructor(
private val productsLocalSource: ProductsLocalSource,
private val productDomainMapper: ProductDomainMapper
) : ProductsRepository {
override val productsFlow: Flow<List<Product>> = productsLocalSource
.productsFlow
.map(productDomainMapper::mapListFromData)
override suspend fun fetch() = productsLocalSource.fetch()
override suspend fun delete(id: String) = productsLocalSource.delete(id)
override suspend fun delete(ids: List<String>) = productsLocalSource.delete(ids.toHashSet())
}
| 0 | Kotlin | 0 | 0 | 15830ac1884f80a82e9730b6cde2934791e58810 | 966 | products-test-app | MIT License |
app/src/main/java/kz/coffee/go/presentation/addCashback/AddCashbackViewModel.kt | rohitnotes | 288,507,024 | true | {"Kotlin": 104712} | package kz.coffee.go.presentation.addCashback
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import kz.coffee.go.domain.purchaseHistory.IPurchaseHistory
import kz.coffee.go.domain.purchaseHistory.PurchaseHistory
import kz.coffee.go.domain.user.IUsers
import kz.coffee.go.domain.user.User
import kz.coffee.go.presentation.base.BaseViewModel
import kz.coffee.go.utils.Resource
import java.lang.Exception
class AddCashbackViewModel(private val useCase: IUsers, private val purchaseUseCase: IPurchaseHistory) : BaseViewModel() {
fun getUserById() = liveData(coroutineContext.io) {
emit(Resource.Loading())
try {
val user = useCase.getUserById()
emit(user)
} catch (e: Exception) {
emit(Resource.Failure(e))
}
}
fun saveUserData(user: User) = liveData(coroutineContext.io) {
emit(Resource.Loading())
try {
val isUserDataSaved = useCase.changeUserData(user)
emit(isUserDataSaved)
} catch (e: Exception) {
emit(Resource.Failure(e))
}
}
fun savePurchaseHistory(purchaseHistory: PurchaseHistory, cafeteriaId: String) = liveData(coroutineContext.io) {
emit(Resource.Loading())
try {
val isPurchaseHistorySaved = purchaseUseCase.savePurchaseHistory(purchaseHistory, cafeteriaId)
emit(isPurchaseHistorySaved)
} catch (e: Exception) {
emit(Resource.Failure(e))
}
}
}
| 0 | null | 0 | 0 | fc72529cdf345d373331dbc516901a049b4ab757 | 1,512 | CoffeeGo | MIT License |
domain/src/main/kotlin/io/github/wykopmobilny/domain/errorhandling/KnownError.kt | otwarty-wykop-mobilny | 374,160,630 | true | {"Kotlin": 1326147, "HTML": 66896, "Java": 38599} | package io.github.wykopmobilny.domain.errorhandling
sealed class KnownError : Throwable() {
data class TwoFactorAuthorizationRequired(override val message: String) : KnownError()
}
| 13 | Kotlin | 4 | 47 | 85b54b736f5fbcd6f62305779ed7ae2085c3b136 | 187 | wykop-android | MIT License |
src/main/kotlin/org/rust/ide/formatter/RsCommaFormatProcessor.kt | torkleyy | 80,134,118 | false | null | package org.rust.ide.formatter
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.impl.source.codeStyle.PostFormatProcessor
import com.intellij.psi.impl.source.codeStyle.PostFormatProcessorHelper
import org.rust.lang.core.psi.RsElementTypes.COMMA
import org.rust.lang.core.psi.RsStructExprBody
import org.rust.lang.core.psi.util.elementType
import org.rust.lang.core.psi.util.getPrevNonCommentSibling
class RsCommaFormatProcessor : PostFormatProcessor {
override fun processElement(source: PsiElement, settings: CodeStyleSettings): PsiElement {
doProcess(source, settings, null)
return source
}
override fun processText(source: PsiFile, rangeToReformat: TextRange, settings: CodeStyleSettings): TextRange {
return doProcess(source, settings, rangeToReformat).resultTextRange
}
private fun doProcess(source: PsiElement, settings: CodeStyleSettings, range: TextRange? = null): PostFormatProcessorHelper {
val helper = PostFormatProcessorHelper(settings)
helper.resultTextRange = range
source.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitElement(element: PsiElement?) {
super.visitElement(element)
if (element is RsStructExprBody && helper.isElementFullyInRange(element)) {
if (fixStructExprBody(element)) {
helper.updateResultRange(1, 0)
}
}
}
})
return helper
}
companion object {
/**
* Delete trailing comma in one-line structs
*/
fun fixStructExprBody(body: RsStructExprBody): Boolean {
if (PostFormatProcessorHelper.isMultiline(body)) return false
val lbrace = body.rbrace ?: return false
val comma = lbrace.getPrevNonCommentSibling() ?: return false
return if (comma.elementType == COMMA) {
comma.delete()
true
} else {
false
}
}
}
}
| 1 | null | 1 | 1 | 4c59102038de2252b150c8c234d39a083632d976 | 2,260 | intellij-rust | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.