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 |
---|---|---|---|---|---|
ediTLJ/novelty | app/src/main/java/ro/edi/novelty/ui/viewmodel/FeedsViewModel.kt | 1 | 2682 | /*
* Copyright 2019 Eduard Scarlat
*
* 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 ro.edi.novelty.ui.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import ro.edi.novelty.R
import ro.edi.novelty.data.DataManager
import ro.edi.novelty.model.Feed
import ro.edi.novelty.model.TYPE_ATOM
import ro.edi.novelty.model.TYPE_RSS
class FeedsViewModel(application: Application) : AndroidViewModel(application) {
val feeds: LiveData<List<Feed>> by lazy(LazyThreadSafetyMode.NONE) {
DataManager.getInstance(getApplication()).getFeeds()
}
fun getFeed(position: Int): Feed? {
return feeds.value?.getOrNull(position)
}
fun getTypeTextRes(position: Int): Int {
getFeed(position)?.let {
return when (it.type) {
TYPE_ATOM -> R.string.type_atom
TYPE_RSS -> R.string.type_rss
else -> R.string.type_none
}
}
return R.string.type_none
}
fun getStarredImageRes(position: Int): Int {
getFeed(position)?.let {
return if (it.isStarred) R.drawable.ic_star else R.drawable.ic_star_border
}
return R.drawable.ic_star_border
}
fun setIsStarred(position: Int, isStarred: Boolean) {
getFeed(position)?.let {
DataManager.getInstance(getApplication()).updateFeedStarred(it, isStarred)
}
}
fun addFeed(title: String, url: String, type: Int, page: Int, isStarred: Boolean) {
DataManager.getInstance(getApplication()).insertFeed(title, url, type, page, isStarred)
}
fun updateFeed(feed: Feed, title: String, url: String) {
DataManager.getInstance(getApplication()).updateFeed(feed, title, url)
}
fun moveFeed(oldPosition: Int, newPosition: Int) {
val oldPositionFeed = getFeed(oldPosition) ?: return
val newPositionFeed = getFeed(newPosition) ?: return
DataManager.getInstance(getApplication()).swapFeedPages(oldPositionFeed, newPositionFeed)
}
fun deleteFeed(feed: Feed) {
DataManager.getInstance(getApplication()).deleteFeed(feed)
}
} | apache-2.0 |
airbnb/epoxy | kotlinsample/src/main/java/com/airbnb/epoxy/kotlinsample/EpoxyDataBindingPatterns.kt | 1 | 195 | package com.airbnb.epoxy.kotlinsample
import com.airbnb.epoxy.EpoxyDataBindingPattern
@EpoxyDataBindingPattern(rClass = R::class, layoutPrefix = "epoxy_layout")
object EpoxyDataBindingPatterns
| apache-2.0 |
Pagejects/pagejects-core | src/test/kotlin/net/pagejects/core/click/ClickUserActionTest.kt | 1 | 3980 | package net.pagejects.core.click
import com.codeborne.selenide.SelenideElement
import net.pagejects.core.annotation.Click
import net.pagejects.core.reflaction.findMethod
import net.pagejects.core.reflaction.userActionAnnotations
import net.pagejects.core.service.PageObjectService
import net.pagejects.core.service.SelenideElementService
import net.pagejects.core.testdata.PageObjectWithClickAction
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
import org.openqa.selenium.By
import org.testng.Assert.assertEquals
import org.testng.Assert.assertNotNull
import org.testng.annotations.BeforeClass
import org.testng.annotations.BeforeMethod
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
import java.util.function.Consumer
class ClickUserActionTest {
@Mock private lateinit var selenideElement: SelenideElement
private val selenideElementService: SelenideElementService = object : SelenideElementService {
override fun get(pageName: String, elementName: String): SelenideElement = selenideElement
override fun getBy(by: By): SelenideElement = selenideElement
}
private val pageObjectService: PageObjectService = object : PageObjectService {
override fun <T : Any?> pageObject(pageObjectClass: Class<T>): T = Mockito.mock(pageObjectClass)
}
@BeforeClass
fun setUpClass() {
MockitoAnnotations.initMocks(this)
}
@BeforeMethod
fun setUp() {
Mockito.reset(selenideElement)
}
@DataProvider(name = "dataForTest")
fun dataForTest(): Array<Array<Any>> {
return arrayOf(
arrayOf(
createClickUserAction("simpleClick"),
{
Mockito.verify(selenideElement).click()
Mockito.verifyNoMoreInteractions(selenideElement)
},
Consumer<Any?>() { assertEquals(it, Unit)}
),
arrayOf(
createClickUserAction("clickWithRedirectToPage"),
{
Mockito.verify(selenideElement).click()
Mockito.verifyNoMoreInteractions(selenideElement)
},
Consumer<Any?>(::assertNotNull)
),
arrayOf(
createClickUserAction("contextClick"),
{
Mockito.verify(selenideElement).contextClick()
Mockito.verifyNoMoreInteractions(selenideElement)
},
Consumer<Any?>() { assertEquals(it, Unit)}
),
arrayOf(
createClickUserAction("doubleClick"),
{
Mockito.verify(selenideElement).doubleClick()
Mockito.verifyNoMoreInteractions(selenideElement)
},
Consumer<Any?>() { assertEquals(it, Unit)}
)
)
}
private fun createClickUserAction(methodName: String): ClickUserAction {
val pageName = "somePage"
val method = PageObjectWithClickAction::class.findMethod(methodName)
val clickAnnotation = method.userActionAnnotations.single() as Click
val returnType = if (method.returnType == Void.TYPE) null else method.returnType
val clickUserAction = ClickUserAction(pageName, clickAnnotation, returnType)
clickUserAction.aware(pageObjectService)
clickUserAction.aware(selenideElementService)
return clickUserAction
}
@Test(dataProvider = "dataForTest")
fun testPerform(clickUserAction: ClickUserAction, checkClick: () -> Unit, checkResult: Consumer<Any?>) {
checkResult.accept(clickUserAction.perform(emptyArray()))
checkClick()
}
} | apache-2.0 |
dmillerw/LoreExpansion | src/main/kotlin/me/dmillerw/loreexpansion/adapter/KotlinAdapter.kt | 1 | 2992 | package me.dmillerw.loreexpansion.adapter
import net.minecraftforge.fml.common.FMLModContainer
import net.minecraftforge.fml.common.ILanguageAdapter
import net.minecraftforge.fml.common.ModContainer
import net.minecraftforge.fml.relauncher.Side
import org.apache.logging.log4j.LogManager
import java.lang.reflect.Field
import java.lang.reflect.Method
/**
* @author Arkan <[email protected]>
*/
public class KotlinAdapter : ILanguageAdapter {
companion object metadata {
public final val ADAPTER_VERSION: String = "@VERSION@-@KOTLIN@"
}
private val log = LogManager.getLogger("ILanguageAdapter/Kotlin")
override fun supportsStatics(): Boolean {
return false
}
override fun setProxy(target: Field, proxyTarget: Class<*>, proxy: Any) {
log.debug("Setting proxy: {}.{} -> {}", target.declaringClass.simpleName, target.name, proxy)
if (proxyTarget.fields.any { x -> x.getName().equals("INSTANCE$") }) {
// Singleton
try {
log.debug("Setting proxy on INSTANCE$; singleton target.")
val obj = proxyTarget.getField("INSTANCE$").get(null)
target.set(obj, proxy)
} catch (ex: Exception) {
throw KotlinAdapterException(ex)
}
} else {
//TODO Log?
target.set(proxyTarget, proxy)
}
}
override fun getNewInstance(container: FMLModContainer?, objectClass: Class<*>, classLoader: ClassLoader, factoryMarkedAnnotation: Method?): Any? {
log.debug("FML has asked for {} to be constructed...", objectClass.getSimpleName())
try {
// Try looking for an object type
val f = objectClass.getField("INSTANCE$")
val obj = f.get(null) ?: throw NullPointerException()
log.debug("Found an object INSTANCE$ reference in {}, using that. ({})", objectClass.getSimpleName(), obj)
return obj
} catch (ex: Exception) {
// Try looking for a class type
log.debug("Failed to get object reference, trying class construction.")
try {
val obj = objectClass.newInstance() ?: throw NullPointerException()
log.debug("Constructed an object from a class type ({}), using that. ({})", objectClass, obj)
log.warn("Hey, you, modder who owns {} - you should be using 'object' instead of 'class' on your @Mod class.", objectClass.getSimpleName())
return obj
} catch (ex: Exception) {
throw KotlinAdapterException(ex)
}
}
}
override fun setInternalProxies(mod: ModContainer?, side: Side?, loader: ClassLoader?) {
// Nothing to do; FML's got this covered for Kotlin.
}
private class KotlinAdapterException(ex:Exception): RuntimeException("Kotlin adapter error - do not report to Forge!", ex)
} | mit |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/autocomplete/receipt/ReceiptAutoCompletionProvider.kt | 2 | 1136 | package co.smartreceipts.android.autocomplete.receipt
import co.smartreceipts.android.autocomplete.AutoCompleteField
import co.smartreceipts.android.autocomplete.AutoCompletionProvider
import co.smartreceipts.core.di.scopes.ApplicationScope
import co.smartreceipts.android.model.Receipt
import co.smartreceipts.android.persistence.database.controllers.TableController
import co.smartreceipts.android.persistence.database.controllers.impl.ReceiptTableController
import java.util.*
import javax.inject.Inject
/**
* Implements the [AutoCompletionProvider] contract for [Receipt] instances
*/
@ApplicationScope
class ReceiptAutoCompletionProvider(override val autoCompletionType: Class<Receipt>,
override val tableController: TableController<Receipt>,
override val supportedAutoCompleteFields: List<AutoCompleteField>) : AutoCompletionProvider<Receipt> {
@Inject
constructor(tableController: ReceiptTableController) :
this(Receipt::class.java, tableController, Arrays.asList(ReceiptAutoCompleteField.Name, ReceiptAutoCompleteField.Comment))
} | agpl-3.0 |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/nbt/lang/psi/mixins/NbttLongMixin.kt | 1 | 342 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.psi.mixins
import com.demonwav.mcdev.nbt.lang.psi.NbttElement
import com.demonwav.mcdev.nbt.tags.TagLong
interface NbttLongMixin : NbttElement {
fun getLongTag(): TagLong
}
| mit |
BreakOutEvent/breakout-backend | src/main/java/backend/util/GeoTools.kt | 1 | 2184 | package backend.util
import backend.model.location.Location
import backend.model.location.SpeedToLocation
import backend.model.misc.Coord
import com.grum.geocalc.DegreeCoordinate
import com.grum.geocalc.EarthCalc
import com.grum.geocalc.Point
import java.time.temporal.ChronoUnit
/**
* Used Library Geocalc:
* Copyright (c) 2015, Grumlimited Ltd (Romain Gallet)
*
* https://github.com/grumlimited/geocalc
*
* Full License Text: https://github.com/grumlimited/geocalc/blob/master/LICENSE.txt
*/
fun speedToLocation(toLocation: Location, fromLocation: Location): SpeedToLocation? {
val secondsDifference = toLocation.date.until(fromLocation.date, ChronoUnit.SECONDS)
val distanceKm = distanceCoordsKM(fromLocation.coord, toLocation.coord)
return calculateSpeed(distanceKm, secondsDifference)
}
fun calculateSpeed(distanceKm: Double, secondsDifference: Long): SpeedToLocation? {
return if (distanceKm > 0 && secondsDifference > 0) {
val speed = distanceKm / (secondsDifference / 3600.0)
SpeedToLocation(speed, secondsDifference, distanceKm)
} else {
null
}
}
fun distanceCoordsKM(from: Coord, to: Coord): Double {
val fromPoint: Point = coordToPoint(from)
val toPoint: Point = coordToPoint(to)
return EarthCalc.getVincentyDistance(fromPoint, toPoint) / 1000
}
fun distanceCoordsListKMfromStart(startingPoint: Coord, list: List<Coord>): Double {
val coordsList = arrayListOf(startingPoint)
coordsList.addAll(list)
return distanceCoordsListKM(coordsList)
}
fun distanceCoordsListKM(list: List<Coord>): Double = coordsListToPairList(list).fold(0.0) { total, (first, second) -> total + distanceCoordsKM(first, second) }
fun coordsListToPairList(list: List<Coord>): List<Pair<Coord, Coord>> {
val coordPairs: MutableList<Pair<Coord, Coord>> = arrayListOf()
var lastCoord: Coord? = null
list.forEach { thisCoord ->
if (lastCoord != null) {
coordPairs.add(Pair(lastCoord!!, thisCoord))
}
lastCoord = thisCoord
}
return coordPairs
}
fun coordToPoint(coord: Coord): Point = Point(DegreeCoordinate(coord.latitude), DegreeCoordinate(coord.longitude)) | agpl-3.0 |
paplorinc/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestThread.kt | 1 | 5512 | // 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.impl
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.framework.param.GuiTestLocalRunnerParam
import com.intellij.testGuiFramework.launcher.GuiTestOptions
import com.intellij.testGuiFramework.launcher.GuiTestOptions.RESUME_LABEL
import com.intellij.testGuiFramework.remote.JUnitClientListener
import com.intellij.testGuiFramework.remote.client.ClientHandler
import com.intellij.testGuiFramework.remote.client.JUnitClient
import com.intellij.testGuiFramework.remote.client.JUnitClientImpl
import com.intellij.testGuiFramework.remote.transport.JUnitTestContainer
import com.intellij.testGuiFramework.remote.transport.MessageType
import com.intellij.testGuiFramework.remote.transport.TransportMessage
import org.junit.runner.JUnitCore
import org.junit.runner.Request
import org.junit.runners.model.TestClass
import org.junit.runners.parameterized.TestWithParameters
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
/**
* @author Sergey Karashevich
*/
class GuiTestThread : Thread(GUI_TEST_THREAD_NAME) {
private var testQueue: BlockingQueue<JUnitTestContainer> = LinkedBlockingQueue()
private val core = JUnitCore()
private val LOG = Logger.getInstance("#com.intellij.testGuiFramework.impl.GuiTestThread")
companion object {
const val GUI_TEST_THREAD_NAME: String = "GuiTest Thread"
var client: JUnitClient? = null
}
override fun run() {
client = JUnitClientImpl(host(), port(), createInitHandlers())
client!!.addHandler(createCloseHandler())
val myListener = JUnitClientListener { jUnitInfo -> client!!.send(TransportMessage(MessageType.JUNIT_INFO, jUnitInfo)) }
core.addListener(myListener)
try {
while (true) {
val testContainer = testQueue.take()
LOG.info("Running test: $testContainer")
runTest(testContainer)
}
}
catch (e: InterruptedException) {
Thread.currentThread().interrupt()
}
}
private fun createInitHandlers(): Array<ClientHandler> {
val testHandler = object : ClientHandler {
override fun accept(message: TransportMessage) = message.type == MessageType.RUN_TEST
override fun handle(message: TransportMessage) {
val content = (message.content as JUnitTestContainer)
LOG.info("Added test to testQueue: $content")
testQueue.add(content)
}
}
val testResumeHandler = object : ClientHandler {
override fun accept(message: TransportMessage) = message.type == MessageType.RESUME_TEST
override fun handle(message: TransportMessage) {
val content = (message.content as JUnitTestContainer)
if (!content.additionalInfo.containsKey(RESUME_LABEL)) throw Exception(
"Cannot resume test without any additional info (label where to resume) in JUnitTestContainer")
System.setProperty(GuiTestOptions.RESUME_LABEL, content.additionalInfo[RESUME_LABEL].toString())
System.setProperty(GuiTestOptions.RESUME_TEST, "${content.testClassName}#${content.testName}")
LOG.info("Added test to testQueue: $content")
testQueue.add(content)
}
}
return arrayOf(testHandler, testResumeHandler)
}
private fun createCloseHandler(): ClientHandler {
return object : ClientHandler {
override fun accept(message: TransportMessage) = message.type == MessageType.CLOSE_IDE
override fun handle(message: TransportMessage) {
client?.send(TransportMessage(MessageType.RESPONSE, null, message.id)) ?: throw Exception(
"Unable to handle transport message: \"$message\", because JUnitClient is accidentally null")
val application = ApplicationManager.getApplication()
(application as ApplicationImpl).exit(true, true)
}
}
}
private fun host(): String = System.getProperty(GuiTestStarter.GUI_TEST_HOST)
private fun port(): Int = System.getProperty(GuiTestStarter.GUI_TEST_PORT).toInt()
private fun runTest(testContainer: JUnitTestContainer) {
val testClass: Class<*> =
try {
Class.forName(testContainer.testClassName)
} catch (e: ClassNotFoundException) {
loadClassFromPlugins(testContainer.testClassName)
}
if (testContainer.additionalInfo["parameters"] == null) {
//todo: replace request with a runner
val request = Request.method(testClass, testContainer.testName)
core.run(request)
} else {
val runner = GuiTestLocalRunnerParam(TestWithParameters(testContainer.testName, TestClass(testClass), testContainer.additionalInfo["parameters"] as MutableList<*>))
core.run(runner)
}
}
private fun loadClassFromPlugins(className: String): Class<*> {
return PluginManagerCore.getPlugins().firstOrNull {
try {
it.pluginClassLoader.loadClass(className)
true
} catch (e: ClassNotFoundException) {
false
}
}?.let { it.pluginClassLoader.loadClass(className) } ?: throw ClassNotFoundException("Unable to find class ($className) in IDE plugin classloaders")
}
private fun String.getParameterisedPart(): String {
return Regex("\\[(.)*]").find(this)?.value ?: ""
}
} | apache-2.0 |
esafirm/android-playground | app/src/main/java/com/esafirm/androidplayground/rxjava2/RxJava2ObservableFlowableAct.kt | 1 | 1291 | package com.esafirm.androidplayground.rxjava2
import android.os.Bundle
import com.esafirm.androidplayground.common.BaseAct
import com.esafirm.androidplayground.libs.Logger
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit
class RxJava2ObservableFlowableAct : BaseAct() {
private var disposable: Disposable? = null
private var secondDisposable: Disposable? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Logger.clear()
setContentView(Logger.getLogView(this))
disposable = Observable.interval(200, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.forEach { aLong -> Logger.log("Observable:$aLong") }
secondDisposable = Flowable.interval(200, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.onBackpressureLatest() // Flowable can be backpressured
.forEach { aLong -> Logger.log("Flowable:$aLong") }
}
override fun onDestroy() {
disposable?.dispose()
secondDisposable?.dispose()
super.onDestroy()
}
}
| mit |
PaulWoitaschek/MaterialAudiobookPlayer | app/src/main/java/de/ph1b/audiobook/misc/ElevateToolbarOnScroll.kt | 1 | 838 | package de.ph1b.audiobook.misc
import androidx.appcompat.widget.Toolbar
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import androidx.recyclerview.widget.RecyclerView
class ElevateToolbarOnScroll(val toolbar: Toolbar) : RecyclerView.OnScrollListener() {
private val interpolator = FastOutSlowInInterpolator()
private val finalElevation = toolbar.context.dpToPxRounded(4F)
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
val toolbarHeight = toolbar.height
if (toolbarHeight == 0) {
return
}
val scrollY = recyclerView.computeVerticalScrollOffset()
val fraction = (scrollY.toFloat() / toolbarHeight).coerceIn(0F, 1F)
val interpolatedFraction = interpolator.getInterpolation(fraction)
toolbar.elevation = interpolatedFraction * finalElevation
}
}
| lgpl-3.0 |
paplorinc/intellij-community | plugins/stats-collector/features/src/com/jetbrains/completion/feature/FeatureInterpreter.kt | 6 | 975 | /*
* Copyright 2000-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 com.jetbrains.completion.feature
interface FeatureInterpreter {
fun binary(name: String, description: Map<String, Double>, order: Map<String, Int>): BinaryFeature
fun double(name: String, defaultValue: Double, order: Map<String, Int>): DoubleFeature
fun categorical(name: String, categories: Set<String>, order: Map<String, Int>): CategoricalFeature
}
| apache-2.0 |
aahlenst/spring-boot | spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/howto/dataaccess/usemultipleentitymanagers/OrderConfiguration.kt | 10 | 1023 | /*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.boot.docs.howto.dataaccess.usemultipleentitymanagers
import org.springframework.context.annotation.Configuration
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
@Configuration(proxyBeanMethods = false)
@EnableJpaRepositories(basePackageClasses = [Order::class], entityManagerFactoryRef = "firstEntityManagerFactory")
class OrderConfiguration
| apache-2.0 |
igorini/kotlin-android-app | app/src/main/java/com/igorini/kotlin/android/app/MainActivity.kt | 1 | 950 | package com.igorini.kotlin.android.app
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Window
import android.widget.Button
import android.widget.EditText
import org.jetbrains.anko.*
/** Represents a main activity */
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_NO_TITLE)
setContentView(R.layout.activity_main)
}
}
/** Represents a main activity UI */
/*class MainActivityUi : AnkoComponent<MainActivity> {
private val customStyle = { v: Any ->
when (v) {
is Button -> v.textSize = 26f
is EditText -> v.textSize = 24f
}
}
override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
verticalLayout {
padding = dip(32)
}.applyRecursively(customStyle)
}
}*/
| apache-2.0 |
apollographql/apollo-android | apollo-runtime/src/commonMain/kotlin/com/apollographql/apollo3/internal/NonMainWorker.kt | 1 | 129 | package com.apollographql.apollo3.internal
internal expect class NonMainWorker() {
suspend fun <R> doWork(block: () -> R): R
} | mit |
JetBrains/intellij-community | plugins/kotlin/idea/tests/testData/decompiler/stubBuilder/InheritingClasses/InheritingClasses.kt | 1 | 979 | package a
class InheritingClasses {
abstract class A(override val c: Int = 1) : C {
open fun of() = 3
abstract fun af(): Int
open val op = 4
abstract val ap: Int
}
open class B : A(2) {
override fun of() = 4
override fun af() = 5
override val op = 5
override val ap = 5
}
interface C {
val c: Int
}
interface D<T> : C {
override val c: Int
}
interface E
class G : B(), C, D<Int>, E
class InheritAny {
interface SomeInterface
interface SomeInterface2
class ImplicitAny
class ExplicitAny : Any()
class OnlyInterface : SomeInterface
class OnlyInterfaces : SomeInterface, SomeInterface2
class InterfaceWithExplicitAny : Any(), SomeInterface
class InterfacesWithExplicitAny : SomeInterface2, Any(), SomeInterface
}
abstract class InheritFunctionType : ((Int, String) -> Int)
} | apache-2.0 |
JetBrains/intellij-community | platform/analysis-impl/src/com/intellij/profile/codeInspection/ProjectInspectionProfileManager.kt | 1 | 9890 | // Copyright 2000-2021 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.profile.codeInspection
import com.intellij.codeInspection.ex.InspectionProfileImpl
import com.intellij.codeInspection.ex.InspectionToolRegistrar
import com.intellij.configurationStore.*
import com.intellij.diagnostic.runActivity
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.packageDependencies.DependencyValidationManager
import com.intellij.profile.ProfileChangeAdapter
import com.intellij.project.isDirectoryBased
import com.intellij.psi.search.scope.packageSet.NamedScopeManager
import com.intellij.psi.search.scope.packageSet.NamedScopesHolder
import com.intellij.util.xmlb.annotations.OptionTag
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.util.function.Function
private const val VERSION = "1.0"
const val PROJECT_DEFAULT_PROFILE_NAME = "Project Default"
private val defaultSchemeDigest = JDOMUtil.load("""<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
</profile>
</component>""").digest()
const val PROFILE_DIR: String = "inspectionProfiles"
const val PROFILES_SETTINGS: String = "profiles_settings.xml"
@State(name = "InspectionProjectProfileManager", storages = [(Storage(value = "$PROFILE_DIR/profiles_settings.xml", exclusive = true))])
open class ProjectInspectionProfileManager(override val project: Project) : BaseInspectionProfileManager(project.messageBus), PersistentStateComponentWithModificationTracker<Element>, ProjectBasedInspectionProfileManager, Disposable {
companion object {
@JvmStatic
fun getInstance(project: Project): ProjectInspectionProfileManager {
return project.getService(InspectionProjectProfileManager::class.java) as ProjectInspectionProfileManager
}
}
private var state = ProjectInspectionProfileManagerState()
protected val schemeManagerIprProvider = if (project.isDirectoryBased) null else SchemeManagerIprProvider("profile")
override val schemeManager = SchemeManagerFactory.getInstance(project).create(PROFILE_DIR, object : InspectionProfileProcessor() {
override fun createScheme(dataHolder: SchemeDataHolder<InspectionProfileImpl>,
name: String,
attributeProvider: Function<in String, String?>,
isBundled: Boolean): InspectionProfileImpl {
val profile = InspectionProfileImpl(name, InspectionToolRegistrar.getInstance(), this@ProjectInspectionProfileManager, dataHolder)
profile.isProjectLevel = true
return profile
}
override fun isSchemeFile(name: CharSequence) = !StringUtil.equals(name, PROFILES_SETTINGS)
override fun isSchemeDefault(scheme: InspectionProfileImpl, digest: ByteArray): Boolean {
return scheme.name == PROJECT_DEFAULT_PROFILE_NAME && digest.contentEquals(defaultSchemeDigest)
}
override fun onSchemeDeleted(scheme: InspectionProfileImpl) {
schemeRemoved(scheme)
}
override fun onSchemeAdded(scheme: InspectionProfileImpl) {
if (scheme.wasInitialized()) {
fireProfileChanged(scheme)
}
}
override fun onCurrentSchemeSwitched(oldScheme: InspectionProfileImpl?,
newScheme: InspectionProfileImpl?,
processChangeSynchronously: Boolean) {
project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profileActivated(oldScheme, newScheme)
}
}, schemeNameToFileName = OLD_NAME_CONVERTER, streamProvider = schemeManagerIprProvider)
override fun initializeComponent() {
val app = ApplicationManager.getApplication()
if (!project.isDirectoryBased || app.isUnitTestMode) {
return
}
runActivity("project inspection profile loading") {
schemeManager.loadSchemes()
currentProfile.initInspectionTools(project)
}
StartupManager.getInstance(project).runAfterOpened {
project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profilesInitialized()
val projectScopeListener = NamedScopesHolder.ScopeListener {
for (profile in schemeManager.allSchemes) {
profile.scopesChanged()
}
}
scopesManager.addScopeListener(projectScopeListener, project)
NamedScopeManager.getInstance(project).addScopeListener(projectScopeListener, project)
}
}
override fun dispose() {
val cleanupInspectionProfilesRunnable = {
cleanupSchemes(project)
(serviceIfCreated<InspectionProfileManager>() as BaseInspectionProfileManager?)?.cleanupSchemes(project)
}
val app = ApplicationManager.getApplication()
if (app.isUnitTestMode || app.isHeadlessEnvironment) {
cleanupInspectionProfilesRunnable.invoke()
}
else {
app.executeOnPooledThread(cleanupInspectionProfilesRunnable)
}
}
override fun getStateModificationCount() = state.modificationCount + severityRegistrar.modificationCount + (schemeManagerIprProvider?.modificationCount ?: 0)
@TestOnly
fun forceLoadSchemes() {
LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode)
schemeManager.loadSchemes()
}
fun isCurrentProfileInitialized() = currentProfile.wasInitialized()
override fun schemeRemoved(scheme: InspectionProfileImpl) {
scheme.cleanup(project)
}
@Synchronized
override fun getState(): Element? {
val result = Element("settings")
schemeManagerIprProvider?.writeState(result)
serializeObjectInto(state, result)
if (result.children.isNotEmpty()) {
result.addContent(Element("version").setAttribute("value", VERSION))
}
severityRegistrar.writeExternal(result)
return wrapState(result, project)
}
@Synchronized
override fun loadState(state: Element) {
val data = unwrapState(state, project, schemeManagerIprProvider, schemeManager)
val newState = ProjectInspectionProfileManagerState()
data?.let {
try {
severityRegistrar.readExternal(it)
}
catch (e: Throwable) {
LOG.error(e)
}
it.deserializeInto(newState)
}
this.state = newState
if (data != null && data.getChild("version")?.getAttributeValue("value") != VERSION) {
for (o in data.getChildren("option")) {
if (o.getAttributeValue("name") == "USE_PROJECT_LEVEL_SETTINGS") {
if (o.getAttributeBooleanValue("value") && newState.projectProfile != null) {
currentProfile.convert(data, project)
}
break
}
}
}
}
override fun getScopesManager() = DependencyValidationManager.getInstance(project)
@Synchronized
override fun getProfiles(): Collection<InspectionProfileImpl> {
currentProfile
return schemeManager.allSchemes
}
val projectProfile: String?
get() = state.projectProfile
@Synchronized
override fun setRootProfile(name: String?) {
state.useProjectProfile = name != null
if (name != null) {
state.projectProfile = name
}
schemeManager.setCurrentSchemeName(name, true)
}
@Synchronized
fun useApplicationProfile(name: String) {
state.useProjectProfile = false
// yes, we reuse the same field - useProjectProfile field will be used to distinguish - is it app or project level
// to avoid data format change
state.projectProfile = name
}
@Synchronized
@TestOnly
fun setCurrentProfile(profile: InspectionProfileImpl?) {
schemeManager.setCurrent(profile)
state.useProjectProfile = profile != null
if (profile != null) {
state.projectProfile = profile.name
}
}
@Synchronized
override fun getCurrentProfile(): InspectionProfileImpl {
if (!state.useProjectProfile) {
val applicationProfileManager = InspectionProfileManager.getInstance()
return (state.projectProfile?.let {
applicationProfileManager.getProfile(it, false)
} ?: applicationProfileManager.currentProfile)
}
var currentScheme = state.projectProfile?.let { schemeManager.findSchemeByName(it) }
if (currentScheme == null) {
currentScheme = schemeManager.allSchemes.firstOrNull()
if (currentScheme == null) {
currentScheme = InspectionProfileImpl(PROJECT_DEFAULT_PROFILE_NAME, InspectionToolRegistrar.getInstance(), this)
currentScheme.copyFrom(InspectionProfileManager.getInstance().currentProfile)
currentScheme.isProjectLevel = true
currentScheme.name = PROJECT_DEFAULT_PROFILE_NAME
schemeManager.addScheme(currentScheme)
}
schemeManager.setCurrent(currentScheme, false)
}
return currentScheme
}
@Synchronized
override fun getProfile(name: String, returnRootProfileIfNamedIsAbsent: Boolean): InspectionProfileImpl? {
val profile = schemeManager.findSchemeByName(name)
return profile ?: InspectionProfileManager.getInstance().getProfile(name, returnRootProfileIfNamedIsAbsent)
}
fun fireProfileChanged() {
fireProfileChanged(currentProfile)
}
override fun fireProfileChanged(profile: InspectionProfileImpl) {
profile.profileChanged()
project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profileChanged(profile)
}
}
private class ProjectInspectionProfileManagerState : BaseState() {
@get:OptionTag("PROJECT_PROFILE")
var projectProfile by string(PROJECT_DEFAULT_PROFILE_NAME)
@get:OptionTag("USE_PROJECT_PROFILE")
var useProjectProfile by property(true)
}
| apache-2.0 |
JetBrains/intellij-community | plugins/devkit/devkit-kotlin-tests/testData/inspections/useCoupleFix/UseCoupleOfFactoryMethodInVariableWhenPairCreateUsed_after.kt | 1 | 245 | import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.Pair
@Suppress("UNUSED_VARIABLE")
class UseCoupleOfFactoryMethodInVariableWhenPairCreateUsed {
fun any() {
val any: Pair<String, String> = Couple.of("a", "b")
}
}
| apache-2.0 |
JetBrains/intellij-community | plugins/kotlin/completion/testData/injava/mockLib/mockLib/foo/main.kt | 1 | 887 | package mockLib.foo
public class LibClass {
public fun foo() {
}
companion object {
fun classObjectFun() {
}
public object NestedObject
}
public class Nested {
public val valInNested: Int = 1
public fun funInNested() {
}
}
public val nested: Nested = Nested()
}
public interface LibInterface {
public fun foo() {
}
}
public enum class LibEnum {
RED,
GREEN,
BLUE
}
public object LibObject
public fun topLevelFunction(): String = ""
public fun String.topLevelExtFunction(): String = ""
public var topLevelVar: String = ""
class F() {
companion object {
class F {
companion object {
object F {
}
}
}
}
}
interface MyInterface {
fun foo() = 1
}
annotation class Anno(val c: Int = 3, val d: String) | apache-2.0 |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/archmodel/FeedStore.kt | 1 | 4839 | package com.nononsenseapps.feeder.archmodel
import com.nononsenseapps.feeder.db.room.Feed
import com.nononsenseapps.feeder.db.room.FeedDao
import com.nononsenseapps.feeder.db.room.FeedTitle
import com.nononsenseapps.feeder.db.room.ID_UNSET
import com.nononsenseapps.feeder.db.room.upsertFeed
import com.nononsenseapps.feeder.model.FeedUnreadCount
import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerFeed
import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerItemWithUnreadCount
import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerTag
import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerTop
import java.net.URL
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.mapLatest
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.instance
import org.threeten.bp.Instant
class FeedStore(override val di: DI) : DIAware {
private val feedDao: FeedDao by instance()
// Need only be internally consistent within the composition
// this object outlives all compositions
private var nextTagUiId: Long = -1000
// But IDs need to be consistent even if tags come and go
private val tagUiIds = mutableMapOf<String, Long>()
private fun getTagUiId(tag: String): Long {
return tagUiIds.getOrPut(tag) {
--nextTagUiId
}
}
suspend fun getFeed(feedId: Long): Feed? = feedDao.loadFeed(feedId)
suspend fun getFeed(url: URL): Feed? = feedDao.loadFeedWithUrl(url)
suspend fun saveFeed(feed: Feed): Long {
return if (feed.id > ID_UNSET) {
feedDao.updateFeed(feed)
feed.id
} else {
feedDao.insertFeed(feed)
}
}
suspend fun getDisplayTitle(feedId: Long): String? =
feedDao.getFeedTitle(feedId)?.displayTitle
suspend fun deleteFeeds(feedIds: List<Long>) {
feedDao.deleteFeeds(feedIds)
}
val allTags: Flow<List<String>> = feedDao.loadAllTags()
@OptIn(ExperimentalCoroutinesApi::class)
val drawerItemsWithUnreadCounts: Flow<List<DrawerItemWithUnreadCount>> =
feedDao.loadFlowOfFeedsWithUnreadCounts()
.mapLatest { feeds ->
mapFeedsToSortedDrawerItems(feeds)
}
private fun mapFeedsToSortedDrawerItems(
feeds: List<FeedUnreadCount>,
): List<DrawerItemWithUnreadCount> {
var topTag = DrawerTop(unreadCount = 0, totalChildren = 0)
val tags: MutableMap<String, DrawerTag> = mutableMapOf()
val data: MutableList<DrawerItemWithUnreadCount> = mutableListOf()
for (feedDbo in feeds) {
val feed = DrawerFeed(
unreadCount = feedDbo.unreadCount,
tag = feedDbo.tag,
id = feedDbo.id,
displayTitle = feedDbo.displayTitle,
imageUrl = feedDbo.imageUrl,
)
data.add(feed)
topTag = topTag.copy(
unreadCount = topTag.unreadCount + feed.unreadCount,
totalChildren = topTag.totalChildren + 1,
)
if (feed.tag.isNotEmpty()) {
val tag = tags[feed.tag] ?: DrawerTag(
tag = feed.tag,
unreadCount = 0,
uiId = getTagUiId(feed.tag),
totalChildren = 0,
)
tags[feed.tag] = tag.copy(
unreadCount = tag.unreadCount + feed.unreadCount,
totalChildren = tag.totalChildren + 1,
)
}
}
data.add(topTag)
data.addAll(tags.values)
return data.sorted()
}
fun getFeedTitles(feedId: Long, tag: String): Flow<List<FeedTitle>> =
when {
feedId > ID_UNSET -> feedDao.getFeedTitlesWithId(feedId)
tag.isNotBlank() -> feedDao.getFeedTitlesWithTag(tag)
else -> feedDao.getAllFeedTitles()
}
fun getCurrentlySyncingLatestTimestamp(): Flow<Instant?> =
feedDao.getCurrentlySyncingLatestTimestamp()
suspend fun setCurrentlySyncingOn(feedId: Long, syncing: Boolean, lastSync: Instant? = null) {
if (lastSync != null) {
feedDao.setCurrentlySyncingOn(feedId = feedId, syncing = syncing, lastSync = lastSync)
} else {
feedDao.setCurrentlySyncingOn(feedId = feedId, syncing = syncing)
}
}
suspend fun upsertFeed(feedSql: Feed) =
feedDao.upsertFeed(feed = feedSql)
suspend fun getFeedsOrderedByUrl(): List<Feed> {
return feedDao.getFeedsOrderedByUrl()
}
fun getFlowOfFeedsOrderedByUrl(): Flow<List<Feed>> {
return feedDao.getFlowOfFeedsOrderedByUrl()
}
suspend fun deleteFeed(url: URL) {
feedDao.deleteFeedWithUrl(url)
}
}
| gpl-3.0 |
raybritton/json-query | cli/src/main/kotlin/com/raybritton/jsonquery/JsonLoader.kt | 1 | 788 | package com.raybritton.jsonquery
import java.io.File
import java.net.URL
import kotlin.streams.toList
internal class JsonLoader {
fun load(input: String): String {
val input = input.trim()
when {
input.startsWith("{") || input.startsWith("[") -> { return input }
input.startsWith("http") -> { return loadFromUrl(input) }
else -> { return loadFromFile(input) }
}
}
private fun loadFromFile(path: String): String {
val file = File(path)
return file.readLines().joinToString("")
}
private fun loadFromUrl(url: String): String {
return URL(url).openStream()
.bufferedReader()
.lines()
.toList()
.joinToString("")
}
} | apache-2.0 |
sheaam30/setlist | app/src/main/java/setlist/shea/setlist/redux/Action.kt | 1 | 96 | package setlist.shea.setlist.redux
/**
* Created by adamshea on 12/30/17.
*/
interface Action | apache-2.0 |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/GHRepositoryOwnerName.kt | 3 | 800 | // 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 org.jetbrains.plugins.github.api.data
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "__typename", visible = false)
@JsonSubTypes(
JsonSubTypes.Type(name = "User", value = GHRepositoryOwnerName.User::class),
JsonSubTypes.Type(name = "Organization", value = GHRepositoryOwnerName.Organization::class)
)
interface GHRepositoryOwnerName {
val login: String
class User(override val login: String) : GHRepositoryOwnerName
class Organization(override val login: String) : GHRepositoryOwnerName
}
| apache-2.0 |
allotria/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/FileNode.kt | 2 | 2422 | // 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.analysis.problemsView.toolWindow
import com.intellij.icons.AllIcons
import com.intellij.ide.projectView.PresentationData
import com.intellij.ide.projectView.impl.CompoundIconProvider.findIcon
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil.getLocationRelativeToUserHome
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.PsiUtilCore.findFileSystemItem
import com.intellij.ui.SimpleTextAttributes.GRAYED_ATTRIBUTES
import com.intellij.ui.SimpleTextAttributes.REGULAR_ATTRIBUTES
import com.intellij.ui.tree.LeafState
import java.util.Objects.hash
internal class FileNode(parent: Node, val file: VirtualFile) : Node(parent) {
override fun getLeafState() = if (parentDescriptor is Root) LeafState.NEVER else LeafState.DEFAULT
override fun getName() = file.presentableName ?: file.name
override fun getVirtualFile() = file
override fun getDescriptor() = project?.let { OpenFileDescriptor(it, file) }
override fun update(project: Project, presentation: PresentationData) {
presentation.addText(name, REGULAR_ATTRIBUTES)
presentation.setIcon(findIcon(findFileSystemItem(project, file), 0) ?: when (file.isDirectory) {
true -> AllIcons.Nodes.Folder
else -> AllIcons.FileTypes.Any_type
})
if (parentDescriptor !is FileNode) {
val url = file.parent?.presentableUrl ?: return
presentation.addText(" ${getLocationRelativeToUserHome(url)}", GRAYED_ATTRIBUTES)
}
val root = findAncestor(Root::class.java)
val count = root?.getFileProblemCount(file) ?: 0
if (count > 0) {
val text = ProblemsViewBundle.message("problems.view.file.problems", count)
presentation.addText(" $text", GRAYED_ATTRIBUTES)
}
}
override fun getChildren(): Collection<Node> {
val root = findAncestor(Root::class.java)
return root?.getChildren(file) ?: super.getChildren()
}
override fun hashCode() = hash(project, file)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (this.javaClass != other?.javaClass) return false
val that = other as? FileNode ?: return false
return that.project == project && that.file == file
}
}
| apache-2.0 |
ursjoss/sipamato | core/core-sync/src/adhoc-test/kotlin/ch/difty/scipamato/core/sync/launcher/RefDataSyncJobLauncherAdHocTest.kt | 2 | 552 | package ch.difty.scipamato.core.sync.launcher
import org.amshove.kluent.shouldBeTrue
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
internal open class RefDataSyncJobLauncherAdHocTest {
@Autowired
private lateinit var launcher: RefDataSyncJobLauncher
@Test
fun run() {
val result = launcher.launch()
result.messages.forEach { println(it) }
result.isSuccessful.shouldBeTrue()
}
}
| gpl-3.0 |
Kotlin/kotlinx.coroutines | ui/kotlinx-coroutines-javafx/test/guide/example-ui-blocking-01.kt | 1 | 2315 | /*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
// This file was automatically generated from coroutines-guide-ui.md by Knit tool. Do not edit.
package kotlinx.coroutines.javafx.guide.exampleUiBlocking01
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.javafx.JavaFx as Main
import javafx.application.Application
import javafx.event.EventHandler
import javafx.geometry.*
import javafx.scene.*
import javafx.scene.input.MouseEvent
import javafx.scene.layout.StackPane
import javafx.scene.paint.Color
import javafx.scene.shape.Circle
import javafx.scene.text.Text
import javafx.stage.Stage
fun main(args: Array<String>) {
Application.launch(ExampleApp::class.java, *args)
}
class ExampleApp : Application() {
val hello = Text("Hello World!").apply {
fill = Color.valueOf("#C0C0C0")
}
val fab = Circle(20.0, Color.valueOf("#FF4081"))
val root = StackPane().apply {
children += hello
children += fab
StackPane.setAlignment(hello, Pos.CENTER)
StackPane.setAlignment(fab, Pos.BOTTOM_RIGHT)
StackPane.setMargin(fab, Insets(15.0))
}
val scene = Scene(root, 240.0, 380.0).apply {
fill = Color.valueOf("#303030")
}
override fun start(stage: Stage) {
stage.title = "Example"
stage.scene = scene
stage.show()
setup(hello, fab)
}
}
fun Node.onClick(action: suspend (MouseEvent) -> Unit) {
val eventActor = GlobalScope.actor<MouseEvent>(Dispatchers.Main, capacity = Channel.CONFLATED) {
for (event in channel) action(event) // pass event to action
}
onMouseClicked = EventHandler { event ->
eventActor.trySend(event)
}
}
fun fib(x: Int): Int =
if (x <= 1) x else fib(x - 1) + fib(x - 2)
fun setup(hello: Text, fab: Circle) {
var result = "none" // the last result
// counting animation
GlobalScope.launch(Dispatchers.Main) {
var counter = 0
while (true) {
hello.text = "${++counter}: $result"
delay(100) // update the text every 100ms
}
}
// compute the next fibonacci number of each click
var x = 1
fab.onClick {
result = "fib($x) = ${fib(x)}"
x++
}
}
| apache-2.0 |
ParaskP7/sample-code-posts-kotlin | app/src/main/java/io/petros/posts/kotlin/app/Dependencies.kt | 1 | 1853 | package io.petros.posts.kotlin.app
import android.arch.persistence.room.Room
import android.content.Context
import com.github.salomonbrys.kodein.Kodein
import io.petros.posts.kotlin.R
import io.petros.posts.kotlin.activity.posts.fragment.adapter.PostsAdapter
import io.petros.posts.kotlin.datastore.db.CommentDao
import io.petros.posts.kotlin.datastore.db.PostDao
import io.petros.posts.kotlin.datastore.db.PostsDatabase
import io.petros.posts.kotlin.datastore.db.UserDao
import io.petros.posts.kotlin.service.retrofit.WebService
import io.petros.posts.kotlin.util.rx.RxSchedulers
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
fun constructPostsAdapter(kodein: Kodein): PostsAdapter = PostsAdapter(kodein)
fun constructRxSchedulers(): RxSchedulers {
return RxSchedulers(Schedulers.io(), Schedulers.computation(), Schedulers.trampoline(), AndroidSchedulers.mainThread())
}
fun constructWebService(context: Context): WebService {
val retrofit = Retrofit.Builder()
.baseUrl(context.getString(R.string.posts_url))
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
return retrofit.create(WebService::class.java)
}
fun constructPostsDatabase(context: Context): PostsDatabase = Room.databaseBuilder(context, PostsDatabase::class.java, "posts.db")
.build()
fun constructUserDao(postsDatabase: PostsDatabase): UserDao = postsDatabase.userDao()
fun constructPostDao(postsDatabase: PostsDatabase): PostDao = postsDatabase.postDao()
fun constructCommentDao(postsDatabase: PostsDatabase): CommentDao = postsDatabase.commentDao()
| apache-2.0 |
neo4j-graphql/neo4j-graphql | src/test/java/org/neo4j/graphql/FilterUserRelationsTest.kt | 1 | 2940 | package org.neo4j.graphql
import graphql.GraphQL
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.neo4j.graphdb.GraphDatabaseService
import org.neo4j.kernel.impl.proc.Procedures
import org.neo4j.kernel.internal.GraphDatabaseAPI
import org.neo4j.test.TestGraphDatabaseFactory
import kotlin.test.assertEquals
/**
* @author mh
* *
* @since 05.05.17
*/
class FilterUserRelationsTest {
private lateinit var db: GraphDatabaseService
private lateinit var ctx: GraphQLContext
private var graphQL: GraphQL? = null
@Before
@Throws(Exception::class)
fun setUp() {
db = TestGraphDatabaseFactory().newImpermanentDatabase()
(db as GraphDatabaseAPI).dependencyResolver.resolveDependency(Procedures::class.java).let {
it.registerFunction(GraphQLProcedure::class.java)
it.registerProcedure(GraphQLProcedure::class.java)
}
db.execute("CREATE (saj:User {username:'Saj'}),(koi:User {username:'Koi'}),(thing:Like {username:'thing'}),(saj)-[:LIKES]->(thing)<-[:LIKES]-(koi), (koi)<-[:FOLLOWS]-(saj),(saj)<-[:FOLLOWS]-(saj)")?.close()
ctx = GraphQLContext(db)
GraphSchemaScanner.storeIdl(db, schema)
graphQL = GraphSchema.getGraphQL(db)
}
val schema = """
type Like @model {
user: User @relation (name:"LIKES", direction:IN)
}
type User @model{
followers: [User] @relation (name:"FOLLOWS", direction: IN)
following: [User] @relation (name:"FOLLOWS", direction: OUT)
username: String!
likes: [Like] @relation (name:"LIKES", direction: OUT)
}
"""
@After
@Throws(Exception::class)
fun tearDown() {
db.shutdown()
}
private fun assertResult(query: String, expected: Any, params: Map<String,Any> = emptyMap()) {
val ctx2 = GraphQLContext(ctx.db, ctx.log, params)
val result = graphQL!!.execute(query, ctx2, params)
if (result.errors.isNotEmpty()) println(result.errors)
assertEquals(expected, result.getData())
}
@Test
fun singleRelation() {
val query = """
query{ u: User(username:"Saj"){
likes(filter:{user:{followers_some:{username:"Saj"}}}){
user{
username
}
}
}
}
"""
// ATTN: Saj has to follow all likers even herself !
assertResult(query, mapOf("u" to listOf(mapOf("likes" to listOf(mapOf("user" to mapOf("username" to "Koi")))))))
}
@Test
fun userName() {
val query = """
query{ u: User(username:"Saj"){
username
}
}
"""
assertResult(query, mapOf("u" to listOf(mapOf("username" to "Saj"))))
}
@Test
fun likesUser() {
val query = """
query{ u: User(username:"Saj"){
likes {
user {
username
}
}
}
}
"""
assertResult(query, mapOf("u" to listOf(mapOf("likes" to listOf(mapOf("user" to mapOf("username" to "Koi")))))))
}
}
| apache-2.0 |
grover-ws-1/http4k | http4k-core/src/test/kotlin/org/http4k/core/StatusTest.kt | 1 | 297 | package org.http4k.core
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.Test
class StatusTest {
@Test
fun `can override description`() {
assertThat(Status.OK.description("all good").description, equalTo("all good"))
}
} | apache-2.0 |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/CreateAllServicesAndExtensionsAction.kt | 1 | 8025 | // Copyright 2000-2021 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.plugins
import com.intellij.diagnostic.PluginException
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.psi.stubs.StubElementTypeHolderEP
import com.intellij.serviceContainer.ComponentManagerImpl
import io.github.classgraph.AnnotationEnumValue
import io.github.classgraph.ClassGraph
import io.github.classgraph.ClassInfo
import java.util.function.BiConsumer
import kotlin.properties.Delegates.notNull
@Suppress("HardCodedStringLiteral")
private class CreateAllServicesAndExtensionsAction : AnAction("Create All Services And Extensions"), DumbAware {
companion object {
@JvmStatic
fun createAllServicesAndExtensions() {
val errors = mutableListOf<Throwable>()
runModalTask("Creating All Services And Extensions", cancellable = true) { indicator ->
val logger = logger<ComponentManagerImpl>()
val taskExecutor: (task: () -> Unit) -> Unit = { task ->
try {
task()
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
logger.error(e)
errors.add(e)
}
}
// check first
checkExtensionPoint(StubElementTypeHolderEP.EP_NAME.point as ExtensionPointImpl<*>, taskExecutor)
checkContainer(ApplicationManager.getApplication() as ComponentManagerImpl, indicator, taskExecutor)
ProjectUtil.getOpenProjects().firstOrNull()?.let {
checkContainer(it as ComponentManagerImpl, indicator, taskExecutor)
}
indicator.text2 = "Checking light services..."
checkLightServices(taskExecutor)
}
// some errors are not thrown but logged
val message = (if (errors.isEmpty()) "No errors" else "${errors.size} errors were logged") + ". Check also that no logged errors."
Notification("Error Report", null, "", message, NotificationType.INFORMATION, null)
.notify(null)
}
}
override fun actionPerformed(e: AnActionEvent) {
createAllServicesAndExtensions()
}
}
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
private val badServices = java.util.Set.of(
"com.intellij.usageView.impl.UsageViewContentManagerImpl",
"com.jetbrains.python.scientific.figures.PyPlotToolWindow",
"org.jetbrains.plugins.grails.runner.GrailsConsole",
"com.intellij.analysis.pwa.analyser.PwaServiceImpl",
"com.intellij.analysis.pwa.view.toolwindow.PwaProblemsViewImpl",
)
@Suppress("HardCodedStringLiteral")
private fun checkContainer(container: ComponentManagerImpl, indicator: ProgressIndicator, taskExecutor: (task: () -> Unit) -> Unit) {
indicator.text2 = "Checking ${container.activityNamePrefix()}services..."
ComponentManagerImpl.createAllServices(container, badServices)
indicator.text2 = "Checking ${container.activityNamePrefix()}extensions..."
container.extensionArea.processExtensionPoints { extensionPoint ->
// requires read action
if (extensionPoint.name == "com.intellij.favoritesListProvider" || extensionPoint.name == "com.intellij.favoritesListProvider") {
return@processExtensionPoints
}
checkExtensionPoint(extensionPoint, taskExecutor)
}
}
private fun checkExtensionPoint(extensionPoint: ExtensionPointImpl<*>, taskExecutor: (task: () -> Unit) -> Unit) {
extensionPoint.processImplementations(false, BiConsumer { supplier, pluginDescriptor ->
var extensionClass: Class<out Any> by notNull()
taskExecutor {
extensionClass = extensionPoint.extensionClass
}
taskExecutor {
try {
val extension = supplier.get() ?: return@taskExecutor
if (!extensionClass.isInstance(extension)) {
throw PluginException("Extension ${extension.javaClass.name} does not implement $extensionClass",
pluginDescriptor.pluginId)
}
}
catch (ignore: ExtensionNotApplicableException) {
}
}
})
taskExecutor {
extensionPoint.extensionList
}
}
private fun checkLightServices(taskExecutor: (task: () -> Unit) -> Unit) {
for (plugin in PluginManagerCore.getLoadedPlugins(null)) {
// we don't check classloader for sub descriptors because url set is the same
if (plugin.classLoader !is PluginClassLoader || plugin.pluginDependencies == null) {
continue
}
ClassGraph()
.enableAnnotationInfo()
.ignoreParentClassLoaders()
.overrideClassLoaders(plugin.classLoader)
.scan()
.use { scanResult ->
val lightServices = scanResult.getClassesWithAnnotation(Service::class.java.name)
for (lightService in lightServices) {
// not clear - from what classloader light service will be loaded in reality
val lightServiceClass = loadLightServiceClass(lightService, plugin)
val isProjectLevel: Boolean
val isAppLevel: Boolean
val annotationParameterValue = lightService.getAnnotationInfo(Service::class.java.name).parameterValues.find { it.name == "value" }
if (annotationParameterValue == null) {
isAppLevel = lightServiceClass.declaredConstructors.any { it.parameterCount == 0 }
isProjectLevel = lightServiceClass.declaredConstructors.any { it.parameterCount == 1 && it.parameterTypes.get(0) == Project::class.java }
}
else {
val list = annotationParameterValue.value as Array<*>
isAppLevel = list.any { v -> (v as AnnotationEnumValue).valueName == Service.Level.APP.name }
isProjectLevel = list.any { v -> (v as AnnotationEnumValue).valueName == Service.Level.PROJECT.name }
}
if (isAppLevel) {
taskExecutor {
ApplicationManager.getApplication().getService(lightServiceClass)
}
}
if (isProjectLevel) {
taskExecutor {
ProjectUtil.getOpenProjects().firstOrNull()?.getService(lightServiceClass)
}
}
}
}
}
}
private fun loadLightServiceClass(lightService: ClassInfo, mainDescriptor: IdeaPluginDescriptorImpl): Class<*> {
//
for (pluginDependency in mainDescriptor.pluginDependencies!!) {
val subPluginClassLoader = pluginDependency.subDescriptor?.classLoader as? PluginClassLoader ?: continue
val packagePrefix = subPluginClassLoader.packagePrefix ?: continue
if (lightService.name.startsWith(packagePrefix)) {
return subPluginClassLoader.loadClass(lightService.name, true)
}
}
for (pluginDependency in mainDescriptor.pluginDependencies!!) {
val subPluginClassLoader = pluginDependency.subDescriptor?.classLoader as? PluginClassLoader ?: continue
val clazz = subPluginClassLoader.loadClass(lightService.name, true)
if (clazz != null && clazz.classLoader === subPluginClassLoader) {
// light class is resolved from this sub plugin classloader - check successful
return clazz
}
}
// ok, or no plugin dependencies at all, or all are disabled, resolve from main
return (mainDescriptor.classLoader as PluginClassLoader).loadClass(lightService.name, true)
} | apache-2.0 |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/test/kotlin/com/vrem/wifianalyzer/wifi/model/WiFiConnectionTest.kt | 1 | 2736 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.model
import com.vrem.util.EMPTY
import org.junit.Assert.*
import org.junit.Test
class WiFiConnectionTest {
private val ipAddress = "21.205.91.7"
private val linkSpeed = 21
private val wiFiIdentifier = WiFiIdentifier("SSID-123", "BSSID-123")
private val fixture: WiFiConnection = WiFiConnection(wiFiIdentifier, ipAddress, linkSpeed)
@Test
fun testWiFiConnectionEmpty() {
// validate
assertEquals(WiFiIdentifier.EMPTY, WiFiConnection.EMPTY.wiFiIdentifier)
assertEquals(String.EMPTY, WiFiConnection.EMPTY.ipAddress)
assertEquals(WiFiConnection.LINK_SPEED_INVALID, WiFiConnection.EMPTY.linkSpeed)
assertFalse(WiFiConnection.EMPTY.connected)
}
@Test
fun testWiFiConnection() {
// validate
assertEquals(wiFiIdentifier, fixture.wiFiIdentifier)
assertEquals(ipAddress, fixture.ipAddress)
assertEquals(linkSpeed, fixture.linkSpeed)
assertTrue(fixture.connected)
}
@Test
fun testEquals() {
// setup
val wiFiIdentifier = WiFiIdentifier("SSID-123", "BSSID-123")
val other = WiFiConnection(wiFiIdentifier, String.EMPTY, WiFiConnection.LINK_SPEED_INVALID)
// execute & validate
assertEquals(fixture, other)
assertNotSame(fixture, other)
}
@Test
fun testHashCode() {
// setup
val wiFiIdentifier = WiFiIdentifier("SSID-123", "BSSID-123")
val other = WiFiConnection(wiFiIdentifier, String.EMPTY, WiFiConnection.LINK_SPEED_INVALID)
// execute & validate
assertEquals(fixture.hashCode(), other.hashCode())
}
@Test
fun testCompareTo() {
// setup
val wiFiIdentifier = WiFiIdentifier("SSID-123", "BSSID-123")
val other = WiFiConnection(wiFiIdentifier, String.EMPTY, WiFiConnection.LINK_SPEED_INVALID)
// execute & validate
assertEquals(0, fixture.compareTo(other))
}
} | gpl-3.0 |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/psi/PSStar.kt | 1 | 110 | package org.purescript.psi
import com.intellij.lang.ASTNode
class PSStar(node: ASTNode) : PSPsiElement(node) | bsd-3-clause |
leafclick/intellij-community | platform/vcs-log/graph/src/com/intellij/vcs/log/graph/utils/BfsUtil.kt | 1 | 1662 | /*
* Copyright 2000-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 com.intellij.vcs.log.graph.utils
import com.intellij.util.containers.ContainerUtil
import com.intellij.vcs.log.graph.api.LiteLinearGraph
import com.intellij.vcs.log.graph.utils.impl.BitSetFlags
class BfsWalk(val start: Int, private val graph: LiteLinearGraph, private val visited: Flags) {
constructor(start: Int, graph: LiteLinearGraph) : this(start, graph, BitSetFlags(graph.nodesCount()))
private val queue = ContainerUtil.newLinkedList(start)
fun isFinished() = queue.isEmpty()
fun currentNodes(): List<Int> = queue
fun step(consumer: (Int) -> Boolean = { true }): List<Int> {
while (!queue.isEmpty()) {
val node = queue.poll()
if (!visited.get(node)) {
visited.set(node, true)
if (!consumer(node)) return emptyList()
val next = graph.getNodes(node, LiteLinearGraph.NodeFilter.DOWN).sorted()
queue.addAll(next)
return next
}
}
return emptyList()
}
fun walk(consumer: (Int) -> Boolean = { true }) {
while (!isFinished()) {
step(consumer)
}
}
} | apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/anonymousObject/anonymousObjectOnDeclarationSite.kt | 3 | 1555 | // FILE: 1.kt
package test
abstract class A<R> {
abstract fun getO() : R
abstract fun getK() : R
abstract fun getParam() : R
}
inline fun <R> doWork(crossinline jobO: ()-> R, crossinline jobK: ()-> R, param: R) : A<R> {
val s = object : A<R>() {
override fun getO(): R {
return jobO()
}
override fun getK(): R {
return jobK()
}
override fun getParam(): R {
return param
}
}
return s;
}
inline fun <R> doWorkInConstructor(crossinline jobO: ()-> R, crossinline jobK: ()-> R, param: R) : A<R> {
val s = object : A<R>() {
val p = param;
val o1 = jobO()
val k1 = jobK()
override fun getO(): R {
return o1
}
override fun getK(): R {
return k1
}
override fun getParam(): R {
return p
}
}
return s;
}
// FILE: 2.kt
//NO_CHECK_LAMBDA_INLINING
import test.*
fun test1(): String {
val o = "O"
val result = doWork ({o}, {"K"}, "GOOD")
return result.getO() + result.getK() + result.getParam()
}
fun test2() : String {
//same names as in object
val o1 = "O"
val k1 = "K"
val result = doWorkInConstructor ({o1}, {k1}, "GOOD")
return result.getO() + result.getK() + result.getParam()
}
fun box() : String {
val result1 = test1();
if (result1 != "OKGOOD") return "fail1 $result1"
val result2 = test2();
if (result2 != "OKGOOD") return "fail2 $result2"
return "OK"
}
| apache-2.0 |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/modcrafters/mclib/ingredients/implementations/BaseItemIngredient.kt | 1 | 2028 | package net.modcrafters.mclib.ingredients.implementations
import net.minecraftforge.fluids.capability.CapabilityFluidHandler
import net.modcrafters.mclib.ingredients.IFluidIngredient
import net.modcrafters.mclib.ingredients.IItemIngredient
import net.modcrafters.mclib.ingredients.IMachineIngredient
import net.modcrafters.mclib.ingredients.IngredientAmountMatch
abstract class BaseItemIngredient : IItemIngredient {
override fun isMatch(ingredient: IMachineIngredient, amountMatch: IngredientAmountMatch) =
when (ingredient) {
is IItemIngredient -> this.isMatchItem(ingredient, amountMatch)
is IFluidIngredient -> this.isMatchFluid(ingredient, amountMatch)
else -> false
}
protected open fun isMatchItem(ingredient: IItemIngredient, amountMatch: IngredientAmountMatch) =
this.itemStacks.any { mine ->
ingredient.itemStacks.any { other ->
mine.isItemEqual(other) && amountMatch.compare(mine.count, other.count)
}
}
protected open fun isMatchFluid(ingredient: IFluidIngredient, amountMatch: IngredientAmountMatch) = this.itemStacks.let {
if ((it.size == 1) && it[0].hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) {
val cap = it[0].getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)
if (cap != null) {
val fluid = cap.drain(ingredient.fluidStack, false)
when (amountMatch) {
IngredientAmountMatch.EXACT -> {
fluid?.amount == ingredient.fluidStack.amount
}
IngredientAmountMatch.BE_ENOUGH -> {
fluid?.amount == ingredient.fluidStack.amount
}
IngredientAmountMatch.IGNORE_SIZE -> {
(fluid?.amount ?: 0) > 0
}
}
}
else false
}
else false
}
}
| mit |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/graph/InferenceUnitGraphBuilder.kt | 13 | 2593 | // 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 org.jetbrains.plugins.groovy.intentions.style.inference.graph
import com.intellij.psi.PsiType
class InferenceUnitGraphBuilder {
private val relations: MutableList<Pair<InferenceUnit, InferenceUnit>> = mutableListOf()
private val registered: MutableSet<InferenceUnit> = mutableSetOf()
private val fixedInstantiations: MutableMap<InferenceUnit, PsiType> = mutableMapOf()
private val directUnits: MutableSet<InferenceUnit> = mutableSetOf()
/**
* Creates a relation between units (left is a supertype of right)
*/
fun addRelation(left: InferenceUnit, right: InferenceUnit): InferenceUnitGraphBuilder {
register(left)
register(right)
relations.add(left to right)
return this
}
fun register(unit: InferenceUnit): InferenceUnitGraphBuilder {
registered.add(unit)
return this
}
fun register(unitNode: InferenceUnitNode): InferenceUnitGraphBuilder {
if (unitNode.direct) {
setDirect(unitNode.core)
}
setType(unitNode.core, unitNode.typeInstantiation)
return this
}
fun setDirect(unit: InferenceUnit): InferenceUnitGraphBuilder {
register(unit)
directUnits.add(unit)
return this
}
fun setType(unit: InferenceUnit, type: PsiType): InferenceUnitGraphBuilder {
register(unit)
fixedInstantiations[unit] = type
return this
}
fun build(): InferenceUnitGraph {
val inferenceNodes = ArrayList<InferenceUnitNode>()
val superTypesMap = mutableListOf<MutableSet<() -> InferenceUnitNode>>()
val subTypesMap = mutableListOf<MutableSet<() -> InferenceUnitNode>>()
val registeredUnits = registered.sortedBy { it.initialTypeParameter.name }
repeat(registeredUnits.size) {
superTypesMap.add(mutableSetOf())
subTypesMap.add(mutableSetOf())
}
val unitIndexMap = registeredUnits.zip(registeredUnits.indices).toMap()
for ((left, right) in relations) {
subTypesMap[unitIndexMap.getValue(left)].add { inferenceNodes[unitIndexMap.getValue(right)] }
superTypesMap[unitIndexMap.getValue(right)].add { inferenceNodes[unitIndexMap.getValue(left)] }
}
for ((unit, index) in unitIndexMap) {
inferenceNodes.add(InferenceUnitNode(unit, superTypesMap[index], subTypesMap[index],
fixedInstantiations[unit] ?: PsiType.NULL,
direct = unit in directUnits))
}
return InferenceUnitGraph(inferenceNodes)
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/override/nothingToOverride/addTypeParameter.kt | 13 | 178 | // "Change function signature to 'fun <T : Number> f(a: T)'" "true"
open class A {
open fun <T : Number> f(a: T) {}
}
class B : A() {
<caret>override fun f(a: Int) {}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/paramTypeLambdaMatchSuspend.kt | 13 | 115 | // "Surround with lambda" "true"
fun foo(action: suspend () -> String) {}
fun usage() {
foo("oraora"<caret>)
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/suppress/annotationPosition/topLevelFunctionUnrelatedAnnotationBare.kt | 26 | 115 | // "Suppress 'REDUNDANT_NULLABLE' for fun foo" "true"
@ann fun foo(): String?<caret>? = null
annotation class ann | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinPropertyWithCustomGetterSetterJvmNameBySetterRef/after/test/test.kt | 13 | 142 | package test
class A {
@get:JvmName("foo")
@set:JvmName("barNew")
var first = 1
}
fun test() {
A().first
A().first = 1
} | apache-2.0 |
ianhanniballake/muzei | main/src/main/java/com/google/android/apps/muzei/wearable/WearableController.kt | 1 | 3800 | /*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.wearable
import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.google.android.apps.muzei.render.ImageLoader
import com.google.android.apps.muzei.room.Artwork
import com.google.android.apps.muzei.room.MuzeiDatabase
import com.google.android.apps.muzei.util.launchWhenStartedIn
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.api.AvailabilityException
import com.google.android.gms.wearable.Asset
import com.google.android.gms.wearable.PutDataMapRequest
import com.google.android.gms.wearable.Wearable
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
/**
* Controller for updating Android Wear devices with new wallpapers.
*/
class WearableController(private val context: Context) : DefaultLifecycleObserver {
companion object {
private const val TAG = "WearableController"
}
override fun onCreate(owner: LifecycleOwner) {
// Update Android Wear whenever the artwork changes
val database = MuzeiDatabase.getInstance(context)
database.artworkDao().currentArtwork.filterNotNull().onEach { artwork ->
updateArtwork(artwork)
}.launchWhenStartedIn(owner)
}
private suspend fun updateArtwork(artwork: Artwork) = withContext(NonCancellable) {
if (ConnectionResult.SUCCESS != GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)) {
return@withContext
}
val dataClient = Wearable.getDataClient(context)
try {
GoogleApiAvailability.getInstance().checkApiAvailability(dataClient).await()
} catch (e: AvailabilityException) {
val connectionResult = e.getConnectionResult(dataClient)
if (connectionResult.errorCode != ConnectionResult.API_UNAVAILABLE) {
Log.w(TAG, "onConnectionFailed: $connectionResult", e.cause)
}
return@withContext
} catch (e: Exception) {
Log.w(TAG, "Unable to check for Wear API availability", e)
return@withContext
}
val image: Bitmap = ImageLoader.decode(
context.contentResolver, artwork.contentUri,
320) ?: return@withContext
val byteStream = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.PNG, 100, byteStream)
val asset = Asset.createFromBytes(byteStream.toByteArray())
val dataMapRequest = PutDataMapRequest.create("/artwork").apply {
dataMap.putDataMap("artwork", artwork.toDataMap())
dataMap.putAsset("image", asset)
}
try {
dataClient.putDataItem(dataMapRequest.asPutDataRequest().setUrgent()).await()
} catch (e: Exception) {
Log.w(TAG, "Error uploading artwork to Wear", e)
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspections/dfa/NothingType.kt | 9 | 238 | // WITH_STDLIB
fun test(x : Int) {
if (x > 5) {
fail(x)
}
if (<warning descr="Condition 'x == 10' is always false">x == 10</warning>) {}
}
fun fail(value: Int) : Nothing {
throw RuntimeException("Oops: ${value}")
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinGradlePluginDescription.kt | 5 | 626 | // 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.gradleJava.configuration
import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle
import org.jetbrains.plugins.gradle.codeInsight.GradlePluginDescriptionsExtension
class KotlinGradlePluginDescription : GradlePluginDescriptionsExtension {
override fun getPluginDescriptions(): Map<String, String> =
mapOf("kotlin" to KotlinIdeaGradleBundle.message("description.text.adds.support.for.building.kotlin.projects"))
}
| apache-2.0 |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertPropertyToFunctionIntention.kt | 2 | 11344 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.*
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.calls.util.getCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.utils.findFunction
class ConvertPropertyToFunctionIntention : SelfTargetingIntention<KtProperty>(
KtProperty::class.java,
KotlinBundle.lazyMessage("convert.property.to.function")
), LowPriorityAction {
private inner class Converter(
project: Project,
editor: Editor?,
descriptor: CallableDescriptor
) : CallableRefactoring<CallableDescriptor>(project, editor, descriptor, text) {
private val newName: String = JvmAbi.getterName(callableDescriptor.name.asString())
private fun convertProperty(originalProperty: KtProperty, psiFactory: KtPsiFactory) {
val property = originalProperty.copy() as KtProperty
val getter = property.getter
val sampleFunction = psiFactory.createFunction("fun foo() {\n\n}")
property.valOrVarKeyword.replace(sampleFunction.funKeyword!!)
property.addAfter(psiFactory.createParameterList("()"), property.nameIdentifier)
if (property.initializer == null) {
if (getter != null) {
val dropGetterTo = (getter.equalsToken ?: getter.bodyExpression)
?.siblings(forward = false, withItself = false)
?.firstOrNull { it !is PsiWhiteSpace }
getter.deleteChildRange(getter.firstChild, dropGetterTo)
val dropPropertyFrom = getter
.siblings(forward = false, withItself = false)
.first { it !is PsiWhiteSpace }
.nextSibling
property.deleteChildRange(dropPropertyFrom, getter.prevSibling)
val typeReference = property.typeReference
if (typeReference != null) {
property.addAfter(psiFactory.createWhiteSpace(), typeReference)
}
}
}
property.setName(newName)
property.annotationEntries.forEach {
if (it.useSiteTarget != null) {
it.replace(psiFactory.createAnnotationEntry("@${it.shortName}${it.valueArgumentList?.text ?: ""}"))
}
}
originalProperty.replace(psiFactory.createFunction(property.text))
}
override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) {
val propertyName = callableDescriptor.name.asString()
val nameChanged = propertyName != newName
val getterName = JvmAbi.getterName(callableDescriptor.name.asString())
val conflicts = MultiMap<PsiElement, String>()
val callables = getAffectedCallables(project, descriptorsForChange)
val kotlinRefsToReplaceWithCall = ArrayList<KtSimpleNameExpression>()
val refsToRename = ArrayList<PsiReference>()
val javaRefsToReplaceWithCall = ArrayList<PsiReferenceExpression>()
project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.and.conflicts"), true) {
runReadAction {
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator.isIndeterminate = false
val progressStep = 1.0 / callables.size
for ((i, callable) in callables.withIndex()) {
progressIndicator.fraction = (i + 1) * progressStep
if (callable !is PsiNamedElement) continue
if (!checkModifiable(callable)) {
val renderedCallable = RefactoringUIUtil.getDescription(callable, true).capitalize()
conflicts.putValue(callable, KotlinBundle.message("can.t.modify.0", renderedCallable))
}
if (callable is KtParameter) {
conflicts.putValue(
callable,
if (callable.hasActualModifier()) KotlinBundle.message("property.has.an.actual.declaration.in.the.class.constructor")
else KotlinBundle.message("property.overloaded.in.child.class.constructor")
)
}
if (callable is KtProperty) {
callableDescriptor.getContainingScope()
?.findFunction(callableDescriptor.name, NoLookupLocation.FROM_IDE) { it.valueParameters.isEmpty() }
?.takeIf { it.receiverType() == callableDescriptor.receiverType() }
?.let { DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) }
?.let { reportDeclarationConflict(conflicts, it) { s -> KotlinBundle.message("0.already.exists", s) } }
} else if (callable is PsiMethod) callable.checkDeclarationConflict(propertyName, conflicts, callables)
val usages = ReferencesSearch.search(callable)
for (usage in usages) {
if (usage is KtReference) {
if (usage is KtSimpleNameReference) {
val expression = usage.expression
if (expression.getCall(expression.analyze(BodyResolveMode.PARTIAL)) != null
&& expression.getStrictParentOfType<KtCallableReferenceExpression>() == null
) {
kotlinRefsToReplaceWithCall.add(expression)
} else if (nameChanged) {
refsToRename.add(usage)
}
} else {
val refElement = usage.element
conflicts.putValue(
refElement,
KotlinBundle.message(
"unrecognized.reference.will.be.skipped.0",
StringUtil.htmlEmphasize(refElement.text)
)
)
}
continue
}
val refElement = usage.element
if (refElement.text.endsWith(getterName)) continue
if (usage is PsiJavaReference) {
if (usage.resolve() is PsiField && usage is PsiReferenceExpression) {
javaRefsToReplaceWithCall.add(usage)
}
continue
}
conflicts.putValue(
refElement,
KotlinBundle.message(
"can.t.replace.foreign.reference.with.call.expression.0",
StringUtil.htmlEmphasize(refElement.text)
)
)
}
}
}
}
project.checkConflictsInteractively(conflicts) {
project.executeWriteCommand(text) {
val kotlinPsiFactory = KtPsiFactory(project)
val javaPsiFactory = PsiElementFactory.getInstance(project)
val newKotlinCallExpr = kotlinPsiFactory.createExpression("$newName()")
kotlinRefsToReplaceWithCall.forEach { it.replace(newKotlinCallExpr) }
refsToRename.forEach { it.handleElementRename(newName) }
javaRefsToReplaceWithCall.forEach {
val getterRef = it.handleElementRename(newName)
getterRef.replace(javaPsiFactory.createExpressionFromText("${getterRef.text}()", null))
}
callables.forEach {
when (it) {
is KtProperty -> convertProperty(it, kotlinPsiFactory)
is PsiMethod -> it.name = newName
}
}
}
}
}
}
override fun startInWriteAction(): Boolean = false
override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean {
val identifier = element.nameIdentifier ?: return false
if (!identifier.textRange.containsOffset(caretOffset)) return false
return element.delegate == null
&& !element.isVar
&& !element.isLocal
&& (element.initializer == null || element.getter == null)
&& !element.hasJvmFieldAnnotation()
&& !element.hasModifier(KtTokens.CONST_KEYWORD)
}
override fun applyTo(element: KtProperty, editor: Editor?) {
val descriptor = element.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? CallableDescriptor ?: return
Converter(element.project, editor, descriptor).run()
}
}
| apache-2.0 |
webscene/webscene-client | src/main/kotlin/org/webscene/client/dom/DomEditor.kt | 1 | 2877 | package org.webscene.client.dom
import org.w3c.dom.Element
import org.webscene.client.html.HtmlSection
import org.webscene.client.html.HtmlTag
import kotlin.browser.document
@Suppress("unused")
/**
* Contains common functionality for editing the DOM.
*/
object DomEditor {
/**
* Supplies a function for editing a [section][htmlSection] of the DOM. Do note that this function doesn't support
* replacing an existing DOM element in a [section][htmlSection], instead use [replaceElement] function.
* @param htmlSection The HTML section to apply the edit.
* @return A function that will perform the edit.
*/
fun editSection(htmlSection: HtmlSection): (domElement: Element, editType: DomEditType) -> Unit {
/**
* Makes changes to the HTML body section.
* @param domElement The DOM element used in the edit.
* @param editType Type of DOM edit to apply. Only [DomEditType.PREPEND] is supported for
* [performance reasons](https://stackoverflow.com/questions/4396849/does-the-script-tag-position-in-html-affects-performance-of-the-webpage).
*/
fun editBody(domElement: Element, editType: DomEditType) {
if (editType == DomEditType.PREPEND) document.prependElement(domElement, HtmlSection.BODY)
}
/**
* Makes changes to the HTML head section.
* @param domElement The DOM element used in the edit.
* @param editType Type of DOM edit to apply.
*/
fun editHead(domElement: Element, editType: DomEditType) {
when (editType) {
DomEditType.APPEND -> document.appendElement(domElement, HtmlSection.HEAD)
DomEditType.PREPEND -> document.prependElement(domElement, HtmlSection.HEAD)
DomEditType.REMOVE -> document.removeElement(domElement, HtmlSection.HEAD)
}
}
// TODO: Remove the block below.
@Suppress("LiftReturnOrAssignment")
when (htmlSection) {
HtmlSection.HEAD -> return ::editHead
else -> return ::editBody
}
// TODO: Uncomment the block below.
// return when(htmlSection) {
// HtmlSection.HEAD -> ::editHead
// else -> ::editBody
// }
}
/**
* Replaces an existing [DOM element][Element] with a new one. The ID for the element to be replaced **MUST** exist
* in the DOM.
* @param block Function for replacing the old element with the [new element][HtmlTag] (must have its ID set),
* which must be returned in the last line.
*/
fun replaceElement(block: () -> HtmlTag) = document.replaceElement(block)
/**
* Removes an existing DOM element by its ID.
* @param id Unique identifier of the DOM element.
*/
fun removeElementById(id: String) = document.removeElementById(id)
} | apache-2.0 |
jotomo/AndroidAPS | app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_SuspendTest.kt | 1 | 883 | package info.nightscout.androidaps.danars.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class DanaRS_Packet_History_SuspendTest : DanaRSTestBase() {
private val packetInjector = HasAndroidInjector {
AndroidInjector {
if (it is DanaRS_Packet) {
it.aapsLogger = aapsLogger
it.dateUtil = dateUtil
}
if (it is DanaRS_Packet_History_Suspend) {
it.rxBus = rxBus
}
}
}
@Test fun runTest() {
val packet = DanaRS_Packet_History_Suspend(packetInjector, System.currentTimeMillis())
Assert.assertEquals("REVIEW__SUSPEND", packet.friendlyName)
}
} | agpl-3.0 |
FuturemanGaming/FutureBot-Discord | src/main/kotlin/com/futuremangaming/futurebot/music/display/DisplaySymbol.kt | 1 | 1266 | /*
* Copyright 2014-2017 FuturemanGaming
*
* 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.futuremangaming.futurebot.music.display
// WHY NOT USE AN ENUM?? CONVERSION IS ANNOYING!!
object DisplaySymbol {
const val PLAY_PAUSE = "\u23EF"
const val PAUSE = "\u23F8"
const val PLAY = "\u25B6"
const val NOTE = "\uD83C\uDFA7"
const val SKIP = "\u23ed"
const val SHUFFLE = "\ud83d\udd00"
const val MUTED = "\ud83d\udd07"
const val VOLUME_LOW = "\ud83d\udd08"
const val VOLUME_DOWN = "\ud83d\udd09"
const val VOLUME_UP = "\ud83d\udd0A"
const val PLAY_BAR = "\u25ac"
const val PLAY_POS = "\ud83d\udd18"
const val REFRESH = "\uD83d\uDD18"
}
| apache-2.0 |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/user/Stats.kt | 1 | 4373 | package com.habitrpg.android.habitica.models.user
import android.content.Context
import com.google.gson.annotations.SerializedName
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.models.HabitRpgClass
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Stats : RealmObject() {
@PrimaryKey
var userId: String? = null
set(userId) {
field = userId
if (buffs?.isManaged == false) {
buffs?.userId = userId
}
if (training?.isManaged == false) {
training?.userId = userId
}
}
internal var user: User? = null
@SerializedName("con")
var constitution: Int? = null
@SerializedName("str")
var strength: Int? = null
@SerializedName("per")
var per: Int? = null
@SerializedName("int")
var intelligence: Int? = null
var training: Training? = null
var buffs: Buffs? = null
var points: Int? = null
var lvl: Int? = null
@SerializedName("class")
var habitClass: String? = null
var gp: Double? = null
var exp: Double? = null
var mp: Double? = null
var hp: Double? = null
var toNextLevel: Int? = null
get() = if (field != null) field else 0
set(value) {
if (value != 0) {
field = value
}
}
var maxHealth: Int? = null
get() = if (field != null) field else 0
set(value) {
if (value != 0) {
field = value
}
}
var maxMP: Int? = null
get() = if (field != null) field else 0
set(value) {
if (value != 0) {
field = value
}
}
val isBuffed: Boolean
get() {
return buffs?.str ?: 0f > 0 ||
buffs?.con ?: 0f > 0 ||
buffs?._int ?: 0f > 0 ||
buffs?.per ?: 0f > 0
}
fun getTranslatedClassName(context: Context): String {
return when (habitClass) {
HEALER -> context.getString(R.string.healer)
ROGUE -> context.getString(R.string.rogue)
WARRIOR -> context.getString(R.string.warrior)
MAGE -> context.getString(R.string.mage)
else -> context.getString(R.string.warrior)
}
}
fun merge(stats: Stats?) {
if (stats == null) {
return
}
this.constitution = if (stats.constitution != null) stats.constitution else this.constitution
this.strength = if (stats.strength != null) stats.strength else this.strength
this.per = if (stats.per != null) stats.per else this.per
this.intelligence = if (stats.intelligence != null) stats.intelligence else this.intelligence
this.training?.merge(stats.training)
this.buffs?.merge(stats.buffs)
this.points = if (stats.points != null) stats.points else this.points
this.lvl = if (stats.lvl != null) stats.lvl else this.lvl
this.habitClass = if (stats.habitClass != null) stats.habitClass else this.habitClass
this.gp = if (stats.gp != null) stats.gp else this.gp
this.exp = if (stats.exp != null) stats.exp else this.exp
this.hp = if (stats.hp != null) stats.hp else this.hp
this.mp = if (stats.mp != null) stats.mp else this.mp
this.toNextLevel = if (stats.toNextLevel != null) stats.toNextLevel else this.toNextLevel
this.maxHealth = if (stats.maxHealth != null) stats.maxHealth else this.maxHealth
this.maxMP = if (stats.maxMP != null) stats.maxMP else this.maxMP
}
fun setHabitClass(habitRpgClass: HabitRpgClass) {
habitClass = habitRpgClass.toString()
}
companion object {
const val STRENGTH = "str"
const val INTELLIGENCE = "int"
const val CONSTITUTION = "con"
const val PERCEPTION = "per"
const val WARRIOR = "warrior"
const val MAGE = "wizard"
const val HEALER = "healer"
const val ROGUE = "rogue"
const val AUTO_ALLOCATE_FLAT = "flat"
const val AUTO_ALLOCATE_CLASSBASED = "classbased"
const val AUTO_ALLOCATE_TASKBASED = "taskbased"
}
}
| gpl-3.0 |
devjn/GithubSearch | ios/src/main/kotlin/com/github/devjn/githubsearch/db/SQLiteCursor.kt | 1 | 1692 | package com.github.devjn.githubsearch.db
import com.github.devjn.githubsearch.database.ISQLiteCursor
import org.sqlite.c.Globals
class SQLiteCursor(private var stmt: SQLiteStatement?) : ISQLiteCursor {
override var isAfterLast = false
init {
moveToNext()
}
override fun moveToFirst() {
if (stmt == null) {
throw RuntimeException("statement is closed")
}
stmt!!.reset()
moveToNext()
}
override fun close() {
if (stmt == null) {
throw RuntimeException("statement is closed")
}
stmt = null
}
override fun getString(i: Int): String {
if (stmt == null) {
throw RuntimeException("statement is closed")
}
return Globals.sqlite3_column_text(stmt!!.stmtHandle, i)
}
override fun getInt(i: Int): Int {
if (stmt == null) {
throw RuntimeException("statement is closed")
}
return Globals.sqlite3_column_int(stmt!!.stmtHandle, i)
}
override fun getLong(i: Int): Long {
if (stmt == null) {
throw RuntimeException("statement is closed")
}
return Globals.sqlite3_column_int64(stmt!!.stmtHandle, i)
}
override fun getDouble(i: Int): Double {
if (stmt == null) {
throw RuntimeException("statement is closed")
}
return Globals.sqlite3_column_double(stmt!!.stmtHandle, i)
}
override fun moveToNext() {
if (stmt == null) {
throw RuntimeException("statement is closed")
}
isAfterLast = !stmt!!.step()
}
} | apache-2.0 |
kohesive/kohesive-iac | model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAmazonCodeDeploy.kt | 1 | 2528 | package uy.kohesive.iac.model.aws.clients
import com.amazonaws.services.codedeploy.AbstractAmazonCodeDeploy
import com.amazonaws.services.codedeploy.AmazonCodeDeploy
import com.amazonaws.services.codedeploy.model.*
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.proxy.makeProxy
open class BaseDeferredAmazonCodeDeploy(val context: IacContext) : AbstractAmazonCodeDeploy(), AmazonCodeDeploy {
override fun addTagsToOnPremisesInstances(request: AddTagsToOnPremisesInstancesRequest): AddTagsToOnPremisesInstancesResult {
return with (context) {
request.registerWithAutoName()
AddTagsToOnPremisesInstancesResult().registerWithSameNameAs(request)
}
}
override fun createApplication(request: CreateApplicationRequest): CreateApplicationResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateApplicationRequest, CreateApplicationResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createDeployment(request: CreateDeploymentRequest): CreateDeploymentResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateDeploymentRequest, CreateDeploymentResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createDeploymentConfig(request: CreateDeploymentConfigRequest): CreateDeploymentConfigResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateDeploymentConfigRequest, CreateDeploymentConfigResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createDeploymentGroup(request: CreateDeploymentGroupRequest): CreateDeploymentGroupResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateDeploymentGroupRequest, CreateDeploymentGroupResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
}
class DeferredAmazonCodeDeploy(context: IacContext) : BaseDeferredAmazonCodeDeploy(context)
| mit |
jotomo/AndroidAPS | app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPluginTest.kt | 1 | 2024 | package info.nightscout.androidaps.plugins.insulin
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.InsulinInterface
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.ArgumentMatchers.eq
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
class InsulinOrefRapidActingPluginTest {
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
private lateinit var sut: InsulinOrefRapidActingPlugin
@Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var rxBus: RxBusWrapper
@Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var aapsLogger: AAPSLogger
private var injector: HasAndroidInjector = HasAndroidInjector {
AndroidInjector {
}
}
@Before
fun setup() {
sut = InsulinOrefRapidActingPlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger)
}
@Test
fun `simple peak test`() {
assertEquals(75, sut.peak)
}
@Test
fun getIdTest() {
assertEquals(InsulinInterface.InsulinType.OREF_RAPID_ACTING, sut.id)
}
@Test
fun commentStandardTextTest() {
`when`(resourceHelper.gs(eq(R.string.fastactinginsulincomment))).thenReturn("Novorapid, Novolog, Humalog")
assertEquals("Novorapid, Novolog, Humalog", sut.commentStandardText())
}
@Test
fun getFriendlyNameTest() {
`when`(resourceHelper.gs(eq(R.string.rapid_acting_oref))).thenReturn("Rapid-Acting Oref")
assertEquals("Rapid-Acting Oref", sut.friendlyName)
}
} | agpl-3.0 |
mdaniel/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceWithEnumMap/inferred.kt | 13 | 103 | // RUNTIME_WITH_FULL_JDK
enum class E {
A, B
}
fun getMap(): Map<E, String> = <caret>hashMapOf()
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/scopeFunctions/runToLet/noReceiver.kt | 3 | 67 | // WITH_RUNTIME
// PROBLEM: none
fun hello() {
<caret>run { }
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/visibility/VisibilityPrivateToThisWithWrongThis.kt | 4 | 218 | // FIR_COMPARISON
class A<in I> {
private val bar: I
private fun foo(): I = null!!
fun test() {
with(A()) {
this.<caret>
}
}
}
// INVOCATION_COUNT: 1
// ABSENT: bar, foo
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/dfa/basicRange.kt | 1 | 133 | // PROBLEM: Condition is always false
// FIX: none
fun test(x : Int) {
if (x > 5) {
if (<caret>x < 3) {
}
}
} | apache-2.0 |
ncoe/rosetta | Latin_Squares_in_reduced_form/Kotlin/src/Latin.kt | 1 | 3150 | typealias Matrix = MutableList<MutableList<Int>>
fun dList(n: Int, sp: Int): Matrix {
val start = sp - 1 // use 0 basing
val a = generateSequence(0) { it + 1 }.take(n).toMutableList()
a[start] = a[0].also { a[0] = a[start] }
a.subList(1, a.size).sort()
val first = a[1]
// recursive closure permutes a[1:]
val r = mutableListOf<MutableList<Int>>()
fun recurse(last: Int) {
if (last == first) {
// bottom of recursion. you get here once for each permutation.
// test if permutation is deranged
for (jv in a.subList(1, a.size).withIndex()) {
if (jv.index + 1 == jv.value) {
return // no, ignore it
}
}
// yes, save a copy with 1 based indexing
val b = a.map { it + 1 }
r.add(b.toMutableList())
return
}
for (i in last.downTo(1)) {
a[i] = a[last].also { a[last] = a[i] }
recurse(last - 1)
a[i] = a[last].also { a[last] = a[i] }
}
}
recurse(n - 1)
return r
}
fun reducedLatinSquares(n: Int, echo: Boolean): Long {
if (n <= 0) {
if (echo) {
println("[]\n")
}
return 0
} else if (n == 1) {
if (echo) {
println("[1]\n")
}
return 1
}
val rlatin = MutableList(n) { MutableList(n) { it } }
// first row
for (j in 0 until n) {
rlatin[0][j] = j + 1
}
var count = 0L
fun recurse(i: Int) {
val rows = dList(n, i)
outer@
for (r in 0 until rows.size) {
rlatin[i - 1] = rows[r].toMutableList()
for (k in 0 until i - 1) {
for (j in 1 until n) {
if (rlatin[k][j] == rlatin[i - 1][j]) {
if (r < rows.size - 1) {
continue@outer
}
if (i > 2) {
return
}
}
}
}
if (i < n) {
recurse(i + 1)
} else {
count++
if (echo) {
printSquare(rlatin)
}
}
}
}
// remaining rows
recurse(2)
return count
}
fun printSquare(latin: Matrix) {
for (row in latin) {
println(row)
}
println()
}
fun factorial(n: Long): Long {
if (n == 0L) {
return 1
}
var prod = 1L
for (i in 2..n) {
prod *= i
}
return prod
}
fun main() {
println("The four reduced latin squares of order 4 are:\n")
reducedLatinSquares(4, true)
println("The size of the set of reduced latin squares for the following orders")
println("and hence the total number of latin squares of these orders are:\n")
for (n in 1 until 7) {
val size = reducedLatinSquares(n, false)
var f = factorial(n - 1.toLong())
f *= f * n * size
println("Order $n: Size %-4d x $n! x ${n - 1}! => Total $f".format(size))
}
}
| mit |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/convertCollection/listToSequence.kt | 4 | 170 | // "Convert expression to 'Sequence' by inserting '.asSequence()'" "true"
// WITH_RUNTIME
fun foo(a: List<String>) {
bar(a<caret>)
}
fun bar(a: Sequence<String>) {} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/filter/filterNot_ifContinue.kt | 4 | 331 | // WITH_RUNTIME
// INTENTION_TEXT: "Replace with 'filterNot{}.map{}.firstOrNull()'"
// INTENTION_TEXT_2: "Replace with 'asSequence().filterNot{}.map{}.firstOrNull()'"
fun foo(list: List<String>): Int? {
<caret>for (s in list) {
if (s.isEmpty()) continue
val l = s.length
return l
}
return null
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/ShortClassNamesInTypePosition.kt | 4 | 152 | // FIR_COMPARISON
package testing
class Hello() {
fun test() {
val a : S<caret>
}
}
// EXIST: Set, Short, ShortArray
// ABSENT: toString
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/jvm-debugger/test/testData/selectExpression/disallowMethodCalls/binaryExpression.kt | 6 | 49 | fun foo() {
1 <caret>+ 1
}
// EXPECTED: null | apache-2.0 |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/cgen/CSyntaxSupport.kt | 4 | 2156 | package org.jetbrains.kotlin.backend.konan.cgen
internal interface CType {
fun render(name: String): String
}
internal class CVariable(val type: CType, val name: String) {
override fun toString() = type.render(name)
}
internal object CTypes {
fun simple(type: String): CType = SimpleCType(type)
fun pointer(pointee: CType): CType = PointerCType(pointee)
fun function(returnType: CType, parameterTypes: List<CType>, variadic: Boolean): CType =
FunctionCType(returnType, parameterTypes, variadic)
fun blockPointer(pointee: CType): CType = object : CType {
override fun render(name: String): String = pointee.render("^$name")
}
val void = simple("void")
val voidPtr = pointer(void)
val signedChar = simple("signed char")
val unsignedChar = simple("unsigned char")
val short = simple("short")
val unsignedShort = simple("unsigned short")
val int = simple("int")
val unsignedInt = simple("unsigned int")
val longLong = simple("long long")
val unsignedLongLong = simple("unsigned long long")
val float = simple("float")
val double = simple("double")
val C99Bool = simple("_Bool")
val char = simple("char")
val vector128 = simple("float __attribute__ ((__vector_size__ (16)))")
val id = simple("id")
}
private class SimpleCType(private val type: String) : CType {
override fun render(name: String): String = if (name.isEmpty()) type else "$type $name"
}
private class PointerCType(private val pointee: CType) : CType {
override fun render(name: String): String = pointee.render("*$name")
}
private class FunctionCType(
private val returnType: CType,
private val parameterTypes: List<CType>,
private val variadic: Boolean
) : CType {
override fun render(name: String): String = returnType.render(buildString {
append("(")
append(name)
append(")(")
parameterTypes.joinTo(this) { it.render("") }
if (parameterTypes.isEmpty()) {
if (!variadic) append("void")
} else {
if (variadic) append(", ...")
}
append(')')
})
}
| apache-2.0 |
vovagrechka/fucking-everything | attic/alraune/alraune-back-kotlin-3/src/SpitOrderPage.kt | 1 | 16208 | package alraune.back
import alraune.back.Al.*
import alraune.back.AlTag.*
import alraune.back.EntityPageTemplate.Identification
import vgrechka.*
import alraune.back.Col.*
import java.util.function.Supplier
@Suppress("unused")
class SpitOrderPage : SpitPage {
val spit = MakeOrderPageShit().dance().spitPage!!
override fun spit() = spit.spit()
override fun isPrivate() = spit.isPrivate
}
class MakeOrderPageShit {
val filesTabID = "Files"
var pedro by notNull<EntityPageTemplate.Pedro<AlUAOrder>>()
fun dance(): EntityPageTemplate.Product {
val t = EntityPageTemplate1<AlUAOrder>()
pedro = object : EntityPageTemplate.Pedro<AlUAOrder>() {
override fun identification() = Identification.ExplicitOrSearch
override fun entityClass() = AlUAOrder::class.java
override fun impersonationMakesSense(impersonateAs: AlUserKind) = when (impersonateAs) {
AlUserKind.Customer -> true
AlUserKind.Admin -> true
AlUserKind.Writer -> Al2.isWriterAssigned(pedro.juan.entity)
}
override fun pageClass() = SpitOrderPage::class.java
override fun applicableEntityAddressings() = when {
rctx().isAdmin -> mutableListOf()
else -> mutableListOf<EntityAddressing<AlUAOrder>>()
}
override fun getTable() = "ua_orders"
override fun getNoEntityWithIDMessage() = t("TOTE", "Заказа с ID <b>%s</b> не существует, такие дела...")
override fun getNoEntityWithUUIDMessage() = t("TOTE", "Заказа с UUID <b>%s</b> не существует, такие дела...")
override fun getNoPermissionsForEntityWithIDMessage() = t("TOTE", "К заказу с ID <b>%s</b> у тебя доступа нет, приятель")
override fun paramsModalContent(): EntityPageTemplate.ParamsModalContent {
return EntityPageTemplate.ParamsModalContent {frc2, fields ->
OrderPile2.renderOrderParamsFormBody(frc2, fields)
}
}
override fun updateEntityParams(fs: BunchOfFields) {
object : Al2.UpdateEntityParams() {
override fun shortOperationDescription() = "Edit order"
override fun entity() = juan.entity
override fun fields() = fs
}.dance()
}
override fun makeFields() = when {
rctx().isAdmin -> OrderFieldsForAdmin()
else -> OrderFields()
}
override fun pagePath() = AlPagePath.order
override fun addTabs(xs: MutableList<EntityPageTemplate.Tab>) {
xs.add(FilesTab())
}
inner class FilesTab : EntityPageTemplate.Tab {
override fun id() = filesTabID
override fun title() = t("Files", "Файлы")
override fun addTopRightControls(trb: TopRightControlsBuilder) {
trb.addOrderingSelect()
val canEdit: Boolean = canEditParams()
if (canEdit) {
trb.addButton(FA.plus, AlDebugTag.topRightButton, {buttonDomid ->
AlRender.bustOutModalOnDomidClick(juan.script, buttonDomid, ModalWithScripts.make {frc, frc2 ->
frc.fileValue = AlFileFormValue()
renderFileModalContent(frc2, null, FieldSource.Initial())
})
})
}
}
override fun render(rpp: RenderingParamsPile) = object : RenderPaginatedShit<AlUAOrderFile>() {
override fun makePageHref(pageFrom1: Int) =
juan.makeHrefKeepingEverythingExcept {it.page.set(pageFrom1)}
override fun renderItem(item: AlUAOrderFile) =
OrderPile2.renderOrderFileItem(juan.script, item, false)
override fun selectItems(offset: Long) =
AlDB.betty(AlDB_Params_betty_Builder.begin()
.counting(false)
.offset(offset)
.orderID(juan.entity.id)
.ordering(rctx().getParams.get().ordering.get()).end())
.selectCompound(AlUAOrderFile::class.java, null)
override fun count() =
AlDB.betty(AlDB_Params_betty_Builder.begin()
.counting(true)
.orderID(juan.entity.id).end())
.selectOneLong()
override fun initGivenItems(alUAOrderFileWithParams: List<AlUAOrderFile>) {}
}.dance()
fun renderFileModalContent(frc2: FormRenderingContext2, file: AlUAOrderFile?, source: FieldSource): Renderable {
val rmc = RenderModalContent()
rmc.title = when {
file == null -> t("TOTE", "Файл")
else -> t("TOTE", "Файл №" + file.id)
}
rmc.blueLeftMargin()
rmc.body = div().with {
val fields = Al.useFields(OrderFileFields(), source)
oo((fields.file as FileField).render(frc2)) // TODO:vgrechka Get rid of cast
oo(fields.title.render(frc2).focused())
oo(fields.details.render(frc2))
}
rmc.footer = ButtonBarWithTicker(rctx().script, frc2)
.tickerLocation(LeftOrRight.Left)
.addSubmitFormButton(MinimalButtonShit(
when {
file == null -> AlConst.Text.create
else -> AlConst.Text.save
},
AlButtonLevel2.Primary,
Servant {serveCreateOrUpdateFile(file)}),
rmc.errorBannerDomid)
.addCloseModalButton()
return rmc.dance()
}
private fun serveCreateOrUpdateFile(file: AlUAOrderFile?) {
val fs = Al.useFields(OrderFileFields(), FieldSource.Post())
val incomingFile = fs.file.value()
if (Al.anyFieldErrors(fs)) return run {
val frc2 = FormRenderingContext2()
frc2.shouldRestoreFilePickerValue = true // TODO:vgrechka Remove from context
AlCommands2.addEval {s -> s.replaceElement(
AlDomid.modalContent.name,
renderFileModalContent(frc2, file, FieldSource.Post()),
Supplier {frc2.initAndOnShowScripts()}
)}
}
if (Alk.isPreflight()) return run {
rctx().keepAdHocServantWithSameUUIDForNextRequest = true
AlCommands2.addEval(AlJS.invokeLastBackendCallTemplate(false, 0))
}
if (file == null) {
val cab = ContentAndBytesFromBase64(incomingFile.base64)
AlDB.insertEntity(cab.bytes)
AlDB.insertEntity(AlUAOrderFile_Builder.begin()
.uuid(Al.longUUID())
.orderID(juan.entity.id)
.state(AlUAOrderFileState.UNKNOWN)
.name(incomingFile.name)
.size(cab.content.size)
.title(fs.title.sanitized())
.details(fs.details.sanitized())
.bytesID(cab.bytes.getId())
.end())
// TODO:vgrechka Operations
// AlOperation operation = new AlOperationData_Rudimentary_V1(AlBasicOperationData_V1.make("Creating file")).toOperation();
AlCommands2.addCloseModal()
juan.reload()
}
else {
object : Al2.UpdateEntityParams() {
override fun entity() = file
override fun fields() = fs
override fun shortOperationDescription() = "Editing freaking file"
}.dance()
AlCommands2.addCloseModal()
imf("Replace shit")
// JSScriptBuilder script = new JSScriptBuilder();
// rctx().commands.add(also(new AlBackToFrontCommandPile(), o -> {
// o.opcode = AlBackToFrontCommandOpcode.ReplaceElement;
// o.domid = AlDomid.item;
// o.domidIndex = rctx().fileWithParams.get().entity.uuid;
// o.initCommands = new ArrayList<>();
// o.html = OrderPile2.renderOrderFileItem(script, rctx().fileWithParams.get(), true).render();
// }));
// rctx().addCommand(AlCommands2.eval(script.getCode()));
}
}
}
override fun canEditParams() = when {
juan.initialParams.impersonate.get() == AlUserKind.Admin -> true
else -> juan.entity.state in setOf(
AlUAOrderState.CustomerDraft,
AlUAOrderState.ReturnedToCustomerForFixing)
}
override fun pageTitle() = t("TOTE", "Заказ №") + juan.entity.id
override fun pageSubTitle() = juan.entity.documentTitle
override fun renderActionBannerBelowTitle() = when {
AlUAOrderState.CustomerDraft == juan.entity.state -> {
if (rctx().pretending.get() == AlUserKind.Customer)
ActionBanner()
.message(t("TOTE", "Убедись, что все верно. Подредактируй, если нужно. Возможно, добавь файлы. А затем..."))
.backgroundColor(Color.BLUE_GRAY_50)
.leftBorderColor(Color.BLUE_GRAY_300)
.accept {banner ->
banner.addButton(MinimalButtonShit(
t("TOTE", "Отправить на проверку"), AlButtonLevel2.Primary,
Servant {
juan.changeEntityStateAndReload("Send order for approval", null, {p ->
// 2a949363-293d-445f-a9f0-95ef1612b51e
p.state = AlUAOrderState.WaitingAdminApproval;
})
}
))
}
else div()
}
AlUAOrderState.ReturnedToCustomerForFixing == juan.entity.state -> object : RejectedBanner() {
override fun entityKindTitle() = "этот заказ"
override fun rejectionReason() = juan.entity.rejectionReason
override fun sendForReviewServant() = object : Servant {
override fun checkPermissions() = imf()
override fun ignite() = imf()
}
}.dance()
AlUAOrderState.WaitingAdminApproval == juan.entity.state -> object : RenderApprovalBanner() {
override fun performRejection(fs: RejectionFields) = imf()
override fun acceptButtonTitle() = t("TOTE", "В стор")
override fun entityKindTitle() = "заказ"
override fun rejectButtonTitle() = t("TOTE", "Завернуть")
override fun acceptServant() = imf()
override fun messageForUser() = t("TOTE", "Мы проверяем заказ и скоро с тобой свяжемся")
override fun questionForAdmin() = t("TOTE", "Что решаем по этому порожняку?")
override fun frc() = juan.frc
override fun frc2() = juan.frc2
override fun wasRejectionReason() = juan.entity.wasRejectionReason
}.dance()
else -> div()
}
override fun shitToGetParams(p: AlGetParams) =
p.uuid.set(juan.entity.uuid)
override fun renderBelowActionBanner() = when {
rctx().pretending.get() == AlUserKind.Admin
&& juan.entity.state == AlUAOrderState.WaitingAdminApproval
&& !juan.entity.rejectionReason.isNullOrBlank()
-> renderRejectionReason(AlConst.Text.potentialRejectionReason)
else -> div()
}
override fun renderParamsTab(rpp: RenderingParamsPile): Renderable {
val order = juan.entity
var className: String? = null
if (rpp.orderParamsClazz != null)
className = rpp.orderParamsClazz
return div().domid(AlDomid.orderParams).style("position: relative;").className(className).with {
oo(Row().with {
oo(AlRender.createdAtCol(3, order.createdAt))
oo(AlRender.renderOrderStateColumn(order))
})
oo(Row().with {
oo(col(3, AlConst.Text.Order.contactName, order.contactName))
oo(col(3, AlConst.Text.Order.email, order.email))
oo(col(3, AlConst.Text.Order.phone, order.phone))
})
oo(Row().with {
oo(AlRender.orderDocumentTypeColumn(order))
oo(AlRender.orderDocumentCategoryColumn(order))
})
oo(AlRender.renderOrderNumsRow(order))
oo(DetailsRow().content(order.documentDetails))
if (rctx().pretending.get() == AlUserKind.Admin) {
if (!order.adminNotes.isNullOrBlank())
oo(DetailsRow().title(AlConst.Text.adminNotes).content(order.adminNotes))
}
}
}
override fun shouldStopRenderingWithMessage() = when {
rctx().pretending.get() == AlUserKind.Writer -> t("TOTE", "Никаким писателям этот заказ не виден")
else -> null
}
fun renderRejectionReason(title: String) =
AlRender.detailsWithUnderlinedTitle(title, juan.entity.rejectionReason)
override fun shouldSkipField(fields: BunchOfFields, field: FormField<*>): Boolean {
// TODO:vgrechka ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
return false
}
override fun isPagePrivate() = AlGetParams().uuid.get() == null
override fun getUUIDSupported() = true
override fun checkPermissionsForEntityAccessedViaIDIfNotAdmin(entity: AlUAOrder) =
when (rctx().userWP().kind) {
AlUserKind.Customer -> imf("Check that this customer is the one who created the order")
AlUserKind.Writer -> imf("Check that this writer is assigned to the order")
AlUserKind.Admin -> wtf()
}
}
return t.build(pedro)
}
}
| apache-2.0 |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/host/recycle/RecycleHostFactory.kt | 2 | 1581 | package com.github.kerubistan.kerub.planner.steps.host.recycle
import com.github.kerubistan.kerub.model.Expectation
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.dynamic.HostDynamic
import com.github.kerubistan.kerub.model.dynamic.HostStatus
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.issues.problems.hosts.RecyclingHost
import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStepFactory
import kotlin.reflect.KClass
object RecycleHostFactory : AbstractOperationalStepFactory<RecycleHost>() {
override val problemHints = setOf(RecyclingHost::class)
override val expectationHints = setOf<KClass<out Expectation>>()
override fun produce(state: OperationalState): List<RecycleHost> =
state.hosts.values.filter { (host, dyn) ->
//the host is being recycled
host.recycling &&
isHostFree(host, state) &&
canDropFreeHost(host, dyn)
}.map {
RecycleHost(it.stat)
}
private fun canDropFreeHost(
host: Host, dyn: HostDynamic?
) =
//it is either dedicated and shut down, or not dedicated
((host.dedicated && (dyn == null || dyn.status == HostStatus.Down))
|| !host.dedicated)
private fun isHostFree(host: Host, state: OperationalState) =
//no more disk allocations on it
state.vStorage.values.none {
it.dynamic?.allocations?.any { allocation ->
allocation.hostId == host.id
} ?: false
} &&
//no vms running on it
state.index.runningVms.none {
it.dynamic?.hostId == host.id
}
} | apache-2.0 |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/host/distros/Cygwin.kt | 2 | 3875 | package com.github.kerubistan.kerub.host.distros
import com.github.kerubistan.kerub.data.dynamic.HostDynamicDao
import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao
import com.github.kerubistan.kerub.data.dynamic.doWithDyn
import com.github.kerubistan.kerub.host.FireWall
import com.github.kerubistan.kerub.host.PackageManager
import com.github.kerubistan.kerub.host.ServiceManager
import com.github.kerubistan.kerub.host.packman.CygwinPackageManager
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.HostCapabilities
import com.github.kerubistan.kerub.model.OperatingSystem
import com.github.kerubistan.kerub.model.SoftwarePackage
import com.github.kerubistan.kerub.model.StorageCapability
import com.github.kerubistan.kerub.model.Version
import com.github.kerubistan.kerub.model.controller.config.ControllerConfig
import com.github.kerubistan.kerub.model.dynamic.HostStatus
import com.github.kerubistan.kerub.model.hardware.BlockDevice
import com.github.kerubistan.kerub.model.lom.PowerManagementInfo
import com.github.kerubistan.kerub.utils.asPercentOf
import com.github.kerubistan.kerub.utils.junix.common.OsCommand
import com.github.kerubistan.kerub.utils.junix.procfs.MemInfo
import com.github.kerubistan.kerub.utils.junix.procfs.Stat
import com.github.kerubistan.kerub.utils.junix.uname.UName
import io.github.kerubistan.kroki.time.now
import org.apache.sshd.client.session.ClientSession
import java.math.BigInteger
class Cygwin : Distribution {
override fun listBlockDevices(session: ClientSession): List<BlockDevice>
// TODO : find a way to get block device list from windows - wmic maybe?
= listOf()
override fun getVersion(session: ClientSession) =
Version.fromVersionString(UName.kernelVersion(session).substringBefore("("))
override fun name(): String =
"Cygwin"
override fun handlesVersion(version: Version): Boolean = version.major.toInt() >= 2
override fun detect(session: ClientSession): Boolean = UName.operatingSystem(session) == "Cygwin"
override fun getPackageManager(session: ClientSession): PackageManager = CygwinPackageManager(session)
override fun installMonitorPackages(session: ClientSession, host: Host) {
// do nothing, cygwin can not install, try to work with what is installed
}
override fun startMonitorProcesses(
session: ClientSession,
host: Host,
hostDynDao: HostDynamicDao,
vStorageDeviceDynamicDao: VirtualStorageDeviceDynamicDao,
controllerConfig: ControllerConfig
) {
Stat.cpuLoadMonitorIncremental(session) { cpus ->
val idle = cpus["cpu"]?.idle ?: 0
val user = cpus["cpu"]?.user ?: 0
val system = cpus["cpu"]?.system ?: 0
val sum = system + idle + user
hostDynDao.doWithDyn(host.id) { dyn ->
dyn.copy(
status = HostStatus.Up,
idleCpu = idle.asPercentOf(sum).toByte(),
systemCpu = system.asPercentOf(sum).toByte(),
userCpu = user.asPercentOf(sum).toByte(),
lastUpdated = now()
)
}
}
}
override fun getRequiredPackages(osCommand: OsCommand, capabilities: HostCapabilities?): List<String> = listOf()
override fun detectStorageCapabilities(
session: ClientSession, osVersion: SoftwarePackage, packages: List<SoftwarePackage>
): List<StorageCapability> = listOf()
override fun detectPowerManagement(session: ClientSession): List<PowerManagementInfo> = listOf() // TODO
override fun detectHostCpuType(session: ClientSession): String = UName.processorType(session).toUpperCase()
override fun getTotalMemory(session: ClientSession): BigInteger =
MemInfo.total(session)
override fun getFireWall(session: ClientSession): FireWall {
TODO()
}
override fun getServiceManager(session: ClientSession): ServiceManager {
TODO()
}
override fun getHostOs(): OperatingSystem = operatingSystem
override val operatingSystem = OperatingSystem.Windows
}
| apache-2.0 |
vovagrechka/fucking-everything | phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/run/PyVirtualEnvReader.kt | 1 | 4457 | /*
* Copyright 2000-2016 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 vgrechka.phizdetsidea.phizdets.run
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.EnvironmentUtil
import com.intellij.util.LineSeparator
import vgrechka.phizdetsidea.phizdets.sdk.PhizdetsSdkType
import java.io.File
/**
* @author traff
*/
class PyVirtualEnvReader(val virtualEnvSdkPath: String) : EnvironmentUtil.ShellEnvReader() {
private val LOG = Logger.getInstance("#vgrechka.phizdetsidea.phizdets.run.PyVirtualEnvReader")
companion object {
val virtualEnvVars = listOf("PATH", "PS1", "VIRTUAL_ENV", "PYTHONHOME", "PROMPT", "_OLD_VIRTUAL_PROMPT", "_OLD_VIRTUAL_PYTHONHOME",
"_OLD_VIRTUAL_PATH")
}
// in case of Conda we need to pass an argument to an activate script that tells which exactly environment to activate
val activate: Pair<String, String?>? = findActivateScript(virtualEnvSdkPath, shell)
override fun getShell(): String? {
if (File("/bin/bash").exists()) {
return "/bin/bash";
}
else
if (File("/bin/sh").exists()) {
return "/bin/sh";
}
else {
return super.getShell();
}
}
override fun readShellEnv(): MutableMap<String, String> {
if (SystemInfo.isUnix) {
return super.readShellEnv()
}
else {
if (activate != null) {
return readVirtualEnvOnWindows(activate);
}
else {
LOG.error("Can't find activate script for $virtualEnvSdkPath")
return mutableMapOf();
}
}
}
private fun readVirtualEnvOnWindows(activate: Pair<String, String?>): MutableMap<String, String> {
val activateFile = FileUtil.createTempFile("pycharm-virualenv-activate.", ".bat", false)
val envFile = FileUtil.createTempFile("pycharm-virualenv-envs.", ".tmp", false)
try {
FileUtil.copy(File(activate.first), activateFile);
FileUtil.appendToFile(activateFile, "\n\nset >" + envFile.absoluteFile)
val command = if (activate.second != null) listOf<String>(activateFile.path, activate.second!!)
else listOf<String>(activateFile.path)
return runProcessAndReadEnvs(command, envFile, LineSeparator.CRLF.separatorString)
}
finally {
FileUtil.delete(activateFile)
FileUtil.delete(envFile)
}
}
override fun getShellProcessCommand(): MutableList<String> {
val shellPath = shell
if (shellPath == null || !File(shellPath).canExecute()) {
throw Exception("shell:" + shellPath)
}
return if (activate != null) {
val activateArg = if (activate.second != null) "'${activate.first}' '${activate.second}'" else "'${activate.first}'"
mutableListOf(shellPath, "-c", ". $activateArg")
}
else super.getShellProcessCommand()
}
}
fun findActivateScript(path: String?, shellPath: String?): Pair<String, String?>? {
val shellName = if (shellPath != null) File(shellPath).name else null
val activate = if (SystemInfo.isWindows) findActivateOnWindows(path)
else if (shellName == "fish" || shellName == "csh") File(File(path).parentFile, "activate." + shellName)
else File(File(path).parentFile, "activate")
return if (activate != null && activate.exists()) {
val sdk = PhizdetsSdkType.findSdkByPath(path)
if (sdk != null && PhizdetsSdkType.isCondaVirtualEnv(sdk)) Pair(activate.absolutePath, condaEnvFolder(path))
else Pair(activate.absolutePath, null)
}
else null
}
private fun condaEnvFolder(path: String?) = if (SystemInfo.isWindows) File(path).parent else File(path).parentFile.parent
private fun findActivateOnWindows(path: String?): File? {
for (location in arrayListOf("activate.bat", "Scripts/activate.bat")) {
val file = File(File(path).parentFile, location)
if (file.exists()) {
return file
}
}
return null
} | apache-2.0 |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/interfaces/WeeklyCalendar.kt | 1 | 195 | package com.simplemobiletools.calendar.pro.interfaces
import com.simplemobiletools.calendar.pro.models.Event
interface WeeklyCalendar {
fun updateWeeklyCalendar(events: ArrayList<Event>)
}
| gpl-3.0 |
kingargyle/serenity-android | emby-lib/src/main/kotlin/us/nineworlds/serenity/emby/server/api/FilterService.kt | 2 | 603 | package us.nineworlds.serenity.emby.server.api
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.HeaderMap
import retrofit2.http.Query
import us.nineworlds.serenity.emby.server.model.QueryFilters
interface FilterService {
@GET("/emby/Genres?EnableUserData=false&SortBy=SortName&SortOrder=Ascending&EnableTotalRecordCount=false&EnableImages=false")
fun availableFilters(
@HeaderMap headerMap: Map<String, String>,
@Query("userId") userId: String,
@Query("ParentId") itemId: String? = null,
@Query("Recursive") recursive: Boolean = true
): Call<QueryFilters>
} | mit |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/cabal/psi/Section.kt | 1 | 1069 | package org.jetbrains.cabal.psi
import com.intellij.lang.ASTNode
import com.intellij.extapi.psi.ASTDelegatePsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.SharedImplUtil
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.cabal.psi.PropertyField
import org.jetbrains.cabal.psi.Checkable
import org.jetbrains.cabal.highlight.ErrorMessage
import java.util.ArrayList
open class Section(node: ASTNode): Field(node), FieldContainer, Checkable {
override fun check(): List<ErrorMessage> = listOf()
fun getSectChildren(): List<PsiElement> = children.filter { it is Field }
fun getSectTypeNode(): PsiElement = (children.firstOrNull { it is SectionType }) ?: throw IllegalStateException()
fun getSectType(): String = getSectTypeNode().text!!
protected open fun getSectName(): String? {
var node = firstChild
while ((node != null) && (node !is Name)) {
node = node.nextSibling
}
return (node as? Name)?.text
}
} | apache-2.0 |
androidx/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/KotlinPoetExt.kt | 3 | 3973 | /*
* Copyright 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 androidx.room.compiler.processing
import androidx.room.compiler.codegen.XTypeName
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.OriginatingElementsHolder
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.javapoet.KClassName
internal val KOTLIN_NONE_TYPE_NAME: KClassName =
KClassName("androidx.room.compiler.processing.error", "NotAType")
/**
* Adds the given element as an originating element for compilation.
* see [OriginatingElementsHolder.Builder.addOriginatingElement].
*/
fun <T : OriginatingElementsHolder.Builder<T>> T.addOriginatingElement(
element: XElement
): T {
element.originatingElementForPoet()?.let(this::addOriginatingElement)
return this
}
internal fun TypeName.rawTypeName(): TypeName {
return if (this is ParameterizedTypeName) {
this.rawType
} else {
this
}
}
object FunSpecHelper {
fun overriding(
elm: XMethodElement,
owner: XType
): FunSpec.Builder {
val asMember = elm.asMemberOf(owner)
return overriding(
executableElement = elm,
resolvedType = asMember
)
}
private fun overriding(
executableElement: XMethodElement,
resolvedType: XMethodType
): FunSpec.Builder {
return FunSpec.builder(executableElement.name).apply {
addModifiers(KModifier.OVERRIDE)
if (executableElement.isPublic()) {
addModifiers(KModifier.PUBLIC)
} else if (executableElement.isProtected()) {
addModifiers(KModifier.PROTECTED)
}
if (executableElement.isSuspendFunction()) {
addModifiers(KModifier.SUSPEND)
}
// TODO(b/251316420): Add type variable names
val isVarArgs = executableElement.isVarArgs()
resolvedType.parameterTypes.let {
// Drop the synthetic Continuation param of suspend functions, always at the last
// position.
// TODO(b/254135327): Revisit with the introduction of a target language.
if (resolvedType.isSuspendFunction()) it.dropLast(1) else it
}.forEachIndexed { index, paramType ->
val typeName: XTypeName
val modifiers: Array<KModifier>
// TODO(b/253268357): In Kotlin the vararg is not always the last param
if (isVarArgs && index == resolvedType.parameterTypes.size - 1) {
typeName = (paramType as XArrayType).componentType.asTypeName()
modifiers = arrayOf(KModifier.VARARG)
} else {
typeName = paramType.asTypeName()
modifiers = emptyArray()
}
addParameter(
executableElement.parameters[index].name,
typeName.kotlin,
*modifiers
)
}
returns(
if (resolvedType.isSuspendFunction()) {
resolvedType.getSuspendFunctionReturnType()
} else {
resolvedType.returnType
}.asTypeName().kotlin
)
}
}
} | apache-2.0 |
androidx/androidx | glance/glance-appwidget/glance-layout-generator/src/main/kotlin/androidx/glance/appwidget/layoutgenerator/ClearResources.kt | 3 | 979 | /*
* Copyright 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 androidx.glance.appwidget.layoutgenerator
import java.io.File
fun cleanResources(resourcesFolder: File, generatedFiles: Set<File>) {
checkNotNull(resourcesFolder.listFiles()).forEach {
if (it.isDirectory) {
cleanResources(it, generatedFiles)
} else if (it !in generatedFiles) {
it.delete()
}
}
}
| apache-2.0 |
androidx/androidx | compose/compiler/compiler-hosted/integration-tests/src/test/java/androidx/compose/compiler/plugins/kotlin/LiveLiteralTransformTests.kt | 3 | 17909 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin
import org.junit.Test
class LiveLiteralTransformTests : AbstractLiveLiteralTransformTests() {
override val liveLiteralsEnabled: Boolean
get() = true
fun testSiblingCallArgs() = assertNoDuplicateKeys(
"""
fun Test() {
print(1)
print(1)
}
"""
)
fun testFunctionCallWithConstArg() = assertKeys(
"Int%arg-0%call-print%fun-Test",
"Int%arg-0%call-print-1%fun-Test"
) {
"""
fun Test() {
print(1)
print(1)
}
"""
}
fun testDispatchReceiver() = assertKeys(
"Int%%this%call-toString%arg-0%call-print%fun-Test",
"Int%arg-0%call-print-1%fun-Test"
) {
"""
fun Test() {
print(1.toString())
print(1)
}
"""
}
fun testInsidePropertyGetter() = assertKeys(
"Int%fun-%get-foo%%get%val-foo"
) {
"""
val foo: Int get() = 1
"""
}
// NOTE(lmr): For static initializer expressions we can/should do more.
fun testInsidePropertyInitializer() = assertKeys {
"""
val foo: Int = 1
"""
}
fun testValueParameter() = assertKeys(
"Int%param-x%fun-Foo"
) {
"""
fun Foo(x: Int = 1) { print(x) }
"""
}
fun testAnnotation() = assertKeys {
"""
annotation class Foo(val value: Int = 1)
@Foo fun Bar() {}
@Foo(2) fun Bam() {}
"""
}
// NOTE(lmr): In the future we should try and get this to work
fun testForLoop() = assertKeys {
"""
fun Foo() {
for (x in 0..10) {
print(x)
}
}
"""
}
fun testWhileTrue() = assertKeys(
"Double%arg-1%call-greater%cond%if%body%loop%fun-Foo",
"Int%arg-0%call-print%body%loop%fun-Foo"
) {
"""
fun Foo() {
while (true) {
print(1)
if (Math.random() > 0.5) break
}
}
"""
}
fun testWhileCondition() = assertKeys(
"Int%arg-0%call-print%body%loop%fun-Foo"
) {
"""
fun Foo() {
while (Math.random() > 0.5) {
print(1)
}
}
"""
}
fun testForInCollection() = assertKeys(
"Int%arg-0%call-print-1%body%loop%fun-Foo"
) {
"""
fun Foo(items: List<Int>) {
for (item in items) {
print(item)
print(1)
}
}
"""
}
// NOTE(lmr): we should deal with this in some cases, but leaving untouched for now
fun testConstantProperty() = assertKeys {
"""
const val foo = 1
"""
}
fun testSafeCall() = assertKeys(
"Boolean%arg-1%call-EQEQ%fun-Foo",
"String%arg-0%call-contains%else%when%arg-0%call-EQEQ%fun-Foo"
) {
"""
fun Foo(bar: String?): Boolean {
return bar?.contains("foo") == true
}
"""
}
fun testElvis() = assertKeys(
"String%branch%when%fun-Foo"
) {
"""
fun Foo(bar: String?): String {
return bar ?: "Hello World"
}
"""
}
fun testTryCatch() = assertKeys(
"Int%arg-0%call-invoke%catch%fun-Foo",
"Int%arg-0%call-invoke%finally%fun-Foo",
"Int%arg-0%call-invoke%try%fun-Foo"
) {
"""
fun Foo(block: (Int) -> Unit) {
try {
block(1)
} catch(e: Exception) {
block(2)
} finally {
block(3)
}
}
"""
}
fun testWhen() = assertKeys(
"Double%arg-1%call-greater%cond%when%fun-Foo",
"Double%arg-1%call-greater%cond-1%when%fun-Foo",
"Int%arg-0%call-print%branch%when%fun-Foo",
"Int%arg-0%call-print%branch-1%when%fun-Foo",
"Int%arg-0%call-print%else%when%fun-Foo"
) {
"""
fun Foo() {
when {
Math.random() > 0.5 -> print(1)
Math.random() > 0.5 -> print(2)
else -> print(3)
}
}
"""
}
fun testWhenWithSubject() = assertKeys(
"Double%%%this%call-rangeTo%%this%call-contains%cond%when%fun-Foo",
"Double%%%this%call-rangeTo%%this%call-contains%cond-1%when%fun-Foo",
"Double%arg-0%call-rangeTo%%this%call-contains%cond%when%fun-Foo",
"Double%arg-0%call-rangeTo%%this%call-contains%cond-1%when%fun-Foo",
"Int%arg-0%call-print%branch%when%fun-Foo",
"Int%arg-0%call-print%branch-1%when%fun-Foo",
"Int%arg-0%call-print%else%when%fun-Foo"
) {
"""
fun Foo() {
when (val x = Math.random()) {
in 0.0..0.5 -> print(1)
in 0.0..0.2 -> print(2)
else -> print(3)
}
}
"""
}
fun testWhenWithSubject2() = assertKeys(
"Int%arg-0%call-print%branch-1%when%fun-Foo",
"Int%arg-0%call-print%else%when%fun-Foo",
"String%arg-0%call-print%branch%when%fun-Foo"
) {
"""
fun Foo(foo: Any) {
when (foo) {
is String -> print("Hello World")
is Int -> print(2)
else -> print(3)
}
}
"""
}
fun testDelegatingCtor() = assertKeys(
"Int%arg-0%call-%init%%class-Bar"
) {
"""
open class Foo(val x: Int)
class Bar() : Foo(123)
"""
}
fun testLocalVal() = assertKeys(
"Int%arg-0%call-plus%set-y%fun-Foo",
"Int%val-x%fun-Foo",
"Int%val-y%fun-Foo"
) {
"""
fun Foo() {
val x = 1
var y = 2
y += 10
}
"""
}
fun testCapturedVar() = assertKeys(
"Int%val-a%fun-Example",
"String%0%str%fun-Example",
"String%2%str%fun-Example"
) {
"""
fun Example(): String {
val a = 123
return "foo ${"$"}a bar"
}
"""
}
@Test
fun testStringTemplate(): Unit = assertKeys(
"Int%val-a%fun-Example",
"String%0%str%fun-Example",
"String%2%str%fun-Example"
) {
"""
fun Example(): String {
val a = 123
return "foo ${"$"}a bar"
}
"""
}
@Test
fun testEnumEntryMultipleArgs(): Unit = assertKeys(
"Int%arg-0%call-%init%%entry-Bar%class-A",
"Int%arg-0%call-%init%%entry-Baz%class-A",
"Int%arg-0%call-%init%%entry-Foo%class-A",
"Int%arg-1%call-%init%%entry-Bar%class-A",
"Int%arg-1%call-%init%%entry-Baz%class-A",
"Int%arg-1%call-%init%%entry-Foo%class-A"
) {
"""
enum class A(val x: Int, val y: Int) {
Foo(1, 2),
Bar(2, 3),
Baz(3, 4)
}
"""
}
fun testCommentsAbove() = assertDurableChange(
"""
fun Test() {
print(1)
}
""".trimIndent(),
"""
fun Test() {
// this is a comment
print(1)
}
""".trimIndent()
)
fun testValsAndStructureAbove() = assertDurableChange(
"""
fun Test() {
print(1)
}
""".trimIndent(),
"""
fun Test() {
val x = Math.random()
println(x)
print(1)
}
""".trimIndent()
)
@Test
fun testAnonymousClass(): Unit = assertTransform(
"""
""",
"""
interface Foo { fun bar(): Int }
fun a(): Foo {
return object : Foo {
override fun bar(): Int { return 1 }
}
}
""",
"""
interface Foo {
abstract fun bar(): Int
}
fun a(): Foo {
return object : Foo {
override fun bar(): Int {
return LiveLiterals%TestKt.Int%fun-bar%class-%no-name-provided%%fun-a()
}
}
}
@LiveLiteralFileInfo(file = "/Test.kt")
internal object LiveLiterals%TestKt {
val Int%fun-bar%class-%no-name-provided%%fun-a: Int = 1
var State%Int%fun-bar%class-%no-name-provided%%fun-a: State<Int>?
@LiveLiteralInfo(key = "Int%fun-bar%class-%no-name-provided%%fun-a", offset = 159)
fun Int%fun-bar%class-%no-name-provided%%fun-a(): Int {
if (!isLiveLiteralsEnabled) {
return Int%fun-bar%class-%no-name-provided%%fun-a
}
val tmp0 = State%Int%fun-bar%class-%no-name-provided%%fun-a
return if (tmp0 == null) {
val tmp1 = liveLiteral("Int%fun-bar%class-%no-name-provided%%fun-a", Int%fun-bar%class-%no-name-provided%%fun-a)
State%Int%fun-bar%class-%no-name-provided%%fun-a = tmp1
tmp1
} else {
tmp0
}
.value
}
}
"""
)
@Test
fun testBasicTransform(): Unit = assertTransform(
"""
""",
"""
fun A() {
print(1)
print("Hello World")
if (true) {
print(3 + 4)
}
if (true) {
print(1.0f)
}
print(3)
}
""",
"""
fun A() {
print(LiveLiterals%TestKt.Int%arg-0%call-print%fun-A())
print(LiveLiterals%TestKt.String%arg-0%call-print-1%fun-A())
if (LiveLiterals%TestKt.Boolean%cond%if%fun-A()) {
print(LiveLiterals%TestKt.Int%%this%call-plus%arg-0%call-print%branch%if%fun-A() + LiveLiterals%TestKt.Int%arg-0%call-plus%arg-0%call-print%branch%if%fun-A())
}
if (LiveLiterals%TestKt.Boolean%cond%if-1%fun-A()) {
print(LiveLiterals%TestKt.Float%arg-0%call-print%branch%if-1%fun-A())
}
print(LiveLiterals%TestKt.Int%arg-0%call-print-2%fun-A())
}
@LiveLiteralFileInfo(file = "/Test.kt")
internal object LiveLiterals%TestKt {
val Int%arg-0%call-print%fun-A: Int = 1
var State%Int%arg-0%call-print%fun-A: State<Int>?
@LiveLiteralInfo(key = "Int%arg-0%call-print%fun-A", offset = 62)
fun Int%arg-0%call-print%fun-A(): Int {
if (!isLiveLiteralsEnabled) {
return Int%arg-0%call-print%fun-A
}
val tmp0 = State%Int%arg-0%call-print%fun-A
return if (tmp0 == null) {
val tmp1 = liveLiteral("Int%arg-0%call-print%fun-A", Int%arg-0%call-print%fun-A)
State%Int%arg-0%call-print%fun-A = tmp1
tmp1
} else {
tmp0
}
.value
}
val String%arg-0%call-print-1%fun-A: String = "Hello World"
var State%String%arg-0%call-print-1%fun-A: State<String>?
@LiveLiteralInfo(key = "String%arg-0%call-print-1%fun-A", offset = 74)
fun String%arg-0%call-print-1%fun-A(): String {
if (!isLiveLiteralsEnabled) {
return String%arg-0%call-print-1%fun-A
}
val tmp0 = State%String%arg-0%call-print-1%fun-A
return if (tmp0 == null) {
val tmp1 = liveLiteral("String%arg-0%call-print-1%fun-A", String%arg-0%call-print-1%fun-A)
State%String%arg-0%call-print-1%fun-A = tmp1
tmp1
} else {
tmp0
}
.value
}
val Boolean%cond%if%fun-A: Boolean = true
var State%Boolean%cond%if%fun-A: State<Boolean>?
@LiveLiteralInfo(key = "Boolean%cond%if%fun-A", offset = 94)
fun Boolean%cond%if%fun-A(): Boolean {
if (!isLiveLiteralsEnabled) {
return Boolean%cond%if%fun-A
}
val tmp0 = State%Boolean%cond%if%fun-A
return if (tmp0 == null) {
val tmp1 = liveLiteral("Boolean%cond%if%fun-A", Boolean%cond%if%fun-A)
State%Boolean%cond%if%fun-A = tmp1
tmp1
} else {
tmp0
}
.value
}
val Int%%this%call-plus%arg-0%call-print%branch%if%fun-A: Int = 3
var State%Int%%this%call-plus%arg-0%call-print%branch%if%fun-A: State<Int>?
@LiveLiteralInfo(key = "Int%%this%call-plus%arg-0%call-print%branch%if%fun-A", offset = 112)
fun Int%%this%call-plus%arg-0%call-print%branch%if%fun-A(): Int {
if (!isLiveLiteralsEnabled) {
return Int%%this%call-plus%arg-0%call-print%branch%if%fun-A
}
val tmp0 = State%Int%%this%call-plus%arg-0%call-print%branch%if%fun-A
return if (tmp0 == null) {
val tmp1 = liveLiteral("Int%%this%call-plus%arg-0%call-print%branch%if%fun-A", Int%%this%call-plus%arg-0%call-print%branch%if%fun-A)
State%Int%%this%call-plus%arg-0%call-print%branch%if%fun-A = tmp1
tmp1
} else {
tmp0
}
.value
}
val Int%arg-0%call-plus%arg-0%call-print%branch%if%fun-A: Int = 4
var State%Int%arg-0%call-plus%arg-0%call-print%branch%if%fun-A: State<Int>?
@LiveLiteralInfo(key = "Int%arg-0%call-plus%arg-0%call-print%branch%if%fun-A", offset = 116)
fun Int%arg-0%call-plus%arg-0%call-print%branch%if%fun-A(): Int {
if (!isLiveLiteralsEnabled) {
return Int%arg-0%call-plus%arg-0%call-print%branch%if%fun-A
}
val tmp0 = State%Int%arg-0%call-plus%arg-0%call-print%branch%if%fun-A
return if (tmp0 == null) {
val tmp1 = liveLiteral("Int%arg-0%call-plus%arg-0%call-print%branch%if%fun-A", Int%arg-0%call-plus%arg-0%call-print%branch%if%fun-A)
State%Int%arg-0%call-plus%arg-0%call-print%branch%if%fun-A = tmp1
tmp1
} else {
tmp0
}
.value
}
val Boolean%cond%if-1%fun-A: Boolean = true
var State%Boolean%cond%if-1%fun-A: State<Boolean>?
@LiveLiteralInfo(key = "Boolean%cond%if-1%fun-A", offset = 129)
fun Boolean%cond%if-1%fun-A(): Boolean {
if (!isLiveLiteralsEnabled) {
return Boolean%cond%if-1%fun-A
}
val tmp0 = State%Boolean%cond%if-1%fun-A
return if (tmp0 == null) {
val tmp1 = liveLiteral("Boolean%cond%if-1%fun-A", Boolean%cond%if-1%fun-A)
State%Boolean%cond%if-1%fun-A = tmp1
tmp1
} else {
tmp0
}
.value
}
val Float%arg-0%call-print%branch%if-1%fun-A: Float = 1.0f
var State%Float%arg-0%call-print%branch%if-1%fun-A: State<Float>?
@LiveLiteralInfo(key = "Float%arg-0%call-print%branch%if-1%fun-A", offset = 147)
fun Float%arg-0%call-print%branch%if-1%fun-A(): Float {
if (!isLiveLiteralsEnabled) {
return Float%arg-0%call-print%branch%if-1%fun-A
}
val tmp0 = State%Float%arg-0%call-print%branch%if-1%fun-A
return if (tmp0 == null) {
val tmp1 = liveLiteral("Float%arg-0%call-print%branch%if-1%fun-A", Float%arg-0%call-print%branch%if-1%fun-A)
State%Float%arg-0%call-print%branch%if-1%fun-A = tmp1
tmp1
} else {
tmp0
}
.value
}
val Int%arg-0%call-print-2%fun-A: Int = 3
var State%Int%arg-0%call-print-2%fun-A: State<Int>?
@LiveLiteralInfo(key = "Int%arg-0%call-print-2%fun-A", offset = 165)
fun Int%arg-0%call-print-2%fun-A(): Int {
if (!isLiveLiteralsEnabled) {
return Int%arg-0%call-print-2%fun-A
}
val tmp0 = State%Int%arg-0%call-print-2%fun-A
return if (tmp0 == null) {
val tmp1 = liveLiteral("Int%arg-0%call-print-2%fun-A", Int%arg-0%call-print-2%fun-A)
State%Int%arg-0%call-print-2%fun-A = tmp1
tmp1
} else {
tmp0
}
.value
}
}
"""
)
}
| apache-2.0 |
androidx/androidx | core/core-ktx/src/androidTest/java/androidx/core/util/SparseIntArrayTest.kt | 3 | 5584 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.util
import android.util.SparseIntArray
import androidx.test.filters.SmallTest
import androidx.testutils.fail
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
@SmallTest
class SparseIntArrayTest {
@Test fun sizeProperty() {
val array = SparseIntArray()
assertEquals(0, array.size)
array.put(1, 11)
assertEquals(1, array.size)
}
@Test fun containsOperator() {
val array = SparseIntArray()
assertFalse(1 in array)
array.put(1, 11)
assertTrue(1 in array)
}
@Test fun containsOperatorWithValue() {
val array = SparseIntArray()
array.put(1, 11)
assertFalse(2 in array)
array.put(2, 22)
assertTrue(2 in array)
}
@Test fun setOperator() {
val array = SparseIntArray()
array[1] = 11
assertEquals(11, array.get(1))
}
@Test fun plusOperator() {
val first = SparseIntArray().apply { put(1, 11) }
val second = SparseIntArray().apply { put(2, 22) }
val combined = first + second
assertEquals(2, combined.size())
assertEquals(1, combined.keyAt(0))
assertEquals(11, combined.valueAt(0))
assertEquals(2, combined.keyAt(1))
assertEquals(22, combined.valueAt(1))
}
@Test fun containsKey() {
val array = SparseIntArray()
assertFalse(array.containsKey(1))
array.put(1, 11)
assertTrue(array.containsKey(1))
}
@Test fun containsKeyWithValue() {
val array = SparseIntArray()
array.put(1, 11)
assertFalse(array.containsKey(2))
array.put(2, 22)
assertTrue(array.containsKey(2))
}
@Test fun containsValue() {
val array = SparseIntArray()
assertFalse(array.containsValue(11))
array.put(1, 11)
assertTrue(array.containsValue(11))
}
@Test fun getOrDefault() {
val array = SparseIntArray()
assertEquals(22, array.getOrDefault(1, 22))
array.put(1, 11)
assertEquals(11, array.getOrDefault(1, 22))
}
@Test fun getOrElse() {
val array = SparseIntArray()
assertEquals(22, array.getOrElse(1) { 22 })
array.put(1, 11)
assertEquals(11, array.getOrElse(1) { fail() })
assertEquals(33, array.getOrElse(2) { 33 })
}
@Test fun isEmpty() {
val array = SparseIntArray()
assertTrue(array.isEmpty())
array.put(1, 11)
assertFalse(array.isEmpty())
}
@Test fun isNotEmpty() {
val array = SparseIntArray()
assertFalse(array.isNotEmpty())
array.put(1, 11)
assertTrue(array.isNotEmpty())
}
@Test fun removeValue() {
val array = SparseIntArray()
array.put(1, 11)
assertFalse(array.remove(2, 11))
assertEquals(1, array.size())
assertFalse(array.remove(1, 22))
assertEquals(1, array.size())
assertTrue(array.remove(1, 11))
assertEquals(0, array.size())
}
@Test fun putAll() {
val dest = SparseIntArray()
val source = SparseIntArray()
source.put(1, 11)
assertEquals(0, dest.size())
dest.putAll(source)
assertEquals(1, dest.size())
}
@Test fun forEach() {
val array = SparseIntArray()
array.forEach { _, _ -> fail() }
array.put(1, 11)
array.put(2, 22)
array.put(6, 66)
val keys = mutableListOf<Int>()
val values = mutableListOf<Int>()
array.forEach { key, value ->
keys.add(key)
values.add(value)
}
assertThat(keys).containsExactly(1, 2, 6)
assertThat(values).containsExactly(11, 22, 66)
}
@Test fun keyIterator() {
val array = SparseIntArray()
assertFalse(array.keyIterator().hasNext())
array.put(1, 11)
array.put(2, 22)
array.put(6, 66)
val iterator = array.keyIterator()
assertTrue(iterator.hasNext())
assertEquals(1, iterator.nextInt())
assertTrue(iterator.hasNext())
assertEquals(2, iterator.nextInt())
assertTrue(iterator.hasNext())
assertEquals(6, iterator.nextInt())
assertFalse(iterator.hasNext())
}
@Test fun valueIterator() {
val array = SparseIntArray()
assertFalse(array.valueIterator().hasNext())
array.put(1, 11)
array.put(2, 22)
array.put(6, 66)
val iterator = array.valueIterator()
assertTrue(iterator.hasNext())
assertEquals(11, iterator.nextInt())
assertTrue(iterator.hasNext())
assertEquals(22, iterator.nextInt())
assertTrue(iterator.hasNext())
assertEquals(66, iterator.nextInt())
assertFalse(iterator.hasNext())
}
}
| apache-2.0 |
androidx/androidx | paging/paging-rxjava2/src/test/java/androidx/paging/RxRemoteMediatorTest.kt | 3 | 2223 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.paging
import androidx.paging.RemoteMediator.InitializeAction.LAUNCH_INITIAL_REFRESH
import androidx.paging.RemoteMediator.InitializeAction.SKIP_INITIAL_REFRESH
import androidx.paging.rxjava2.RxRemoteMediator
import io.reactivex.Single
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import kotlin.test.assertEquals
import kotlin.test.fail
@OptIn(ExperimentalCoroutinesApi::class, ExperimentalPagingApi::class)
@RunWith(JUnit4::class)
class RxRemoteMediatorTest {
@Test
fun initializeSingle() = runTest {
val remoteMediator = object : RxRemoteMediator<Int, Int>() {
override fun loadSingle(
loadType: LoadType,
state: PagingState<Int, Int>
): Single<MediatorResult> {
fail("Unexpected call")
}
override fun initializeSingle(): Single<InitializeAction> {
return Single.just(SKIP_INITIAL_REFRESH)
}
}
assertEquals(SKIP_INITIAL_REFRESH, remoteMediator.initialize())
}
@Test
fun initializeSingleDefault() = runTest {
val remoteMediator = object : RxRemoteMediator<Int, Int>() {
override fun loadSingle(
loadType: LoadType,
state: PagingState<Int, Int>
): Single<MediatorResult> {
fail("Unexpected call")
}
}
assertEquals(LAUNCH_INITIAL_REFRESH, remoteMediator.initialize())
}
}
| apache-2.0 |
stoyicker/dinger | data/src/main/kotlin/data/tinder/recommendation/RecommendationUserCommonFriendPhotoDao.kt | 1 | 364 | package data.tinder.recommendation
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Insert
import android.arch.persistence.room.OnConflictStrategy
@Dao
internal interface RecommendationUserCommonFriendPhotoDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertPhoto(photo: RecommendationUserCommonFriendPhotoEntity)
}
| mit |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/testData/stepping/custom/severalFunLiterals.kt | 4 | 435 | package severalFunLiterals
fun main(args: Array<String>) {
val myClass = MyClass()
//Breakpoint! (lambdaOrdinal = -1)
myClass.f1 { test() }.f2 {
test()
}
}
class MyClass {
fun f1(f1Param: () -> Unit): MyClass {
f1Param()
return this
}
fun f2(f2Param: () -> Unit): MyClass {
f2Param()
return this
}
}
fun test() {}
// SMART_STEP_INTO_BY_INDEX: 4
// IGNORE_K2 | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/intentions/addAnnotationUseSiteTarget/constructor/var/file.kt | 13 | 121 | // CHOOSE_USE_SITE_TARGET: file
// IS_APPLICABLE: false
annotation class A
class Constructor(@A<caret> var foo: String) | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/base/indices/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeFqNameIndex.kt | 4 | 959 | // 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.StringStubIndexExtension
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey
import org.jetbrains.kotlin.psi.KtFile
object KotlinFileFacadeFqNameIndex : StringStubIndexExtension<KtFile>() {
private val KEY: StubIndexKey<String, KtFile> =
StubIndexKey.createIndexKey("org.jetbrains.kotlin.idea.stubindex.KotlinFileFacadeFqNameIndex")
override fun getKey(): StubIndexKey<String, KtFile> = KEY
override fun get(key: String, project: Project, scope: GlobalSearchScope): Collection<KtFile> {
return StubIndex.getElements(KEY, key, project, scope, KtFile::class.java)
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/multiModuleHighlighting/multiplatform/jvmKotlinReferencesCommonKotlinThroughJavaDifferentJvmImpls/a_jvm_id1/jvmA1.kt | 15 | 132 | package common
actual class A {
fun id1() {}
}
fun use() {
j1.Use.acceptA(j1.Use.returnA())
j1.Use.returnA().id1()
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/KotlinDebuggerCoroutinesBundle.kt | 4 | 695 | // 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.debugger.coroutine
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.kotlin.util.AbstractKotlinBundle
@NonNls
private const val BUNDLE = "messages.KotlinDebuggerCoroutinesBundle"
object KotlinDebuggerCoroutinesBundle : AbstractKotlinBundle(BUNDLE) {
@Nls
@JvmStatic
fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/service/WizardService.kt | 3 | 840 | // 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.core.service
interface WizardService
interface IdeaIndependentWizardService : WizardService
object Services {
val IDEA_INDEPENDENT_SERVICES: List<IdeaIndependentWizardService> = listOf(
ProjectImportingWizardServiceImpl(),
OsFileSystemWizardService(),
BuildSystemAvailabilityWizardServiceImpl(),
DummyFileFormattingService(),
CoreKotlinVersionProviderService(),
CoreJvmTargetVersionsProviderService(),
RunConfigurationsServiceImpl(),
EmptyInspectionWizardService(),
SettingSavingWizardServiceImpl(),
VelocityTemplateEngineServiceImpl()
)
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/completion/impl-shared/src/org/jetbrains/kotlin/idea/completion/implCommon/handlers/WithTailInsertHandler.kt | 4 | 4169 | // 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.completion.handlers
import com.intellij.codeInsight.AutoPopupController
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.components.serviceOrNull
import com.intellij.openapi.editor.Document
import com.intellij.psi.PsiDocumentManager
abstract class SmartCompletionTailOffsetProvider {
abstract fun getTailOffset(context: InsertionContext, item: LookupElement): Int
}
class WithTailInsertHandler(
val tailText: String,
val spaceBefore: Boolean,
val spaceAfter: Boolean,
val overwriteText: Boolean = true
) : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
item.handleInsert(context)
postHandleInsert(context, item)
}
val asPostInsertHandler: InsertHandler<LookupElement>
get() = InsertHandler { context, item ->
postHandleInsert(context, item)
}
fun postHandleInsert(context: InsertionContext, item: LookupElement) {
val completionChar = context.completionChar
if (completionChar == tailText.singleOrNull() || (spaceAfter && completionChar == ' ')) {
context.setAddCompletionChar(false)
}
//TODO: what if completion char is different?
val document = context.document
PsiDocumentManager.getInstance(context.project).doPostponedOperationsAndUnblockDocument(document)
var tailOffset = serviceOrNull<SmartCompletionTailOffsetProvider>()?.getTailOffset(context, item)
?:context.tailOffset
val moveCaret = context.editor.caretModel.offset == tailOffset
//TODO: analyze parenthesis balance to decide whether to replace or not
var insert = true
if (overwriteText) {
var offset = tailOffset
if (tailText != " ") {
offset = document.charsSequence.skipSpacesAndLineBreaks(offset)
}
if (shouldOverwriteChar(document, offset)) {
insert = false
offset += tailText.length
tailOffset = offset
if (spaceAfter && document.charsSequence.isCharAt(offset, ' ')) {
document.deleteString(offset, offset + 1)
}
}
}
var textToInsert = ""
if (insert) {
textToInsert = tailText
if (spaceBefore) textToInsert = " " + textToInsert
}
if (spaceAfter) textToInsert += " "
document.insertString(tailOffset, textToInsert)
if (moveCaret) {
context.editor.caretModel.moveToOffset(tailOffset + textToInsert.length)
if (tailText == ",") {
AutoPopupController.getInstance(context.project)?.autoPopupParameterInfo(context.editor, null)
}
}
}
private fun shouldOverwriteChar(document: Document, offset: Int): Boolean {
if (!document.isTextAt(offset, tailText)) return false
if (tailText == " " && document.charsSequence.isCharAt(offset + 1, '}')) return false // do not overwrite last space before '}'
return true
}
companion object {
val COMMA = WithTailInsertHandler(",", spaceBefore = false, spaceAfter = true /*TODO: use code style option*/)
val RPARENTH = WithTailInsertHandler(")", spaceBefore = false, spaceAfter = false)
val RBRACKET = WithTailInsertHandler("]", spaceBefore = false, spaceAfter = false)
val RBRACE = WithTailInsertHandler("}", spaceBefore = true, spaceAfter = false)
val ELSE = WithTailInsertHandler("else", spaceBefore = true, spaceAfter = true)
val EQ = WithTailInsertHandler("=", spaceBefore = true, spaceAfter = true) /*TODO: use code style options*/
val SPACE = WithTailInsertHandler(" ", spaceBefore = false, spaceAfter = false, overwriteText = true)
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/java/findJavaClassUsages/JKAliasedClassAllUsages.1.kt | 4 | 510 | import AAA as A
public class X(bar: String? = A.BAR): A() {
var next: A? = A()
val myBar: String? = A.BAR
init {
A.BAR = ""
AAA.foos()
}
fun foo(a: A) {
val aa: AAA = a
aa.bar = ""
}
fun getNext(): A? {
return next
}
public override fun foo() {
super<A>.foo()
}
companion object: AAA() {
}
}
object O: A() {
}
fun X.bar(a: A = A()) {
}
fun Any.toA(): A? {
return if (this is A) this as A else null
} | apache-2.0 |
lsmaira/gradle | buildSrc/subprojects/integration-testing/src/main/kotlin/org/gradle/gradlebuild/test/fixtures/TestFixturesExtension.kt | 1 | 1278 | /*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.gradlebuild.test.fixtures
/**
* Test Fixtures.
*
* Configures the project to use the test fixtures from another project, which by default is core.
* Note this is not used to create test fixtures in this project, see [TestFixturesPlugin] for that.
*/
open class TestFixturesExtension {
fun from(project: String) =
from(project, "test")
fun from(project: String, sourceSet: String) =
origins.add(TestFixturesOrigin(project, sourceSet))
internal
val origins: MutableList<TestFixturesOrigin> = mutableListOf()
}
internal
data class TestFixturesOrigin(val projectPath: String, val sourceSetName: String)
| apache-2.0 |
jwren/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/SearchResultUiState.kt | 2 | 316 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion
internal data class SearchResultUiState(
val selectedVersion: NormalizedPackageVersion<*>?,
val selectedScope: PackageScope?
)
| apache-2.0 |
PaleoCrafter/VanillaImmersion | src/main/kotlin/de/mineformers/vanillaimmersion/network/CraftingDrag.kt | 1 | 2006 | package de.mineformers.vanillaimmersion.network
import de.mineformers.vanillaimmersion.immersion.CraftingHandler
import de.mineformers.vanillaimmersion.tileentity.CraftingTableLogic
import io.netty.buffer.ByteBuf
import net.minecraft.util.math.BlockPos
import net.minecraftforge.fml.common.network.simpleimpl.IMessage
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext
/**
* Message and handler for notifying the server about a dragging operation on a crafting table.
*/
object CraftingDrag {
/**
* The message just holds the table's position and the list of slots affected by the operation.
*/
data class Message(var pos: BlockPos = BlockPos.ORIGIN,
var slots: MutableList<Int> = mutableListOf()) : IMessage {
override fun toBytes(buf: ByteBuf) {
buf.writeLong(pos.toLong())
buf.writeInt(slots.size)
for (i in slots)
buf.writeInt(i)
}
override fun fromBytes(buf: ByteBuf) {
pos = BlockPos.fromLong(buf.readLong())
val count = buf.readInt()
for (i in 1..count)
slots.add(buf.readInt())
}
}
object Handler : IMessageHandler<Message, IMessage> {
override fun onMessage(msg: Message, ctx: MessageContext): IMessage? {
val player = ctx.serverHandler.player
// We interact with the world, hence schedule our action
player.serverWorld.addScheduledTask {
if (!player.world.isBlockLoaded(msg.pos))
return@addScheduledTask
val tile = player.world.getTileEntity(msg.pos)
if (tile is CraftingTableLogic) {
// Delegate the dragging to the dedicated method
CraftingHandler.performDrag(tile, player, msg.slots)
}
}
return null
}
}
}
| mit |
GunoH/intellij-community | plugins/kotlin/completion/testData/keywords/NonLocalContinueEnabled.kt | 2 | 560 | // FIR_IDENTICAL
// FIR_COMPARISON
// COMPILER_ARGUMENTS: -XXLanguage:+BreakContinueInInlineLambdas
fun foo() {
myFor@
for (i in 1..10) {
while (x()) {
run {
cont<caret>
}
}
}
}
inline fun <T> run(block: () -> T): T = block()
// NUMBER: 2
// EXIST: {"lookupString":"continue","attributes":"bold","allLookupStrings":"continue","itemText":"continue"}
// EXIST: {"lookupString":"continue@myFor","tailText":"@myFor","attributes":"bold","allLookupStrings":"continue@myFor","itemText":"continue"} | apache-2.0 |
GunoH/intellij-community | platform/util/src/com/intellij/util/io/sanitize-name.kt | 3 | 1160 | package com.intellij.util.io
import java.util.function.Predicate
import kotlin.math.min
private val illegalChars = hashSetOf('/', '\\', '?', '<', '>', ':', '*', '|', '"')
// https://github.com/parshap/node-sanitize-filename/blob/master/index.js
fun sanitizeFileName(name: String, replacement: String? = "_", truncateIfNeeded: Boolean = true, extraIllegalChars: Predicate<Char>? = null): String {
var result: StringBuilder? = null
var last = 0
val length = name.length
for (i in 0 until length) {
val c = name[i]
if (!illegalChars.contains(c) && !c.isISOControl() && (extraIllegalChars == null || !extraIllegalChars.test(c))) {
continue
}
if (result == null) {
result = StringBuilder()
}
if (last < i) {
result.append(name, last, i)
}
if (replacement != null) {
result.append(replacement)
}
last = i + 1
}
fun truncateFileName(s: String) = if (truncateIfNeeded) s.substring(0, min(length, 255)) else s
if (result == null) {
return truncateFileName(name)
}
if (last < length) {
result.append(name, last, length)
}
return truncateFileName(result.toString())
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/base/codeInsight/tooling/AbstractNativeIdePlatformKindTooling.kt | 5 | 3306 | // 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.codeInsight.tooling
import com.intellij.execution.actions.RunConfigurationProducer
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.idea.base.facet.externalSystemNativeMainRunTasks
import org.jetbrains.kotlin.idea.base.facet.isTestModule
import org.jetbrains.kotlin.idea.base.platforms.KotlinNativeLibraryKind
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.highlighter.KotlinTestRunLineMarkerContributor
import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import javax.swing.Icon
interface KotlinNativeRunConfigurationProvider {
val isForTests: Boolean
}
abstract class AbstractNativeIdePlatformKindTooling : IdePlatformKindTooling() {
override val kind = NativeIdePlatformKind
override val mavenLibraryIds: List<String> get() = emptyList()
override val gradlePluginId: String get() = ""
override val gradlePlatformIds: List<KotlinPlatform> get() = listOf(KotlinPlatform.NATIVE)
override val libraryKind: PersistentLibraryKind<*> = KotlinNativeLibraryKind
override fun acceptsAsEntryPoint(function: KtFunction): Boolean {
val functionName = function.fqName?.asString() ?: return false
val module = function.module ?: return false
if (module.isTestModule) return false
val hasRunTask = module.externalSystemNativeMainRunTasks().any { it.entryPoint == functionName }
if (!hasRunTask) return false
val hasRunConfigurations = RunConfigurationProducer
.getProducers(function.project)
.asSequence()
.filterIsInstance<KotlinNativeRunConfigurationProvider>()
.any { !it.isForTests }
if (!hasRunConfigurations) return false
return true
}
protected fun getTestIcon(declaration: KtNamedDeclaration, moduleName: String): Icon? {
val targetName = moduleName.substringAfterLast(".").removeSuffix("Test>")
val urls = when (declaration) {
is KtClassOrObject -> {
val lightClass = declaration.toLightClass() ?: return null
listOf("java:suite://${lightClass.qualifiedName}")
}
is KtNamedFunction -> {
val lightMethod = declaration.toLightMethods().firstOrNull() ?: return null
val lightClass = lightMethod.containingClass as? KtLightClass ?: return null
val baseName = "java:test://${lightClass.qualifiedName}.${lightMethod.name}"
listOf("$baseName[${targetName}X64]", "$baseName[$targetName]", baseName)
}
else -> return null
}
return KotlinTestRunLineMarkerContributor.getTestStateIcon(urls, declaration)
}
} | apache-2.0 |
howard-e/just-quotes-kt | app/src/main/java/com/heed/justquotes/data/remote/quotesapis/TheySaidSoService.kt | 1 | 166 | package com.heed.justquotes.data.remote.quotesapis
/**
* @author Howard.
* * See: <a href>https://theysaidso.com/api/</a>
*/
interface TheySaidSoService
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/keywords/BreakContinue.kt | 3 | 1005 | fun foo() {
myFor@
for (i in 1..10) {
myWhile@
while (x()) {
myDo@
do {
<caret>
} while (y())
}
}
}
// EXIST: { lookupString: "break", itemText: "break", tailText: null, attributes: "bold" }
// EXIST: { lookupString: "continue", itemText: "continue", tailText: null, attributes: "bold" }
// EXIST: { lookupString: "break@myDo", itemText: "break", tailText: "@myDo", attributes: "bold" }
// EXIST: { lookupString: "continue@myDo", itemText: "continue", tailText: "@myDo", attributes: "bold" }
// EXIST: { lookupString: "break@myWhile", itemText: "break", tailText: "@myWhile", attributes: "bold" }
// EXIST: { lookupString: "continue@myWhile", itemText: "continue", tailText: "@myWhile", attributes: "bold" }
// EXIST: { lookupString: "break@myFor", itemText: "break", tailText: "@myFor", attributes: "bold" }
// EXIST: { lookupString: "continue@myFor", itemText: "continue", tailText: "@myFor", attributes: "bold" }
| apache-2.0 |
smmribeiro/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/ModuleModel.kt | 1 | 1037 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.intellij.openapi.application.readAction
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.RepositoryDeclaration
internal data class ModuleModel(
val projectModule: ProjectModule,
val declaredRepositories: List<RepositoryDeclaration>,
) {
companion object {
suspend operator fun invoke(projectModule: ProjectModule) = readAction {
ModuleModel(
projectModule = projectModule,
declaredRepositories = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType)
?.listRepositoriesInModule(projectModule)
?.map { RepositoryDeclaration(it.id, it.name, it.url, projectModule) }
?: emptyList()
)
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | platform/execution-impl/src/com/intellij/execution/impl/RunnerAndConfigurationSettingsImpl.kt | 2 | 22929 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.impl
import com.intellij.configurationStore.SerializableScheme
import com.intellij.configurationStore.deserializeAndLoadState
import com.intellij.configurationStore.serializeStateInto
import com.intellij.diagnostic.PluginException
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.Executor
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.configuration.PersistentAwareRunConfiguration
import com.intellij.execution.configurations.*
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.runners.ProgramRunner
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.impl.ProjectPathMacroManager
import com.intellij.openapi.options.Scheme
import com.intellij.openapi.options.SchemeState
import com.intellij.openapi.util.*
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.getAttributeBooleanValue
import com.intellij.util.text.nullize
import org.jdom.Element
import org.jetbrains.jps.model.serialization.PathMacroUtil
private const val RUNNER_ID = "RunnerId"
private const val CONFIGURATION_TYPE_ATTRIBUTE = "type"
private const val FACTORY_NAME_ATTRIBUTE = "factoryName"
private const val FOLDER_NAME = "folderName"
const val NAME_ATTR: String = "name"
const val DUMMY_ELEMENT_NAME: String = "dummy"
private const val TEMPORARY_ATTRIBUTE = "temporary"
private const val EDIT_BEFORE_RUN = "editBeforeRun"
private const val ACTIVATE_TOOLWINDOW_BEFORE_RUN = "activateToolWindowBeforeRun"
private const val TEMP_CONFIGURATION = "tempConfiguration"
internal const val TEMPLATE_FLAG_ATTRIBUTE = "default"
const val SINGLETON = "singleton"
enum class RunConfigurationLevel {
WORKSPACE, PROJECT, TEMPORARY
}
class RunnerAndConfigurationSettingsImpl @JvmOverloads constructor(
val manager: RunManagerImpl,
private var _configuration: RunConfiguration? = null,
private var isTemplate: Boolean = false,
private var level: RunConfigurationLevel = RunConfigurationLevel.WORKSPACE
) : Cloneable, RunnerAndConfigurationSettings, Comparable<Any>, SerializableScheme, Scheme {
init {
(_configuration as? PersistentAwareRunConfiguration)?.setTemplate(isTemplate)
}
companion object {
@JvmStatic
fun getUniqueIdFor(configuration: RunConfiguration): String {
val type = configuration.type
if (!type.isManaged) {
configuration.id?.let {
return it
}
}
// we cannot use here configuration.type.id because it will break previously stored list of stored settings
@Suppress("DEPRECATION")
return "${configuration.type.displayName}.${configuration.name}${(configuration as? UnknownRunConfiguration)?.uniqueID ?: ""}"
}
}
private val runnerSettings = object : RunnerItem<RunnerSettings>("RunnerSettings") {
override fun createSettings(runner: ProgramRunner<*>) = runner.createConfigurationData(InfoProvider(runner))
}
private val configurationPerRunnerSettings = object : RunnerItem<ConfigurationPerRunnerSettings>("ConfigurationWrapper") {
override fun createSettings(runner: ProgramRunner<*>) = configuration.createRunnerSettings(InfoProvider(runner))
}
private var pathIfStoredInArbitraryFile: String? = null
private var isEditBeforeRun = false
private var isActivateToolWindowBeforeRun = true
private var wasSingletonSpecifiedExplicitly = false
private var folderName: String? = null
private var uniqueId: String? = null
override fun getFactory() = _configuration?.factory ?: UnknownConfigurationType.getInstance()
override fun isTemplate() = isTemplate
override fun isTemporary() = level == RunConfigurationLevel.TEMPORARY
override fun setTemporary(value: Boolean) {
level = if (value) RunConfigurationLevel.TEMPORARY else RunConfigurationLevel.WORKSPACE
pathIfStoredInArbitraryFile = null
}
override fun storeInLocalWorkspace() {
if (level != RunConfigurationLevel.TEMPORARY) {
level = RunConfigurationLevel.WORKSPACE
}
pathIfStoredInArbitraryFile = null
}
override fun isStoredInLocalWorkspace() = level == RunConfigurationLevel.WORKSPACE || level == RunConfigurationLevel.TEMPORARY
override fun storeInDotIdeaFolder() {
level = RunConfigurationLevel.PROJECT
pathIfStoredInArbitraryFile = null
}
override fun isStoredInDotIdeaFolder() = level == RunConfigurationLevel.PROJECT && pathIfStoredInArbitraryFile == null
override fun storeInArbitraryFileInProject(filePath: String) {
level = RunConfigurationLevel.PROJECT
pathIfStoredInArbitraryFile = filePath
}
override fun isStoredInArbitraryFileInProject() = level == RunConfigurationLevel.PROJECT && pathIfStoredInArbitraryFile != null
override fun getPathIfStoredInArbitraryFileInProject(): String? = pathIfStoredInArbitraryFile
override fun getConfiguration() = _configuration ?: UnknownConfigurationType.getInstance().createTemplateConfiguration(manager.project)
fun setConfiguration(configuration: RunConfiguration?) {
_configuration = configuration
}
override fun createFactory(): Factory<RunnerAndConfigurationSettings> {
return Factory {
val configuration = configuration
RunnerAndConfigurationSettingsImpl(manager, configuration.factory!!.createConfiguration(ExecutionBundle.message("default.run.configuration.name"), configuration))
}
}
override fun setName(name: String) {
val existing = uniqueId != null && manager.getConfigurationById(uniqueID) != null
uniqueId = null
configuration.name = name
if (existing) {
manager.addConfiguration(this)
}
}
override fun getName(): String {
val configuration = configuration
if (isTemplate) {
return "<template> of ${factory.id}"
}
return configuration.name
}
override fun getUniqueID(): String {
var result = uniqueId
// check name if configuration name was changed not using our setName
if (result == null || !result.contains(configuration.name)) {
val configuration = configuration
@Suppress("DEPRECATION")
result = getUniqueIdFor(configuration)
uniqueId = result
}
return result
}
override fun setEditBeforeRun(value: Boolean) {
isEditBeforeRun = value
}
override fun isEditBeforeRun() = isEditBeforeRun
override fun setActivateToolWindowBeforeRun(value: Boolean) {
isActivateToolWindowBeforeRun = value
}
override fun isActivateToolWindowBeforeRun() = isActivateToolWindowBeforeRun
override fun setFolderName(value: String?) {
folderName = value
}
override fun getFolderName() = folderName
fun readExternal(element: Element, isStoredInDotIdeaFolder: Boolean) {
isTemplate = element.getAttributeBooleanValue(TEMPLATE_FLAG_ATTRIBUTE)
if (isStoredInDotIdeaFolder) {
level = RunConfigurationLevel.PROJECT
}
else {
level = if (element.getAttributeBooleanValue(TEMPORARY_ATTRIBUTE) || TEMP_CONFIGURATION == element.name) RunConfigurationLevel.TEMPORARY else RunConfigurationLevel.WORKSPACE
}
isEditBeforeRun = (element.getAttributeBooleanValue(EDIT_BEFORE_RUN))
val value = element.getAttributeValue(ACTIVATE_TOOLWINDOW_BEFORE_RUN)
@Suppress("PlatformExtensionReceiverOfInline")
isActivateToolWindowBeforeRun = value == null || value.toBoolean()
folderName = element.getAttributeValue(FOLDER_NAME)
val factory = manager.getFactory(element.getAttributeValue(CONFIGURATION_TYPE_ATTRIBUTE), element.getAttributeValue(FACTORY_NAME_ATTRIBUTE), !isTemplate) ?: return
val configuration = factory.createTemplateConfiguration(manager.project, manager)
if (!isTemplate) {
// shouldn't call createConfiguration since it calls StepBeforeRunProviders that
// may not be loaded yet. This creates initialization order issue.
configuration.name = element.getAttributeValue(NAME_ATTR) ?: return
}
_configuration = configuration
uniqueId = null
PathMacroManager.getInstance(configuration.project).expandPaths(element)
if (configuration is ModuleBasedConfiguration<*, *> && configuration.isModuleDirMacroSupported) {
val moduleName = element.getChild("module")?.getAttributeValue("name")
if (moduleName != null) {
configuration.configurationModule.findModule(moduleName)?.let {
PathMacroManager.getInstance(it).expandPaths(element)
}
}
}
deserializeConfigurationFrom(configuration, element, isTemplate)
// must be after deserializeConfigurationFrom
wasSingletonSpecifiedExplicitly = false
val singletonStr = element.getAttributeValue(SINGLETON)
if (singletonStr.isNullOrEmpty()) {
configuration.isAllowRunningInParallel = factory.singletonPolicy.isAllowRunningInParallel
}
else {
wasSingletonSpecifiedExplicitly = true
@Suppress("PlatformExtensionReceiverOfInline")
configuration.isAllowRunningInParallel = !singletonStr.toBoolean()
}
runnerSettings.loadState(element)
configurationPerRunnerSettings.loadState(element)
manager.readBeforeRunTasks(element.getChild(METHOD), this, configuration)
}
// do not call directly
// cannot be private - used externally
fun writeExternal(element: Element) {
val configuration = configuration
if (configuration.type.isManaged) {
if (isTemplate) {
element.setAttribute(TEMPLATE_FLAG_ATTRIBUTE, "true")
}
else {
if (!isNewSerializationAllowed) {
element.setAttribute(TEMPLATE_FLAG_ATTRIBUTE, "false")
}
configuration.name.nullize()?.let {
element.setAttribute(NAME_ATTR, it)
}
}
val factory = factory
element.setAttribute(CONFIGURATION_TYPE_ATTRIBUTE, factory.type.id)
if (factory.type !is SimpleConfigurationType) {
element.setAttribute(FACTORY_NAME_ATTRIBUTE, factory.id)
}
if (folderName != null) {
element.setAttribute(FOLDER_NAME, folderName!!)
}
if (isEditBeforeRun) {
element.setAttribute(EDIT_BEFORE_RUN, "true")
}
if (!isActivateToolWindowBeforeRun) {
element.setAttribute(ACTIVATE_TOOLWINDOW_BEFORE_RUN, "false")
}
if (wasSingletonSpecifiedExplicitly || configuration.isAllowRunningInParallel != factory.singletonPolicy.isAllowRunningInParallel) {
element.setAttribute(SINGLETON, (!configuration.isAllowRunningInParallel).toString())
}
if (isTemporary) {
element.setAttribute(TEMPORARY_ATTRIBUTE, "true")
}
}
serializeConfigurationInto(configuration, element)
if (configuration.type.isManaged) {
runnerSettings.getState(element)
configurationPerRunnerSettings.getState(element)
}
if (configuration.type.isManaged) {
manager.writeBeforeRunTasks(configuration)?.let {
element.addContent(it)
}
}
if (configuration is ModuleBasedConfiguration<*, *> && configuration.isModuleDirMacroSupported) {
configuration.configurationModule.module?.let {
PathMacroManager.getInstance(it).collapsePathsRecursively(element)
}
}
val project = configuration.project
val macroManager = PathMacroManager.getInstance(project)
// https://youtrack.jetbrains.com/issue/IDEA-178510
val projectParentPath = project.basePath?.let { PathUtilRt.getParentPath(it) }
if (!projectParentPath.isNullOrEmpty()) {
val replacePathMap = (macroManager as? ProjectPathMacroManager)?.replacePathMap
if (replacePathMap != null) {
replacePathMap.addReplacement(projectParentPath, '$' + PathMacroUtil.PROJECT_DIR_MACRO_NAME + "$/..", true)
PathMacroManager.collapsePaths(element, true, replacePathMap)
return
}
}
PathMacroManager.getInstance(project).collapsePathsRecursively(element)
}
override fun writeScheme(): Element {
val element = Element("configuration")
writeExternal(element)
return element
}
override fun checkSettings(executor: Executor?) {
val configuration = configuration
var warning: RuntimeConfigurationException? = null
ReadAction.nonBlocking {
try {
configuration.checkConfiguration()
}
catch (e: RuntimeConfigurationException) {
warning = e
}
}.executeSynchronously()
if (configuration !is RunConfigurationBase<*>) {
if (warning != null) {
throw warning as RuntimeConfigurationException
}
return
}
val runners = HashSet<ProgramRunner<*>>()
runners.addAll(runnerSettings.settings.keys.mapNotNull { ProgramRunner.findRunnerById(it) })
runners.addAll(configurationPerRunnerSettings.settings.keys.mapNotNull { ProgramRunner.findRunnerById(it) })
executor?.let { ProgramRunner.getRunner(executor.id, configuration)?.let { runners.add(it) } }
var runnerFound = false
for (runner in runners) {
if (executor == null || runner.canRun(executor.id, configuration)) {
val runnerWarning = doCheck { configuration.checkRunnerSettings(runner, runnerSettings.settings[runner.runnerId], configurationPerRunnerSettings.settings[runner.runnerId]) }
if (runnerWarning != null) {
if (warning == null) {
warning = runnerWarning
}
}
else {
// there is at least one runner to run specified configuration
runnerFound = true
}
}
}
if (executor != null && executor != DefaultRunExecutor.getRunExecutorInstance() && !runnerFound) {
throw RuntimeConfigurationError(ExecutionBundle.message("dialog.message.no.runners.for.configuration", executor.id, configuration))
}
if (executor != null) {
val beforeRunWarning = doCheck { configuration.checkSettingsBeforeRun() }
if (warning == null && beforeRunWarning != null) {
warning = beforeRunWarning
}
}
if (warning != null) {
throw warning as RuntimeConfigurationException
}
}
private inline fun doCheck(crossinline check: () -> Unit): RuntimeConfigurationWarning? {
try {
check()
return null
} catch (ex: RuntimeConfigurationWarning) {
return ex
}
}
override fun <T : RunnerSettings> getRunnerSettings(runner: ProgramRunner<T>): T? {
@Suppress("UNCHECKED_CAST")
return runnerSettings.getOrCreateSettings(runner) as T?
}
override fun getConfigurationSettings(runner: ProgramRunner<*>) = configurationPerRunnerSettings.getOrCreateSettings(runner)
override fun getType() = factory.type
public override fun clone(): RunnerAndConfigurationSettingsImpl {
val copy = RunnerAndConfigurationSettingsImpl(manager, _configuration!!.clone())
copy.importRunnerAndConfigurationSettings(this)
copy.level = this.level
copy.pathIfStoredInArbitraryFile = this.pathIfStoredInArbitraryFile
return copy
}
internal fun importRunnerAndConfigurationSettings(template: RunnerAndConfigurationSettingsImpl) {
importFromTemplate(template.runnerSettings, runnerSettings)
importFromTemplate(template.configurationPerRunnerSettings, configurationPerRunnerSettings)
isEditBeforeRun = template.isEditBeforeRun
isActivateToolWindowBeforeRun = template.isActivateToolWindowBeforeRun
}
private fun <T> importFromTemplate(templateItem: RunnerItem<T>, item: RunnerItem<T>) {
for (runnerId in templateItem.settings.keys) {
val runner = ProgramRunner.findRunnerById(runnerId) ?: continue
val data = item.createSettings(runner)
item.settings.put(runnerId, data)
if (data == null) {
continue
}
val temp = Element(DUMMY_ELEMENT_NAME)
val templateSettings = templateItem.settings.get(runnerId) ?: continue
try {
@Suppress("DEPRECATION")
(templateSettings as JDOMExternalizable).writeExternal(temp)
@Suppress("DEPRECATION")
(data as JDOMExternalizable).readExternal(temp)
}
catch (e: WriteExternalException) {
RunManagerImpl.LOG.error(e)
}
catch (e: InvalidDataException) {
RunManagerImpl.LOG.error(e)
}
}
}
fun handleRunnerRemoved(runner: ProgramRunner<*>) {
runnerSettings.handleRunnerRemoved(runner)
}
override fun compareTo(other: Any) = if (other is RunnerAndConfigurationSettings) name.compareTo(other.name) else 0
override fun toString() = "${type.displayName}: ${if (isTemplate) "<template>" else name} (level: $level)"
private inner class InfoProvider(override val runner: ProgramRunner<*>) : ConfigurationInfoProvider {
override val configuration: RunConfiguration
get() = [email protected]
override val runnerSettings: RunnerSettings?
get() = [email protected](runner)
override val configurationSettings: ConfigurationPerRunnerSettings?
get() = [email protected](runner)
}
override fun getSchemeState(): SchemeState? {
val configuration = _configuration
return when {
configuration == null -> SchemeState.UNCHANGED
configuration is UnknownRunConfiguration -> if (configuration.isDoNotStore) SchemeState.NON_PERSISTENT else SchemeState.UNCHANGED
!configuration.type.isManaged -> SchemeState.NON_PERSISTENT
else -> null
}
}
fun needsToBeMigrated(): Boolean = (_configuration as? PersistentAwareRunConfiguration)?.needsToBeMigrated() ?: false
private abstract inner class RunnerItem<T>(private val childTagName: String) {
val settings: MutableMap<String, T?> = HashMap()
private var unloadedSettings: MutableList<Element>? = null
// to avoid changed files
private val loadedIds = HashSet<String>()
fun loadState(element: Element) {
settings.clear()
if (unloadedSettings != null) {
unloadedSettings!!.clear()
}
loadedIds.clear()
val iterator = element.getChildren(childTagName).iterator()
while (iterator.hasNext()) {
val state = iterator.next()
val runner = state.getAttributeValue(RUNNER_ID)?.let { findRunner(it) }
if (runner == null) {
iterator.remove()
}
@Suppress("IfThenToSafeAccess")
add(state, runner, if (runner == null) null else createSettings(runner))
}
}
private fun findRunner(runnerId: String): ProgramRunner<*>? {
val runnersById = ProgramRunner.PROGRAM_RUNNER_EP.iterable.filter { runnerId == it.runnerId }
return when {
runnersById.isEmpty() -> null
runnersById.size == 1 -> runnersById.firstOrNull()
else -> {
RunManagerImpl.LOG.error("More than one runner found for ID: $runnerId")
for (executor in Executor.EXECUTOR_EXTENSION_NAME.extensionList) {
runnersById.firstOrNull { it.canRun(executor.id, configuration) }?.let {
return it
}
}
null
}
}
}
fun getState(element: Element) {
val runnerSettings = SmartList<Element>()
for (runnerId in settings.keys) {
val settings = this.settings.get(runnerId)
val wasLoaded = loadedIds.contains(runnerId)
if (settings == null && !wasLoaded) {
continue
}
val state = Element(childTagName)
if (settings != null) {
@Suppress("DEPRECATION")
(settings as JDOMExternalizable).writeExternal(state)
}
if (wasLoaded || !JDOMUtil.isEmpty(state)) {
state.setAttribute(RUNNER_ID, runnerId)
runnerSettings.add(state)
}
}
unloadedSettings?.mapTo(runnerSettings) { it.clone() }
runnerSettings.sortWith<Element>(Comparator { o1, o2 ->
val attributeValue1 = o1.getAttributeValue(RUNNER_ID) ?: return@Comparator 1
StringUtil.compare(attributeValue1, o2.getAttributeValue(RUNNER_ID), false)
})
for (runnerSetting in runnerSettings) {
element.addContent(runnerSetting)
}
}
abstract fun createSettings(runner: ProgramRunner<*>): T?
private fun add(state: Element, runner: ProgramRunner<*>?, data: T?) {
if (runner == null) {
if (unloadedSettings == null) {
unloadedSettings = SmartList()
}
unloadedSettings!!.add(JDOMUtil.internElement(state))
return
}
if (data != null) {
@Suppress("DEPRECATION")
(data as JDOMExternalizable).readExternal(state)
}
settings.put(runner.runnerId, data)
loadedIds.add(runner.runnerId)
}
fun getOrCreateSettings(runner: ProgramRunner<*>): T? {
try {
return settings.getOrPut(runner.runnerId) { createSettings(runner) }
}
catch (e: AbstractMethodError) {
PluginException.logPluginError(RunManagerImpl.LOG, "Update failed for: ${configuration.type.displayName}, runner: ${runner.runnerId}", e, runner.javaClass)
return null
}
}
fun handleRunnerRemoved(runner: ProgramRunner<*>) {
val runnerSettings = settings[runner.runnerId] as RunnerSettings?
if (runnerSettings != null) {
settings.remove(runner.runnerId)
val element = Element(childTagName)
runnerSettings.writeExternal(element)
if (unloadedSettings == null) {
unloadedSettings = SmartList()
}
unloadedSettings!!.add(JDOMUtil.internElement(element))
loadedIds.remove(runner.runnerId)
}
}
}
}
// always write method element for shared settings for now due to preserve backward compatibility
private val RunnerAndConfigurationSettings.isNewSerializationAllowed: Boolean
get() = ApplicationManager.getApplication().isUnitTestMode || isStoredInLocalWorkspace
fun serializeConfigurationInto(configuration: RunConfiguration, element: Element) {
when (configuration) {
is PersistentStateComponent<*> -> serializeStateInto(configuration, element)
is PersistentAwareRunConfiguration -> configuration.writePersistent(element)
else -> configuration.writeExternal(element)
}
}
fun deserializeConfigurationFrom(configuration: RunConfiguration, element: Element, isTemplate: Boolean = false) {
when (configuration) {
is PersistentStateComponent<*> -> deserializeAndLoadState(configuration, element)
is PersistentAwareRunConfiguration -> {
configuration.setTemplate(isTemplate)
configuration.readPersistent(element)
}
else -> configuration.readExternal(element)
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/generate/equalsWithHashCode/genericClass.kt | 13 | 54 | class A<T>(val n: T) {<caret>
fun foo() {
}
} | apache-2.0 |
android/compose-samples | Jetcaster/app/src/main/java/com/example/jetcaster/data/room/PodcastsDao.kt | 1 | 4321 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.jetcaster.data.room
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.example.jetcaster.data.Podcast
import com.example.jetcaster.data.PodcastWithExtraInfo
import kotlinx.coroutines.flow.Flow
/**
* [Room] DAO for [Podcast] related operations.
*/
@Dao
abstract class PodcastsDao {
@Query("SELECT * FROM podcasts WHERE uri = :uri")
abstract fun podcastWithUri(uri: String): Flow<Podcast>
@Transaction
@Query(
"""
SELECT podcasts.*, last_episode_date, (followed_entries.podcast_uri IS NOT NULL) AS is_followed
FROM podcasts
INNER JOIN (
SELECT podcast_uri, MAX(published) AS last_episode_date
FROM episodes
GROUP BY podcast_uri
) episodes ON podcasts.uri = episodes.podcast_uri
LEFT JOIN podcast_followed_entries AS followed_entries ON followed_entries.podcast_uri = episodes.podcast_uri
ORDER BY datetime(last_episode_date) DESC
LIMIT :limit
"""
)
abstract fun podcastsSortedByLastEpisode(
limit: Int
): Flow<List<PodcastWithExtraInfo>>
@Transaction
@Query(
"""
SELECT podcasts.*, last_episode_date, (followed_entries.podcast_uri IS NOT NULL) AS is_followed
FROM podcasts
INNER JOIN (
SELECT episodes.podcast_uri, MAX(published) AS last_episode_date
FROM episodes
INNER JOIN podcast_category_entries ON episodes.podcast_uri = podcast_category_entries.podcast_uri
WHERE category_id = :categoryId
GROUP BY episodes.podcast_uri
) inner_query ON podcasts.uri = inner_query.podcast_uri
LEFT JOIN podcast_followed_entries AS followed_entries ON followed_entries.podcast_uri = inner_query.podcast_uri
ORDER BY datetime(last_episode_date) DESC
LIMIT :limit
"""
)
abstract fun podcastsInCategorySortedByLastEpisode(
categoryId: Long,
limit: Int
): Flow<List<PodcastWithExtraInfo>>
@Transaction
@Query(
"""
SELECT podcasts.*, last_episode_date, (followed_entries.podcast_uri IS NOT NULL) AS is_followed
FROM podcasts
INNER JOIN (
SELECT podcast_uri, MAX(published) AS last_episode_date FROM episodes GROUP BY podcast_uri
) episodes ON podcasts.uri = episodes.podcast_uri
INNER JOIN podcast_followed_entries AS followed_entries ON followed_entries.podcast_uri = episodes.podcast_uri
ORDER BY datetime(last_episode_date) DESC
LIMIT :limit
"""
)
abstract fun followedPodcastsSortedByLastEpisode(
limit: Int
): Flow<List<PodcastWithExtraInfo>>
@Query("SELECT COUNT(*) FROM podcasts")
abstract suspend fun count(): Int
/**
* The following methods should really live in a base interface. Unfortunately the Kotlin
* Compiler which we need to use for Compose doesn't work with that.
* TODO: remove this once we move to a more recent Kotlin compiler
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract suspend fun insert(entity: Podcast): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract suspend fun insertAll(vararg entity: Podcast)
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract suspend fun insertAll(entities: Collection<Podcast>)
@Update(onConflict = OnConflictStrategy.REPLACE)
abstract suspend fun update(entity: Podcast)
@Delete
abstract suspend fun delete(entity: Podcast): Int
}
| apache-2.0 |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/hprof/analysis/LiveInstanceStats.kt | 12 | 1858 | /*
* Copyright (C) 2018 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.intellij.diagnostic.hprof.analysis
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.ProjectManager
internal class LiveInstanceStats {
fun createReport(): String {
val result = StringBuilder()
// Count open projects
val openProjects = ProjectManager.getInstance().openProjects
val projectsOpenCount = openProjects.size
result.appendln("Projects open: $projectsOpenCount")
openProjects.forEachIndexed { projectIndex, project ->
result.appendln("Project ${projectIndex + 1}:")
val modulesCount = ModuleManager.getInstance(project).modules.count()
result.appendln(" Module count: $modulesCount")
val allEditors = FileEditorManager.getInstance(project).allEditors
val typeToCount = allEditors.groupingBy { "${it.javaClass.name}[${it.file?.fileType?.javaClass?.name}]" }.eachCount()
result.appendln(" Editors opened: ${allEditors.size}. Counts by type:")
typeToCount.entries.sortedByDescending { it.value }.forEach { (typeString, count) ->
result.appendln(" * $count $typeString")
}
result.appendln()
}
return result.toString()
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/supertypeInitialization/addParenthesisForObjectExpression.kt | 13 | 126 | // "Change to constructor invocation" "true"
fun bar() {
abstract class Foo {}
val foo: Foo = object : <caret>Foo {}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertReferenceToLambda/staticTwoParameters.kt | 13 | 25 | val x = <caret>Utils::foo | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantCompanionReference/sameNameGlobalFunction.kt | 13 | 153 | class Test {
companion object {
fun globalFun() = 1
}
fun test() {
<caret>Companion.globalFun()
}
}
fun globalFun() = 2 | apache-2.0 |
paul58914080/ff4j-spring-boot-starter-parent | ff4j-spring-services/src/main/kotlin/org/ff4j/services/PropertyStoreServices.kt | 1 | 2163 | /*-
* #%L
* ff4j-spring-services
* %%
* Copyright (C) 2013 - 2019 FF4J
* %%
* 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.
* #L%
*/
package org.ff4j.services
import org.ff4j.FF4j
import org.ff4j.cache.FF4jCacheProxy
import org.ff4j.services.domain.CacheApiBean
import org.ff4j.services.domain.PropertyApiBean
import org.ff4j.services.domain.PropertyStoreApiBean
import org.ff4j.services.exceptions.PropertyStoreNotCached
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.util.CollectionUtils
import java.util.stream.Collectors
/**
* Created by Paul
*
* @author <a href="mailto:[email protected]">Paul Williams</a>
*/
@Service
class PropertyStoreServices(@Autowired val ff4j: FF4j) {
fun getPropertyStore(): PropertyStoreApiBean {
return PropertyStoreApiBean(ff4j.propertiesStore)
}
fun getAllProperties(): List<PropertyApiBean> {
val allProperties = ff4j.propertiesStore.readAllProperties()
return if (CollectionUtils.isEmpty(allProperties)) {
ArrayList(0)
} else {
allProperties.values.stream().map { PropertyApiBean(it) }.collect(Collectors.toList())
}
}
fun deleteAllProperties() {
ff4j.propertiesStore.clear()
}
fun getPropertiesFromCache(): CacheApiBean {
ff4j.cacheProxy ?: throw PropertyStoreNotCached()
return CacheApiBean(ff4j.propertiesStore)
}
fun clearCachedPropertyStore() {
val cacheProxy = ff4j.cacheProxy ?: throw PropertyStoreNotCached()
cacheProxy.cacheManager.clearProperties()
}
}
| apache-2.0 |
mhshams/yekan | vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/core/internal/Helper.kt | 2 | 687 | package io.vertx.kotlin.core.internal
import io.vertx.core.AsyncResult
import io.vertx.core.Future
import io.vertx.core.Handler
open class KotlinAsyncHandler<K, J>(val handler: (AsyncResult<K>) -> Unit, val converter: (J) -> K) :
Handler<AsyncResult<J>> {
override fun handle(event: AsyncResult<J>) {
if (event.succeeded()) {
handler(Future.succeededFuture(converter(event.result())))
} else {
handler(Future.failedFuture(event.cause()))
}
}
}
open class KotlinHandler<K, J>(val handler: (K) -> Unit, val converter: (J) -> K) : Handler<J> {
override fun handle(event: J) {
handler(converter(event))
}
}
| apache-2.0 |
AMARJITVS/NoteDirector | app/src/main/kotlin/com/amar/notesapp/dialogs/ChangeSortingDialog.kt | 1 | 3706 | package com.amar.NoteDirector.dialogs
import android.content.DialogInterface
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.helpers.*
import com.amar.NoteDirector.activities.SimpleActivity
import com.amar.NoteDirector.extensions.config
import kotlinx.android.synthetic.main.dialog_change_sorting.view.*
class ChangeSortingDialog(val activity: SimpleActivity, val isDirectorySorting: Boolean, showFolderCheckbox: Boolean,
val path: String = "", val callback: () -> Unit) :
DialogInterface.OnClickListener {
private var currSorting = 0
private var config = activity.config
private var view: View
init {
view = LayoutInflater.from(activity).inflate(com.amar.NoteDirector.R.layout.dialog_change_sorting, null).apply {
use_for_this_folder_divider.beVisibleIf(showFolderCheckbox)
sorting_dialog_use_for_this_folder.beVisibleIf(showFolderCheckbox)
sorting_dialog_use_for_this_folder.isChecked = config.hasCustomSorting(path)
}
AlertDialog.Builder(activity)
.setPositiveButton(com.amar.NoteDirector.R.string.ok, this)
.setNegativeButton(com.amar.NoteDirector.R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this, com.amar.NoteDirector.R.string.sort_by)
}
currSorting = if (isDirectorySorting) config.directorySorting else config.getFileSorting(path)
setupSortRadio()
setupOrderRadio()
}
private fun setupSortRadio() {
val sortingRadio = view.sorting_dialog_radio_sorting
var sortBtn = sortingRadio.sorting_dialog_radio_name
if (currSorting and SORT_BY_SIZE != 0) {
sortBtn = sortingRadio.sorting_dialog_radio_size
} else if (currSorting and SORT_BY_DATE_MODIFIED != 0) {
sortBtn = sortingRadio.sorting_dialog_radio_last_modified
} else if (currSorting and SORT_BY_DATE_TAKEN != 0)
sortBtn = sortingRadio.sorting_dialog_radio_date_taken
sortBtn.isChecked = true
}
private fun setupOrderRadio() {
val orderRadio = view.sorting_dialog_radio_order
var orderBtn = orderRadio.sorting_dialog_radio_ascending
if (currSorting and SORT_DESCENDING != 0) {
orderBtn = orderRadio.sorting_dialog_radio_descending
}
orderBtn.isChecked = true
}
override fun onClick(dialog: DialogInterface, which: Int) {
val sortingRadio = view.sorting_dialog_radio_sorting
var sorting = when (sortingRadio.checkedRadioButtonId) {
com.amar.NoteDirector.R.id.sorting_dialog_radio_name -> SORT_BY_NAME
com.amar.NoteDirector.R.id.sorting_dialog_radio_size -> SORT_BY_SIZE
com.amar.NoteDirector.R.id.sorting_dialog_radio_last_modified -> SORT_BY_DATE_MODIFIED
else -> SORT_BY_DATE_TAKEN
}
if (view.sorting_dialog_radio_order.checkedRadioButtonId == com.amar.NoteDirector.R.id.sorting_dialog_radio_descending) {
sorting = sorting or SORT_DESCENDING
}
if (isDirectorySorting) {
config.directorySorting = sorting
} else {
if (view.sorting_dialog_use_for_this_folder.isChecked) {
config.saveFileSorting(path, sorting)
} else {
config.removeFileSorting(path)
config.fileSorting = sorting
}
}
callback()
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.