repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/destructuringDeclInLambdaParam/stdlibUsages.kt | 2 | 279 | // WITH_RUNTIME
fun box(): String {
val r1 = listOf("O", "K", "fail").let {
(x, y) -> x + y
}
if (r1 != "OK") return "fail 1: $r1"
val r2 = listOf(Pair("O", "K")).map { (x, y) -> x + y }[0]
if (r2 != "OK") return "fail 2: $r2"
return "OK"
}
| apache-2.0 |
hardikamal/AppIntro | appintro/src/main/java/com/github/appintro/AppIntroViewPagerListener.kt | 4 | 690 | package com.github.appintro
/**
* Register an instance of AppIntroViewPagerListener.
* Before the user swipes to the next page, this listener will be called and
* can interrupt swiping by returning false to [onCanRequestNextPage]
*
* [onIllegallyRequestedNextPage] will be called if the user tries to swipe and was not allowed
* to do so (useful for showing a toast or something similar).
*
* [onUserRequestedPermissionsDialog] will be called when the user swipes forward on a slide
* that contains permissions.
*/
interface AppIntroViewPagerListener {
fun onCanRequestNextPage(): Boolean
fun onIllegallyRequestedNextPage()
fun onUserRequestedPermissionsDialog()
}
| apache-2.0 |
olivierperez/crapp | lib/src/main/java/fr/o80/sample/lib/core/presenter/PresenterView.kt | 1 | 103 | package fr.o80.sample.lib.core.presenter
/**
* @author Olivier Perez
*/
interface PresenterView {
}
| apache-2.0 |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/track/EnhancedTrackService.kt | 1 | 1401 | package eu.kanade.tachiyomi.data.track
import eu.kanade.domain.track.model.Track
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import eu.kanade.tachiyomi.source.Source
import eu.kanade.domain.manga.model.Manga as DomainManga
/**
* An Enhanced Track Service will never prompt the user to match a manga with the remote.
* It is expected that such Track Service can only work with specific sources and unique IDs.
*/
interface EnhancedTrackService {
/**
* This TrackService will only work with the sources that are accepted by this filter function.
*/
fun accept(source: Source): Boolean {
return source::class.qualifiedName in getAcceptedSources()
}
/**
* Fully qualified source classes that this track service is compatible with.
*/
fun getAcceptedSources(): List<String>
/**
* match is similar to TrackService.search, but only return zero or one match.
*/
suspend fun match(manga: Manga): TrackSearch?
/**
* Checks whether the provided source/track/manga triplet is from this TrackService
*/
fun isTrackFrom(track: Track, manga: DomainManga, source: Source?): Boolean
/**
* Migrates the given track for the manga to the newSource, if possible
*/
fun migrateTrack(track: Track, manga: DomainManga, newSource: Source): Track?
}
| apache-2.0 |
exponentjs/exponent | packages/expo-image/android/src/main/java/expo/modules/image/svg/SVGSoftwareLayerSetter.kt | 2 | 1617 | package expo.modules.image.svg
import android.widget.ImageView
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.ImageViewTarget
import com.bumptech.glide.request.target.Target
/**
* Listener which updates the [ImageView] to be software rendered, because [ ]/[android.graphics.Picture] can't render on a
* hardware backed [Canvas][android.graphics.Canvas].
*
* Copied from https://github.com/bumptech/glide/blob/10acc31a16b4c1b5684f69e8de3117371dfa77a8/samples/svg/src/main/java/com/bumptech/glide/samples/svg/SvgSoftwareLayerSetter.java
* and rewritten to Kotlin.
*/
class SVGSoftwareLayerSetter @JvmOverloads constructor(private val mDefaultLayerType: Int = ImageView.LAYER_TYPE_NONE) : RequestListener<Any> {
override fun onLoadFailed(e: GlideException?, model: Any, target: Target<Any>, isFirstResource: Boolean): Boolean {
getViewOfTarget(target)?.setLayerType(mDefaultLayerType, null)
return false
}
override fun onResourceReady(resource: Any, model: Any, target: Target<Any>, dataSource: DataSource, isFirstResource: Boolean): Boolean {
getViewOfTarget(target)?.apply {
if (resource is SVGDrawable) {
setLayerType(ImageView.LAYER_TYPE_SOFTWARE, null)
}
}
return false
}
private fun getViewOfTarget(target: Target<Any>): ImageView? {
if (target is ImageViewTarget<*>) {
val imageViewTarget: ImageViewTarget<*> = target as ImageViewTarget<Any>
return imageViewTarget.view
}
return null
}
}
| bsd-3-clause |
hgschmie/jdbi | kotlin/src/test/kotlin/org/jdbi/v3/core/kotlin/KotlinPluginTest.kt | 2 | 3825 | /*
* 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.jdbi.v3.core.kotlin
import org.jdbi.v3.core.extension.ExtensionCallback
import org.jdbi.v3.core.extension.ExtensionConsumer
import org.jdbi.v3.sqlobject.customizer.Bind
import org.jdbi.v3.sqlobject.statement.SqlQuery
import org.jdbi.v3.testing.junit5.JdbiExtension
import org.jdbi.v3.testing.junit5.internal.TestingInitializers
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
import kotlin.test.assertEquals
class KotlinPluginTest {
@RegisterExtension
@JvmField
val h2Extension: JdbiExtension = JdbiExtension.h2().installPlugins().withInitializer(TestingInitializers.something())
data class Thing(
val id: Int,
val name: String,
val nullable: String?,
val nullableDefaultedNull: String? = null,
val nullableDefaultedNotNull: String? = "not null",
val defaulted: String = "default value"
)
interface ThingDao {
@SqlQuery("select id, name from something where id = :id")
fun getById(@Bind("id") id: Int): Thing
}
val brian = Thing(1, "Brian", null)
val keith = Thing(2, "Keith", null)
@BeforeEach
fun setUp() {
val upd = h2Extension.sharedHandle.prepareBatch("insert into something (id, name) values (:id, :name)")
listOf(brian, keith).forEach {
upd.bindBean(it).add()
}
upd.execute()
}
@Test
fun testFindById() {
val qry = h2Extension.sharedHandle.createQuery("select id, name from something where id = :id")
val things: List<Thing> = qry.bind("id", brian.id).mapTo<Thing>().list()
assertEquals(1, things.size)
assertEquals(brian, things[0])
}
@Test
fun testFindByIdWithNulls() {
val qry = h2Extension.sharedHandle.createQuery(
"select " +
"id, " +
"name, " +
"null as nullable, " +
"null as nullableDefaultedNull, " +
"null as nullableDefaultedNotNull, " +
"'test' as defaulted " +
"from something where id = :id"
)
val things: List<Thing> = qry.bind("id", brian.id).mapTo<Thing>().list()
assertEquals(1, things.size)
assertEquals(brian.copy(nullableDefaultedNotNull = null, defaulted = "test"), things[0])
}
@Test
fun testFindAll() {
val qryAll = h2Extension.sharedHandle.createQuery("select id, name from something")
qryAll.mapTo<Thing>().useSequence {
assertEquals(keith, it.drop(1).first())
}
}
@Test
fun testWithExtensionKClass() {
val result = h2Extension.jdbi.withExtension(
ThingDao::class,
ExtensionCallback<Thing, ThingDao, RuntimeException> { extension ->
extension.getById(brian.id)
}
)
assertEquals(result, brian)
}
@Test
fun testUseExtensionKClass() {
h2Extension.jdbi.useExtension(
ThingDao::class,
ExtensionConsumer<ThingDao, RuntimeException> { extension ->
val result = extension.getById(brian.id)
assertEquals(result, brian)
}
)
}
}
| apache-2.0 |
sjnyag/stamp | app/src/androidTest/java/com/sjn/stamp/ExampleInstrumentedTest.kt | 1 | 671 | package com.sjn.stamp
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.sjn.stamp", appContext.packageName)
}
}
| apache-2.0 |
square/wire | wire-library/wire-tests/src/jvmKotlinInteropTest/proto-kotlin/com/squareup/wire/protos/custom_options/EnumValueOptionOption.kt | 2 | 637 | // Code generated by Wire protocol buffer compiler, do not edit.
// Source: squareup.protos.custom_options.enum_value_option in custom_options.proto
package com.squareup.wire.protos.custom_options
import kotlin.Int
import kotlin.`annotation`.AnnotationRetention
import kotlin.`annotation`.AnnotationTarget
import kotlin.`annotation`.Retention
import kotlin.`annotation`.Target
/**
* This is a nice option! Apply it to your friendly enum constants.
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(
AnnotationTarget.PROPERTY,
AnnotationTarget.FIELD,
)
public annotation class EnumValueOptionOption(
public val `value`: Int,
)
| apache-2.0 |
ThoseGrapefruits/intellij-rust | src/test/kotlin/org/rust/lang/core/resolve/RustUseResolveTestCase.kt | 1 | 545 | package org.rust.lang.core.resolve
class RustUseResolveTestCase : RustResolveTestCaseBase() {
override fun getTestDataPath() = super.getTestDataPath() + "/use"
fun testViewPath() = checkIsBound()
fun testUsePath() = checkIsBound()
fun testChildFromParent() = checkIsBound(atOffset = 117)
fun testPathRename() = checkIsBound(atOffset = 3)
fun testDeepRedirection() = checkIsBound(atOffset = 21)
fun testRelativeChild() = checkIsBound()
fun testNoUse() = checkIsUnbound()
fun testCycle() = checkIsUnbound()
}
| mit |
Maccimo/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/PackageSearchPanelBase.kt | 2 | 1770 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataProvider
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
internal abstract class PackageSearchPanelBase(@Nls val title: String) : DataProvider {
val content: JComponent by lazy { build() }
val toolbar: JComponent? by lazy { buildToolbar() }
val topToolbar: JComponent? by lazy { buildTopToolbar() }
val gearActions: ActionGroup? by lazy { buildGearActions() }
val titleActions: Array<AnAction>? by lazy { buildTitleActions() }
protected abstract fun build(): JComponent
protected open fun buildToolbar(): JComponent? = null
protected open fun buildTopToolbar(): JComponent? = null
protected open fun buildGearActions(): ActionGroup? = null
protected open fun buildTitleActions(): Array<AnAction>? = null
}
| apache-2.0 |
onoderis/failchat | src/main/kotlin/failchat/goodgame/GgColors.kt | 2 | 690 | package failchat.goodgame
import javafx.scene.paint.Color
object GgColors {
val defaultColor: Color = Color.web("#73adff")
val byRole = mapOf(
"bronze" to Color.web("#e7820a"),
"silver" to Color.web("#b4b4b4"),
"gold" to Color.web("#eefc08"),
"diamond" to Color.web("#8781bd"),
"king" to Color.web("#30d5c8"),
"top-one" to Color.web("#3bcbff"),
"premium" to Color.web("#bd70d7"),
"premium-personal" to Color.web("#31a93a"),
"moderator" to Color.web("#ec4058"),
"streamer" to Color.web("#e8bb00"),
"streamer-helper" to Color.web("#e8bb00")
)
}
| gpl-3.0 |
abigpotostew/easypolitics | ui/src/main/kotlin/bz/stew/bracken/ui/common/bill/BillSubject.kt | 1 | 82 | package bz.stew.bracken.ui.common.bill
data class BillSubject(val subject:String) | apache-2.0 |
PolymerLabs/arcs | java/arcs/core/util/performance/CounterStatistics.kt | 1 | 2828 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.util.performance
import arcs.core.util.RunningStatistics
/**
* Accumulator of [RunningStatistics] about a collection of [Counters].
*
* **Note:** Not thread-safe.
*/
class CounterStatistics private constructor(
private val statistics: Map<String, RunningStatistics>
) {
/** Creates a [CounterStatistics] object for the given [counterNames]. */
constructor(vararg counterNames: String) : this(counterNames.toSet())
/** Creates a [CounterStatistics] object for the given [counterNames]. */
constructor(counterNames: Set<String>) :
this(counterNames.associateWith { RunningStatistics() })
/** Creates a [CounterStatistics] object based on a previous [Snapshot]. */
constructor(previous: Snapshot) :
this(previous.statistics.mapValues { RunningStatistics(it.value) })
/** Creates a new [Counters] object for this [CounterStatistics]' counter names. */
fun createCounters(): Counters = Counters(statistics.keys)
/** Absorbs the provided [newCounts] [Counters] into the [CounterStatistics]. */
fun append(newCounts: Counters) {
statistics.forEach { (key, stats) -> stats.logStat(newCounts[key].toDouble()) }
}
/** Takes a snapshot of the current [RunningStatistics] for each counter. */
fun snapshot(): Snapshot = Snapshot(statistics.mapValues { it.value.snapshot() })
/** Frozen snapshot of [CounterStatistics]. */
data class Snapshot(val statistics: Map<String, RunningStatistics.Snapshot>) {
/** Names of the registered counters. */
val counterNames = statistics.keys
/** Creates a new/empty [Snapshot] for the provided [counterNames]. */
constructor(counterNames: Set<String>) :
this(counterNames.associateWith { RunningStatistics.Snapshot() })
/**
* Returns a [Snapshot] with the current [RunningStatistics.Snapshot] values for names
* within [counterNames], and new/empty values for names not found within this snapshot.
*
* **Note:**
* For counters with names not in [counterNames], their statistics will be dropped.
*/
fun withNames(counterNames: Set<String>): Snapshot {
val newStats = mutableMapOf<String, RunningStatistics.Snapshot>()
counterNames.forEach {
newStats[it] = statistics[it] ?: RunningStatistics.Snapshot()
}
return Snapshot(newStats)
}
operator fun get(counterName: String): RunningStatistics.Snapshot =
requireNotNull(statistics[counterName]) {
"Counter with name \"$counterName\" not registered"
}
}
}
| bsd-3-clause |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantRequireNotNullCallInspection.kt | 1 | 4517 | // 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 org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.callExpressionVisitor
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullable
class RedundantRequireNotNullCallInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(callExpression) {
val callee = callExpression.calleeExpression ?: return
val resolutionFacade = callExpression.getResolutionFacade()
val context = callExpression.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL)
if (!callExpression.isCalling(FqName("kotlin.requireNotNull"), context)
&& !callExpression.isCalling(FqName("kotlin.checkNotNull"), context)
) return
val argument = callExpression.valueArguments.firstOrNull()?.getArgumentExpression()?.referenceExpression() ?: return
val descriptor = argument.getResolvedCall(context)?.resultingDescriptor ?: return
val type = descriptor.returnType ?: return
if (argument.isNullable(descriptor, type, context, resolutionFacade)) return
val functionName = callee.text
holder.registerProblem(
callee,
KotlinBundle.message("redundant.0.call", functionName),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
RemoveRequireNotNullCallFix(functionName)
)
})
private fun KtReferenceExpression.isNullable(
descriptor: CallableDescriptor,
type: KotlinType,
context: BindingContext,
resolutionFacade: ResolutionFacade,
): Boolean {
if (!type.isNullable()) return false
val dataFlowValueFactory = resolutionFacade.dataFlowValueFactory
val dataFlow = dataFlowValueFactory.createDataFlowValue(this, type, context, descriptor)
val stableTypes = context.getDataFlowInfoBefore(this).getStableTypes(dataFlow, this.languageVersionSettings)
return stableTypes.none { !it.isNullable() }
}
}
private class RemoveRequireNotNullCallFix(private val functionName: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.require.not.null.call.fix.text", functionName)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val callExpression = descriptor.psiElement.getStrictParentOfType<KtCallExpression>() ?: return
val argument = callExpression.valueArguments.firstOrNull()?.getArgumentExpression() ?: return
val target = callExpression.getQualifiedExpressionForSelector() ?: callExpression
if (callExpression.isUsedAsExpression(callExpression.analyze(BodyResolveMode.PARTIAL_WITH_CFA))) {
target.replace(argument)
} else {
target.delete()
}
}
} | apache-2.0 |
slesar/Layers | app/src/main/java/com/psliusar/layers/sample/screen/child/ChildrenContainerLayer.kt | 1 | 1373 | package com.psliusar.layers.sample.screen.child
import android.os.Bundle
import android.view.View
import com.psliusar.layers.Layer
import com.psliusar.layers.sample.R
class ChildrenContainerLayer : Layer(R.layout.screen_children_container) {
override fun onBindView(savedState: Bundle?, view: View) {
super.onBindView(savedState, view)
if (!isFromSavedState) {
layers.at(R.id.children_container_top)
.add<ChildLayer> {
withLayer { setParameters("Top layer") }
name = "Top"
}
layers.at(R.id.children_container_middle)
.add<ChildLayer> {
withLayer { setParameters("Middle layer") }
name = "Middle"
}
layers.at(R.id.children_container_bottom)
.add<ChildLayer> {
withLayer { setParameters("Bottom layer") }
name = "Bottom"
}
}
getView<View>(R.id.children_container_add_layer).setOnClickListener {
val number = layers.stackSize + 1
layers
.add<ChildLayer> {
withLayer { setParameters("Stack layer $number") }
name = "Stack #$number"
opaque = false
}
}
}
}
| apache-2.0 |
Tiofx/semester_6 | TRPSV/src/main/kotlin/task2/graph/util.kt | 1 | 2942 | package task2.graph
val INFINITE = Int.MAX_VALUE
val NO_EDGE = INFINITE
typealias AdjacencyMatrix = Array<IntArray>
typealias AdjacencyMatrix1D = IntArray
typealias AdjacencyList = Array<Adjacency>
typealias PlainAdjacencyList = IntArray
typealias Adjacency = Triple<Int, Int, Int>
data class InputGraph(val adjacencyMatrix: AdjacencyMatrix,
val sourceVertex: Int,
val vertexNumber: Int = adjacencyMatrix.size)
enum class PlainAdjacency(val number: Int) {
SOURCE(0), DESTINATION(1), WEIGHT(2)
}
object Util {
object AdjacencyUtil {
val Adjacency.source: Int
get() = this.first
val Adjacency.destination: Int
get() = this.second
val Adjacency.weight: Int
get() = this.third
}
object AdjacencyMatrixUtil {
inline fun AdjacencyMatrix.vertexNumber() = this.size
inline fun AdjacencyMatrix.toIntArray(): AdjacencyMatrix1D = this.reduce { acc, ints -> acc + ints }
fun AdjacencyMatrix.toPlainAdjacencyList(): PlainAdjacencyList =
this.mapIndexed { rowNum, row ->
row.mapIndexed { colNum, weight -> if (weight != INFINITE) intArrayOf(rowNum, colNum, weight) else null }
.filterNotNull()
.reduce { acc, ints -> acc + ints }
}
.reduce { acc, list -> acc + list }
fun AdjacencyMatrix.toAdjacencyList() = this.mapIndexed { row, ints ->
ints.mapIndexed { col, w -> if (w != INFINITE) Triple(row, col, w) else null }
.filterNotNull()
}
.reduce { acc, list -> acc + list }
.toTypedArray()
}
object AdjacencyMatrix1DUtil {
inline fun AdjacencyMatrix1D.toAdjacencyMatrix(rowColNum: Int = Math.sqrt(this.size.toDouble()).toInt()): AdjacencyMatrix
= Array(rowColNum, { this.copyOfRange(it * rowColNum, (it + 1) * rowColNum) })
}
object AdjacencyListUtil {
val AdjacencyList.edgeNumber: Int
get() = this.size
inline fun AdjacencyList.toIntArray(): PlainAdjacencyList =
this.map { it.toList().toIntArray() }.reduce { acc, ints -> acc + ints }
}
object PlainAdjacencyListUtil {
inline operator fun PlainAdjacencyList.get(index: Int, col: Int) = this[3 * index + col]
inline operator fun PlainAdjacencyList.get(index: Int, content: PlainAdjacency) = this[index, content.number]
val PlainAdjacencyList.edgeNumber: Int
get() = (this.size + 1) / 3
inline fun PlainAdjacencyList.toAdjacencyList(): AdjacencyList = this
.mapIndexed { index, value -> index to value }
.groupBy({ it.first / 3 }, { it.second })
.map { (_, value) -> Triple(value[0], value[1], value[2]) }
.toTypedArray()
}
}
| gpl-3.0 |
JStege1206/AdventOfCode | aoc-archetype/src/main/resources/archetype-resources/src/main/kotlin/days/Day13.kt | 1 | 285 | package ${package}.days
import nl.jstege.adventofcode.aoccommon.days.Day
class Day13 : Day(title = "") {
override fun first(input: Sequence<String>): Any {
TODO("Implement")
}
override fun second(input: Sequence<String>): Any {
TODO("Implement")
}
}
| mit |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/data/Size.kt | 1 | 5470 | package org.hexworks.zircon.api.data
import org.hexworks.zircon.internal.data.DefaultSize
import kotlin.jvm.JvmStatic
/**
* Represents a rectangular area in a 2D space.
* This class is immutable and cannot change its internal state after creation.
* [Size] supports destructuring to [width] and [height].
*/
@Suppress("JVM_STATIC_IN_INTERFACE_1_6")
interface Size : Comparable<Size> {
val width: Int
val height: Int
operator fun plus(other: Size): Size
operator fun minus(other: Size): Size
operator fun component1() = width
operator fun component2() = height
/**
* Tells whether this [Size] **is** the same as [Size.unknown].
*/
val isUnknown: Boolean
/**
* Tells whether this [Size] **is not** the same as [Size.unknown].
*/
val isNotUnknown: Boolean
/**
* Returns this [Size] or [other] if this size [isUnknown].
*/
fun orElse(other: Size) = if (isUnknown) other else this
/**
* Creates a list of [Position]s in the order in which they should
* be iterated when drawing (first rows, then columns in those rows).
*/
fun fetchPositions(): Iterable<Position>
/**
* Creates a list of [Position]s which represent the
* bounding box of this size. So for example a size of (3x3)
* will have a bounding box of
* `[(0, 0), (1, 0), (2, 0), (0, 1), (2, 1), (0, 2), (1, 2), (2, 2)]`
*/
fun fetchBoundingBoxPositions(): Set<Position>
fun fetchTopLeftPosition(): Position
fun fetchTopRightPosition(): Position
fun fetchBottomLeftPosition(): Position
fun fetchBottomRightPosition(): Position
/**
* Creates a new size based on this size, but with a different width.
*/
fun withWidth(width: Int): Size
/**
* Creates a new size based on this size, but with a different height.
*/
fun withHeight(height: Int): Size
/**
* Creates a new [Size] object representing a size with the same number of height, but with
* a width size offset by a supplied value. Calling this method with delta 0 will return this,
* calling it with a positive delta will return
* a grid size <code>delta</code> number of width wider and for negative numbers shorter.
*/
fun withRelativeWidth(delta: Int): Size
/**
* Creates a new [Size] object representing a size with the same number of width, but with a height
* size offset by a supplied value. Calling this method with delta 0 will return this, calling
* it with a positive delta will return
* a grid size <code>delta</code> number of height longer and for negative numbers shorter.
*/
fun withRelativeHeight(delta: Int): Size
/**
* Creates a new [Size] object representing a size based on this object's size but with a delta applied.
* This is the same as calling `withRelativeXLength(delta.getXLength()).withRelativeYLength(delta.getYLength())`
*/
fun withRelative(delta: Size): Size
/**
* Takes a different [Size] and returns a new [Size] that has the largest dimensions of the two,
* measured separately. So calling 3x5 on a 5x3 will return 5x5.
*/
fun max(other: Size): Size
/**
* Takes a different [Size] and returns a new [Size] that has the smallest dimensions of the two,
* measured separately. So calling 3x5 on a 5x3 will return 3x3.
*/
fun min(other: Size): Size
/**
* Returns itself if it is equal to the supplied size, otherwise the supplied size.
* You can use this if you have a size field which is frequently recalculated but often resolves
* to the same size; it will keep the same object
* in memory instead of swapping it out every cycle.
*/
fun with(size: Size): Size
/**
* Tells whether this [Size] contains the given [Position].
* Works in the same way as [Rect.containsPosition].
*/
fun containsPosition(position: Position): Boolean
/**
* Converts this [Size] to a [Position]:
* [Size.width] to [Position.x] and [Size.height] to [Position.y]
*/
fun toPosition(): Position
/**
* Converts this [Size] to a [Rect] using [Position.zero].
*/
fun toRect(): Rect
/**
* Converts this [Size] to a [Rect] with the given [Position].
*/
fun toRect(position: Position): Rect
/**
* Creates a new [Size3D] from this [Size] and the given [zLength].
*/
fun toSize3D(zLength: Int = 0) = Size3D.from2DSize(this, zLength)
companion object {
/**
* Represents a [Size] which is an unknown (can be used instead of a `null` value).
*/
@JvmStatic
fun unknown() = UNKNOWN
/**
* The default grid size is (80 * 24)
*/
@JvmStatic
fun defaultGridSize() = DEFAULT_GRID_SIZE
/**
* Size of (0 * 0).
*/
@JvmStatic
fun zero() = ZERO
/**
* Size of (1 * 1).
*/
@JvmStatic
fun one() = ONE
/**
* Creates a new [Size] using the given `width` (width) and `height` (height).
*/
@JvmStatic
fun create(width: Int, height: Int): Size = DefaultSize(width, height)
private val UNKNOWN = create(Int.MAX_VALUE, Int.MAX_VALUE)
private val DEFAULT_GRID_SIZE = create(60, 30)
private val ZERO = create(0, 0)
private val ONE = create(1, 1)
}
}
| apache-2.0 |
JohnnyShieh/Gank | app/src/main/kotlin/com/johnny/gank/adapter/CategoryGankAdapter.kt | 1 | 2871 | package com.johnny.gank.adapter
/*
* Copyright (C) 2016 Johnny Shieh 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.
*/
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.johnny.gank.R
import com.johnny.gank.model.ui.GankNormalItem
import kotlinx.android.synthetic.main.recycler_item_gank.view.*
/**
* description
*
* @author Johnny Shieh ([email protected])
* @version 1.0
*/
class CategoryGankAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val items = mutableListOf<GankNormalItem>()
var curPage = 0
private set
var onItemClickListener: OnItemClickListener? = null
interface OnItemClickListener {
fun onClickNormalItem(view: View, normalItem: GankNormalItem)
}
fun updateData(page: Int, list: List<GankNormalItem>?) {
if (null == list || list.isEmpty()) return
if (page - curPage > 1) return
if (page <= 1) {
if (!items.containsAll(list)) {
items.clear()
items.addAll(list)
curPage = page
notifyDataSetChanged()
}
} else if (1 == page - curPage) {
val oldSize = items.size
items.addAll(oldSize, list)
notifyItemRangeInserted(oldSize, list.size)
curPage = page
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return NormalViewHolder(parent)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is NormalViewHolder) {
val normalItem = items[position]
holder.itemView.title.text =
getGankTitleStr(normalItem.gank.desc, normalItem.gank.who)
holder.itemView.title.setOnClickListener { view -> onItemClickListener?.onClickNormalItem(view, normalItem) }
}
}
override fun getItemCount(): Int {
return items.size
}
class NormalViewHolder
constructor(parent: ViewGroup) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.recycler_item_gank, parent, false)) {
init {
itemView.align_pic.visibility = View.GONE
}
}
}
| apache-2.0 |
pyamsoft/pydroid | arch/src/main/java/com/pyamsoft/pydroid/arch/UiSavedStateWriter.kt | 1 | 1222 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.arch
import android.os.Bundle
import androidx.annotation.CheckResult
import com.pyamsoft.pydroid.arch.internal.BundleUiSavedStateWriter
/** Abstraction over saving data into the save-restore lifecycle */
public interface UiSavedStateWriter {
/** Save a value at key */
public fun <T : Any> put(key: String, value: T)
/** Remove a value at key */
public fun <T : Any> remove(key: String): T?
}
/** Convenience function for converting a Bundle into a SavedStateWriter */
@CheckResult
public fun Bundle.toWriter(): UiSavedStateWriter {
return BundleUiSavedStateWriter(this)
}
| apache-2.0 |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/sitecreation/misc/SearchInputWithHeader.kt | 1 | 3589 | package org.wordpress.android.ui.sitecreation.misc
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import org.wordpress.android.R
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.ActivityUtils
class SearchInputWithHeader(private val uiHelpers: UiHelpers, rootView: View, onClear: () -> Unit) {
private val headerLayout = rootView.findViewById<ViewGroup>(R.id.site_creation_header_item)
private val headerTitle = rootView.findViewById<TextView>(R.id.title)
private val headerSubtitle = rootView.findViewById<TextView>(R.id.subtitle)
private val searchInput = rootView.findViewById<EditText>(R.id.input)
private val progressBar = rootView.findViewById<View>(R.id.progress_bar)
private val clearAllLayout = rootView.findViewById<View>(R.id.clear_all_layout)
private val divider = rootView.findViewById<View>(R.id.divider)
private val showKeyboardHandler = Handler(Looper.getMainLooper())
var onTextChanged: ((String) -> Unit)? = null
init {
clearAllLayout.setOnClickListener {
onClear()
}
searchInput.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onTextChanged?.invoke(s?.toString() ?: "")
}
})
}
fun setInputText(text: String) {
// If the text hasn't changed avoid triggering the text watcher
if (searchInput.text.toString() != text) {
searchInput.setText(text)
}
}
fun updateHeader(context: Context, uiState: SiteCreationHeaderUiState?) {
val headerShouldBeVisible = uiState != null
if (!headerShouldBeVisible && headerLayout.visibility == View.VISIBLE) {
headerLayout.animate().translationY(-headerLayout.height.toFloat())
} else if (headerShouldBeVisible && headerLayout.visibility == View.GONE) {
headerLayout.animate().translationY(0f)
}
uiState?.let {
uiHelpers.updateVisibility(headerLayout, true)
headerTitle.text = uiHelpers.getTextOfUiString(context, uiState.title)
headerSubtitle.text = uiHelpers.getTextOfUiString(context, uiState.subtitle)
} ?: uiHelpers.updateVisibility(headerLayout, false)
}
fun updateSearchInput(context: Context, uiState: SiteCreationSearchInputUiState) {
searchInput.hint = uiHelpers.getTextOfUiString(context, uiState.hint)
uiHelpers.updateVisibility(progressBar, uiState.showProgress)
uiHelpers.updateVisibility(clearAllLayout, uiState.showClearButton)
uiHelpers.updateVisibility(divider, uiState.showDivider)
showKeyboard(uiState.showKeyboard)
}
private fun showKeyboard(shouldShow: Boolean) {
if (shouldShow) {
searchInput.requestFocus()
/**
* This workaround handles the case where the SiteCreationDomainsFragment appears after the
* DesignPreviewFragment dismisses and the keyboard fails to appear
*/
showKeyboardHandler.postDelayed({
ActivityUtils.showKeyboard(searchInput)
}, 200)
}
}
}
| gpl-2.0 |
TomsUsername/Phoenix | src/main/kotlin/phoenix/bot/pogo/nRnMK9r/tasks/HatchEggs.kt | 1 | 3376 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package phoenix.bot.pogo.nRnMK9r.tasks
import POGOProtos.Networking.Responses.UseItemEggIncubatorResponseOuterClass
import phoenix.bot.pogo.api.request.GetHatchedEggs
import phoenix.bot.pogo.api.request.UseItemEggIncubator
import phoenix.bot.pogo.nRnMK9r.Bot
import phoenix.bot.pogo.nRnMK9r.Context
import phoenix.bot.pogo.nRnMK9r.Settings
import phoenix.bot.pogo.nRnMK9r.Task
import phoenix.bot.pogo.nRnMK9r.util.Log
import phoenix.bot.pogo.nRnMK9r.util.pokemon.getIvPercentage
import phoenix.bot.pogo.nRnMK9r.util.pokemon.incubated
class HatchEggs : Task {
override fun run(bot: Bot, ctx: Context, settings: Settings) {
// not necessary, update profile is executed before this already in the tasks
//bot.api.queueRequest(GetInventory().withLastTimestampMs(0))
bot.api.queueRequest(GetHatchedEggs()).subscribe {
val response = it.response
response.pokemonIdList.forEachIndexed { index, it ->
val newPokemon = ctx.api.inventory.pokemon[it]
val candy = response.candyAwardedList[index]
val experience = response.experienceAwardedList[index]
val stardust = response.stardustAwardedList[index]
val stats = "+${candy} candy; +${experience} XP; +${stardust} stardust"
if (newPokemon == null) {
Log.cyan("Hatched pokemon; $stats")
} else {
Log.cyan("Hatched ${newPokemon.pokemonData.pokemonId.name} with ${newPokemon.pokemonData.cp} CP " +
"and ${newPokemon.pokemonData.getIvPercentage()}% IV; $stats")
}
}
}
val incubators = ctx.api.inventory.eggIncubators
val eggs = ctx.api.inventory.eggs
val freeIncubators = incubators.map { it.value }
.filter { it.targetKmWalked < bot.api.inventory.playerStats.kmWalked }
.sortedByDescending { it.usesRemaining }
val filteredEggs = eggs.map { it.value }
.filter { !it.pokemonData.incubated }
.sortedByDescending { it.pokemonData.eggKmWalkedTarget }
if (freeIncubators.isNotEmpty() && filteredEggs.isNotEmpty() && settings.autoFillIncubator) {
var eggResult = filteredEggs.first()
if (freeIncubators.first().usesRemaining == 0) {
eggResult = filteredEggs.last()
}
val use = UseItemEggIncubator().withPokemonId(eggResult.pokemonData.id).withItemId(freeIncubators.first().id)
bot.api.queueRequest(use).subscribe {
val response = it.response
if (response.result == UseItemEggIncubatorResponseOuterClass.UseItemEggIncubatorResponse.Result.SUCCESS) {
Log.cyan("Put egg of ${eggResult.pokemonData.eggKmWalkedTarget}km in unused incubator")
} else {
Log.red("Failed to put egg in incubator; error: ${response.result}")
}
}
}
}
}
| gpl-3.0 |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/accounts/login/jetpack/LoginSiteCheckErrorViewModel.kt | 1 | 1459 | package org.wordpress.android.ui.accounts.login.jetpack
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.accounts.LoginNavigationEvents
import org.wordpress.android.ui.accounts.LoginNavigationEvents.ShowInstructions
import org.wordpress.android.ui.accounts.LoginNavigationEvents.ShowSignInForResultJetpackOnly
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import javax.inject.Inject
import javax.inject.Named
@HiltViewModel
class LoginSiteCheckErrorViewModel @Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher
) : ScopedViewModel(mainDispatcher) {
private val _navigationEvents = MediatorLiveData<Event<LoginNavigationEvents>>()
val navigationEvents: LiveData<Event<LoginNavigationEvents>> = _navigationEvents
private var isStarted = false
fun start() {
if (isStarted) return
isStarted = true
}
fun onSeeInstructionsPressed() {
_navigationEvents.postValue(Event(ShowInstructions()))
}
fun onTryAnotherAccountPressed() {
_navigationEvents.postValue(Event(ShowSignInForResultJetpackOnly))
}
fun onBackPressed() {
_navigationEvents.postValue(Event(ShowSignInForResultJetpackOnly))
}
}
| gpl-2.0 |
DiUS/pact-jvm | core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/util/CollectionUtils.kt | 1 | 725 | package au.com.dius.pact.core.matchers.util
fun tails(col: List<String>): List<List<String>> {
val result = mutableListOf<List<String>>()
var acc = col
while (acc.isNotEmpty()) {
result.add(acc)
acc = acc.drop(1)
}
result.add(acc)
return result
}
fun <A, B> corresponds(l1: List<A>, l2: List<B>, fn: (a: A, b: B) -> Boolean): Boolean {
return if (l1.size == l2.size) {
l1.zip(l2).all { fn(it.first, it.second) }
} else {
false
}
}
fun <E> List<E>.padTo(size: Int, item: E): List<E> {
return if (size < this.size) {
this.dropLast(this.size - size)
} else {
val list = this.toMutableList()
for (i in this.size.until(size)) {
list.add(item)
}
return list
}
}
| apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/base/fir/code-insight/src/org/jetbrains/kotlin/idea/base/fir/codeInsight/SymbolBasedShortenReferencesFacility.kt | 1 | 612 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.fir.codeInsight
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.analysis.api.utils.shortenReferencesInRange
import org.jetbrains.kotlin.idea.base.codeInsight.ShortenReferencesFacility
import org.jetbrains.kotlin.psi.KtFile
internal class SymbolBasedShortenReferencesFacility : ShortenReferencesFacility {
override fun shorten(file: KtFile, range: TextRange) {
shortenReferencesInRange(file, range)
}
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/unwrapAndRemove/unwrapTry/tryCompoundInReturn.kt | 13 | 154 | // IS_APPLICABLE: false
fun foo(n : Int): Int {
return <caret>try {
val m = n + 1
m/0
} catch (e: Exception) {
-1
}
}
| apache-2.0 |
ingokegel/intellij-community | python/src/com/jetbrains/python/inspections/PyRelativeImportInspection.kt | 5 | 6185 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.inspections
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.command.undo.BasicUndoableAction
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.namespacePackages.PyNamespacePackagesService
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.psi.PyElementGenerator
import com.jetbrains.python.psi.PyFromImportStatement
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.psi.types.TypeEvalContext
class PyRelativeImportInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor {
if (!PyNamespacePackagesService.isEnabled() ||
LanguageLevel.forElement(holder.file).isOlderThan(LanguageLevel.PYTHON34)) {
return PsiElementVisitor.EMPTY_VISITOR
}
return Visitor(holder, PyInspectionVisitor.getContext(session))
}
private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) {
override fun visitPyFromImportStatement(node: PyFromImportStatement) {
val directory = node.containingFile?.containingDirectory ?: return
if (node.relativeLevel > 0 && !PyUtil.isExplicitPackage(directory) && !isInsideOrdinaryPackage(directory)) {
handleRelativeImportNotInsidePackage(node, directory)
}
}
private fun isInsideOrdinaryPackage(directory: PsiDirectory): Boolean {
var curDir: PsiDirectory? = directory
while (curDir != null) {
if (PyUtil.isOrdinaryPackage(curDir)) return true
curDir = curDir.parentDirectory
}
return false
}
private fun handleRelativeImportNotInsidePackage(node: PyFromImportStatement, directory: PsiDirectory) {
val fixes = mutableListOf<LocalQuickFix>()
getMarkAsNamespacePackageQuickFix(directory) ?.let { fixes.add(it) }
if (node.relativeLevel == 1) {
fixes.add(PyChangeToSameDirectoryImportQuickFix())
}
val message = PyPsiBundle.message("INSP.relative.import.relative.import.outside.package")
registerProblem(node, message, *fixes.toTypedArray())
}
private fun getMarkAsNamespacePackageQuickFix(directory: PsiDirectory): PyMarkAsNamespacePackageQuickFix? {
val module = ModuleUtilCore.findModuleForPsiElement(directory) ?: return null
var curDir: PsiDirectory? = directory
while (curDir != null) {
val virtualFile = curDir.virtualFile
if (PyUtil.isRoot(curDir)) return null
val parentDir = curDir.parentDirectory
if (parentDir != null && (PyUtil.isRoot(parentDir) || PyUtil.isOrdinaryPackage(parentDir))) {
return PyMarkAsNamespacePackageQuickFix(module, virtualFile)
}
curDir = parentDir
}
return null
}
}
private class PyMarkAsNamespacePackageQuickFix(val module: Module, val directory: VirtualFile) : LocalQuickFix {
override fun getFamilyName(): String = PyBundle.message("QFIX.mark.as.namespace.package", directory.name)
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val document = PsiDocumentManager.getInstance(project).getDocument(descriptor.psiElement.containingFile)
val undoableAction = object: BasicUndoableAction(document) {
override fun undo() {
PyNamespacePackagesService.getInstance(module).toggleMarkingAsNamespacePackage(directory)
}
override fun redo() {
PyNamespacePackagesService.getInstance(module).toggleMarkingAsNamespacePackage(directory)
}
}
undoableAction.redo()
UndoManager.getInstance(project).undoableActionPerformed(undoableAction)
}
override fun generatePreview(project: Project, previewDescriptor: ProblemDescriptor): IntentionPreviewInfo {
// The quick fix updates a directory's properties in the project structure, nothing changes in the current file
return IntentionPreviewInfo.EMPTY
}
}
private class PyChangeToSameDirectoryImportQuickFix : LocalQuickFix {
override fun getFamilyName(): String = PyBundle.message("QFIX.change.to.same.directory.import")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val oldImport = descriptor.psiElement as? PyFromImportStatement ?: return
assert(oldImport.relativeLevel == 1)
val qualifier = oldImport.importSource
if (qualifier != null) {
val possibleDot = PsiTreeUtil.prevVisibleLeaf(qualifier)
assert(possibleDot != null && possibleDot.node.elementType == PyTokenTypes.DOT)
possibleDot?.delete()
}
else {
replaceByImportStatements(oldImport)
}
}
private fun replaceByImportStatements(oldImport: PyFromImportStatement) {
val project = oldImport.project
val generator = PyElementGenerator.getInstance(project)
val names = oldImport.importElements.map { it.text }
if (names.isEmpty()) return
val langLevel = LanguageLevel.forElement(oldImport)
for (name in names.reversed()) {
val newImport = generator.createImportStatement(langLevel, name, null)
oldImport.parent.addAfter(newImport, oldImport)
}
oldImport.delete()
}
}
} | apache-2.0 |
mdaniel/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUArrayAccessExpression.kt | 1 | 1104 | // 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 org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.psi.KtArrayAccessExpression
import org.jetbrains.uast.UArrayAccessExpression
import org.jetbrains.uast.UElement
@ApiStatus.Internal
class KotlinUArrayAccessExpression(
override val sourcePsi: KtArrayAccessExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UArrayAccessExpression, KotlinUElementWithType, KotlinEvaluatableUElement {
override val receiver by lz {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.arrayExpression, this)
}
override val indices by lz {
sourcePsi.indexExpressions.map {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(it, this)
}
}
override fun resolve(): PsiElement? {
return baseResolveProviderService.resolveCall(sourcePsi)
}
}
| apache-2.0 |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/conversation/colors/ui/ChatColorsOptionsLiveData.kt | 2 | 1556 | package org.thoughtcrime.securesms.conversation.colors.ui
import androidx.lifecycle.LiveData
import org.signal.core.util.concurrent.SignalExecutors
import org.thoughtcrime.securesms.conversation.colors.ChatColors
import org.thoughtcrime.securesms.conversation.colors.ChatColorsPalette
import org.thoughtcrime.securesms.database.ChatColorsDatabase
import org.thoughtcrime.securesms.database.DatabaseFactory
import org.thoughtcrime.securesms.database.DatabaseObserver
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.util.concurrent.SerialMonoLifoExecutor
import java.util.concurrent.Executor
class ChatColorsOptionsLiveData : LiveData<List<ChatColors>>() {
private val chatColorsDatabase: ChatColorsDatabase = DatabaseFactory.getChatColorsDatabase(ApplicationDependencies.getApplication())
private val observer: DatabaseObserver.Observer = DatabaseObserver.Observer { refreshChatColors() }
private val executor: Executor = SerialMonoLifoExecutor(SignalExecutors.BOUNDED)
override fun onActive() {
refreshChatColors()
ApplicationDependencies.getDatabaseObserver().registerChatColorsObserver(observer)
}
override fun onInactive() {
ApplicationDependencies.getDatabaseObserver().unregisterObserver(observer)
}
private fun refreshChatColors() {
executor.execute {
val options = mutableListOf<ChatColors>().apply {
addAll(ChatColorsPalette.Bubbles.all)
addAll(chatColorsDatabase.getSavedChatColors())
}
postValue(options)
}
}
}
| gpl-3.0 |
GunoH/intellij-community | plugins/gradle/java/testSources/execution/test/GradleJavaTestEventsIntegrationTestCase.kt | 2 | 3765 | // 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.plugins.gradle.execution.test
import com.intellij.openapi.externalSystem.model.task.*
import com.intellij.openapi.externalSystem.model.task.event.ExternalSystemTaskExecutionEvent
import com.intellij.openapi.externalSystem.model.task.event.TestOperationDescriptor
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.util.registry.Registry
import org.assertj.core.api.AbstractThrowableAssert
import org.assertj.core.api.Condition
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.service.task.GradleTaskManager
import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings
import org.jetbrains.plugins.gradle.testFramework.GradleProjectTestCase
import org.jetbrains.plugins.gradle.testFramework.GradleTestFixtureBuilder
import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID
abstract class GradleJavaTestEventsIntegrationTestCase : GradleProjectTestCase() {
override fun test(gradleVersion: GradleVersion, fixtureBuilder: GradleTestFixtureBuilder, test: () -> Unit) {
super.test(gradleVersion, fixtureBuilder) {
val testLauncherApi = Registry.get("gradle.testLauncherAPI.enabled")
if (testLauncherAPISupported()) {
testLauncherApi.setValue(true)
}
try {
test()
}
finally {
if (testLauncherAPISupported()) {
testLauncherApi.setValue(false)
}
}
}
}
fun testLauncherAPISupported(): Boolean {
return isGradleAtLeast("6.1")
}
fun executeTasks(vararg tasks: String, configure: GradleExecutionSettings.() -> Unit = {}): LoggingESOutputListener {
val listener = LoggingESOutputListener()
executeTasks(listener, *tasks, configure = configure)
return listener
}
fun executeTasks(
listener: LoggingESOutputListener,
vararg tasks: String,
configure: GradleExecutionSettings.() -> Unit = {}
) {
val id = ExternalSystemTaskId.create(SYSTEM_ID, ExternalSystemTaskType.EXECUTE_TASK, project)
val settings = ExternalSystemApiUtil.getExecutionSettings<GradleExecutionSettings>(project, projectPath, SYSTEM_ID)
settings.configure()
GradleTaskManager().executeTasks(id, tasks.toList(), projectPath, settings, null, listener)
}
class LoggingESOutputListener(
private val delegate: LoggingESStatusChangeListener = LoggingESStatusChangeListener()
) : ExternalSystemTaskNotificationListenerAdapter(delegate) {
val eventLog = mutableListOf<String>()
val testsDescriptors: List<TestOperationDescriptor>
get() = delegate.testsDescriptors
override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) {
addEventLogLines(text, eventLog)
}
private fun addEventLogLines(text: String, eventLog: MutableList<String>) {
text.split("<ijLogEol/>").mapTo(eventLog) { it.trim('\r', '\n', ' ') }
}
}
class LoggingESStatusChangeListener : ExternalSystemTaskNotificationListenerAdapter() {
private val eventLog = mutableListOf<ExternalSystemTaskNotificationEvent>()
val testsDescriptors: List<TestOperationDescriptor>
get() = eventLog
.filterIsInstance<ExternalSystemTaskExecutionEvent>()
.map { it.progressEvent.descriptor }
.filterIsInstance<TestOperationDescriptor>()
override fun onStatusChange(event: ExternalSystemTaskNotificationEvent) {
eventLog.add(event)
}
}
companion object {
fun <T : AbstractThrowableAssert<*, *>> T.`is`(message: String, predicate: (String) -> Boolean): T = apply {
`is`(Condition({ predicate(it.message ?: "") }, message))
}
}
}
| apache-2.0 |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/classes.kt | 5 | 2090 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.lang.documentation
import com.intellij.model.Pointer
import com.intellij.openapi.progress.blockingContext
import com.intellij.util.AsyncSupplier
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.Nls
import java.awt.Image
import java.util.function.Supplier
internal data class DocumentationContentData internal constructor(
val html: @Nls String,
val imageResolver: DocumentationImageResolver?,
) : DocumentationContent
internal data class LinkData(
val externalUrl: String? = null,
val linkUrls: List<String> = emptyList(),
)
internal class AsyncDocumentation(
val supplier: AsyncSupplier<DocumentationResult.Data?>
) : DocumentationResult
internal class ResolvedTarget(
val target: DocumentationTarget,
) : LinkResolveResult
internal class AsyncLinkResolveResult(
val supplier: AsyncSupplier<LinkResolveResult.Async?>,
) : LinkResolveResult
internal class AsyncResolvedTarget(
val pointer: Pointer<out DocumentationTarget>,
) : LinkResolveResult.Async
internal fun <X> Supplier<X>.asAsyncSupplier(): AsyncSupplier<X> = {
withContext(Dispatchers.IO) {
blockingContext {
[email protected]()
}
}
}
internal fun imageResolver(map: Map<String, Image>): DocumentationImageResolver? {
if (map.isEmpty()) {
return null
}
return DocumentationImageResolver(map.toMap()::get)
}
internal fun DocumentationContentUpdater.asFlow(): Flow<DocumentationContent> {
val flow = channelFlow {
blockingContext {
updateContent { content ->
check(trySend(content).isSuccess) // sanity check
}
}
}
return flow
.buffer(capacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
.flowOn(Dispatchers.IO)
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/expressions/outOfNestedClosureWithParams1.kt | 13 | 121 | // MOVE: up
fun foo() {
val x = run(1, 2) {
x ->
<caret>println("foo")
println("bar")
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/base/indices/src/org/jetbrains/kotlin/idea/stubindex/KotlinSuperClassIndex.kt | 4 | 1156 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.stubindex
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey
import org.jetbrains.kotlin.psi.KtClassOrObject
object KotlinSuperClassIndex : KotlinStringStubIndexExtension<KtClassOrObject>(KtClassOrObject::class.java) {
private val KEY: StubIndexKey<String, KtClassOrObject> =
StubIndexKey.createIndexKey("org.jetbrains.kotlin.idea.stubindex.KotlinSuperClassIndex")
override fun getKey(): StubIndexKey<String, KtClassOrObject> = KEY
override fun get(s: String, project: Project, scope: GlobalSearchScope): Collection<KtClassOrObject> {
return StubIndex.getElements(KEY, s, project, scope, KtClassOrObject::class.java)
}
@JvmStatic
@Deprecated("Use KotlinSuperClassIndex as an object.", ReplaceWith("KotlinSuperClassIndex"))
fun getInstance(): KotlinSuperClassIndex = KotlinSuperClassIndex
} | apache-2.0 |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/GHPullRequestReviewCommentWithPendingReview.kt | 8 | 1781 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api.data.pullrequest
import com.fasterxml.jackson.annotation.JsonProperty
import org.jetbrains.plugins.github.api.data.GHActor
import org.jetbrains.plugins.github.api.data.GHCommitHash
import org.jetbrains.plugins.github.api.data.GHNode
import java.util.*
open class GHPullRequestReviewCommentWithPendingReview(id: String,
databaseId: Long,
url: String,
author: GHActor?,
body: String,
createdAt: Date,
state: GHPullRequestReviewCommentState,
commit: GHCommitHash?,
originalCommit: GHCommitHash?,
replyTo: GHNode?,
diffHunk: String,
@JsonProperty("pullRequestReview") val pullRequestReview: GHPullRequestPendingReview,
viewerCanDelete: Boolean,
viewerCanUpdate: Boolean)
: GHPullRequestReviewComment(id, databaseId, url, author, body, createdAt, state, commit, originalCommit,
replyTo, diffHunk, pullRequestReview, viewerCanDelete, viewerCanUpdate) {
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/k2/test/org/jetbrains/kotlin/idea/k2/debugger/test/K2DebuggerTestCompilerFacility.kt | 4 | 1437 | // 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.debugger.test
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.codegen.ClassBuilderFactory
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.idea.debugger.test.DebuggerTestCompilerFacility
import org.jetbrains.kotlin.idea.debugger.test.TestFileWithModule
import java.io.File
internal class K2DebuggerTestCompilerFacility(
private val project: Project,
files: List<TestFileWithModule>,
jvmTarget: JvmTarget,
useIrBackend: Boolean
) : DebuggerTestCompilerFacility(files, jvmTarget, useIrBackend) {
override fun compileTestSources(
project: Project,
srcDir: File,
classesDir: File,
classBuilderFactory: ClassBuilderFactory
): CompilationResult {
return withTestServicesNeededForCodeCompilation(project) {
super.compileTestSources(project, srcDir, classesDir, classBuilderFactory)
}
}
override fun compileTestSources(module: Module, jvmSrcDir: File, commonSrcDir: File, classesDir: File, libClassesDir: File): String {
return withTestServicesNeededForCodeCompilation(project) {
super.compileTestSources(module, jvmSrcDir, commonSrcDir, classesDir, libClassesDir)
}
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinAutoImportsFilter.kt | 4 | 1705 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.codeInsight
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.IntellijInternalApi
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
@IntellijInternalApi
interface KotlinAutoImportsFilter {
/**
* Even if the option to perform auto import is disabled for Kotlin but [forceAutoImportForElement] is true, auto import must happen
*/
fun forceAutoImportForElement(file: KtFile, suggestions: Collection<FqName>): Boolean
/**
* Allows transforming suggested imports list by any rule.
*/
fun filterSuggestions(suggestions: Collection<FqName>): Collection<FqName>
companion object {
val EP_NAME = ExtensionPointName.create<KotlinAutoImportsFilter>("org.jetbrains.kotlin.idea.codeInsight.unambiguousImports")
private fun findRelevantExtension(file: KtFile, suggestions: Collection<FqName>): KotlinAutoImportsFilter? =
EP_NAME.findFirstSafe { it.forceAutoImportForElement(file, suggestions) }
fun filterSuggestionsIfApplicable(context: KtFile, suggestions: Collection<FqName>): Collection<FqName> {
val extension = findRelevantExtension(context, suggestions)
if (extension != null) return extension.filterSuggestions(suggestions)
return if (KotlinCodeInsightSettings.getInstance().addUnambiguousImportsOnTheFly) {
suggestions
} else {
emptyList()
}
}
}
} | apache-2.0 |
GunoH/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleJvmUtil.kt | 10 | 1799 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("GradleJvmUtil")
@file:ApiStatus.Internal
package org.jetbrains.plugins.gradle.util
import com.intellij.openapi.externalSystem.service.execution.createJdkInfo
import com.intellij.openapi.externalSystem.service.execution.nonblockingResolveJdkInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider
import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider.SdkInfo
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Paths
const val USE_GRADLE_JAVA_HOME = "#GRADLE_JAVA_HOME"
fun SdkLookupProvider.nonblockingResolveGradleJvmInfo(project: Project, externalProjectPath: String?, gradleJvm: String?): SdkInfo {
val projectSdk = ProjectRootManager.getInstance(project).projectSdk
return nonblockingResolveGradleJvmInfo(project, projectSdk, externalProjectPath, gradleJvm)
}
fun SdkLookupProvider.nonblockingResolveGradleJvmInfo(project: Project, projectSdk: Sdk?, externalProjectPath: String?, gradleJvm: String?): SdkInfo {
return when (gradleJvm) {
USE_GRADLE_JAVA_HOME -> createJdkInfo(GRADLE_JAVA_HOME_PROPERTY, getGradleJavaHome(project, externalProjectPath))
else -> nonblockingResolveJdkInfo(projectSdk, gradleJvm)
}
}
fun getGradleJavaHome(project: Project, externalProjectPath: String?): String? {
if (externalProjectPath == null) {
return null
}
val properties = getGradleProperties(project, Paths.get(externalProjectPath))
val javaHomeProperty = properties.javaHomeProperty ?: return null
return javaHomeProperty.value
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/configuration/ScriptResidenceExceptionProvider.kt | 2 | 1450 | // 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.script.configuration
import com.intellij.openapi.vfs.VirtualFile
internal open class ScriptResidenceExceptionProvider(
private val suffix: String,
private val supportedUnderSourceRoot: Boolean = false
) {
open fun isSupportedScriptExtension(virtualFile: VirtualFile): Boolean =
virtualFile.name.endsWith(suffix)
fun isSupportedUnderSourceRoot(virtualFile: VirtualFile): Boolean =
if (supportedUnderSourceRoot) isSupportedScriptExtension(virtualFile) else false
}
internal val scriptResidenceExceptionProviders = listOf(
ScriptResidenceExceptionProvider(".gradle.kts", true),
ScriptResidenceExceptionProvider(".main.kts"),
ScriptResidenceExceptionProvider(".space.kts"),
ScriptResidenceExceptionProvider(".ws.kts", true),
object : ScriptResidenceExceptionProvider(".teamcity.kts", true) {
override fun isSupportedScriptExtension(virtualFile: VirtualFile): Boolean {
if (!virtualFile.name.endsWith(".kts")) return false
var parent = virtualFile.parent
while (parent != null) {
if (parent.isDirectory && parent.name == ".teamcity") {
return true
}
parent = parent.parent
}
return false
}
}
) | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/regression/callVariableAsFunctionWithAnonymousObjectArg.kt | 10 | 83 | // FIR_IDENTICAL
fun f() {
val g = 3
<error>g</error>(object : Any() {})
}
| apache-2.0 |
GunoH/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInspection/DuplicateExpressionsFixTest.kt | 8 | 3794 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.java.codeInspection
import com.intellij.JavaTestUtil
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.duplicateExpressions.DuplicateExpressionsInspection
import com.intellij.java.JavaBundle
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import com.intellij.ui.ChooserInterceptor
import com.intellij.ui.UiInterceptors
import java.util.regex.Pattern
/**
* @author Pavel.Dolgov
*/
class DuplicateExpressionsFixTest : LightJavaCodeInsightFixtureTestCase() {
val inspection = DuplicateExpressionsInspection()
override fun setUp() {
super.setUp()
myFixture.enableInspections(inspection)
}
override fun getBasePath() = JavaTestUtil.getRelativeJavaTestDataPath() + "/inspection/duplicateExpressionsFix"
fun testIntroduceVariable() {
UiInterceptors.register(ChooserInterceptor(null, Pattern.quote("Replace all 0 occurrences")))
doTest(introduce("s.substring(s.length() - 9)"))
}
fun testReuseVariable() = doTest(reuse("substr", "s.substring(s.length() - 9)"))
fun testReplaceOthers() = doTest(replace("substr", "s.substring(s.length() - 9)"))
fun testIntroduceVariableOtherVariableNotInScope() {
UiInterceptors.register(ChooserInterceptor(null, Pattern.quote("Replace all 0 occurrences")))
doTest(introduce("s.substring(s.length() - 9)"))
}
fun testVariableNotInScopeCantReplaceOthers() = doNegativeTest(replace("substr", "s.substring(s.length() - 9)"))
fun testIntroducePathVariableTwoPathOf() {
UiInterceptors.register(ChooserInterceptor(null, Pattern.quote("Replace all 0 occurrences")))
doTest(introduce("Path.of(fileName)"))
}
fun testIntroducePathVariableTwoPathsGet() {
UiInterceptors.register(ChooserInterceptor(null, Pattern.quote("Replace all 0 occurrences")))
doTest(introduce("Paths.get(fileName)"))
}
fun testIntroducePathVariablePathOfPathsGet() {
UiInterceptors.register(ChooserInterceptor(null, Pattern.quote("Replace all 0 occurrences")))
doTest(introduce("Paths.get(fileName)"))
}
fun testRandomUUIDIsNotReplaced() {
doNegativeTest(replace("s1", "String.valueOf(UUID.randomUUID().getMostSignificantBits())"))
}
private fun doTest(message: String, threshold: Int = 50) =
withThreshold(threshold) {
myFixture.configureByFile("${getTestName(false)}.java")
myFixture.launchAction(myFixture.findSingleIntention(message))
myFixture.checkResultByFile("${getTestName(false)}_after.java")
}
private fun doNegativeTest(message: String, threshold: Int = 50) =
withThreshold(threshold) {
myFixture.configureByFile("${getTestName(false)}.java")
val intentions = myFixture.filterAvailableIntentions(message)
assertEquals(emptyList<IntentionAction>(), intentions)
}
private fun withThreshold(threshold: Int, block: () -> Unit) {
val oldThreshold = inspection.complexityThreshold
try {
inspection.complexityThreshold = threshold
block()
}
finally {
inspection.complexityThreshold = oldThreshold
}
}
override fun getProjectDescriptor(): LightProjectDescriptor {
return JAVA_11
}
private fun introduce(expr: String) =
JavaBundle.message("inspection.duplicate.expressions.introduce.variable.fix.name", expr)
private fun reuse(name: String, expr: String) =
JavaBundle.message("inspection.duplicate.expressions.reuse.variable.fix.name", name, expr)
private fun replace(name: String, expr: String) =
JavaBundle.message("inspection.duplicate.expressions.replace.other.occurrences.fix.name", name, expr)
}
| apache-2.0 |
mvmike/min-cal-widget | app/src/main/kotlin/cat/mvmike/minimalcalendarwidget/domain/Instance.kt | 1 | 1659 | // Copyright (c) 2016, Miquel Martí <[email protected]>
// See LICENSE for licensing information
package cat.mvmike.minimalcalendarwidget.domain
import android.content.Context
import cat.mvmike.minimalcalendarwidget.infrastructure.resolver.CalendarResolver
import cat.mvmike.minimalcalendarwidget.infrastructure.resolver.SystemResolver
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
data class Instance(
val eventId: Int,
val start: Instant,
val end: Instant,
val zoneId: ZoneId,
val isDeclined: Boolean
) {
// take out 5 milliseconds to avoid erratic behaviour events that end at midnight
fun isInDay(day: LocalDate): Boolean {
val instanceStartLocalDate = LocalDateTime.ofInstant(start, zoneId).toLocalDate()
val instanceEndLocalDate = LocalDateTime.ofInstant(end.minusMillis(5), zoneId).toLocalDate()
return !instanceStartLocalDate.isAfter(day)
&& !instanceEndLocalDate.isBefore(day)
}
}
fun getInstances(context: Context, from: LocalDate, to: LocalDate): Set<Instance> {
return when (CalendarResolver.isReadCalendarPermitted(context)) {
false -> HashSet()
true -> {
val systemZoneId = SystemResolver.getSystemZoneId()
CalendarResolver.getInstances(
context = context,
begin = from.toStartOfDayInEpochMilli(systemZoneId),
end = to.toStartOfDayInEpochMilli(systemZoneId)
)
}
}
}
private fun LocalDate.toStartOfDayInEpochMilli(zoneId: ZoneId) =
this.atStartOfDay(zoneId).toInstant().toEpochMilli()
| bsd-3-clause |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/NucleusConductorLifecycleListener.kt | 3 | 1041 | package eu.kanade.tachiyomi.ui.base.presenter
import android.os.Bundle
import android.view.View
import com.bluelinelabs.conductor.Controller
class NucleusConductorLifecycleListener(private val delegate: NucleusConductorDelegate<*>) : Controller.LifecycleListener() {
override fun postCreateView(controller: Controller, view: View) {
delegate.onTakeView(controller)
}
override fun preDestroyView(controller: Controller, view: View) {
delegate.onDropView()
}
override fun preDestroy(controller: Controller) {
delegate.onDestroy()
}
override fun onSaveInstanceState(controller: Controller, outState: Bundle) {
outState.putBundle(PRESENTER_STATE_KEY, delegate.onSaveInstanceState())
}
override fun onRestoreInstanceState(controller: Controller, savedInstanceState: Bundle) {
delegate.onRestoreInstanceState(savedInstanceState.getBundle(PRESENTER_STATE_KEY))
}
companion object {
private const val PRESENTER_STATE_KEY = "presenter_state"
}
}
| apache-2.0 |
code-disaster/lwjgl3 | modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/QCOM_texture_foveated.kt | 4 | 3804 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengles.templates
import org.lwjgl.generator.*
import opengles.*
val QCOM_texture_foveated = "QCOMTextureFoveated".nativeClassGLES("QCOM_texture_foveated", postfix = QCOM) {
documentation =
"""
Native bindings to the $registryLink extension.
Foveated rendering is a technique that aims to reduce fragment processing workload and bandwidth by reducing the average resolution of a render target.
Perceived image quality is kept high by leaving the focal point of rendering at full resolution.
It exists in two major forms:
${ul(
"""
Static foveated (lens matched) rendering: where the gaze point is fixed with a large fovea region and designed to match up with the lens
characteristics.
""",
"""
Eye-tracked foveated rendering: where the gaze point is continuously tracked by a sensor to allow a smaller fovea region (further reducing average
resolution)
"""
)}
Traditionally foveated rendering involves breaking a render target's area into smaller regions such as bins, tiles, viewports, or layers which are
rendered to individually. Each of these regions has the geometry projected or scaled differently so that the net resolution of these layers is less
than the original render target's resolution. When these regions are mapped back to the original render target, they create a rendered result with
decreased quality as pixels get further from the focal point.
Foveated rendering is currently achieved by large modifications to an applications render pipelines to manually implement the required geometry
amplifications, blits, and projection changes. This presents a large implementation cost to an application developer and is generally inefficient as it
can not make use of a platforms unique hardware features or optimized software paths. This extension aims to address these problems by exposing
foveated rendering in an explicit and vendor neutral way, and by providing an interface with minimal changes to how an application specifies its render
targets.
"""
IntConstant(
"""
Accepted as a value for {@code pname} for the TexParameter{if} and TexParameter{if}v commands and for the {@code pname} parameter of
GetTexParameter{if}v.
""",
"TEXTURE_FOVEATED_FEATURE_BITS_QCOM"..0x8BFB,
"TEXTURE_FOVEATED_MIN_PIXEL_DENSITY_QCOM"..0x8BFC
)
IntConstant(
"Accepted as the {@code pname} parameter of GetTexParameter{if}v.",
"TEXTURE_FOVEATED_FEATURE_QUERY_QCOM"..0x8BFD,
"TEXTURE_FOVEATED_NUM_FOCAL_POINTS_QUERY_QCOM"..0x8BFE
)
IntConstant(
"""
Accepted as a value to {@code param} for the TexParameter{if} and to {@code params} for the TexParameter{if}v commands with a {@code pname} of
#TEXTURE_FOVEATED_FEATURE_BITS_QCOM; returned as possible values for {@code params} when GetTexParameter{if}v is queried with a {@code pname} of
#TEXTURE_FOVEATED_FEATURE_BITS_QCOM.
""",
"FOVEATION_ENABLE_BIT_QCOM"..0x1,
"FOVEATION_SCALED_BIN_METHOD_BIT_QCOM"..0x2
)
IntConstant(
"Returned by #CheckFramebufferStatus().",
"FRAMEBUFFER_INCOMPLETE_FOVEATION_QCOM"..0x8BFF
)
void(
"TextureFoveationParametersQCOM",
"",
GLuint("texture", ""),
GLuint("layer", ""),
GLuint("focalPoint", ""),
float("focalX", ""),
float("focalY", ""),
float("gainX", ""),
float("gainY", ""),
float("foveaArea", "")
)
} | bsd-3-clause |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/trackedentity/TrackedEntityInstanceFilterAPI37.kt | 1 | 3391 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity
import java.util.*
import org.hisp.dhis.android.core.common.*
import org.hisp.dhis.android.core.enrollment.EnrollmentStatus
internal data class TrackedEntityInstanceFilterAPI37(
val id: String,
val code: String?,
val name: String?,
val displayName: String?,
val created: Date?,
val lastUpdated: Date?,
val deleted: Boolean?,
val program: ObjectWithUid?,
val description: String?,
val sortOrder: Int?,
val enrollmentStatus: EnrollmentStatus?,
val followup: Boolean?,
val enrollmentCreatedPeriod: FilterPeriod?,
val eventFilters: List<TrackedEntityInstanceEventFilter>?
) {
fun toTrackedEntityInstanceFilter(): TrackedEntityInstanceFilter =
TrackedEntityInstanceFilter.builder()
.uid(id)
.code(code)
.name(name)
.displayName(displayName)
.created(created)
.lastUpdated(lastUpdated)
.deleted(deleted)
.program(program)
.description(description)
.sortOrder(sortOrder)
.entityQueryCriteria(
EntityQueryCriteria.builder()
.followUp(followup)
.enrollmentStatus(enrollmentStatus)
.enrollmentCreatedDate(
enrollmentCreatedPeriod?.let {
DateFilterPeriod.builder()
.startBuffer(it.periodFrom())
.endBuffer(it.periodTo())
.type(DatePeriodType.RELATIVE)
.build()
}
)
.build()
)
.eventFilters(eventFilters)
.build()
}
| bsd-3-clause |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/util/ContentProviderClientCompat.kt | 1 | 350 | package org.wikipedia.util
import android.content.ContentProviderClient
import android.os.Build
object ContentProviderClientCompat {
@JvmStatic
fun close(client: ContentProviderClient) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
client.close()
} else {
client.release()
}
}
}
| apache-2.0 |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/period/internal/RelativePeriodGeneratorImplShould.kt | 1 | 5260 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.period.internal
import com.google.common.truth.Truth.assertThat
import org.hisp.dhis.android.core.common.RelativePeriod
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class RelativePeriodGeneratorImplShould {
private lateinit var periodGenerator: ParentPeriodGeneratorImpl
@Before
fun setUp() {
periodGenerator = ParentPeriodGeneratorImpl.create(CalendarProviderFactory.createFixed())
}
@Test
@Suppress("ComplexMethod")
fun `Should create relative periods for all period types`() {
RelativePeriod.values().forEach { relativePeriod ->
val periods = periodGenerator.generateRelativePeriods(relativePeriod)
when (relativePeriod) {
RelativePeriod.TODAY,
RelativePeriod.YESTERDAY,
RelativePeriod.THIS_WEEK,
RelativePeriod.THIS_BIWEEK,
RelativePeriod.THIS_MONTH,
RelativePeriod.THIS_BIMONTH,
RelativePeriod.THIS_SIX_MONTH,
RelativePeriod.THIS_QUARTER,
RelativePeriod.THIS_YEAR,
RelativePeriod.THIS_FINANCIAL_YEAR,
RelativePeriod.LAST_MONTH,
RelativePeriod.LAST_WEEK,
RelativePeriod.LAST_BIWEEK,
RelativePeriod.LAST_BIMONTH,
RelativePeriod.LAST_SIX_MONTH,
RelativePeriod.LAST_QUARTER,
RelativePeriod.LAST_YEAR,
RelativePeriod.LAST_FINANCIAL_YEAR -> assertThat(periods.size).isEqualTo(1)
RelativePeriod.LAST_2_SIXMONTHS -> assertThat(periods.size).isEqualTo(2)
RelativePeriod.LAST_3_DAYS,
RelativePeriod.LAST_3_MONTHS -> assertThat(periods.size).isEqualTo(3)
RelativePeriod.LAST_4_WEEKS,
RelativePeriod.LAST_4_BIWEEKS,
RelativePeriod.LAST_4_QUARTERS -> assertThat(periods.size).isEqualTo(4)
RelativePeriod.LAST_5_YEARS,
RelativePeriod.LAST_5_FINANCIAL_YEARS -> assertThat(periods.size).isEqualTo(5)
RelativePeriod.LAST_10_YEARS,
RelativePeriod.LAST_10_FINANCIAL_YEARS -> assertThat(periods.size).isEqualTo(10)
RelativePeriod.LAST_6_MONTHS,
RelativePeriod.LAST_6_BIMONTHS -> assertThat(periods.size).isEqualTo(6)
RelativePeriod.LAST_7_DAYS -> assertThat(periods.size).isEqualTo(7)
RelativePeriod.LAST_14_DAYS -> assertThat(periods.size).isEqualTo(14)
RelativePeriod.LAST_30_DAYS -> assertThat(periods.size).isEqualTo(30)
RelativePeriod.LAST_60_DAYS -> assertThat(periods.size).isEqualTo(60)
RelativePeriod.LAST_90_DAYS -> assertThat(periods.size).isEqualTo(90)
RelativePeriod.LAST_180_DAYS -> assertThat(periods.size).isEqualTo(180)
RelativePeriod.LAST_12_WEEKS,
RelativePeriod.LAST_12_MONTHS -> assertThat(periods.size).isEqualTo(12)
RelativePeriod.LAST_52_WEEKS,
RelativePeriod.WEEKS_THIS_YEAR -> assertThat(periods.size).isEqualTo(52)
RelativePeriod.MONTHS_THIS_YEAR,
RelativePeriod.MONTHS_LAST_YEAR -> assertThat(periods.size).isEqualTo(12)
RelativePeriod.BIMONTHS_THIS_YEAR -> assertThat(periods.size).isEqualTo(6)
RelativePeriod.QUARTERS_THIS_YEAR,
RelativePeriod.QUARTERS_LAST_YEAR -> assertThat(periods.size).isEqualTo(4)
}
}
}
}
| bsd-3-clause |
mdanielwork/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/util/FinderPredicate.kt | 7 | 769 | // 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 file.
package com.intellij.testGuiFramework.util
typealias FinderPredicate = (String, String) -> Boolean
object Predicate{
val equality: FinderPredicate = { found: String, wanted: String -> found == wanted }
val notEquality: FinderPredicate = { found: String, wanted: String -> found != wanted }
val withVersion: FinderPredicate = { found: String, wanted: String ->
val pattern = Regex("\\s+\\(.*\\)$")
if (found.contains(pattern)) {
pattern.split(found).first().trim() == wanted
}
else found == wanted
}
val startWith: FinderPredicate = {found: String, wanted: String -> found.startsWith(wanted)}
} | apache-2.0 |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/util/conversion/ConversionResolve.kt | 1 | 3201 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores.util.conversion
import com.github.jonathanxd.kores.base.FieldDeclaration
import com.github.jonathanxd.kores.base.MethodDeclaration
import com.github.jonathanxd.kores.base.TypeDeclaration
import com.github.jonathanxd.kores.type.`is`
import com.github.jonathanxd.kores.type.koresType
import java.lang.reflect.Field
import java.lang.reflect.Method
/**
* Searches [methodDeclaration] in this [Class].
*/
fun <T : Any> Class<T>.find(methodDeclaration: MethodDeclaration): Method? {
val filter = filter@ { it: Method ->
val name = it.name
val returnType = it.returnType.koresType
val parameterTypes = it.parameterTypes.map { it.koresType }
return@filter name == methodDeclaration.name
&& returnType.`is`(methodDeclaration.returnType)
&& parameterTypes.isEqual(methodDeclaration.parameters)
}
return this.declaredMethods.first(filter) ?: this.methods.first(filter)
}
/**
* Searches [fieldDeclaration] in this [Class].
*/
fun <T : Any> Class<T>.find(fieldDeclaration: FieldDeclaration): Field? {
val filter = filter@ { it: Field ->
val name = it.name
val type = it.type.koresType
return@filter name == fieldDeclaration.name
&& type.`is`(fieldDeclaration.type)
}
return this.declaredFields.first(filter) ?: this.fields.first(filter)
}
/**
* Searches the [typeDeclaration] in this [Class].
*/
fun <T : Any> Class<T>.find(typeDeclaration: TypeDeclaration): Class<*>? {
val filter = filter@ { it: Class<*> ->
val type = it.koresType
return@filter type.`is`(typeDeclaration)
}
return this.declaredClasses.first(filter) ?: this.classes.first(filter)
} | mit |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/toolbar/ToolbarFrameHeader.kt | 2 | 6058 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.customFrameDecorations.header.toolbar
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettingsListener
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.wm.IdeFrame
import com.intellij.openapi.wm.impl.IdeMenuBar
import com.intellij.openapi.wm.impl.ToolbarHolder
import com.intellij.openapi.wm.impl.customFrameDecorations.header.FrameHeader
import com.intellij.openapi.wm.impl.customFrameDecorations.header.MainFrameCustomHeader
import com.intellij.openapi.wm.impl.headertoolbar.MainToolbar
import com.intellij.openapi.wm.impl.headertoolbar.isToolbarInHeader
import com.intellij.ui.awt.RelativeRectangle
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.util.ui.GridBag
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.CurrentTheme.CustomFrameDecorations
import com.jetbrains.CustomWindowDecoration.MENU_BAR
import java.awt.*
import java.awt.GridBagConstraints.*
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import javax.swing.Box
import javax.swing.JComponent
import javax.swing.JFrame
import javax.swing.JPanel
import kotlin.math.roundToInt
private enum class ShowMode {
MENU, TOOLBAR
}
internal class ToolbarFrameHeader(frame: JFrame, ideMenu: IdeMenuBar) : FrameHeader(frame), UISettingsListener, ToolbarHolder, MainFrameCustomHeader {
private val myMenuBar = ideMenu
private val mainMenuButton = MainMenuButton()
private var myToolbar : MainToolbar? = null
private val myToolbarPlaceholder = NonOpaquePanel()
private val myHeaderContent = createHeaderContent()
private val contentResizeListener = object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
updateCustomDecorationHitTestSpots()
}
}
private var mode = ShowMode.MENU
init {
layout = GridBagLayout()
val gb = GridBag().anchor(WEST)
updateLayout(UISettings.getInstance())
productIcon.border = JBUI.Borders.empty(V, 0, V, 0)
add(productIcon, gb.nextLine().next().anchor(WEST).insetLeft(H))
add(myHeaderContent, gb.next().fillCell().anchor(CENTER).weightx(1.0).weighty(1.0))
val buttonsView = buttonPanes.getView()
if (SystemInfo.isWindows) buttonsView.border = JBUI.Borders.emptyLeft(8)
add(buttonsView, gb.next().anchor(EAST))
setCustomFrameTopBorder({ false }, {true})
Disposer.register(this, mainMenuButton.menuShortcutHandler)
}
override fun updateToolbar() {
removeToolbar()
val toolbar = MainToolbar()
toolbar.init((frame as? IdeFrame)?.project)
toolbar.isOpaque = false
toolbar.addComponentListener(contentResizeListener)
myToolbar = toolbar
myToolbarPlaceholder.add(myToolbar)
myToolbarPlaceholder.revalidate()
}
override fun removeToolbar() {
myToolbar?.removeComponentListener(contentResizeListener)
myToolbarPlaceholder.removeAll()
myToolbarPlaceholder.revalidate()
}
override fun installListeners() {
super.installListeners()
mainMenuButton.menuShortcutHandler.registerShortcuts(frame.rootPane)
myMenuBar.addComponentListener(contentResizeListener)
}
override fun uninstallListeners() {
super.uninstallListeners()
mainMenuButton.menuShortcutHandler.unregisterShortcuts()
myMenuBar.removeComponentListener(contentResizeListener)
myToolbar?.removeComponentListener(contentResizeListener)
}
override fun updateMenuActions(forceRebuild: Boolean) {} //todo remove
override fun getComponent(): JComponent = this
override fun uiSettingsChanged(uiSettings: UISettings) {
updateLayout(uiSettings)
when (mode) {
ShowMode.TOOLBAR -> updateToolbar()
ShowMode.MENU -> removeToolbar()
}
}
override fun getHitTestSpots(): List<Pair<RelativeRectangle, Int>> {
val result = super.getHitTestSpots().toMutableList()
when (mode) {
ShowMode.MENU -> {
result.add(Pair(getElementRect(myMenuBar) { rect ->
val state = frame.extendedState
if (state != Frame.MAXIMIZED_VERT && state != Frame.MAXIMIZED_BOTH) {
val topGap = (rect.height / 3).toFloat().roundToInt()
rect.y += topGap
rect.height -= topGap
}
}, MENU_BAR))
}
ShowMode.TOOLBAR -> {
result.add(Pair(getElementRect(mainMenuButton.button), MENU_BAR))
myToolbar?.components?.filter { it.isVisible }?.forEach { result.add(Pair(getElementRect(it), MENU_BAR)) }
}
}
return result
}
override fun getHeaderBackground(active: Boolean) = CustomFrameDecorations.mainToolbarBackground(active)
private fun getElementRect(comp: Component, rectProcessor: ((Rectangle) -> Unit)? = null): RelativeRectangle {
val rect = Rectangle(comp.size)
rectProcessor?.invoke(rect)
return RelativeRectangle(comp, rect)
}
fun createHeaderContent(): JPanel {
val res = NonOpaquePanel(CardLayout())
res.border = JBUI.Borders.empty()
val menuPnl = NonOpaquePanel(GridBagLayout()).apply {
val gb = GridBag().anchor(WEST).nextLine()
add(myMenuBar, gb.next().insetLeft(JBUI.scale(20)).fillCellVertically().weighty(1.0))
add(Box.createHorizontalGlue(), gb.next().weightx(1.0).fillCell())
}
val toolbarPnl = NonOpaquePanel(GridBagLayout()).apply {
val gb = GridBag().anchor(WEST).nextLine()
add(mainMenuButton.button, gb.next().insetLeft(JBUI.scale(20)))
add(myToolbarPlaceholder, gb.next().weightx(1.0).fillCellHorizontally().insetLeft(JBUI.scale(16)))
}
res.add(ShowMode.MENU.name, menuPnl)
res.add(ShowMode.TOOLBAR.name, toolbarPnl)
return res
}
private fun updateLayout(settings: UISettings) {
mode = if (isToolbarInHeader(settings)) ShowMode.TOOLBAR else ShowMode.MENU
val layout = myHeaderContent.layout as CardLayout
layout.show(myHeaderContent, mode.name)
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | platform/diff-impl/tests/testSrc/com/intellij/diff/comparison/LineComparisonMergeUtilTest.kt | 17 | 3334 | // 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 file.
package com.intellij.diff.comparison
class LineComparisonMergeUtilTest : ComparisonMergeUtilTestBase() {
fun testSimpleCases() {
lines_merge {
("" - "" - "")
("" - "" - "").matching()
changes()
test()
}
lines_merge {
("x_y_z" - "x_y_z" - "x_y_z")
(" _ _ " - " _ _ " - " _ _ ").matching()
changes()
test()
}
lines_merge {
("" - "" - "x")
changes(mod(0, 0, 0, 1, 1, 1))
test()
}
lines_merge {
("" - "" - "_x")
("" - "" - "_-").matching()
changes(mod(1, 1, 1, 0, 0, 1))
test()
}
lines_merge {
("x" - "y" - "x")
("-" - "-" - "-").matching()
test()
}
lines_merge {
("x" - "x_y" - "x")
(" " - " _-" - " ").matching()
test()
}
lines_merge {
("x" - "y_x" - "x")
(" " - "-_ " - " ").matching()
test()
}
lines_merge {
("x_y_z" - "x_Y_z" - "x_y_z")
(" _-_ " - " _-_ " - " _-_ ").matching()
test()
}
lines_merge {
("x_y_z" - "X_y_Z" - "x_y_z")
("-_ _-" - "-_ _-" - "-_ _-").matching()
test()
}
}
fun testIgnoreWhitespaces() {
lines_diff {
("x_ y _z" - "x_y_z" - "x_ y_ z")
changes()
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
lines_merge {
("x_ y _z" - "x_y_z" - "x_ y_ z")
changes(mod(1, 1, 1, 2, 2, 2))
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
lines_diff {
("x_ y _z" - "x_Y_z" - "x_ y_ z")
changes(mod(1, 1, 1, 1, 1, 1))
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
lines_merge {
("x_ y _z" - "x_Y_z" - "x_ y_ z")
changes(mod(1, 1, 1, 1, 1, 1),
mod(2, 2, 2, 1, 1, 1))
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
lines_merge {
("x_ y _z" - "x_Y_z" - "x_ y_z")
changes(mod(1, 1, 1, 1, 1, 1))
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
lines_merge {
("x_ y _z" - "x_y_z" - "x_ y_z")
changes(mod(1, 1, 1, 1, 1, 1))
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
lines_merge {
(" x _y_z" - "x_y_z" - "x_y_ z")
changes(mod(0, 0, 0, 1, 1, 1),
mod(2, 2, 2, 1, 1, 1))
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
lines_diff {
(" x_new_y_z" - "x_ y _z" - "x_y_new_ z")
changes(mod(1, 1, 1, 1, 0, 0),
mod(3, 2, 2, 0, 0, 1))
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
lines_merge {
(" x_new_y_z" - "x_ y _z" - "x_y_new_ z")
changes(mod(0, 0, 0, 1, 1, 1),
mod(1, 1, 1, 1, 0, 0),
mod(2, 1, 1, 1, 1, 1),
mod(3, 2, 2, 0, 0, 1),
mod(3, 2, 3, 1, 1, 1))
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
lines_diff {
(" x_new_y1_z" - "x_ y _z" - "x_y2_new_ z")
changes(mod(1, 1, 1, 2, 1, 2))
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
lines_merge {
(" x_new_y1_z" - "x_ y _z" - "x_y2_new_ z")
changes(mod(0, 0, 0, 1, 1, 1),
mod(1, 1, 1, 2, 1, 2),
mod(3, 2, 3, 1, 1, 1))
test(ComparisonPolicy.IGNORE_WHITESPACES)
}
}
}
| apache-2.0 |
dkandalov/katas | kotlin-native/hello-lib/src/hello.kt | 1 | 54 |
fun hello(s: String): String {
return s + "!!!"
} | unlicense |
kingargyle/serenity-android | serenity-app/src/main/kotlin/us/nineworlds/serenity/ui/activity/login/LoginUserPresenter.kt | 2 | 2460 | package us.nineworlds.serenity.ui.activity.login
import com.birbit.android.jobqueue.JobManager
import moxy.InjectViewState
import moxy.MvpPresenter
import moxy.viewstate.strategy.SkipStrategy
import moxy.viewstate.strategy.StateStrategyType
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode.MAIN
import toothpick.Toothpick
import us.nineworlds.serenity.common.Server
import us.nineworlds.serenity.common.annotations.InjectionConstants
import us.nineworlds.serenity.common.rest.SerenityClient
import us.nineworlds.serenity.common.rest.SerenityUser
import us.nineworlds.serenity.core.logger.Logger
import us.nineworlds.serenity.events.users.AllUsersEvent
import us.nineworlds.serenity.events.users.AuthenticatedUserEvent
import us.nineworlds.serenity.jobs.AuthenticateUserJob
import us.nineworlds.serenity.jobs.RetrieveAllUsersJob
import us.nineworlds.serenity.ui.activity.login.LoginUserContract.LoginUserView
import javax.inject.Inject
@InjectViewState
@StateStrategyType(SkipStrategy::class)
class LoginUserPresenter : MvpPresenter<LoginUserView>(), LoginUserContract.LoginUserPresnter {
@Inject
lateinit var logger: Logger
@Inject
lateinit var client: SerenityClient
var eventBus = EventBus.getDefault()
@Inject
lateinit var jobManager: JobManager
lateinit var server: Server
init {
Toothpick.inject(this, Toothpick.openScope(InjectionConstants.APPLICATION_SCOPE))
}
override fun attachView(view: LoginUserView?) {
super.attachView(view)
eventBus.register(this)
}
override fun detachView(view: LoginUserView?) {
super.detachView(view)
eventBus.unregister(this)
}
override fun initPresenter(server: Server) {
this.server = server
if (server.port != null) {
client.updateBaseUrl("http://${server.ipAddress}:${server.port}/")
} else {
client.updateBaseUrl("http://${server.ipAddress}:8096/")
}
}
override fun retrieveAllUsers() {
jobManager.addJobInBackground(RetrieveAllUsersJob())
}
override fun loadUser(user: SerenityUser) {
jobManager.addJobInBackground(AuthenticateUserJob(user))
}
@Subscribe(threadMode = MAIN)
fun processAllUsersEvent(allUsersEvent: AllUsersEvent) {
viewState.displayUsers(allUsersEvent.users)
}
@Subscribe(threadMode = MAIN)
fun showUsersStartScreen(authenticatUserEvent: AuthenticatedUserEvent) {
viewState.launchNextScreen()
}
} | mit |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/removeRedundantQualifierName/notApplicableExpression4.kt | 13 | 227 | // PROBLEM: none
package foo
class Foo {
fun test() {
<caret>foo.myRun {
42
}
}
}
inline fun <R> myRun(block: () -> R): R = block()
inline fun <T, R> T.myRun(block: T.() -> R): R = block() | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReturnSaver.kt | 6 | 2919 | // 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 org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReturnSaver(val function: KtNamedFunction) {
companion object {
private val RETURN_KEY = Key<Unit>("RETURN_KEY")
}
val isEmpty: Boolean
init {
var hasReturn = false
val body = function.bodyExpression!!
body.forEachDescendantOfType<KtReturnExpression> {
if (it.getTargetFunction(it.analyze(BodyResolveMode.PARTIAL)) == function) {
hasReturn = true
it.putCopyableUserData(RETURN_KEY, Unit)
}
}
isEmpty = !hasReturn
}
private fun clear() {
val body = function.bodyExpression!!
body.forEachDescendantOfType<KtReturnExpression> { it.putCopyableUserData(RETURN_KEY, null) }
}
fun restore(lambda: KtLambdaExpression, label: Name) {
clear()
val factory = KtPsiFactory(lambda)
val lambdaBody = lambda.bodyExpression!!
val returnToReplace = lambda.collectDescendantsOfType<KtReturnExpression>() { it.getCopyableUserData(RETURN_KEY) != null }
for (returnExpression in returnToReplace) {
val value = returnExpression.returnedExpression
val replaceWith = if (value != null && returnExpression.isValueOfBlock(lambdaBody)) {
value
} else if (value != null) {
factory.createExpressionByPattern("return@$0 $1", label, value)
} else {
factory.createExpressionByPattern("return@$0", label)
}
returnExpression.replace(replaceWith)
}
}
private fun KtExpression.isValueOfBlock(inBlock: KtBlockExpression): Boolean = when (val parent = parent) {
inBlock -> {
this == inBlock.statements.last()
}
is KtBlockExpression -> {
isValueOfBlock(parent) && parent.isValueOfBlock(inBlock)
}
is KtContainerNode -> {
val owner = parent.parent
if (owner is KtIfExpression) {
(this == owner.then || this == owner.`else`) && owner.isValueOfBlock(inBlock)
} else
false
}
is KtWhenEntry -> {
this == parent.expression && (parent.parent as KtWhenExpression).isValueOfBlock(inBlock)
}
else -> false
}
} | apache-2.0 |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/model/impl/columns/receipts/ReceiptNameColumn.kt | 2 | 656 | package co.smartreceipts.android.model.impl.columns.receipts
import co.smartreceipts.android.model.Receipt
import co.smartreceipts.android.model.impl.columns.AbstractColumnImpl
import co.smartreceipts.core.sync.model.SyncState
import java.util.*
/**
* Provides a column that returns the category code for a particular receipt
*/
class ReceiptNameColumn(id: Int, syncState: SyncState, customOrderId: Long, uuid: UUID) :
AbstractColumnImpl<Receipt>(
id,
ReceiptColumnDefinitions.ActualDefinition.NAME,
syncState,
customOrderId,
uuid
) {
override fun getValue(rowItem: Receipt): String = rowItem.name
} | agpl-3.0 |
jaredsburrows/android-gif-example | app/src/main/java/com/burrowsapps/gif/search/data/source/network/GifDto.kt | 1 | 301 | package com.burrowsapps.gif.search.data.source.network
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
internal data class GifDto(
@field:Json(name = "url")
val url: String = "",
@field:Json(name = "preview")
val preview: String = "",
)
| apache-2.0 |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/eventLog/FeatureUsageData.kt | 1 | 6391 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.eventLog
import com.intellij.internal.statistic.service.fus.collectors.FUSUsageContext
import com.intellij.internal.statistic.utils.PluginInfo
import com.intellij.internal.statistic.utils.getPluginType
import com.intellij.internal.statistic.utils.getProjectId
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.Version
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.impl.content.ToolWindowContentUi
import com.intellij.psi.PsiFile
import com.intellij.util.containers.ContainerUtil
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.util.*
/**
* <p>FeatureUsageData represents additional data for reported event.</p>
*
* <h3>Example</h3>
*
* <p>My usage collector collects actions invocations. <i>"my.foo.action"</i> could be invoked from one of the following contexts:
* "main.menu", "context.menu", "my.dialog", "all-actions-run".</p>
*
* <p>If I write {@code FUCounterUsageLogger.logEvent("my.foo.action", "bar")}, I'll know how many times the action "bar" was invoked (e.g. 239)</p>
*
* <p>If I write {@code FUCounterUsageLogger.logEvent("my.foo.action", "bar", new FeatureUsageData().addPlace(place))}, I'll get the same
* total count of action invocations (239), but I'll also know that the action was called 3 times from "main.menu", 235 times from "my.dialog" and only once from "context.menu".
* <br/>
* </p>
*/
class FeatureUsageData {
private var data: MutableMap<String, Any> = ContainerUtil.newHashMap<String, Any>()
fun addFeatureContext(context: FUSUsageContext?): FeatureUsageData {
if (context != null) {
data.putAll(context.data)
}
return this
}
fun addProject(project: Project?): FeatureUsageData {
if (project != null) {
data["project"] = getProjectId(project)
}
return this
}
fun addVersionByString(version: String?): FeatureUsageData {
if (version == null) {
data["version"] = "unknown"
}
else {
addVersion(Version.parseVersion(version))
}
return this
}
fun addVersion(version: Version?): FeatureUsageData {
data["version"] = if (version != null) "${version.major}.${version.minor}" else "unknown.format"
return this
}
fun addOS(): FeatureUsageData {
data["os"] = getOS()
return this
}
private fun getOS(): String {
if (SystemInfo.isWindows) return "Windows"
if (SystemInfo.isMac) return "Mac"
return if (SystemInfo.isLinux) "Linux" else "Other"
}
fun addPluginInfo(info: PluginInfo): FeatureUsageData {
data["plugin_type"] = info.type.name
if (info.type.isSafeToReport() && info.id != null && StringUtil.isNotEmpty(info.id)) {
data["plugin"] = info.id
}
return this
}
fun addLanguage(language: Language): FeatureUsageData {
val type = getPluginType(language.javaClass)
if (type.isSafeToReport()) {
data["lang"] = language.id
}
return this
}
fun addCurrentFile(language: Language): FeatureUsageData {
val type = getPluginType(language.javaClass)
if (type.isSafeToReport()) {
data["current_file"] = language.id
}
return this
}
fun addInputEvent(event: AnActionEvent): FeatureUsageData {
val inputEvent = ShortcutDataProvider.getActionEventText(event)
if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) {
data["input_event"] = inputEvent
}
return this
}
fun addInputEvent(event: KeyEvent): FeatureUsageData {
val inputEvent = ShortcutDataProvider.getKeyEventText(event)
if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) {
data["input_event"] = inputEvent
}
return this
}
fun addInputEvent(event: MouseEvent): FeatureUsageData {
val inputEvent = ShortcutDataProvider.getMouseEventText(event)
if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) {
data["input_event"] = inputEvent
}
return this
}
fun addPlace(place: String?): FeatureUsageData {
if (place == null) return this
var reported = ActionPlaces.UNKNOWN
if (isCommonPlace(place)) {
reported = place
}
else if (ActionPlaces.isPopupPlace(place)) {
reported = ActionPlaces.POPUP
}
data["place"] = reported
return this
}
private fun isCommonPlace(place: String): Boolean {
return ActionPlaces.isCommonPlace(place) || ToolWindowContentUi.POPUP_PLACE == place
}
fun addData(key: String, value: Boolean): FeatureUsageData {
return addDataInternal(key, value)
}
fun addData(key: String, value: Int): FeatureUsageData {
return addDataInternal(key, value)
}
fun addData(key: String, value: Long): FeatureUsageData {
return addDataInternal(key, value)
}
fun addData(key: String, value: String): FeatureUsageData {
return addDataInternal(key, value)
}
private fun addDataInternal(key: String, value: Any): FeatureUsageData {
data[key] = value
return this
}
fun build(): Map<String, Any> {
if (data.isEmpty()) {
return Collections.emptyMap()
}
return data
}
fun merge(next: FeatureUsageData, prefix: String): FeatureUsageData {
for ((key, value) in next.build()) {
val newKey = if (key.startsWith("data_")) "$prefix$key" else key
addDataInternal(newKey, value)
}
return this
}
fun copy(): FeatureUsageData {
val result = FeatureUsageData()
for ((key, value) in data) {
result.addDataInternal(key, value)
}
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FeatureUsageData
if (data != other.data) return false
return true
}
override fun hashCode(): Int {
return data.hashCode()
}
}
fun newData(project: Project?, context: FUSUsageContext?): Map<String, Any> {
if (project == null && context == null) return Collections.emptyMap()
return FeatureUsageData().addProject(project).addFeatureContext(context).build()
} | apache-2.0 |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/SaveAllAction.kt | 2 | 1588 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.impl.TrailingSpacesStripper
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.DumbAware
// class is "open" due to backward compatibility - do not extend it.
open class SaveAllAction : AnAction(), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
CommonDataKeys.EDITOR.getData(e.dataContext)?.let(::stripSpacesFromCaretLines)
val project = CommonDataKeys.PROJECT.getData(e.dataContext)
FileDocumentManager.getInstance().saveAllDocuments()
(SaveAndSyncHandler.getInstance()).scheduleSave(SaveAndSyncHandler.SaveTask(onlyProject = project, forceSavingAllSettings = true, saveDocuments = false), forceExecuteImmediately = true)
}
}
private fun stripSpacesFromCaretLines(editor: Editor) {
val document = editor.document
val options = TrailingSpacesStripper.getOptions(editor.document)
if (options != null) {
if (options.isStripTrailingSpaces && !options.isKeepTrailingSpacesOnCaretLine) {
TrailingSpacesStripper.strip(document, options.isChangedLinesOnly, false)
}
}
}
| apache-2.0 |
jaredsburrows/android-gif-example | app/src/main/java/com/burrowsapps/gif/search/ui/giflist/GifImageInfo.kt | 1 | 333 | package com.burrowsapps.gif.search.ui.giflist
import androidx.compose.runtime.Immutable
/**
* Model for the GifAdapter in order to display the gifs.
*/
@Immutable
internal data class GifImageInfo(
var tinyGifUrl: String = "",
var tinyGifPreviewUrl: String = "",
var gifUrl: String = "",
var gifPreviewUrl: String = "",
)
| apache-2.0 |
antlr/grammars-v4 | kotlin/kotlin-formal/examples/fuzzer/genericOverriddenProperty.kt-1818173800.kt_minimized.kt | 1 | 196 | sealed interface H<T> {
val parent: (T)?
}
interface A: H<A>
fun box(): String {
assertEquals("T?", (if ((H<A>::parent) >= (H<A>::parent)) {
(H<A>::parent)
} else {
}).returnType.toString())
} | mit |
google/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/firstStep/ProjectTemplateSettingComponent.kt | 2 | 5154 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.firstStep
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.ui.JBUI
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.DropDownSettingType
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectTemplates.ProjectTemplatesPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectTemplates.applyProjectTemplate
import org.jetbrains.kotlin.tools.projectWizard.projectTemplates.*
import org.jetbrains.kotlin.tools.projectWizard.wizard.OnUserSettingChangeStatisticsLogger
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.*
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.SettingComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.ValidationIndicator
import java.awt.Dimension
import javax.swing.Icon
import javax.swing.JComponent
class ProjectTemplateSettingComponent(
context: Context
) : SettingComponent<ProjectTemplate, DropDownSettingType<ProjectTemplate>>(
ProjectTemplatesPlugin.template.reference,
context
) {
override val validationIndicator: ValidationIndicator? get() = null
private val templateDescriptionComponent = TemplateDescriptionComponent().asSubComponent()
private val templateGroups = setting.type.values
.groupBy { it.projectKind }
.map { (group, templates) ->
ListWithSeparators.ListGroup(group.text, templates)
}
private val list = ListWithSeparators(
templateGroups,
render = { value ->
icon = value.icon
append(value.title)
value.projectKind.message?.let { message ->
append(" ")
append(message, SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
},
onValueSelected = { newValue ->
newValue?.let {
OnUserSettingChangeStatisticsLogger.logSettingValueChangedByUser(
context.contextComponents.get(),
ProjectTemplatesPlugin.template.path,
it
)
}
value = newValue
}
)
override val alignment: TitleComponentAlignment
get() = TitleComponentAlignment.AlignFormTopWithPadding(4)
private val scrollPane = ScrollPaneFactory.createScrollPane(list)
override val component: JComponent = borderPanel {
addToCenter(borderPanel { addToCenter(scrollPane) }.addBorder(JBUI.Borders.empty(0,/*left*/ 3, 0, /*right*/ 3)))
addToBottom(templateDescriptionComponent.component.addBorder(JBUI.Borders.empty(/*top*/8,/*left*/ 3, 0, 0)))
}
private fun applySelectedTemplate() = modify {
value?.let(::applyProjectTemplate)
}
override fun onValueUpdated(reference: SettingReference<*, *>?) {
super.onValueUpdated(reference)
if (reference == ProjectTemplatesPlugin.template.reference) {
applySelectedTemplate()
updateHint()
}
}
override fun onInit() {
super.onInit()
if (setting.type.values.isNotEmpty()) {
list.selectedIndex = 0
value = setting.type.values.firstOrNull()
applySelectedTemplate()
updateHint()
}
}
private fun updateHint() {
value?.let { template ->
list.setSelectedValue(template, true)
templateDescriptionComponent.setTemplate(template)
}
}
}
private val ProjectTemplate.icon: Icon?
get() = when (this) {
ConsoleApplicationProjectTemplateWithSample -> KotlinIcons.Wizard.CONSOLE
MultiplatformLibraryProjectTemplate -> KotlinIcons.Wizard.MULTIPLATFORM_LIBRARY
FullStackWebApplicationProjectTemplate -> KotlinIcons.Wizard.WEB
NativeApplicationProjectTemplate -> KotlinIcons.Wizard.NATIVE
FrontendApplicationProjectTemplate -> KotlinIcons.Wizard.JS
ReactApplicationProjectTemplate -> KotlinIcons.Wizard.REACT_JS
NodeJsApplicationProjectTemplate -> KotlinIcons.Wizard.NODE_JS
ComposeDesktopApplicationProjectTemplate -> KotlinIcons.Wizard.COMPOSE
ComposeMultiplatformApplicationProjectTemplate -> KotlinIcons.Wizard.COMPOSE
ComposeWebApplicationProjectTemplate -> KotlinIcons.Wizard.COMPOSE
else -> null
}
class TemplateDescriptionComponent : Component() {
private val descriptionLabel = CommentLabel().apply {
preferredSize = Dimension(preferredSize.width, 45)
}
fun setTemplate(template: ProjectTemplate) {
descriptionLabel.text = template.description.asHtml()
}
override val component: JComponent = descriptionLabel
} | apache-2.0 |
google/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/config/SettingsSyncConfigurable.kt | 5 | 10186 | package com.intellij.settingsSync.config
import com.intellij.icons.AllIcons
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.ConfigurableProvider
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.Messages
import com.intellij.settingsSync.*
import com.intellij.settingsSync.SettingsSyncBundle.message
import com.intellij.settingsSync.auth.SettingsSyncAuthService
import com.intellij.ui.JBColor
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.layout.*
import com.intellij.util.text.DateFormatUtil
import org.jetbrains.annotations.Nls
import javax.swing.JButton
import javax.swing.JCheckBox
import javax.swing.JLabel
internal class SettingsSyncConfigurable : BoundConfigurable(message("title.settings.sync")),
SettingsSyncEnabler.Listener,
SettingsSyncStatusTracker.Listener {
private lateinit var configPanel: DialogPanel
private lateinit var enableButton: Cell<JButton>
private lateinit var statusLabel: JLabel
private val syncEnabler = SettingsSyncEnabler()
init {
syncEnabler.addListener(this)
SettingsSyncStatusTracker.getInstance().addListener(this)
}
inner class LoggedInPredicate : ComponentPredicate() {
override fun addListener(listener: (Boolean) -> Unit) =
SettingsSyncAuthService.getInstance().addListener(object : SettingsSyncAuthService.Listener {
override fun stateChanged() {
listener(invoke())
}
}, disposable!!)
override fun invoke() = SettingsSyncAuthService.getInstance().isLoggedIn()
}
inner class EnabledPredicate : ComponentPredicate() {
override fun addListener(listener: (Boolean) -> Unit) {
SettingsSyncEvents.getInstance().addEnabledStateChangeListener(object : SettingsSyncEnabledStateListener {
override fun enabledStateChanged(syncEnabled: Boolean) {
listener(invoke())
}
}, disposable!!)
}
override fun invoke() = SettingsSyncSettings.getInstance().syncEnabled
}
inner class SyncEnablerRunning : ComponentPredicate() {
private var isRunning = false
override fun addListener(listener: (Boolean) -> Unit) {
syncEnabler.addListener(object : SettingsSyncEnabler.Listener {
override fun serverRequestStarted() {
updateRunning(listener, true)
}
override fun serverRequestFinished() {
updateRunning(listener, false)
}
})
}
private fun updateRunning(listener: (Boolean) -> Unit, isRunning: Boolean) {
this.isRunning = isRunning
listener(invoke())
}
override fun invoke(): Boolean = isRunning
}
override fun createPanel(): DialogPanel {
val categoriesPanel = SettingsSyncPanelFactory.createPanel(message("configurable.what.to.sync.label"))
val authService = SettingsSyncAuthService.getInstance()
configPanel = panel {
val isSyncEnabled = LoggedInPredicate().and(EnabledPredicate())
row {
val statusCell = label("")
statusCell.visibleIf(LoggedInPredicate())
statusLabel = statusCell.component
updateStatusInfo()
label(message("sync.status.login.message")).visibleIf(LoggedInPredicate().not())
}
row {
comment(message("settings.sync.info.message"), 80)
.visibleIf(isSyncEnabled.not())
}
row {
button(message("config.button.login")) {
authService.login()
}.visibleIf(LoggedInPredicate().not()).enabled(authService.isLoginAvailable())
label(message("error.label.login.not.available")).component.apply {
isVisible = !authService.isLoginAvailable()
icon = AllIcons.General.Error
foreground = JBColor.red
}
enableButton = button(message("config.button.enable")) {
syncEnabler.checkServerState()
}.visibleIf(LoggedInPredicate().and(EnabledPredicate().not())).enabledIf(SyncEnablerRunning().not())
button(message("config.button.disable")) {
LoggedInPredicate().and(EnabledPredicate())
disableSync()
}.visibleIf(isSyncEnabled)
}
row {
cell(categoriesPanel)
.visibleIf(LoggedInPredicate().and(EnabledPredicate()))
.onApply { categoriesPanel.apply() }
.onReset { categoriesPanel.reset() }
.onIsModified { categoriesPanel.isModified() }
}
}
SettingsSyncAuthService.getInstance().addListener(object : SettingsSyncAuthService.Listener {
override fun stateChanged() {
if (SettingsSyncAuthService.getInstance().isLoggedIn() && !SettingsSyncSettings.getInstance().syncEnabled) {
syncEnabler.checkServerState()
}
}
}, disposable!!)
return configPanel
}
override fun serverStateCheckFinished(state: ServerState) {
when (state) {
ServerState.FileNotExists -> showEnableSyncDialog(false)
ServerState.UpToDate, ServerState.UpdateNeeded -> showEnableSyncDialog(true)
is ServerState.Error -> {
if (state != SettingsSyncEnabler.State.CANCELLED) {
showError(message("notification.title.update.error"), state.message)
}
}
}
}
override fun updateFromServerFinished(result: UpdateResult) {
when (result) {
is UpdateResult.Success -> {
SettingsSyncSettings.getInstance().syncEnabled = true
}
UpdateResult.NoFileOnServer -> {
showError(message("notification.title.update.error"), message("notification.title.update.no.such.file"))
}
is UpdateResult.Error -> {
showError(message("notification.title.update.error"), result.message)
}
}
updateStatusInfo()
}
private fun showEnableSyncDialog(remoteSettingsFound: Boolean) {
EnableSettingsSyncDialog.showAndGetResult(configPanel, remoteSettingsFound)?.let {
reset()
when (it) {
EnableSettingsSyncDialog.Result.GET_FROM_SERVER -> syncEnabler.getSettingsFromServer()
EnableSettingsSyncDialog.Result.PUSH_LOCAL -> {
SettingsSyncSettings.getInstance().syncEnabled = true
syncEnabler.pushSettingsToServer()
}
}
}
}
companion object DisableResult {
const val RESULT_CANCEL = 0
const val RESULT_REMOVE_DATA_AND_DISABLE = 1
const val RESULT_DISABLE = 2
}
private fun disableSync() {
@Suppress("DialogTitleCapitalization")
val result = Messages.showCheckboxMessageDialog( // TODO<rv>: Use AlertMessage instead
message("disable.dialog.text"),
message("disable.dialog.title"),
arrayOf(Messages.getCancelButton(), message("disable.dialog.disable.button")),
message("disable.dialog.remove.data.box"),
false,
1,
1,
Messages.getInformationIcon()
) { index: Int, checkbox: JCheckBox ->
if (index == 1) {
if (checkbox.isSelected) RESULT_REMOVE_DATA_AND_DISABLE else RESULT_DISABLE
}
else {
RESULT_CANCEL
}
}
when (result) {
RESULT_DISABLE -> {
SettingsSyncSettings.getInstance().syncEnabled = false
updateStatusInfo()
}
RESULT_REMOVE_DATA_AND_DISABLE -> disableAndRemoveData()
}
}
private fun disableAndRemoveData() {
val remoteCommunicator = SettingsSyncMain.getInstance().getRemoteCommunicator()
object : Task.Modal(null, message("disable.remove.data.title"), false) {
override fun run(indicator: ProgressIndicator) {
SettingsSyncSettings.getInstance().syncEnabled = false
remoteCommunicator.delete()
}
override fun onThrowable(error: Throwable) {
showError(message("disable.remove.data.failure"), error.localizedMessage)
}
override fun onSuccess() {
updateStatusInfo()
}
}.queue()
}
private fun showError(message: @Nls String, details: @Nls String) {
val messageBuilder = StringBuilder()
messageBuilder.append(message("sync.status.failed"))
statusLabel.icon = AllIcons.General.Error
messageBuilder.append(' ').append("$message: $details")
@Suppress("HardCodedStringLiteral")
statusLabel.text = messageBuilder.toString()
}
private fun updateStatusInfo() {
if (::statusLabel.isInitialized) {
val messageBuilder = StringBuilder()
statusLabel.icon = null
if (SettingsSyncSettings.getInstance().syncEnabled) {
val statusTracker = SettingsSyncStatusTracker.getInstance()
if (statusTracker.isSyncSuccessful()) {
messageBuilder
.append(message("sync.status.enabled"))
if (statusTracker.isSynced()) {
messageBuilder
.append(' ')
.append(message("sync.status.last.sync.message", getReadableSyncTime(), getUserName()))
}
}
else {
messageBuilder.append(message("sync.status.failed"))
statusLabel.icon = AllIcons.General.Error
messageBuilder.append(' ').append(statusTracker.getErrorMessage())
}
}
else {
messageBuilder.append(message("sync.status.disabled"))
}
@Suppress("HardCodedStringLiteral") // The above strings are localized
statusLabel.text = messageBuilder.toString()
}
}
private fun getReadableSyncTime(): String {
return DateFormatUtil.formatPrettyDateTime(SettingsSyncStatusTracker.getInstance().getLastSyncTime()).lowercase()
}
private fun getUserName(): String {
return SettingsSyncAuthService.getInstance().getUserData()?.loginName ?: "?"
}
override fun syncStatusChanged() {
updateStatusInfo()
}
override fun disposeUIResources() {
super.disposeUIResources()
SettingsSyncStatusTracker.getInstance().removeListener(this)
}
}
class SettingsSyncConfigurableProvider : ConfigurableProvider() {
override fun createConfigurable(): Configurable = SettingsSyncConfigurable()
override fun canCreateConfigurable() = isSettingsSyncEnabledByKey()
} | apache-2.0 |
boxtape/boxtape-cli | boxtape-cli/src/main/java/io/boxtape/cli/commands/BootCommand.kt | 1 | 787 | package io.boxtape.cli.commands
import io.boxtape.cli.core.Project
import org.apache.commons.exec.CommandLine
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
Component
public class BootCommand
Autowired constructor(val vagrantUp : VagrantUpCommand,
val ansible: AnsibleCommand)
: ShellCommand {
override fun run(project: Project) {
// vagrantUp.run(project)
ansible.run(project)
val ip = "10.0.2.15"
project.config.registerPropertyWithDefault("serverIp",ip)
project.writeConfigurationFile()
val cmd = project.command("mvn")
.addArgument("spring-boot:run")
project.run(cmd)
}
override fun name() = "boot"
}
| apache-2.0 |
google/intellij-community | platform/testFramework/src/com/intellij/testFramework/PsiTestUtil.kt | 3 | 1794 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.testFramework
import com.intellij.injected.editor.DocumentWindow
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiReference
import com.intellij.refactoring.suggested.startOffset
import com.intellij.util.castSafelyTo
import com.intellij.util.text.allOccurrencesOf
@JvmOverloads
fun PsiFile.findReferenceByText(str: String, refOffset: Int = str.length / 2): PsiReference =
findAllReferencesByText(str, refOffset).firstOrNull() ?: throw AssertionError("can't find reference for '$str'")
@JvmOverloads
fun PsiFile.findAllReferencesByText(str: String, refOffset: Int = str.length / 2): Sequence<PsiReference> {
var offset = refOffset
if (offset < 0) {
offset += str.length
}
return this.text.allOccurrencesOf(str).map { index ->
val pos = index + offset
val element = findElementAt(pos) ?: throw AssertionError("can't find element for '$str' at $pos")
element.findReferenceAt(pos - element.startOffset)
?: findInInjected(this, pos)
?: throw AssertionError("can't find reference for '$str' at $pos")
}
}
private fun findInInjected(psiFile: PsiFile, pos: Int): PsiReference? {
val injected = InjectedLanguageManager.getInstance(psiFile.project).findInjectedElementAt(psiFile, pos) ?: return null
val documentWindow = PsiDocumentManager.getInstance(psiFile.project).getDocument(injected.containingFile).castSafelyTo<DocumentWindow>()
?: return null
val hostToInjected = documentWindow.hostToInjected(pos)
return injected.findReferenceAt(hostToInjected - injected.startOffset)
} | apache-2.0 |
avram/zandy | src/main/java/com/gimranov/zandy/app/DrawerNavigationActivity.kt | 1 | 4681 | package com.gimranov.zandy.app
import android.content.Intent
import android.os.Bundle
import androidx.core.view.GravityCompat
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import com.gimranov.zandy.app.data.Database
import com.gimranov.zandy.app.data.Item
import com.gimranov.zandy.app.data.ItemCollection
import kotlinx.android.synthetic.main.activity_drawer_navigation.*
import kotlinx.android.synthetic.main.app_bar_drawer_navigation.*
import kotlinx.android.synthetic.main.content_drawer_navigation.*
class DrawerNavigationActivity : AppCompatActivity() {
private val collectionKey = "com.gimranov.zandy.app.collectionKey"
private val database = Database(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_drawer_navigation)
setSupportActionBar(toolbar)
}
override fun onResume() {
super.onResume()
val itemListingRule = intent?.extras?.getString(collectionKey)?.let {
Children(ItemCollection.load(it, database), true)
} ?: AllItems
title = when (itemListingRule::class) {
Children::class -> {
(itemListingRule as Children).parent?.title ?: this.getString(R.string.all_items)
}
else -> {
this.getString(R.string.all_items)
}
}
val itemAdapter = ItemAdapter(database, itemListingRule) { item: Item, itemAction: ItemAction ->
run {
when (itemAction) {
ItemAction.EDIT -> {
val i = Intent(baseContext, ItemDataActivity::class.java)
i.putExtra("com.gimranov.zandy.app.itemKey", item.key)
i.putExtra("com.gimranov.zandy.app.itemDbId", item.dbId)
startActivity(i)
}
ItemAction.ORGANIZE -> {
val i = Intent(baseContext, CollectionMembershipActivity::class.java)
i.putExtra("com.gimranov.zandy.app.itemKey", item.key)
startActivity(i)
}
ItemAction.VIEW -> TODO()
}
}
}
val collectionAdapter = CollectionAdapter(database, itemListingRule) { collection: ItemCollection, itemAction: ItemAction ->
run {
when (itemAction) {
ItemAction.VIEW -> {
val i = Intent(baseContext, DrawerNavigationActivity::class.java)
i.putExtra(collectionKey, collection.key)
startActivity(i)
}
ItemAction.EDIT -> TODO()
ItemAction.ORGANIZE -> TODO()
}
}
}
navigation_drawer_sidebar_recycler.adapter = collectionAdapter
navigation_drawer_sidebar_recycler.setHasFixedSize(true)
navigation_drawer_sidebar_recycler.layoutManager = LinearLayoutManager(this)
navigation_drawer_content_recycler.adapter = itemAdapter
navigation_drawer_content_recycler.setHasFixedSize(true)
navigation_drawer_content_recycler.layoutManager = LinearLayoutManager(this)
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.drawer_navigation, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> {
startActivity(Intent(baseContext, SettingsActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| agpl-3.0 |
vhromada/Catalog | core/src/test/kotlin/com/github/vhromada/catalog/utils/EpisodeUtils.kt | 1 | 13887 | package com.github.vhromada.catalog.utils
import com.github.vhromada.catalog.domain.io.EpisodeStatistics
import com.github.vhromada.catalog.entity.ChangeEpisodeRequest
import com.github.vhromada.catalog.entity.Episode
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import javax.persistence.EntityManager
/**
* Updates episode fields.
*
* @return updated episode
*/
fun com.github.vhromada.catalog.domain.Episode.updated(): com.github.vhromada.catalog.domain.Episode {
number = 2
name = "Name"
length = 5
note = "Note"
return this
}
/**
* Updates episode fields.
*
* @return updated episode
*/
fun Episode.updated(): Episode {
return copy(
number = 2,
name = "Name",
length = 5,
note = "Note"
)
}
/**
* A class represents utility class for episodes.
*
* @author Vladimir Hromada
*/
object EpisodeUtils {
/**
* Count of episodes
*/
const val EPISODES_COUNT = 27
/**
* Count of episodes in season
*/
const val EPISODES_PER_SEASON_COUNT = 3
/**
* Count of episodes in show
*/
const val EPISODES_PER_SHOW_COUNT = 9
/**
* Multipliers for length
*/
private val LENGTH_MULTIPLIERS = intArrayOf(1, 10, 100)
/**
* Returns episodes.
*
* @param show show ID
* @param season season ID
* @return episodes
*/
fun getDomainEpisodes(show: Int, season: Int): MutableList<com.github.vhromada.catalog.domain.Episode> {
val episodes = mutableListOf<com.github.vhromada.catalog.domain.Episode>()
for (i in 1..EPISODES_PER_SEASON_COUNT) {
episodes.add(getDomainEpisode(showIndex = show, seasonIndex = season, episodeIndex = i))
}
return episodes
}
/**
* Returns episodes.
*
* @param show show ID
* @param season season ID
* @return episodes
*/
fun getEpisodes(show: Int, season: Int): List<Episode> {
val episodes = mutableListOf<Episode>()
for (i in 1..EPISODES_PER_SEASON_COUNT) {
episodes.add(getEpisode(showIndex = show, seasonIndex = season, episodeIndex = i))
}
return episodes
}
/**
* Returns episode for indexes.
*
* @param showIndex show index
* @param seasonIndex season index
* @param episodeIndex episode index
* @return episode for indexes
*/
private fun getDomainEpisode(showIndex: Int, seasonIndex: Int, episodeIndex: Int): com.github.vhromada.catalog.domain.Episode {
return com.github.vhromada.catalog.domain.Episode(
id = (showIndex - 1) * EPISODES_PER_SHOW_COUNT + (seasonIndex - 1) * EPISODES_PER_SEASON_COUNT + episodeIndex,
uuid = getUuid(index = (showIndex - 1) * EPISODES_PER_SHOW_COUNT + (seasonIndex - 1) * EPISODES_PER_SEASON_COUNT + episodeIndex),
number = episodeIndex,
name = "Show $showIndex Season $seasonIndex Episode $episodeIndex",
length = episodeIndex * LENGTH_MULTIPLIERS[seasonIndex - 1],
note = if (episodeIndex != 3) "Show $showIndex Season $seasonIndex Episode $episodeIndex note" else null
).fillAudit(audit = AuditUtils.getAudit())
}
/**
* Returns UUID for index.
*
* @param index index
* @return UUID for index
*/
private fun getUuid(index: Int): String {
return when (index) {
1 -> "29f94c0f-aa0e-48b2-a74d-68991778871b"
2 -> "fa623148-896d-40be-9702-9cb2d30c4f3e"
3 -> "b58bb43c-b391-4de2-8972-08e13b8ab059"
4 -> "71a04e1f-3218-4797-b9c0-de68f16262bf"
5 -> "b4fad1a0-3f67-435a-8dd9-e27ae090dd17"
6 -> "806f59b5-5e3d-478f-aeb8-fc2c7158801f"
7 -> "77661951-c3ec-431f-a3a4-b7db93009504"
8 -> "2aea5877-cee1-42d2-a421-f048409baaf6"
9 -> "ccff3e04-25d2-4141-8a66-b2fd0c8938ec"
10 -> "724861fb-43ac-450e-9ca4-f6454d16bd5a"
11 -> "40fdfeb7-04df-4a02-a23a-4a5fb5927671"
12 -> "ee456688-196e-4389-9e54-3aa31e3d8e8e"
13 -> "5c272380-3c38-43f1-9726-226a9f182942"
14 -> "4269d91c-4d36-4fd8-9de3-1134f09f6e4e"
15 -> "3b35f6e3-e8e0-4677-a79a-c3b89f43345a"
16 -> "6b602097-5072-422c-9691-93b074fc6cee"
17 -> "c77e013c-bea9-4679-8e4e-df9aa622caa1"
18 -> "9b9d0874-a483-4677-b90f-7b604c07926b"
19 -> "057f61ef-0e20-497e-a0c0-4fc964a2ca0c"
20 -> "8be0b3cd-30cf-4d47-8d67-c39f0bf6eb04"
21 -> "a8a29438-e615-4721-8857-f92aad24b3f5"
22 -> "abe105ee-6d9d-4c1e-a900-087555da3fb5"
23 -> "2333c9e3-c9dc-4e40-8a42-4a6a7a079078"
24 -> "b7111ede-c022-4967-bd2a-55d9d73d4cf7"
25 -> "418234ed-59e8-4277-90ea-0e4ba87685e9"
26 -> "05fe7e5f-0b5b-4cd3-91b9-d3b1d5ec203d"
27 -> "54e645db-697c-45b1-8335-e4d65a0fd547"
else -> throw IllegalArgumentException("Bad index")
}
}
/**
* Returns episode.
*
* @param entityManager entity manager
* @param id episode ID
* @return episode
*/
fun getDomainEpisode(entityManager: EntityManager, id: Int): com.github.vhromada.catalog.domain.Episode? {
return entityManager.find(com.github.vhromada.catalog.domain.Episode::class.java, id)
}
/**
* Returns episode for index.
*
* @param index episode index
* @return episode for index
*/
fun getEpisode(index: Int): Episode {
val showNumber = (index - 1) / EPISODES_PER_SHOW_COUNT + 1
val seasonNumber = (index - 1) % EPISODES_PER_SHOW_COUNT / EPISODES_PER_SEASON_COUNT + 1
val episodeNumber = (index - 1) % EPISODES_PER_SEASON_COUNT + 1
return getEpisode(showIndex = showNumber, seasonIndex = seasonNumber, episodeIndex = episodeNumber)
}
/**
* Returns episode for indexes.
*
* @param showIndex show index
* @param seasonIndex season index
* @param episodeIndex episode index
* @return episode for indexes
*/
private fun getEpisode(showIndex: Int, seasonIndex: Int, episodeIndex: Int): Episode {
return Episode(
uuid = getUuid(index = (showIndex - 1) * EPISODES_PER_SHOW_COUNT + (seasonIndex - 1) * EPISODES_PER_SEASON_COUNT + episodeIndex),
number = episodeIndex,
name = "Show $showIndex Season $seasonIndex Episode $episodeIndex",
length = episodeIndex * LENGTH_MULTIPLIERS[seasonIndex - 1],
note = if (episodeIndex != 3) "Show $showIndex Season $seasonIndex Episode $episodeIndex note" else null,
)
}
/**
* Returns statistics for episodes.
*
* @return statistics for episodes
*/
fun getStatistics(): EpisodeStatistics {
return EpisodeStatistics(count = EPISODES_COUNT.toLong(), length = 1998L)
}
/**
* Returns count of episodes.
*
* @param entityManager entity manager
* @return count of episodes
*/
fun getEpisodesCount(entityManager: EntityManager): Int {
return entityManager.createQuery("SELECT COUNT(e.id) FROM Episode e", java.lang.Long::class.java).singleResult.toInt()
}
/**
* Returns episode.
*
* @param id ID
* @return episode
*/
fun newDomainEpisode(id: Int?): com.github.vhromada.catalog.domain.Episode {
return com.github.vhromada.catalog.domain.Episode(
id = id,
uuid = TestConstants.UUID,
number = 0,
name = "",
length = 0,
note = null
).updated()
}
/**
* Returns episode.
*
* @return episode
*/
fun newEpisode(): Episode {
return Episode(
uuid = TestConstants.UUID,
number = 0,
name = "",
length = 0,
note = null
).updated()
}
/**
* Returns request for changing episode.
*
* @return request for changing episode
*/
fun newRequest(): ChangeEpisodeRequest {
return ChangeEpisodeRequest(
name = "Name",
number = 2,
length = 5,
note = "Note"
)
}
/**
* Asserts list of episodes deep equals.
*
* @param expected expected list of episodes
* @param actual actual list of episodes
*/
fun assertDomainEpisodesDeepEquals(expected: List<com.github.vhromada.catalog.domain.Episode>, actual: List<com.github.vhromada.catalog.domain.Episode>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertEpisodeDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts episode deep equals.
*
* @param expected expected episode
* @param actual actual episode
*/
fun assertEpisodeDeepEquals(expected: com.github.vhromada.catalog.domain.Episode?, actual: com.github.vhromada.catalog.domain.Episode?) {
if (expected == null) {
assertThat(actual).isNull()
} else {
assertThat(actual).isNotNull
assertSoftly {
it.assertThat(actual!!.id).isEqualTo(expected.id)
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.number).isEqualTo(expected.number)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.length).isEqualTo(expected.length)
it.assertThat(actual.note).isEqualTo(expected.note)
}
AuditUtils.assertAuditDeepEquals(expected = expected, actual = actual!!)
if (expected.season != null) {
assertThat(actual.season).isNotNull
assertThat(actual.season!!.episodes).hasSameSizeAs(expected.season!!.episodes)
SeasonUtils.assertSeasonDeepEquals(expected = expected.season!!, actual = actual.season!!, checkEpisodes = false)
}
}
}
/**
* Asserts list of episodes deep equals.
*
* @param expected expected list of episodes
* @param actual actual list of episodes
*/
fun assertEpisodesDeepEquals(expected: List<com.github.vhromada.catalog.domain.Episode>, actual: List<Episode>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertEpisodeDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts episode deep equals.
*
* @param expected expected episode
* @param actual actual episode
*/
fun assertEpisodeDeepEquals(expected: com.github.vhromada.catalog.domain.Episode, actual: Episode) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.number).isEqualTo(expected.number)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.length).isEqualTo(expected.length)
it.assertThat(actual.note).isEqualTo(expected.note)
}
}
/**
* Asserts list of episodes deep equals.
*
* @param expected expected list of episodes
* @param actual actual list of episodes
*/
fun assertEpisodeListDeepEquals(expected: List<Episode>, actual: List<Episode>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertEpisodeDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts episode deep equals.
*
* @param expected expected episode
* @param actual actual episode
*/
fun assertEpisodeDeepEquals(expected: Episode, actual: Episode) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.number).isEqualTo(expected.number)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.length).isEqualTo(expected.length)
it.assertThat(actual.note).isEqualTo(expected.note)
}
}
/**
* Asserts request and episode deep equals.
*
* @param expected expected request for changing episode
* @param actual actual episode
* @param uuid UUID
*/
fun assertRequestDeepEquals(expected: ChangeEpisodeRequest, actual: com.github.vhromada.catalog.domain.Episode, uuid: String) {
assertSoftly {
it.assertThat(actual.id).isNull()
it.assertThat(actual.uuid).isEqualTo(uuid)
it.assertThat(actual.number).isEqualTo(expected.number)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.length).isEqualTo(expected.length)
it.assertThat(actual.note).isEqualTo(expected.note)
it.assertThat(actual.season).isNull()
it.assertThat(actual.createdUser).isNull()
it.assertThat(actual.createdTime).isNull()
it.assertThat(actual.updatedUser).isNull()
it.assertThat(actual.updatedTime).isNull()
}
}
/**
* Asserts statistics for episodes deep equals.
*
* @param expected expected statistics for episodes
* @param actual actual statistics for episodes
*/
fun assertStatisticsDeepEquals(expected: EpisodeStatistics, actual: EpisodeStatistics) {
assertSoftly {
it.assertThat(actual.count).isEqualTo(expected.count)
it.assertThat(actual.length).isEqualTo(expected.length)
}
}
}
| mit |
JetBrains/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/TodoCheckinHandler.kt | 1 | 9519 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.checkin
import com.intellij.CommonBundle.getCancelButtonText
import com.intellij.ide.todo.*
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressSink
import com.intellij.openapi.progress.asContextElement
import com.intellij.openapi.progress.coroutineToIndicator
import com.intellij.openapi.progress.progressSink
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.JBPopupMenu
import com.intellij.openapi.ui.MessageDialogBuilder.Companion.yesNo
import com.intellij.openapi.ui.MessageDialogBuilder.Companion.yesNoCancel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.Messages.YesNoCancelResult
import com.intellij.openapi.util.NlsContexts.*
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption
import com.intellij.openapi.vcs.checkin.TodoCheckinHandler.Companion.showDialog
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.openapi.wm.ToolWindowId.TODO_VIEW
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.search.TodoItem
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.util.text.DateFormatUtil.formatDateTime
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.UIUtil.getWarningIcon
import com.intellij.vcs.commit.isPostCommitCheck
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.swing.JComponent
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.coroutineContext
class TodoCheckinHandlerFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
return TodoCheckinHandler(panel.project)
}
}
class TodoCommitProblem(val worker: TodoCheckinHandlerWorker,
val isPostCommit: Boolean) : CommitProblemWithDetails {
override val text: String get() = message("label.todo.items.found", worker.inOneList().size)
override fun showDetails(project: Project) {
TodoCheckinHandler.showTodoItems(project, worker.changes, worker.inOneList(), isPostCommit)
}
override fun showModalSolution(project: Project, commitInfo: CommitInfo): CheckinHandler.ReturnResult {
return showDialog(project, worker, commitInfo.commitActionText)
}
override val showDetailsAction: String
get() = message("todo.in.new.review.button")
}
class TodoCheckinHandler(private val project: Project) : CheckinHandler(), CommitCheck, DumbAware {
private val settings: VcsConfiguration get() = VcsConfiguration.getInstance(project)
private val todoSettings: TodoPanelSettings get() = settings.myTodoPanelSettings
override fun getExecutionOrder(): CommitCheck.ExecutionOrder = CommitCheck.ExecutionOrder.POST_COMMIT
override fun isEnabled(): Boolean = settings.CHECK_NEW_TODO
override suspend fun runCheck(commitInfo: CommitInfo): TodoCommitProblem? {
val sink = coroutineContext.progressSink
sink?.text(message("progress.text.checking.for.todo"))
val isPostCommit = commitInfo.isPostCommitCheck
val todoFilter = settings.myTodoPanelSettings.todoFilterName?.let { TodoConfiguration.getInstance().getTodoFilter(it) }
val changes = commitInfo.committedChanges
val worker = TodoCheckinHandlerWorker(project, changes, todoFilter)
withContext(Dispatchers.Default + textToDetailsSinkContext(sink)) {
coroutineToIndicator {
worker.execute()
}
}
val noTodo = worker.inOneList().isEmpty()
val noSkipped = worker.skipped.isEmpty()
if (noTodo && noSkipped) return null
return TodoCommitProblem(worker, isPostCommit)
}
override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent = TodoCommitOption().withCheckinHandler(this)
private inner class TodoCommitOption : BooleanCommitOption(project, "", false, settings::CHECK_NEW_TODO) {
override fun getComponent(): JComponent {
val filter = TodoConfiguration.getInstance().getTodoFilter(todoSettings.todoFilterName)
setFilterText(filter?.name)
val showFiltersPopup = LinkListener<Any> { sourceLink, _ ->
val group = SetTodoFilterAction.createPopupActionGroup(project, todoSettings, true) { setFilter(it) }
JBPopupMenu.showBelow(sourceLink, ActionPlaces.TODO_VIEW_TOOLBAR, group)
}
val configureFilterLink = LinkLabel(message("settings.filter.configure.link"), null, showFiltersPopup)
return simplePanel(4, 0).addToLeft(checkBox).addToCenter(configureFilterLink)
}
private fun setFilter(filter: TodoFilter?) {
todoSettings.todoFilterName = filter?.name
setFilterText(filter?.name)
}
private fun setFilterText(filterName: String?) {
if (filterName != null) {
val text = message("checkin.filter.filter.name", filterName)
checkBox.text = message("before.checkin.new.todo.check", text)
}
else {
checkBox.text = message("before.checkin.new.todo.check.no.filter")
}
}
}
companion object {
internal fun showDialog(project: Project,
worker: TodoCheckinHandlerWorker,
@Button commitActionText: String): ReturnResult {
val noTodo = worker.addedOrEditedTodos.isEmpty() && worker.inChangedTodos.isEmpty()
val noSkipped = worker.skipped.isEmpty()
if (noTodo && noSkipped) return ReturnResult.COMMIT
if (noTodo) {
val commit = confirmCommitWithSkippedFiles(worker, commitActionText)
if (commit) {
return ReturnResult.COMMIT
}
else {
return ReturnResult.CANCEL
}
}
when (askReviewCommitCancel(worker, commitActionText)) {
Messages.YES -> {
showTodoItems(project, worker.changes, worker.inOneList(), isPostCommit = false)
return ReturnResult.CLOSE_WINDOW
}
Messages.NO -> return ReturnResult.COMMIT
else -> return ReturnResult.CANCEL
}
}
internal fun showTodoItems(project: Project, changes: Collection<Change>, todoItems: Collection<TodoItem>, isPostCommit: Boolean) {
val todoView = project.service<TodoView>()
val content = todoView.addCustomTodoView(
{ tree, _ ->
if (isPostCommit) {
PostCommitChecksTodosTreeBuilder(tree, project, changes, todoItems)
}
else {
CommitChecksTodosTreeBuilder(tree, project, changes, todoItems)
}
},
message("checkin.title.for.commit.0", formatDateTime(System.currentTimeMillis())),
TodoPanelSettings(VcsConfiguration.getInstance(project).myTodoPanelSettings)
)
if (content == null) return
runInEdt(ModalityState.NON_MODAL) {
if (project.isDisposed) return@runInEdt
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(TODO_VIEW) ?: return@runInEdt
toolWindow.show {
toolWindow.contentManager.setSelectedContent(content, true)
}
}
}
}
}
internal fun textToDetailsSinkContext(sink: ProgressSink?): CoroutineContext {
if (sink == null) {
return EmptyCoroutineContext
}
else {
return TextToDetailsProgressSink(sink).asContextElement()
}
}
internal class TextToDetailsProgressSink(private val original: ProgressSink) : ProgressSink {
override fun update(text: @ProgressText String?, details: @ProgressDetails String?, fraction: Double?) {
original.update(
text = null,
details = text, // incoming text will be shown as details in the original sink
fraction = fraction,
)
}
}
private fun confirmCommitWithSkippedFiles(worker: TodoCheckinHandlerWorker, @Button commitActionText: String) =
yesNo(message("checkin.dialog.title.todo"), getDescription(worker))
.icon(getWarningIcon())
.yesText(commitActionText)
.noText(getCancelButtonText())
.ask(worker.project)
@YesNoCancelResult
private fun askReviewCommitCancel(worker: TodoCheckinHandlerWorker, @Button commitActionText: String): Int =
yesNoCancel(message("checkin.dialog.title.todo"), getDescription(worker))
.icon(getWarningIcon())
.yesText(message("todo.in.new.review.button"))
.noText(commitActionText)
.cancelText(getCancelButtonText())
.show(worker.project)
@DialogMessage
private fun getDescription(worker: TodoCheckinHandlerWorker): String {
val added = worker.addedOrEditedTodos.size
val changed = worker.inChangedTodos.size
val skipped = worker.skipped.size
return when {
added == 0 && changed == 0 -> message("todo.handler.only.skipped", skipped)
changed == 0 -> message("todo.handler.only.added", added, skipped)
added == 0 -> message("todo.handler.only.in.changed", changed, skipped)
else -> message("todo.handler.only.both", added, changed, skipped)
}
} | apache-2.0 |
exercism/xkotlin | exercises/practice/sum-of-multiples/src/main/kotlin/SumOfMultiples.kt | 1 | 144 | object SumOfMultiples {
fun sum(factors: Set<Int>, limit: Int): Int {
TODO("Implement this function to complete the task")
}
}
| mit |
StepicOrg/stepik-android | billing/src/main/java/org/stepik/android/data/billing/source/BillingRemoteDataSource.kt | 1 | 455 | package org.stepik.android.data.billing.source
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.SkuDetails
import io.reactivex.Completable
import io.reactivex.Single
interface BillingRemoteDataSource {
fun getInventory(productType: String, skuIds: List<String>): Single<List<SkuDetails>>
fun getAllPurchases(productType: String): Single<List<Purchase>>
fun consumePurchase(purchase: Purchase): Completable
} | apache-2.0 |
Hexworks/snap | src/main/kotlin/org/codetome/snap/service/impl/SnapService.kt | 1 | 1138 | package org.codetome.snap.service.impl
import com.vladsch.flexmark.parser.Parser
import com.vladsch.flexmark.parser.ParserEmulationProfile
import com.vladsch.flexmark.util.options.MutableDataSet
import org.codetome.snap.adapter.parser.MarkdownParser
import org.codetome.snap.model.rest.RestService
import org.codetome.snap.service.RestServiceGenerator
import java.io.File
/**
* Creates REST services based on a service description markdown file
* (see sample_config.md for example) using <code>linkContent</code> as the
* access linkContent.
*/
class SnapService(private val restServiceGenerator: RestServiceGenerator,
private val markdownParser: MarkdownParser) {
fun run(descriptor: File): RestService {
val options = MutableDataSet()
options.setFrom(ParserEmulationProfile.MARKDOWN)
val parser: Parser = Parser.builder(options).build()
val md = descriptor.readText()
val document = parser.parse(md)
val restService = markdownParser.parse(document).blockingGet()
restServiceGenerator.generateServiceFrom(restService)
return restService
}
} | agpl-3.0 |
EddyArellanes/Kotlin | Hello-World-Scripts/Singleton.kt | 1 | 700 | /**/
object Validations{
/*
fun password(psw:String):Boolean{
if(psw.length>0 && psw.length>10){
return true
}else{
return false
}
}
*/
fun password(psw:String) =psw.isNotEmpty() && psw.length>10
fun isNumeric(dato:Any)= dato is Int
}
class UniversalClass{
companion object{
fun create():UniversalClass= UniversalClass()
}
}
fun main(args:Array<String>){
println("Ingresa tu contraseña" )
val pass:String= readLine()!! //!! = No importa si es nulo
println(Validations.password(pass))
val number:Int= readLine()?.toInt() ?:0
println(number)
println(Validations.isNumeric(number))
val universe:UniversalClass= UniversalClass.create()
} | mit |
allotria/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XThreadsView.kt | 4 | 3830 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.impl.frame
import com.intellij.openapi.project.Project
import com.intellij.ui.SimpleColoredComponent
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.frame.*
import com.intellij.xdebugger.frame.presentation.XRegularValuePresentation
import com.intellij.xdebugger.impl.XDebugSessionImpl
import com.intellij.xdebugger.impl.ui.DebuggerUIUtil
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTreePanel
import com.intellij.xdebugger.impl.ui.tree.nodes.XValueContainerNode
import javax.swing.JPanel
class XThreadsView(val project: Project, session: XDebugSessionImpl) : XDebugView() {
private val treePanel = XDebuggerTreePanel(project, session.debugProcess.editorsProvider, this, null, "", null)
private fun getTree() = treePanel.tree
fun getPanel(): JPanel = treePanel.mainPanel
fun getDefaultFocusedComponent(): XDebuggerTree = treePanel.tree
override fun clear() {
DebuggerUIUtil.invokeLater {
getTree().setRoot(object : XValueContainerNode<XValueContainer>(getTree(), null, true, object : XValueContainer() {}) {}, false)
}
}
override fun processSessionEvent(event: XDebugView.SessionEvent, session: XDebugSession) {
if (event == XDebugView.SessionEvent.BEFORE_RESUME) {
return
}
val suspendContext = session.suspendContext
if (suspendContext == null) {
requestClear()
return
}
if (event == XDebugView.SessionEvent.PAUSED) {
// clear immediately
cancelClear()
clear()
}
DebuggerUIUtil.invokeLater {
getTree().setRoot(XThreadsRootNode(getTree(), suspendContext), false)
}
}
override fun dispose() {
}
class ThreadsContainer(val suspendContext: XSuspendContext) : XValueContainer() {
override fun computeChildren(node: XCompositeNode) {
suspendContext.computeExecutionStacks(object : XSuspendContext.XExecutionStackContainer {
override fun errorOccurred(errorMessage: String) {
}
override fun addExecutionStack(executionStacks: MutableList<out XExecutionStack>, last: Boolean) {
val children = XValueChildrenList()
executionStacks.map { FramesContainer(it) }.forEach { children.add("", it) }
node.addChildren(children, last)
}
})
}
}
class FramesContainer(private val executionStack: XExecutionStack) : XValue() {
override fun computeChildren(node: XCompositeNode) {
executionStack.computeStackFrames(0, object : XExecutionStack.XStackFrameContainer {
override fun errorOccurred(errorMessage: String) {
}
override fun addStackFrames(stackFrames: MutableList<out XStackFrame>, last: Boolean) {
val children = XValueChildrenList()
stackFrames.forEach { children.add("", FrameValue(it)) }
node.addChildren(children, last)
}
})
}
override fun computePresentation(node: XValueNode, place: XValuePlace) {
node.setPresentation(executionStack.icon, XRegularValuePresentation(executionStack.displayName, null, ""), true)
}
}
class FrameValue(val frame : XStackFrame) : XValue() {
override fun computePresentation(node: XValueNode, place: XValuePlace) {
val component = SimpleColoredComponent()
frame.customizePresentation(component)
node.setPresentation(component.icon, XRegularValuePresentation(component.getCharSequence(false).toString(), null, ""), false)
}
}
class XThreadsRootNode(tree: XDebuggerTree, suspendContext: XSuspendContext) :
XValueContainerNode<ThreadsContainer>(tree, null, false, ThreadsContainer(suspendContext))
}
| apache-2.0 |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/impl/projectLoader.kt | 1 | 3469 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("ProjectLoadHelper")
@file:ApiStatus.Internal
package com.intellij.openapi.project.impl
import com.intellij.diagnostic.Activity
import com.intellij.diagnostic.PluginException
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.StartUpMeasurer.Activities
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
// Code maybe located in a ProjectImpl, but it is not possible due to non-technical reasons to convert ProjectImpl into modern language.
internal fun registerComponents(project: ProjectImpl) {
var activity = createActivity(project) { "project ${Activities.REGISTER_COMPONENTS_SUFFIX}" }
// at this point of time plugins are already loaded by application - no need to pass indicator to getLoadedPlugins call
@Suppress("UNCHECKED_CAST")
project.registerComponents(PluginManagerCore.getLoadedPlugins() as List<IdeaPluginDescriptorImpl>, null)
activity = activity?.endAndStart("projectComponentRegistered")
runOnlyCorePluginExtensions(
ProjectServiceContainerCustomizer.getEp()) {
it.serviceRegistered(project)
}
activity?.end()
}
private inline fun createActivity(project: ProjectImpl, message: () -> String): Activity? {
return if (project.isDefault || !StartUpMeasurer.isEnabled()) null else StartUpMeasurer.startActivity(message())
}
internal inline fun <T : Any> runOnlyCorePluginExtensions(ep: ExtensionPointImpl<T>, crossinline executor: (T) -> Unit) {
ep.processWithPluginDescriptor(true) { handler, pluginDescriptor ->
if (pluginDescriptor.pluginId != PluginManagerCore.CORE_ID) {
logger<ProjectImpl>().error(PluginException("Plugin $pluginDescriptor is not approved to add ${ep.name}", pluginDescriptor.pluginId))
}
try {
executor(handler)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
logger<ProjectImpl>().error(PluginException(e, pluginDescriptor.pluginId))
}
}
}
/**
* Usage requires IJ Platform team approval (including plugin into white-list).
*/
@ApiStatus.Internal
interface ProjectServiceContainerCustomizer {
companion object {
@JvmStatic
fun getEp() = (ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl)
.getExtensionPoint<ProjectServiceContainerCustomizer>("com.intellij.projectServiceContainerCustomizer")
}
/**
* Invoked after implementation classes for project's components were determined (and loaded),
* but before components are instantiated.
*/
fun serviceRegistered(project: Project)
}
/**
* Usage requires IJ Platform team approval (including plugin into white-list).
*/
@ApiStatus.Internal
interface ProjectServiceContainerInitializedListener {
/**
* Invoked after implementation classes for project's components were determined (and loaded),
* but before components are instantiated.
*/
fun serviceCreated(project: Project)
} | apache-2.0 |
ursjoss/sipamato | core/core-logic/src/test/kotlin/ch/difty/scipamato/core/logic/parsing/AuthorParsingTest.kt | 2 | 3971 | @file:Suppress("SpellCheckingInspection")
package ch.difty.scipamato.core.logic.parsing
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeInstanceOf
import org.amshove.kluent.shouldBeNull
import org.amshove.kluent.shouldContain
import org.amshove.kluent.shouldContainAll
import org.junit.jupiter.api.Test
internal class PubmedAuthorParserTest {
private lateinit var p: PubmedAuthorParser
@Test
fun withNoAuthor_firstAuthorIsNull() {
p = PubmedAuthorParser("")
p.firstAuthor.shouldBeNull()
}
@Test
fun canReturnOriginalAuthorsString() {
val authorsString = "Bond J."
p = PubmedAuthorParser(authorsString)
p.authorsString shouldBeEqualTo authorsString
}
private fun assertFirstAuthorOf(input: String, expected: String) {
p = PubmedAuthorParser(input)
p.firstAuthor shouldBeEqualTo expected
}
@Test
fun canReturnFirstAuthor_withSingleAuthorOnly() {
// proper format
assertFirstAuthorOf("Bond J.", "Bond")
// unclean format
assertFirstAuthorOf("Bond J.", "Bond")
assertFirstAuthorOf("Bond J", "Bond")
assertFirstAuthorOf("Bond ", "Bond")
assertFirstAuthorOf(" Bond ", "Bond")
assertFirstAuthorOf(" Bond.", "Bond")
}
@Test
fun canReturnFirstAuthor_withMultipleAuthors() {
// proper format
assertFirstAuthorOf(
"""Turner MC, Cohen A, Jerret M, Gapstur SM, Driver WR, Pope CA 3rd, Krewsky D
|, Beckermann BS, Samet JM.""".trimMargin(),
"Turner"
)
}
@Test
fun canReturnFirstAuthor_withMultipleLastNames() {
assertFirstAuthorOf("Lloyd Webber A.", "Lloyd Webber")
assertFirstAuthorOf("Lloyd Webber A", "Lloyd Webber")
assertFirstAuthorOf("Lloyd Webber Andrew", "Lloyd Webber")
}
@Test
fun canParseNameWithCardinality() {
p = PubmedAuthorParser("Ln FN 1st, Ln FN 2nd, Ln FN 3rd, Ln FN 4th, Ln FN 5th, Ln FN 100th, Ln FN.")
p.firstAuthor shouldBeEqualTo "Ln"
p.authors.map { it.lastName } shouldContain "Ln"
p.authors.map { it.firstName } shouldContainAll listOf(
"FN 1st", "FN 2nd", "FN 3rd", "FN 4th", "FN 5th", "FN 100th", "FN"
)
}
@Test
fun canReturnFirstAuthor_evenWhenCardinalityStandsAfterFirstName() {
assertFirstAuthorOf("Pope CA 3rd, Lloyd Webber A.", "Pope")
}
@Test
fun canReturnFirstAuthor_evenWhenNameContainsJunior() {
assertFirstAuthorOf("Cox LA Jr.", "Cox")
}
@Test
fun canReturnFirstAuthor_letsNotBeFooledByInitialsLookingLikeJunior() {
assertFirstAuthorOf("Cox JR.", "Cox")
}
@Test
fun cannotProperlyReturnFirstAuthor_withInitialsAndCapitalJR() {
// this is probably not a valid case, but let's state it explicitly here
assertFirstAuthorOf("Cox LA JR.", "Cox LA")
}
@Test
fun canReturnAuthors() {
p = PubmedAuthorParser(
"Turner MC, Cohen A, Jerret M, Gapstur SM, Driver WR, Krewsky D, Beckermann BS, Samet JM."
)
p.authors.map { it.lastName } shouldContainAll listOf(
"Turner", "Cohen", "Jerret", "Gapstur", "Driver", "Krewsky", "Beckermann", "Samet"
)
p.authors.map { it.firstName } shouldContainAll listOf("MC", "A", "M", "SM", "WR", "D", "BS", "JM")
}
@Test
fun canDoUmlaute() {
p = PubmedAuthorParser("Flückiger P, Bäni HU.")
p.authors.map { it.lastName } shouldContainAll listOf("Flückiger", "Bäni")
p.authors.map { it.firstName } shouldContainAll listOf("P", "HU")
}
}
internal class AuthorParserFactoryTest {
@Test
fun cratingParser_withNoSetting_usesDefaultAuthorParser() {
val parser = AuthorParserFactory.create(AuthorParserStrategy.PUBMED).createParser("Turner MC.")
parser shouldBeInstanceOf PubmedAuthorParser::class
}
}
| gpl-3.0 |
bmunzenb/feed-buddy | src/test/kotlin/com/munzenberger/feed/FeedTest.kt | 1 | 789 | package com.munzenberger.feed
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import java.time.Instant
class FeedTest {
@Test
fun `it can parse a valid timestamp in ISO format`() {
val timestamp = "2003-12-13T18:30:02Z"
val instant = Instant.ofEpochSecond(1071340202)
assertEquals(instant, timestamp.toInstant())
}
@Test
fun `it can parse timestamp in RFC format`() {
val timestamp = "Thu, 23 Apr 2020 04:01:23 +0000"
val instant = Instant.ofEpochSecond(1587614483)
assertEquals(instant, timestamp.toInstant())
}
@Test
fun `it does not parse an invalid timestamp format`() {
val timestamp = ""
assertNull(timestamp.toInstant())
}
}
| apache-2.0 |
ursjoss/sipamato | common/common-wicket/src/main/kotlin/ch/difty/scipamato/common/web/AbstractPage.kt | 1 | 6886 | package ch.difty.scipamato.common.web
import ch.difty.scipamato.common.DateTimeService
import ch.difty.scipamato.common.config.ApplicationProperties
import ch.difty.scipamato.common.web.component.SerializableSupplier
import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxButton
import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons
import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel
import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.Navbar
import org.apache.wicket.ajax.AjaxRequestTarget
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession
import org.apache.wicket.bean.validation.PropertyValidator
import org.apache.wicket.devutils.debugbar.DebugBar
import org.apache.wicket.markup.head.IHeaderResponse
import org.apache.wicket.markup.head.MetaDataHeaderItem
import org.apache.wicket.markup.head.PriorityHeaderItem
import org.apache.wicket.markup.head.filter.HeaderResponseContainer
import org.apache.wicket.markup.html.GenericWebPage
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.form.FormComponent
import org.apache.wicket.markup.html.panel.EmptyPanel
import org.apache.wicket.model.IModel
import org.apache.wicket.model.Model
import org.apache.wicket.model.StringResourceModel
import org.apache.wicket.request.mapper.parameter.PageParameters
import org.apache.wicket.settings.DebugSettings
import org.apache.wicket.spring.injection.annot.SpringBean
@Suppress("SameParameterValue")
abstract class AbstractPage<T> : GenericWebPage<T> {
@SpringBean
lateinit var dateTimeService: DateTimeService
private set
lateinit var feedbackPanel: NotificationPanel
private set
lateinit var navBar: Navbar
private set
open val debugSettings: DebugSettings
get() = application.debugSettings
/**
* Override if you do not want to show the navbar or only conditionally.
* @return whether to show the Navbar or not.
*/
open val isNavbarVisible: Boolean
get() = true
protected val isSignedIn: Boolean
get() = AuthenticatedWebSession.get().isSignedIn
protected abstract val properties: ApplicationProperties
private val title: IModel<String>
get() = Model.of(properties.titleOrBrand)
constructor(parameters: PageParameters?) : super(parameters)
constructor(model: IModel<T>?) : super(model)
override fun renderHead(response: IHeaderResponse) {
response.apply {
super.renderHead(this)
render(PriorityHeaderItem(MetaDataHeaderItem.forMetaTag("charset", "utf-8")))
render(PriorityHeaderItem(MetaDataHeaderItem.forMetaTag("X-UA-Compatible", "IE=edge")))
render(PriorityHeaderItem(MetaDataHeaderItem.forMetaTag("viewport", "width=device-width, initial-scale=1")))
render(PriorityHeaderItem(MetaDataHeaderItem.forMetaTag("Content-Type", "text/html; charset=UTF-8")))
}
}
override fun onInitialize() {
super.onInitialize()
createAndAddTitle("pageTitle")
createAndAddNavBar("navbar")
createAndAddFeedbackPanel("feedback")
createAndAddDebugBar("debug")
createAndAddFooterContainer(FOOTER_CONTAINER)
}
private fun createAndAddTitle(id: String) {
queue(Label(id, title))
}
private fun createAndAddNavBar(id: String) {
navBar = newNavbar(id).also {
queue(it)
}
extendNavBar()
}
/**
* Override if you need to extend the [Navbar]
*/
private fun extendNavBar() {
// no default implementation
}
private fun createAndAddFeedbackPanel(label: String) {
feedbackPanel = NotificationPanel(label).apply {
outputMarkupId = true
}.also {
queue(it)
}
}
private fun createAndAddDebugBar(label: String) {
if (debugSettings.isDevelopmentUtilitiesEnabled)
queue(DebugBar(label).positionBottom())
else queue(EmptyPanel(label).setVisible(false))
}
private fun createAndAddFooterContainer(id: String) {
queue(HeaderResponseContainer(id, id))
}
private fun newNavbar(markupId: String): Navbar =
object : Navbar(markupId) {
override fun onConfigure() {
super.onConfigure()
isVisible = isNavbarVisible
}
}.apply {
fluid()
position = Navbar.Position.STATIC_TOP
setBrandName(Model.of(getBrandName(properties.brand)))
setInverted(true)
}.also {
addLinksTo(it)
}
fun getBrandName(brand: String?): String =
if (brand == null || brand.isBlank() || "n.a." == brand)
StringResourceModel("brandname", this, null).string
else brand
protected open fun addLinksTo(nb: Navbar) {}
@JvmOverloads
fun queueFieldAndLabel(field: FormComponent<*>, pv: PropertyValidator<*>? = null) {
val id = field.id
val labelModel = StringResourceModel(id + LABEL_RESOURCE_TAG, this, null)
val label = Label(id + LABEL_TAG, labelModel)
queue(label)
field.label = labelModel
queue(field)
pv?.let { field.add(it) }
label.isVisible = field.isVisible
}
protected fun newResponsePageButton(
id: String,
responsePage: SerializableSupplier<AbstractPage<*>?>,
): BootstrapAjaxButton =
object : BootstrapAjaxButton(
id,
StringResourceModel(id + LABEL_RESOURCE_TAG, this@AbstractPage, null),
Buttons.Type.Default
) {
override fun onSubmit(target: AjaxRequestTarget) {
super.onSubmit(target)
setResponsePage(responsePage.get())
}
override fun onConfigure() {
super.onConfigure()
isEnabled = setResponsePageButtonEnabled()
}
}
/**
* Controls the enabled status of the response page button. Override if needed.
*
* @return true if response page button shall be enabled (default). false otherwise.
*/
protected open fun setResponsePageButtonEnabled(): Boolean = true
protected fun queuePanelHeadingFor(id: String) {
queue(
Label(
id + LABEL_TAG,
StringResourceModel(id + PANEL_HEADER_RESOURCE_TAG, this, null)
)
)
}
protected fun signIn(username: String?, password: String?): Boolean =
AuthenticatedWebSession.get().signIn(username, password)
protected fun signOutAndInvalidate() {
AuthenticatedWebSession.get().invalidate()
}
companion object {
private const val serialVersionUID = 1L
const val FOOTER_CONTAINER = "footer-container"
}
}
| gpl-3.0 |
allotria/intellij-community | java/idea-ui/testSrc/com/intellij/openapi/roots/ui/configuration/projectRoot/CloneOrderEntriesTest.kt | 2 | 6503 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots.ui.configuration.projectRoot
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.testFramework.JavaModuleTestCase
import junit.framework.TestCase
import org.assertj.core.api.Assertions.assertThat
class CloneOrderEntriesTest : JavaModuleTestCase() {
override fun isRunInWriteAction(): Boolean = true
fun `test copied jdk and module source`() {
val copyToModifiableModel = ModuleRootManager.getInstance(createModule("Copy To Module")).modifiableModel
val originalModifiableModel = ModuleRootManager.getInstance(module).modifiableModel
val path = originalModifiableModel.module.moduleNioFile
// Tested methods
val builder = ModuleStructureConfigurable.CopiedModuleBuilder(originalModifiableModel, path, project)
builder.setupRootModel(copyToModifiableModel)
originalModifiableModel.commit()
copyToModifiableModel.commit()
val originalOrderEntries = originalModifiableModel.orderEntries
val copiedOrderEntries = copyToModifiableModel.orderEntries
assertThat(copiedOrderEntries).hasSize(2)
val originalSdk = originalOrderEntries.filterIsInstance<JdkOrderEntry>().first()
val copiedSdk = copiedOrderEntries.filterIsInstance<JdkOrderEntry>().first()
TestCase.assertEquals(originalSdk.jdk, copiedSdk.jdk)
val originalModuleSource = originalOrderEntries.filterIsInstance<ModuleSourceOrderEntry>().first()
val copiedModuleSource = copiedOrderEntries.filterIsInstance<ModuleSourceOrderEntry>().first()
TestCase.assertEquals(originalModuleSource.presentableName, copiedModuleSource.presentableName)
}
fun `test copy module with module library`() {
val copyToModifiableModel = ModuleRootManager.getInstance(createModule("Copy To Module")).modifiableModel
val modifiableRootModel = ModuleRootManager.getInstance(module).modifiableModel
val library = modifiableRootModel.moduleLibraryTable.createLibrary("My Library") as LibraryEx
val path = modifiableRootModel.module.moduleNioFile
// Tested methods
val builder = ModuleStructureConfigurable.CopiedModuleBuilder(modifiableRootModel, path, project)
builder.setupRootModel(copyToModifiableModel)
modifiableRootModel.commit()
copyToModifiableModel.commit()
val copiedOrderEntries = copyToModifiableModel.moduleLibraryTable.libraries
TestCase.assertEquals(1, copiedOrderEntries.size)
TestCase.assertNotSame(library, copiedOrderEntries.first())
TestCase.assertEquals(library.name, copiedOrderEntries.first().name)
}
fun `test copy module with project library`() {
val projectLibrary = LibraryTablesRegistrar.getInstance().getLibraryTable(project).createLibrary("My Library")
val copyToModifiableModel = ModuleRootManager.getInstance(createModule("My Module")).modifiableModel
ModuleRootModificationUtil.updateModel(module) {
it.addLibraryEntry(projectLibrary)
}
val modifiableRootModel = ModuleRootManager.getInstance(module).modifiableModel
val path = modifiableRootModel.module.moduleNioFile
// Tested methods
val builder = ModuleStructureConfigurable.CopiedModuleBuilder(modifiableRootModel, path, project)
builder.setupRootModel(copyToModifiableModel)
copyToModifiableModel.commit()
modifiableRootModel.commit()
val originalOrderEntries = modifiableRootModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
val copiedOrderEntries = copyToModifiableModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
TestCase.assertEquals(1, copiedOrderEntries.size)
TestCase.assertSame(projectLibrary, copiedOrderEntries.first().library)
TestCase.assertNotSame(originalOrderEntries.first(), copiedOrderEntries.first())
}
fun `test copy module with global library`() {
val copyToModifiableModel = ModuleRootManager.getInstance(createModule("My Module")).modifiableModel
val globalLibraryTable = LibraryTablesRegistrar.getInstance().libraryTable
val globalLibrary = globalLibraryTable.createLibrary("My Library")
ModuleRootModificationUtil.updateModel(module) {
it.addLibraryEntry(globalLibrary)
}
val modifiableRootModel = ModuleRootManager.getInstance(module).modifiableModel
val path = modifiableRootModel.module.moduleNioFile
// Tested methods
val builder = ModuleStructureConfigurable.CopiedModuleBuilder(modifiableRootModel, path, project)
builder.setupRootModel(copyToModifiableModel)
copyToModifiableModel.commit()
modifiableRootModel.commit()
val originalOrderEntries = modifiableRootModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
val copiedOrderEntries = copyToModifiableModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
TestCase.assertEquals(1, copiedOrderEntries.size)
TestCase.assertSame(globalLibrary, copiedOrderEntries.first().library)
TestCase.assertNotSame(originalOrderEntries.first(), copiedOrderEntries.first())
}
fun `test copy module with module`() {
val mainModule = createModule("Copy To Model")
val depModule = createModule("My Module")
val copyToModifiableModel = ModuleRootManager.getInstance(mainModule).modifiableModel
ModuleRootModificationUtil.updateModel(module) {
it.addModuleOrderEntry(depModule)
}
val modifiableRootModel = ModuleRootManager.getInstance(module).modifiableModel
val path = modifiableRootModel.module.moduleNioFile
// Tested methods
val builder = ModuleStructureConfigurable.CopiedModuleBuilder(modifiableRootModel, path, project)
builder.setupRootModel(copyToModifiableModel)
copyToModifiableModel.commit()
modifiableRootModel.commit()
val originalOrderEntries = modifiableRootModel.orderEntries
val copiedOrderEntries = copyToModifiableModel.orderEntries
TestCase.assertEquals(originalOrderEntries.size, copiedOrderEntries.size)
val originalModule = originalOrderEntries.filterIsInstance<ModuleOrderEntry>().first()
val copiedModule = copiedOrderEntries.filterIsInstance<ModuleOrderEntry>().first()
TestCase.assertNotSame(originalModule, copiedModule)
TestCase.assertEquals(originalModule.module, copiedModule.module)
TestCase.assertEquals(originalModule.scope, copiedModule.scope)
}
}
| apache-2.0 |
ursjoss/sipamato | core/core-entity/src/test/kotlin/ch/difty/scipamato/core/entity/code/CodeTranslationTest.kt | 2 | 596 | package ch.difty.scipamato.core.entity.code
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
internal class CodeTranslationTest {
@Test
fun comment() {
val ntt = CodeTranslation(1, "de", "code1", "comment", 1)
ntt.comment shouldBeEqualTo "comment"
}
@Test
fun displayValue() {
val ntt = CodeTranslation(1, "de", "code1", "comment", 1)
ntt.displayValue shouldBeEqualTo "de: code1"
}
@Test
fun field() {
CodeTranslation.CodeTranslationFields.COMMENT.fieldName shouldBeEqualTo "comment"
}
}
| gpl-3.0 |
ursjoss/sipamato | public/public-persistence-jooq/src/main/kotlin/ch/difty/scipamato/publ/persistence/codeclass/JooqCodeClassService.kt | 2 | 554 | package ch.difty.scipamato.publ.persistence.codeclass
import ch.difty.scipamato.common.persistence.codeclass.JooqCodeClassLikeService
import ch.difty.scipamato.publ.entity.CodeClass
import ch.difty.scipamato.publ.persistence.api.CodeClassService
import org.springframework.stereotype.Service
/**
* jOOQ specific implementation of the [CodeClassService] interface.
*/
@Service
class JooqCodeClassService(
codeClassRepository: CodeClassRepository,
) : JooqCodeClassLikeService<CodeClass, CodeClassRepository>(codeClassRepository), CodeClassService
| gpl-3.0 |
CORDEA/MackerelClient | app/src/main/java/jp/cordea/mackerelclient/activity/LicenseActivity.kt | 1 | 1345 | package jp.cordea.mackerelclient.activity
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import dagger.android.AndroidInjection
import io.reactivex.disposables.Disposable
import jp.cordea.mackerelclient.R
import jp.cordea.mackerelclient.databinding.ActivityLicenseBinding
import jp.cordea.mackerelclient.viewmodel.LicenseViewModel
class LicenseActivity : AppCompatActivity() {
private val viewModel by lazy { LicenseViewModel(this) }
private var disposable: Disposable? = null
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
val binding = DataBindingUtil
.setContentView<ActivityLicenseBinding>(this, R.layout.activity_license)
disposable = viewModel.licensesObservable
.subscribe({
binding.licenseTextView.text = it
binding.container.visibility = View.VISIBLE
binding.progress.visibility = View.GONE
}, {
binding.errorLayout.root.visibility = View.VISIBLE
binding.progress.visibility = View.GONE
})
}
override fun onDestroy() {
super.onDestroy()
disposable?.dispose()
}
}
| apache-2.0 |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/ui/view/app/tabs/BugTab.kt | 1 | 7351 | /*
* (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.faendir.acra.ui.view.app.tabs
import com.faendir.acra.i18n.Messages
import com.faendir.acra.model.App
import com.faendir.acra.model.Permission
import com.faendir.acra.model.QBug
import com.faendir.acra.model.QReport
import com.faendir.acra.model.QStacktrace
import com.faendir.acra.model.Version
import com.faendir.acra.model.view.VBug
import com.faendir.acra.navigation.ParseAppParameter
import com.faendir.acra.navigation.View
import com.faendir.acra.security.SecurityUtils
import com.faendir.acra.service.BugMerger
import com.faendir.acra.service.DataService
import com.faendir.acra.settings.LocalSettings
import com.faendir.acra.ui.component.Translatable
import com.faendir.acra.ui.component.dialog.createButton
import com.faendir.acra.ui.component.dialog.showFluentDialog
import com.faendir.acra.ui.component.grid.AcrariumGridView
import com.faendir.acra.ui.component.grid.TimeSpanRenderer
import com.faendir.acra.ui.component.grid.column
import com.faendir.acra.ui.component.grid.grid
import com.faendir.acra.ui.ext.content
import com.faendir.acra.ui.view.app.AppView
import com.faendir.acra.ui.view.bug.tabs.BugTab
import com.faendir.acra.ui.view.bug.tabs.ReportTab
import com.querydsl.jpa.impl.JPAQuery
import com.vaadin.flow.component.AbstractField.ComponentValueChangeEvent
import com.vaadin.flow.component.button.ButtonVariant
import com.vaadin.flow.component.grid.Grid
import com.vaadin.flow.component.grid.GridSortOrder
import com.vaadin.flow.component.notification.Notification
import com.vaadin.flow.component.radiobutton.RadioButtonGroup
import com.vaadin.flow.component.select.Select
import com.vaadin.flow.data.renderer.ComponentRenderer
import com.vaadin.flow.router.Route
/**
* @author lukas
* @since 14.07.18
*/
@View
@Route(value = "bug", layout = AppView::class)
class BugTab(
private val dataService: DataService,
private val bugMerger: BugMerger,
private val localSettings: LocalSettings,
@ParseAppParameter
private val app: App
) : AppTab<AcrariumGridView<VBug>>(app) {
init {
content {
val mergeButton = Translatable.createButton(Messages.MERGE_BUGS) {
val selectedItems: List<VBug> = ArrayList(grid.selectedItems)
if (selectedItems.size > 1) {
val titles = RadioButtonGroup<String>()
titles.setItems(selectedItems.map { bug: VBug -> bug.bug.title })
titles.value = selectedItems[0].bug.title
showFluentDialog {
header(Messages.CHOOSE_BUG_GROUP_TITLE)
add(titles)
createButton {
bugMerger.mergeBugs(selectedItems.map { it.bug }, titles.value)
grid.deselectAll()
grid.dataProvider.refreshAll()
}
}
} else {
Notification.show(Messages.ONLY_ONE_BUG_SELECTED)
}
}.with {
isEnabled = false
removeThemeVariants(ButtonVariant.LUMO_PRIMARY)
}
header.addComponentAsFirst(mergeButton)
grid {
setSelectionMode(Grid.SelectionMode.MULTI)
asMultiSelect().addSelectionListener { mergeButton.content.isEnabled = it.allSelectedItems.size >= 2 }
column({ it.reportCount }) {
setSortable(QReport.report.count())
setCaption(Messages.REPORTS)
}
column(TimeSpanRenderer { it.lastReport }) {
setSortable(QReport.report.date.max())
setCaption(Messages.LATEST_REPORT)
sort(GridSortOrder.desc(this).build())
}
val versions = dataService.findAllVersions(app)
val versionCodeNameMap = versions.associate { it.code to it.name }
column({ versionCodeNameMap[it.highestVersionCode] }) {
setSortable(QReport.report.stacktrace.version.code.max())
setCaption(Messages.LATEST_VERSION)
}
column({ it.userCount }) {
setSortable(QReport.report.installationId.countDistinct())
setCaption(Messages.AFFECTED_USERS)
}
column({ it.bug.title }) {
setSortableAndFilterable(QBug.bug.title, Messages.TITLE)
setCaption(Messages.TITLE)
isAutoWidth = false
flexGrow = 1
}
column(ComponentRenderer { bug: VBug ->
Select(*versions.toTypedArray()).apply {
setTextRenderer { it.name }
isEmptySelectionAllowed = true
emptySelectionCaption = getTranslation(Messages.NOT_SOLVED)
value = bug.bug.solvedVersion
isEnabled = SecurityUtils.hasPermission(app, Permission.Level.EDIT)
addValueChangeListener { e: ComponentValueChangeEvent<Select<Version?>?, Version?> ->
dataService.setBugSolved(bug.bug, e.value)
style["--select-background-color"] =
if (bug.highestVersionCode > bug.bug.solvedVersion?.code ?: Int.MAX_VALUE) "var(--lumo-error-color-50pct)" else null
}
if (bug.highestVersionCode > bug.bug.solvedVersion?.code ?: Int.MAX_VALUE) {
style["--select-background-color"] = "var(--lumo-error-color-50pct)"
}
}
}) {
setSortable(QBug.bug.solvedVersion)
setFilterable(
//not solved or regression
QBug.bug.solvedVersion.isNull.or(
QBug.bug.solvedVersion.code.lt(
JPAQuery<Any>().select(QStacktrace.stacktrace1.version.code.max()).from(QStacktrace.stacktrace1)
.where(QStacktrace.stacktrace1.bug.eq(QBug.bug))
)
),
true,
Messages.HIDE_SOLVED
)
setCaption(Messages.SOLVED)
}
addOnClickNavigation(ReportTab::class.java) { BugTab.getNavigationParams(it.bug) }
}
}
}
override fun initContent() = AcrariumGridView(dataService.getBugProvider(app), localSettings::bugGridSettings)
} | apache-2.0 |
googlecodelabs/android-sleep | start/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventEntity.kt | 2 | 1921 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.sleepcodelab.data.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.android.gms.location.SleepClassifyEvent
/**
* Entity class (table version of the class) for [SleepClassifyEvent] which represents a sleep
* classification event including the classification timestamp, the sleep confidence, and the
* supporting data such as device motion and ambient light level. Classification events are
* reported regularly.
*/
@Entity(tableName = "sleep_classify_events_table")
data class SleepClassifyEventEntity(
@PrimaryKey
@ColumnInfo(name = "time_stamp_seconds")
val timestampSeconds: Int,
@ColumnInfo(name = "confidence")
val confidence: Int,
@ColumnInfo(name = "motion")
val motion: Int,
@ColumnInfo(name = "light")
val light: Int
) {
companion object {
fun from(sleepClassifyEvent: SleepClassifyEvent): SleepClassifyEventEntity {
return SleepClassifyEventEntity(
timestampSeconds = (sleepClassifyEvent.timestampMillis / 1000).toInt(),
confidence = sleepClassifyEvent.confidence,
motion = sleepClassifyEvent.motion,
light = sleepClassifyEvent.light
)
}
}
}
| apache-2.0 |
agoda-com/Kakao | kakao/src/main/kotlin/com/agoda/kakao/edit/KEditText.kt | 1 | 762 | @file:Suppress("unused")
package com.agoda.kakao.edit
import android.view.View
import androidx.test.espresso.DataInteraction
import com.agoda.kakao.common.builders.ViewBuilder
import com.agoda.kakao.common.views.KBaseView
import com.agoda.kakao.text.TextViewAssertions
import org.hamcrest.Matcher
/**
* View with EditableActions and TextViewAssertions
*
* @see EditableActions
* @see TextViewAssertions
*/
class KEditText : KBaseView<KEditText>, EditableActions, TextViewAssertions {
constructor(function: ViewBuilder.() -> Unit) : super(function)
constructor(parent: Matcher<View>, function: ViewBuilder.() -> Unit) : super(parent, function)
constructor(parent: DataInteraction, function: ViewBuilder.() -> Unit) : super(parent, function)
}
| apache-2.0 |
zdary/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/editors/PackageVersionTableCellEditor.kt | 1 | 2854 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.editors
import com.intellij.ui.components.editors.JBComboBoxTableCellEditorComponent
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.AbstractTableCellEditor
import com.jetbrains.packagesearch.intellij.plugin.ui.components.ComboBoxTableCellEditorComponent
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.VersionViewModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers.PopupMenuListItemCellRenderer
import java.awt.Component
import javax.swing.JTable
internal class PackageVersionTableCellEditor : AbstractTableCellEditor() {
private val comboBox = JBComboBoxTableCellEditorComponent()
private var onlyStable = false
fun updateData(onlyStable: Boolean) {
this.onlyStable = onlyStable
}
override fun getCellEditorValue(): Any? = comboBox.editorValue
override fun getTableCellEditorComponent(table: JTable, value: Any, isSelected: Boolean, row: Int, column: Int): Component {
val viewModel = value as VersionViewModel<*>
val versionViewModels = when (viewModel) {
is VersionViewModel.InstalledPackage ->
viewModel.packageModel.getAvailableVersions(onlyStable)
.map { viewModel.copy(selectedVersion = it) }
is VersionViewModel.InstallablePackage ->
viewModel.packageModel.getAvailableVersions(onlyStable)
.map { viewModel.copy(selectedVersion = it) }
}
return createComboBoxEditor(table, versionViewModels, viewModel.selectedVersion).apply {
table.colors.applyTo(this, isSelected = true)
setCell(row, column)
}
}
private fun createComboBoxEditor(
table: JTable,
versionViewModels: List<VersionViewModel<*>>,
selectedVersion: PackageVersion
): ComboBoxTableCellEditorComponent<*> {
require(table is JBTable) { "The packages list table is expected to be a JBTable, but was a ${table::class.qualifiedName}" }
val selectedViewModel = versionViewModels.find { it.selectedVersion == selectedVersion }
val cellRenderer = PopupMenuListItemCellRenderer(selectedViewModel, table.colors) { it.selectedVersion.displayName }
return ComboBoxTableCellEditorComponent(table, cellRenderer).apply {
isShowBelowCell = false
isForcePopupMatchCellWidth = false
options = versionViewModels
value = selectedViewModel
}
}
}
| apache-2.0 |
zdary/intellij-community | plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxEventHandlerReferenceQuickFixProvider.kt | 12 | 3489 | // 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 file.
package org.jetbrains.plugins.javaFX.fxml.refs
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.*
import com.intellij.psi.PsiJvmSubstitutor
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.PsiType
import com.intellij.psi.codeStyle.JavaCodeStyleSettings
import com.intellij.psi.util.createSmartPointer
import com.intellij.psi.xml.XmlAttribute
import com.intellij.psi.xml.XmlAttributeValue
import com.intellij.util.VisibilityUtil
import org.jetbrains.plugins.javaFX.fxml.JavaFxCommonNames
import org.jetbrains.plugins.javaFX.fxml.JavaFxPsiUtil
class JavaFxEventHandlerReferenceQuickFixProvider : UnresolvedReferenceQuickFixProvider<JavaFxEventHandlerReference>() {
override fun getReferenceClass(): Class<JavaFxEventHandlerReference> = JavaFxEventHandlerReference::class.java
override fun registerFixes(ref: JavaFxEventHandlerReference, registrar: QuickFixActionRegistrar) {
val controller = ref.myController ?: return
if (ref.myEventHandler != null) return
val element = ref.element
val request = CreateEventHandlerRequest(element)
createMethodActions(controller, request).forEach(registrar::register)
}
}
class CreateEventHandlerRequest(element: XmlAttributeValue) : CreateMethodRequest {
private val myProject = element.project
private val myVisibility = getVisibility(element)
private val myPointer = element.createSmartPointer(myProject)
override fun isValid(): Boolean = myPointer.element.let {
it != null && it.value.let { value ->
value != null && value.length > 2
}
}
private val myElement get() = myPointer.element!!
override fun getMethodName(): String = myElement.value!!.substring(1)
override fun getReturnType(): List<ExpectedType> = listOf(expectedType(PsiType.VOID, ExpectedType.Kind.EXACT))
override fun getExpectedParameters(): List<ExpectedParameter> {
val eventType = expectedType(getEventType(myElement), ExpectedType.Kind.EXACT)
val parameter = expectedParameter(eventType)
return listOf(parameter)
}
override fun getModifiers(): Set<JvmModifier> = setOf(myVisibility)
override fun getAnnotations(): List<AnnotationRequest> = if (myVisibility != JvmModifier.PUBLIC) {
listOf(annotationRequest(JavaFxCommonNames.JAVAFX_FXML_ANNOTATION))
}
else {
emptyList()
}
override fun getTargetSubstitutor(): PsiJvmSubstitutor = PsiJvmSubstitutor(myProject, PsiSubstitutor.EMPTY)
}
private fun getVisibility(element: XmlAttributeValue): JvmModifier {
val visibility = JavaCodeStyleSettings.getInstance(element.containingFile).VISIBILITY
if (VisibilityUtil.ESCALATE_VISIBILITY == visibility) return JvmModifier.PRIVATE
if (visibility == PsiModifier.PACKAGE_LOCAL) return JvmModifier.PACKAGE_LOCAL
return JvmModifier.valueOf(visibility.toUpperCase())
}
private fun getEventType(element: XmlAttributeValue): PsiType {
val parent = element.parent
if (parent is XmlAttribute) {
val eventType = JavaFxPsiUtil.getDeclaredEventType(parent)
if (eventType != null) {
return eventType
}
}
return PsiType.getTypeByName(JavaFxCommonNames.JAVAFX_EVENT, element.project, element.resolveScope)
}
| apache-2.0 |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/args/ArgsSchema.kt | 1 | 8317 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common.args
import slatekit.common.Types
import slatekit.results.Try
import slatekit.results.builders.Tries
/**
* stores and builds a list of 1 or more arguments which collectively represent the schema.
*
* @note this schema is immutable and returns a schema when adding additional arguments
* @param items : the list of arguments.
*/
class ArgsSchema(val items: List<Arg> = listOf(), val builder:ArgsWriter? = null) {
val any: Boolean get() = items.isNotEmpty()
/**
* Adds a argument of type text to the schema
*
* @param alias : Short hand alias for the name
* @param name : Name of argument
* @param desc : Description
* @param required : Whether this is required or not
* @param defaultVal : Default value for argument
* @param example : Example of value shown for help text
* @param exampleMany : Examples of values shown for help text
* @param group : Used to group arguments into categories
* @return
*/
fun text(
alias: String = "",
name: String,
desc: String = "",
required: Boolean = false,
defaultVal: String = "",
example: String = "",
exampleMany: String = "",
group: String = ""
): ArgsSchema =
add(alias, name, desc, Types.JStringClass, required, defaultVal, example, exampleMany, group)
/**
* Adds a argument of type boolean to the schema
*
* @param alias : Short hand alias for the name
* @param name : Name of argument
* @param desc : Description
* @param required : Whether this is required or not
* @param defaultVal : Default value for argument
* @param example : Example of value shown for help text
* @param exampleMany : Examples of values shown for help text
* @param group : Used to group arguments into categories
* @return
*/
fun flag(
alias: String = "",
name: String,
desc: String = "",
required: Boolean = false,
defaultVal: String = "",
example: String = "",
exampleMany: String = "",
group: String = ""
): ArgsSchema =
add(alias, name, desc, Types.JBoolClass, required, defaultVal, example, exampleMany, group)
/**
* Adds a argument of type number to the schema
*
* @param alias : Short hand alias for the name
* @param name : Name of argument
* @param desc : Description
* @param required : Whether this is required or not
* @param defaultVal : Default value for argument
* @param example : Example of value shown for help text
* @param exampleMany : Examples of values shown for help text
* @param group : Used to group arguments into categories
* @return
*/
fun number(
alias: String = "",
name: String,
desc: String = "",
required: Boolean = false,
defaultVal: String = "",
example: String = "",
exampleMany: String = "",
group: String = ""
): ArgsSchema =
add(alias, name, desc, Types.JIntClass, required, defaultVal, example, exampleMany, group)
/**
* Adds a argument to the schema
*
* @param alias : Short hand alias for the name
* @param name : Name of argument
* @param desc : Description
* @param dataType : Data type of the argument
* @param required : Whether this is required or not
* @param defaultVal : Default value for argument
* @param example : Example of value shown for help text
* @param exampleMany : Examples of values shown for help text
* @param group : Used to group arguments into categories
* @return
*/
fun add(
alias: String = "",
name: String,
desc: String = "",
dataType: Class<*>,
required: Boolean = false,
defaultVal: String = "",
example: String = "",
exampleMany: String = "",
group: String = ""
): ArgsSchema {
val typeName = dataType.simpleName
val arg = Arg(alias, name, desc, typeName
?: "string", required, false, false, false, group, "", defaultVal, example, exampleMany)
val newList = items.plus(arg)
return ArgsSchema(newList)
}
/**
* whether or not the argument supplied is missing
*
* @param args
* @param arg
* @return
*/
fun missing(args: Args, arg: Arg): Boolean = arg.isRequired && !args.containsKey(arg.name)
fun buildHelp(prefix: String? = "-", separator: String? = "=") {
val maxLen = maxLengthOfName()
items.forEach { arg ->
when(builder) {
null -> {
val nameLen = maxLen ?: arg.name.length
val nameFill = arg.name.padEnd(nameLen)
val namePart = (prefix ?: "-") + nameFill
println(namePart)
print(separator ?: "=")
println(arg.desc)
print(" ".repeat(nameLen + 6))
if (arg.isRequired) {
println("!" )
println("required ")
} else {
println("?" )
println("optional ")
}
println("[${arg.dataType}] " )
println("e.g. ${arg.example}")
}
else -> {
builder.write(arg, prefix, separator, maxLen)
}
}
}
}
/**
* gets the maximum length of an argument name from all arguments
*
* @return
*/
private fun maxLengthOfName(): Int = if (items.isEmpty()) 0 else items.maxByOrNull { it.name.length }?.name ?.length ?: 0
companion object {
@JvmStatic val empty:ArgsSchema = ArgsSchema()
/**
* Parses the line against the schema and transforms any aliases into canonical names
*/
@JvmStatic fun parse(schema:ArgsSchema, line:String):Try<Args> {
val parsed = Args.parse(line, "-", "=", true)
return parsed.map { transform(schema, it) }
}
/**
* Transforms the arguments which may have aliases into their canonical names
* @param schema: The argument schema to transform aliases against
* @param args : The parsed arguments
*/
@JvmStatic fun transform(schema: ArgsSchema?, args: Args): Args {
if(schema == null) return args
val canonical = args.named.toMutableMap()
val aliased = schema.items.filter { !it.alias.isNullOrBlank() }
if(aliased.isEmpty()) {
return args
}
aliased.forEach { arg ->
if(canonical.containsKey(arg.alias)){
val value = canonical.get(arg.alias)
if(value != null){
canonical.remove(arg.alias)
canonical[arg.name] = value
}
}
}
val finalArgs = args.copy(namedArgs = canonical)
return finalArgs
}
/**
* Validates the arguments against this schema
* @param schema: The argument schema to validate against
* @param args : The parsed arguments
*/
@JvmStatic fun validate(schema: ArgsSchema, args: Args): Try<Boolean> {
val missing = schema.items.filter { arg -> arg.isRequired && !args.containsKey(arg.name) }
return if (missing.isNotEmpty()) {
Tries.errored("invalid arguments supplied: Missing : " + missing.first().name)
} else {
Tries.success(true)
}
}
}
}
| apache-2.0 |
zdary/intellij-community | python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyDataclassFieldStubImpl.kt | 4 | 5545 | /*
* 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 file.
*/
package com.jetbrains.python.psi.impl.stubs
import com.intellij.psi.stubs.StubInputStream
import com.intellij.psi.stubs.StubOutputStream
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.PyDataclassParameters
import com.jetbrains.python.codeInsight.resolvesToOmittedDefault
import com.jetbrains.python.psi.PyCallExpression
import com.jetbrains.python.psi.PyReferenceExpression
import com.jetbrains.python.psi.PyTargetExpression
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.resolve.PyResolveUtil
import com.jetbrains.python.psi.stubs.PyDataclassFieldStub
import java.io.IOException
class PyDataclassFieldStubImpl private constructor(private val calleeName: QualifiedName,
private val parameters: FieldParameters) : PyDataclassFieldStub {
companion object {
fun create(expression: PyTargetExpression): PyDataclassFieldStub? {
val value = expression.findAssignedValue() as? PyCallExpression ?: return null
val callee = value.callee as? PyReferenceExpression ?: return null
val calleeNameAndType = calculateCalleeNameAndType(callee) ?: return null
val parameters = analyzeArguments(value, calleeNameAndType.second) ?: return null
return PyDataclassFieldStubImpl(calleeNameAndType.first, parameters)
}
@Throws(IOException::class)
fun deserialize(stream: StubInputStream): PyDataclassFieldStub? {
val calleeName = stream.readNameString() ?: return null
val hasDefault = stream.readBoolean()
val hasDefaultFactory = stream.readBoolean()
val initValue = stream.readBoolean()
val kwOnly = stream.readBoolean()
return PyDataclassFieldStubImpl(
QualifiedName.fromDottedString(calleeName),
FieldParameters(hasDefault, hasDefaultFactory, initValue, kwOnly)
)
}
private fun calculateCalleeNameAndType(callee: PyReferenceExpression): Pair<QualifiedName, PyDataclassParameters.PredefinedType>? {
val qualifiedName = callee.asQualifiedName() ?: return null
val dataclassesField = QualifiedName.fromComponents("dataclasses", "field")
val attrIb = QualifiedName.fromComponents("attr", "ib")
val attrAttr = QualifiedName.fromComponents("attr", "attr")
val attrAttrib = QualifiedName.fromComponents("attr", "attrib")
for (originalQName in PyResolveUtil.resolveImportedElementQNameLocally(callee)) {
when (originalQName) {
dataclassesField -> return qualifiedName to PyDataclassParameters.PredefinedType.STD
attrIb, attrAttr, attrAttrib -> return qualifiedName to PyDataclassParameters.PredefinedType.ATTRS
}
}
return null
}
private fun analyzeArguments(call: PyCallExpression, type: PyDataclassParameters.PredefinedType): FieldParameters? {
val initValue = PyEvaluator.evaluateAsBooleanNoResolve(call.getKeywordArgument("init"), true)
if (type == PyDataclassParameters.PredefinedType.STD) {
val default = call.getKeywordArgument("default")
val defaultFactory = call.getKeywordArgument("default_factory")
return FieldParameters(default != null && !resolvesToOmittedDefault(default, type),
defaultFactory != null && !resolvesToOmittedDefault(defaultFactory, type),
initValue,
false)
}
else if (type == PyDataclassParameters.PredefinedType.ATTRS) {
val default = call.getKeywordArgument("default")
val hasFactory = call.getKeywordArgument("factory").let { it != null && it.text != PyNames.NONE }
val kwOnly = PyEvaluator.evaluateAsBooleanNoResolve(call.getKeywordArgument("kw_only"), false)
if (default != null && !resolvesToOmittedDefault(default, type)) {
val callee = (default as? PyCallExpression)?.callee as? PyReferenceExpression
val hasFactoryInDefault =
callee != null &&
QualifiedName.fromComponents("attr", "Factory") in PyResolveUtil.resolveImportedElementQNameLocally(callee)
return FieldParameters(!hasFactoryInDefault, hasFactory || hasFactoryInDefault, initValue, kwOnly)
}
return FieldParameters(false, hasFactory, initValue, kwOnly)
}
return null
}
}
override fun getTypeClass(): Class<out CustomTargetExpressionStubType<out CustomTargetExpressionStub>> {
return PyDataclassFieldStubType::class.java
}
override fun serialize(stream: StubOutputStream) {
stream.writeName(calleeName.toString())
stream.writeBoolean(parameters.hasDefault)
stream.writeBoolean(parameters.hasDefaultFactory)
stream.writeBoolean(parameters.initValue)
stream.writeBoolean(parameters.kwOnly)
}
override fun getCalleeName(): QualifiedName = calleeName
override fun hasDefault(): Boolean = parameters.hasDefault
override fun hasDefaultFactory(): Boolean = parameters.hasDefaultFactory
override fun initValue(): Boolean = parameters.initValue
override fun kwOnly(): Boolean = parameters.kwOnly
private data class FieldParameters(val hasDefault: Boolean,
val hasDefaultFactory: Boolean,
val initValue: Boolean,
val kwOnly: Boolean)
}
| apache-2.0 |
leafclick/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/problems/UsageSink.kt | 1 | 4434 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.daemon.problems
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiSearchHelper
class UsageSink(private val project: Project) {
internal fun checkUsages(prevMember: Member?, curMember: Member?, containingFile: PsiFile): List<Problem>? {
// member properties were changed
if (prevMember != null && curMember != null && prevMember.name == curMember.name) {
return processMemberChange(prevMember, curMember, containingFile)
}
/**
* In other cases we need to use module scope since we might already have some problems
* that are outside of current member scope but that might resolve after the change.
* @see com.intellij.java.codeInsight.daemon.problems.MethodProblemsTest#testMethodOverrideScopeIsChanged
* as an example how it might happen.
*/
val problems = mutableListOf<Problem>()
// member was renamed or removed
if (prevMember != null) {
val memberProblems = processUsages(prevMember, containingFile) ?: return null
problems.addAll(memberProblems)
}
// member was renamed or created
if (curMember != null) {
val memberProblems = processUsages(curMember, containingFile) ?: return null
problems.addAll(memberProblems)
}
return problems
}
private fun processUsages(member: Member,
containingFile: PsiFile,
scope: GlobalSearchScope? = extractScope(member, containingFile)): List<Problem>? {
if (scope == null) return null
val memberName = member.name
val isMethodSearch = member.psiMember is PsiMethod
val usageExtractor: (PsiFile, Int) -> PsiElement? = { psiFile, index ->
val elementAt = psiFile.findElementAt(index) as? PsiIdentifier
if (elementAt != null) extractMemberUsage(elementAt, isMethodSearch) else null
}
val collector = MemberUsageCollector(memberName, containingFile, usageExtractor)
PsiSearchHelper.getInstance(project).processAllFilesWithWord(memberName, scope, collector, true)
val usages = collector.collectedUsages ?: return null
val problems = mutableListOf<Problem>()
for (usage in usages) {
problems.addAll(ProblemMatcher.getProblems(usage))
}
return problems
}
private fun processMemberChange(prevMember: Member, curMember: Member, containingFile: PsiFile): List<Problem>? {
val prevScope = prevMember.scope
val curScope = curMember.scope
if (prevScope == curScope) return processUsages(curMember, containingFile, curScope)
val unionScope = prevScope.union(curScope)
val problems = processUsages(curMember, containingFile, unionScope)
if (problems != null) return problems
/**
* If we reported errors for this member previously and union scope is too big and cannot be analysed,
* then we stuck with already reported problems even after the fix.
* To prevent that we need to remove all previously reported problems for this element (even though they are still valid).
* @see com.intellij.java.codeInsight.daemon.problems.FieldProblemsTest#testErrorsRemovedAfterScopeChanged as an example.
*/
val prevProblems = processUsages(curMember, containingFile, prevScope)
// ok, we didn't analyse this element before
if (prevProblems == null) return null
return prevProblems.map { if (it.message == null) it else Problem(it.file, null, it.place) }
}
companion object {
private fun extractScope(member: Member, containingFile: PsiFile): GlobalSearchScope? =
ModuleUtil.findModuleForFile(containingFile)?.moduleScope ?: member.scope
private fun extractMemberUsage(identifier: PsiIdentifier, isMethodSearch: Boolean): PsiElement? {
val parent = identifier.parent
val usage = when {
parent is PsiReference -> {
val javaReference = parent.element as? PsiJavaReference
if (javaReference != null) javaReference as? PsiElement else null
}
parent is PsiMethod && isMethodSearch -> parent
else -> null
}
return if (usage is Navigatable) usage else null
}
}
} | apache-2.0 |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/psi/expression/PSExpressionIdentifier.kt | 1 | 734 | package org.purescript.psi.expression
import com.intellij.lang.ASTNode
import org.purescript.psi.PSPsiElement
import org.purescript.psi.name.PSQualifiedIdentifier
/**
* A identifier in an expression, e.g.
* ```
* add
* ```
* in
* ```
* f = add 1 3
* ```
*/
class PSExpressionIdentifier(node: ASTNode) : PSPsiElement(node) {
/**
* @return the [PSQualifiedIdentifier] identifying this constructor
*/
internal val qualifiedIdentifier: PSQualifiedIdentifier
get() = findNotNullChildByClass(PSQualifiedIdentifier::class.java)
override fun getName(): String = qualifiedIdentifier.name
override fun getReference(): ExpressionIdentifierReference =
ExpressionIdentifierReference(this)
}
| bsd-3-clause |
JuliusKunze/kotlin-native | Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/TypeUtils.kt | 1 | 2642 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.native.interop.gen
import org.jetbrains.kotlin.native.interop.indexer.*
val EnumDef.isAnonymous: Boolean
get() = spelling.contains("(anonymous ") // TODO: it is a hack
/**
* Returns the expression which could be used for this type in C code.
* Note: the resulting string doesn't exactly represent this type, but it is enough for current purposes.
*
* TODO: use libclang to implement?
*/
fun Type.getStringRepresentation(): String = when (this) {
is VoidType -> "void"
is CharType -> "char"
is BoolType -> "BOOL"
is IntegerType -> this.spelling
is FloatingType -> this.spelling
is PointerType, is ArrayType -> "void*"
is RecordType -> this.decl.spelling
is EnumType -> if (this.def.isAnonymous) {
this.def.baseType.getStringRepresentation()
} else {
this.def.spelling
}
is Typedef -> this.def.aliased.getStringRepresentation()
is ObjCPointer -> when (this) {
is ObjCIdType -> "id$protocolQualifier"
is ObjCClassPointer -> "Class$protocolQualifier"
is ObjCObjectPointer -> "${def.name}$protocolQualifier*"
is ObjCInstanceType -> TODO(this.toString()) // Must have already been handled.
is ObjCBlockPointer -> "id"
}
else -> throw kotlin.NotImplementedError()
}
private val ObjCQualifiedPointer.protocolQualifier: String
get() = if (this.protocols.isEmpty()) "" else " <${protocols.joinToString { it.name }}>"
tailrec fun Type.unwrapTypedefs(): Type = if (this is Typedef) {
this.def.aliased.unwrapTypedefs()
} else {
this
}
fun blockTypeStringRepresentation(type: ObjCBlockPointer): String {
return buildString {
append(type.returnType.getStringRepresentation())
append("(^)")
append("(")
val blockParameters = if (type.parameterTypes.isEmpty()) {
"void"
} else {
type.parameterTypes.joinToString { it.getStringRepresentation() }
}
append(blockParameters)
append(")")
}
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/call/incorrectNumberOfArguments.kt | 2 | 2694 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.KCallable
import kotlin.reflect.KFunction
import kotlin.reflect.KMutableProperty
var foo: String = ""
class A(private var bar: String = "") {
fun getBar() = A::bar
}
object O {
@JvmStatic
private var baz: String = ""
@JvmStatic
fun getBaz() = (O::class.members.single { it.name == "baz" } as KMutableProperty<*>).apply { isAccessible = true }
fun getGetBaz() = O::class.members.single { it.name == "getBaz" } as KFunction<*>
}
fun check(callable: KCallable<*>, vararg args: Any?) {
val expected = callable.parameters.size
val actual = args.size
if (expected == actual) {
throw AssertionError("Bad test case: expected and actual number of arguments should differ (was $expected vs $actual)")
}
val expectedExceptionMessage = "Callable expects $expected arguments, but $actual were provided."
try {
callable.call(*args)
throw AssertionError("Fail: an IllegalArgumentException should have been thrown")
} catch (e: IllegalArgumentException) {
if (e.message != expectedExceptionMessage) {
// This most probably means that we don't check number of passed arguments in reflection
// and the default check from Java reflection yields an IllegalArgumentException, but with a not that helpful message
throw AssertionError("Fail: an exception with an unrecognized message was thrown: \"${e.message}\"" +
"\nExpected message was: $expectedExceptionMessage")
}
}
}
fun box(): String {
check(::box, null)
check(::box, "")
check(::A)
check(::A, null, "")
check(O.getGetBaz())
check(O.getGetBaz(), null, "")
val f = ::foo
check(f, null)
check(f, null, null)
check(f, arrayOf<Any?>(null))
check(f, "")
check(f.getter, null)
check(f.getter, null, null)
check(f.getter, arrayOf<Any?>(null))
check(f.getter, "")
check(f.setter)
check(f.setter, null, null)
check(f.setter, null, "")
val b = A().getBar()
check(b)
check(b, null, null)
check(b, "", "")
check(b.getter)
check(b.getter, null, null)
check(b.getter, "", "")
check(b.setter)
check(b.setter, null)
check(b.setter, "")
val z = O.getBaz()
check(z)
check(z, null, null)
check(z, "", "")
check(z.getter)
check(z.getter, null, null)
check(z.getter, "", "")
check(z.setter)
check(z.setter, null)
check(z.setter, "")
return "OK"
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/properties/lateinit/isInitializedAndDeinitialize/sideEffects.kt | 1 | 435 | // IGNORE_BACKEND: NATIVE
// LANGUAGE_VERSION: 1.2
// WITH_RUNTIME
class Foo {
lateinit var bar: String
fun test(): String {
var state = 0
if (run { state++; this }::bar.isInitialized) return "Fail 1"
bar = "A"
if (!run { state++; this }::bar.isInitialized) return "Fail 3"
return if (state == 2) "OK" else "Fail: state=$state"
}
}
fun box(): String {
return Foo().test()
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/StaticDataUtils.kt | 2 | 1733 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.llvm
import llvm.*
/**
* Creates const array-typed global with given name and value.
* Returns pointer to the first element of the array.
*
* If [elements] is empty, then null pointer is returned.
*/
internal fun StaticData.placeGlobalConstArray(name: String,
elemType: LLVMTypeRef,
elements: List<ConstValue>): ConstPointer {
if (elements.isNotEmpty()) {
val global = this.placeGlobalArray(name, elemType, elements)
global.setConstant(true)
return global.pointer.getElementPtr(0)
} else {
return NullPointer(elemType)
}
}
internal fun StaticData.createAlias(name: String, aliasee: ConstPointer): ConstPointer {
val alias = LLVMAddAlias(context.llvmModule, aliasee.llvmType, aliasee.llvm, name)!!
return constPointer(alias)
}
internal fun StaticData.placeCStringLiteral(value: String): ConstPointer {
val chars = value.toByteArray(Charsets.UTF_8).map { Int8(it) } + Int8(0)
return placeGlobalConstArray("", int8Type, chars)
} | apache-2.0 |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/world/EmpireManager.kt | 1 | 4570 | package au.com.codeka.warworlds.client.game.world
import au.com.codeka.warworlds.client.App
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.client.concurrency.Threads
import au.com.codeka.warworlds.client.store.ProtobufStore
import au.com.codeka.warworlds.client.util.eventbus.EventHandler
import au.com.codeka.warworlds.common.Log
import au.com.codeka.warworlds.common.proto.Empire
import au.com.codeka.warworlds.common.proto.EmpireDetailsPacket
import au.com.codeka.warworlds.common.proto.Packet
import au.com.codeka.warworlds.common.proto.RequestEmpirePacket
import com.google.common.collect.Lists
import java.util.*
/** Manages empires. */
object EmpireManager {
private val log = Log("EmpireManager")
/**
* The number of milliseconds to delay sending the empire request to the server, so that we can
* batch them up a bit in case of a burst of requests (happens when you open chat for example).
*/
private const val EMPIRE_REQUEST_DELAY_MS: Long = 150
private val empires: ProtobufStore<Empire> = App.dataStore.empires()
/** The list of pending empire requests. */
private val pendingEmpireRequests: MutableSet<Long> = HashSet()
/** An object to synchronize on when updating [.pendingEmpireRequests]. */
private val pendingRequestLock = Any()
/** Whether a request for empires is currently pending. */
private var requestPending = false
/** Our current empire, will be null before we're connected. */
private var myEmpire: Empire? = null
/** A placeholder [Empire] for native empires. */
private val nativeEmpire = Empire(
id = 0,
display_name = App.getString(R.string.native_colony),
state = Empire.EmpireState.ACTIVE)
private val eventListener: Any = object : Any() {
@EventHandler(thread = Threads.BACKGROUND)
fun handleEmpireUpdatedPacket(pkt: EmpireDetailsPacket) {
for (empire in pkt.empires) {
val startTime = System.nanoTime()
empires.put(empire.id, empire)
App.eventBus.publish(empire)
val endTime = System.nanoTime()
log.debug("Refreshed empire %d [%s] in %dms.",
empire.id, empire.display_name, (endTime - startTime) / 1000000L)
}
}
}
init {
App.eventBus.register(eventListener)
}
/** Called by the server when we get the 'hello', and lets us know the empire. */
fun onHello(empire: Empire) {
empires.put(empire.id, empire)
myEmpire = empire
App.eventBus.publish(empire)
}
/** Returns [true] if my empire has been set, or false if it's not ready yet. */
fun hasMyEmpire(): Boolean {
return myEmpire != null
}
/** Gets my empire, if my empire hasn't been set yet, IllegalStateException is thrown. */
fun getMyEmpire(): Empire {
return myEmpire!!
}
/** @return true if the given empire is mine.
*/
fun isMyEmpire(empire: Empire?): Boolean {
return if (empire?.id == null) {
false
} else empire.id == getMyEmpire().id
}
/** @return true if the given empire is an enemy of us.
*/
fun isEnemy(empire: Empire?): Boolean {
if (empire == null) {
return false
}
return myEmpire != null && empire.id != myEmpire!!.id
}
/**
* Gets the [Empire] with the given id. If the id is 0, returns a pseudo-Empire that
* can be used for native colonies/fleets.
*/
fun getEmpire(id: Long): Empire? {
if (id == 0L) {
return nativeEmpire
}
if (myEmpire != null && myEmpire!!.id == id) {
return myEmpire
}
val empire = empires[id]
if (empire == null) {
requestEmpire(id)
}
return empire
}
/**
* Request the [Empire] with the given ID from the server. To save a storm of requests when
* showing the chat screen (and others), we delay sending the request by a couple hundred
* milliseconds.
*/
private fun requestEmpire(id: Long) {
synchronized(pendingRequestLock) {
pendingEmpireRequests.add(id)
if (!requestPending) {
App.taskRunner.runTask({ sendPendingEmpireRequests() },
Threads.BACKGROUND,
EMPIRE_REQUEST_DELAY_MS)
}
}
}
/** Called on a background thread to actually send the request empire request to the server. */
private fun sendPendingEmpireRequests() {
var empireIds: List<Long>
synchronized(pendingRequestLock) {
empireIds = Lists.newArrayList(pendingEmpireRequests)
pendingEmpireRequests.clear()
requestPending = false
}
App.server.send(Packet(request_empire = RequestEmpirePacket(empire_id = empireIds)))
}
}
| mit |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/inheritance/classOneExtendsBaseWithOneParam.kt | 13 | 104 | internal open class Base(name: String?)
internal class One(name: String?, second: String?) : Base(name) | apache-2.0 |
smmribeiro/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/actions/EditorActions.kt | 7 | 5052 | package training.featuresSuggester.actions
import com.intellij.lang.Language
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import training.featuresSuggester.TextFragment
sealed class EditorAction : Action() {
abstract val editor: Editor
abstract val psiFile: PsiFile?
override val language: Language?
get() = psiFile?.language
override val project: Project?
get() = editor.project
val document: Document
get() = editor.document
protected fun getPsiFileFromEditor(): PsiFile? {
val project = editor.project ?: return null
return PsiDocumentManager.getInstance(project).getPsiFile(editor.document)
}
}
// -------------------------------------EDITOR AFTER ACTIONS-------------------------------------
data class EditorBackspaceAction(
val textFragment: TextFragment?,
val caretOffset: Int,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class EditorCopyAction(
val text: String,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class EditorCutAction(
val text: String,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class EditorPasteAction(
val text: String,
val caretOffset: Int,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class EditorTextInsertedAction(
val text: String,
val caretOffset: Int,
override val editor: Editor,
override val timeMillis: Long
) : EditorAction() {
override val psiFile: PsiFile?
get() = getPsiFileFromEditor()
}
data class EditorTextRemovedAction(
val textFragment: TextFragment,
val caretOffset: Int,
override val editor: Editor,
override val timeMillis: Long
) : EditorAction() {
override val psiFile: PsiFile?
get() = getPsiFileFromEditor()
}
data class EditorFindAction(
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class EditorCodeCompletionAction(
val caretOffset: Int,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class CompletionChooseItemAction(
val caretOffset: Int,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class EditorEscapeAction(
val caretOffset: Int,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class EditorFocusGainedAction(
override val editor: Editor,
override val timeMillis: Long
) : EditorAction() {
override val psiFile: PsiFile?
get() = getPsiFileFromEditor()
}
// -------------------------------------EDITOR BEFORE ACTIONS-------------------------------------
data class BeforeEditorBackspaceAction(
val textFragment: TextFragment?,
val caretOffset: Int,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class BeforeEditorCopyAction(
val text: String,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class BeforeEditorCutAction(
val textFragment: TextFragment?,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class BeforeEditorPasteAction(
val text: String,
val caretOffset: Int,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class BeforeEditorTextInsertedAction(
val text: String,
val caretOffset: Int,
override val editor: Editor,
override val timeMillis: Long
) : EditorAction() {
override val psiFile: PsiFile?
get() = getPsiFileFromEditor()
}
data class BeforeEditorTextRemovedAction(
val textFragment: TextFragment,
val caretOffset: Int,
override val editor: Editor,
override val timeMillis: Long
) : EditorAction() {
override val psiFile: PsiFile?
get() = getPsiFileFromEditor()
}
data class BeforeEditorFindAction(
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class BeforeEditorCodeCompletionAction(
val caretOffset: Int,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class BeforeCompletionChooseItemAction(
val caretOffset: Int,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
data class BeforeEditorEscapeAction(
val caretOffset: Int,
override val editor: Editor,
override val psiFile: PsiFile?,
override val timeMillis: Long
) : EditorAction()
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/wordSelection/ValueParametersInLambda3/0.kt | 12 | 103 | fun foo(f: (Int) -> Int) {}
fun test() {
foo { it ->
<caret>it + 1
it + 1
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/autoImports/ambiguousNamePreferFromJdk.after.kt | 3 | 147 | // "Import" "true"
// ERROR: Unresolved reference: Date
import java.util.*
import dependency.*
import java.util.Date
fun foo(d: Date<caret>) {
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/autoImports/enumEntries.kt | 10 | 98 | // "Import" "true"
package e
enum class ImportEnum {
RED, GREEN, BLUE
}
val v5 = <caret>BLUE | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findPropertyUsages/javaPropertyReadUsages2.0.kt | 1 | 366 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter
// OPTIONS: usages, skipWrite
package server
open class A<T>(open var <caret>foo: T)
open class B : A<String>("") {
override var foo: String
get() {
println("get")
return ""
}
set(value: String) {
println("set:" + value)
}
}
// FIR_IGNORE | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.