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
vicboma1/GameBoyEmulatorEnvironment
src/main/kotlin/assets/table/model/TableModelImpl.kt
1
2097
package assets.table.model import assets.table.comparator.TableHeaderComparator import java.util.stream.IntStream import javax.swing.table.AbstractTableModel /** * Created by vbolinch on 02/01/2017. */ class TableModelImpl internal constructor(val columnNames : Array<Any>?, val data: Array<Array<Any>>?, var isEditable : Boolean = false ) : AbstractTableModel() { companion object { fun factoryArrayOf(size:Int, elements :Int) : Array<Array<Any>>? { return Array<Array<Any>>(size) { factoryArrayOf(elements) } } fun factoryArrayOf(elements :Int) : Array<Any> { val list = arrayListOf("") IntStream.range(0,elements-1).forEach { list.add("") } return list.toArray() } fun create(columnNames: Array<Any>?, data: Array<Array<Any>>?) = TableModelImpl(columnNames, data) fun create(columnNames: Int, size:Int, rows:Int) = TableModelImpl( factoryArrayOf(columnNames), factoryArrayOf(size,rows)) } init { } override fun getValueAt(rowIndex: Int, columnIndex: Int) : Any = data!![rowIndex][columnIndex] override fun getColumnCount(): Int = columnNames!!.size override fun getRowCount(): Int { if(data != null) return data.size; return 0 } override fun getColumnName(col: Int): String = columnNames!![col].toString() override fun getColumnClass(columnIndex: Int) : Class<*> = this.getValueAt(0, columnIndex).javaClass override fun isCellEditable(rowIndex: Int, columnIndex: Int) = isEditable override fun setValueAt(aValue: Any?, rowIndex: Int, columnIndex: Int) { data!![rowIndex][columnIndex] = aValue!! fireTableCellUpdated(rowIndex,columnIndex) } fun sortWith(cmp : TableHeaderComparator) = data?.sortWith(cmp) fun removeAll() { for (i in getRowCount() - 1 downTo 0) data!![i] = arrayOf() } fun toString(rowIndex: Int): String { return "${getValueAt(rowIndex,0)} ${getValueAt(rowIndex,1)} ${getValueAt(rowIndex,2)} ${getValueAt(rowIndex,3)} ${getValueAt(rowIndex,4)}" } }
lgpl-3.0
MarkusAmshove/Kluent
common/src/test/kotlin/org/amshove/kluent/tests/charsequence/ShouldNotBeEmptyShould.kt
1
387
package org.amshove.kluent.tests.charsequence import org.amshove.kluent.shouldNotBeEmpty import kotlin.test.Test import kotlin.test.assertFails class ShouldNotBeEmptyShould { @Test fun passWhenTestingANonEmptyCharSequence() { "test".shouldNotBeEmpty() } @Test fun failWhenTestingAnEmptyCharSequence() { assertFails { "".shouldNotBeEmpty() } } }
mit
phrase/Phrase-AndroidStudio
src/main/kotlin/com/phrase/intellij/PhraseBundle.kt
1
604
package com.phrase.intellij import com.intellij.AbstractBundle import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey @NonNls private const val BUNDLE = "messages.Phrase" object PhraseBundle : AbstractBundle(BUNDLE) { @Suppress("SpreadOperator") @JvmStatic fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) = getMessage(key, *params) @Suppress("SpreadOperator") @JvmStatic fun messagePointer(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) = getLazyMessage(key, *params) }
bsd-3-clause
zbeboy/ISY
src/main/java/top/zbeboy/isy/service/graduate/design/DefenseArrangementService.kt
1
882
package top.zbeboy.isy.service.graduate.design import org.jooq.Record import top.zbeboy.isy.domain.tables.pojos.DefenseArrangement import java.util.* /** * Created by zbeboy 2018-02-06 . **/ interface DefenseArrangementService { /** * 根据主键查询 * * @param id 主键 * @return 数据 */ fun findById(id: String): DefenseArrangement /** * 通过毕业设计发布id查询 * * @param graduationDesignReleaseId 毕业设计发布id * @return 数据 */ fun findByGraduationDesignReleaseId(graduationDesignReleaseId: String): Optional<Record> /** * 保存 * * @param defenseArrangement 数据 */ fun save(defenseArrangement: DefenseArrangement) /** * 更新 * * @param defenseArrangement 数据 */ fun update(defenseArrangement: DefenseArrangement) }
mit
airbnb/epoxy
epoxy-composeinterop-maverickssample/src/main/java/com/airbnb/epoxy/composeinterop/maverickssample/ComposeInteropListFragmnet.kt
1
3633
package com.airbnb.epoxy.composeinterop.maverickssample import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.text.ClickableText import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle import androidx.fragment.app.Fragment import com.airbnb.epoxy.EpoxyRecyclerView import com.airbnb.epoxy.TypedEpoxyController import com.airbnb.epoxy.composableInterop import com.airbnb.epoxy.composeinterop.maverickssample.epoxyviews.headerView import com.airbnb.mvrx.MavericksState import com.airbnb.mvrx.MavericksView import com.airbnb.mvrx.MavericksViewModel import com.airbnb.mvrx.fragmentViewModel import com.airbnb.mvrx.withState data class CounterState( val counter: List<Int> = List(100) { it }, ) : MavericksState class HelloWorldViewModel(initialState: CounterState) : MavericksViewModel<CounterState>(initialState) { fun increase(index: Int) { withState { state -> val updatedCounterList = state.counter.mapIndexed { i, value -> if (i == index) value + 1 else value } setState { copy(counter = updatedCounterList) } } } } class ComposeInteropListFragmnet : Fragment(R.layout.fragment_my), MavericksView { private val viewModel by fragmentViewModel(HelloWorldViewModel::class) private val controller: MyEpoxyController by lazy { MyEpoxyController(viewModel) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = inflater.inflate(R.layout.fragment_my, container, false).apply { findViewById<EpoxyRecyclerView>(R.id.epoxyRecyclerView).apply { setController(controller) } } override fun invalidate() = withState(viewModel) { controller.setData(it) } } class MyEpoxyController(private val viewModel: HelloWorldViewModel) : TypedEpoxyController<CounterState>() { private fun annotatedString(str: String) = buildAnnotatedString { withStyle( style = SpanStyle(fontWeight = FontWeight.Bold) ) { append(str) } } override fun buildModels(state: CounterState) { state.counter.forEachIndexed { index, counterValue -> composableInterop("$index", counterValue) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { TextFromCompose(counterValue) { [email protected](index) } } } headerView { id(index) title("Text from normal epoxy model: $counterValue") clickListener { _ -> [email protected](index) } } } } @Composable fun TextFromCompose(counterValue: Int, onClick: () -> Unit) { ClickableText( text = annotatedString("Text from composable interop $counterValue"), onClick = { onClick() } ) } }
apache-2.0
paplorinc/intellij-community
python/src/com/jetbrains/python/inspections/PyThirdPartyInspectionExtension.kt
1
2218
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.inspections import com.intellij.util.containers.ContainerUtil import com.jetbrains.python.codeInsight.stdlib.PyDataclassParameters import com.jetbrains.python.codeInsight.stdlib.parseDataclassParameters import com.jetbrains.python.psi.PyElement import com.jetbrains.python.psi.PyExpression import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.PyUtil import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.QualifiedNameFinder import com.jetbrains.python.psi.types.PyClassType import com.jetbrains.python.psi.types.PyType import com.jetbrains.python.psi.types.TypeEvalContext class PyThirdPartyInspectionExtension : PyInspectionExtension() { override fun ignoreMethodParameters(function: PyFunction, context: TypeEvalContext): Boolean { val cls = function.containingClass if (cls != null) { // zope.interface.Interface inheritor could have any parameters val interfaceQName = "zope.interface.interface.Interface" if (cls.isSubclass(interfaceQName, context)) return true // Checking for subclassing above does not help while zope.interface.Interface is defined as target with call expression assigned val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context) for (expression in cls.superClassExpressions) { if (resolvesTo(expression, interfaceQName, resolveContext)) return true } } return false } override fun ignoreUnresolvedMember(type: PyType, name: String, context: TypeEvalContext): Boolean { return name == "__attrs_attrs__" && type is PyClassType && parseDataclassParameters(type.pyClass, context)?.type == PyDataclassParameters.Type.ATTRS } private fun resolvesTo(expression: PyExpression, qualifiedName: String, resolveContext: PyResolveContext): Boolean { return ContainerUtil.exists(PyUtil.multiResolveTopPriority(expression, resolveContext)) { it is PyElement && QualifiedNameFinder.getQualifiedName(it) == qualifiedName } } }
apache-2.0
vladmm/intellij-community
platform/platform-impl/src/org/jetbrains/io/netty.kt
1
2737
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.io import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Conditions import io.netty.bootstrap.Bootstrap import io.netty.channel.* import io.netty.channel.oio.OioEventLoopGroup import io.netty.channel.socket.oio.OioSocketChannel import io.netty.util.concurrent.GenericFutureListener import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.ide.PooledThreadExecutor import java.net.InetSocketAddress import java.util.concurrent.TimeUnit inline fun Bootstrap.handler(crossinline task: (Channel) -> Unit): Bootstrap { handler(object : ChannelInitializer<Channel>() { override fun initChannel(channel: Channel) { task(channel) } }) return this } fun oioClientBootstrap(): Bootstrap { val bootstrap = Bootstrap().group(OioEventLoopGroup(1, PooledThreadExecutor.INSTANCE)).channel(OioSocketChannel::class.java) bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true) return bootstrap } inline fun ChannelFuture.addListener(crossinline listener: (future: ChannelFuture) -> Unit) { addListener(object : GenericFutureListener<ChannelFuture> { override fun operationComplete(future: ChannelFuture) { listener(future) } }) } // if NIO, so, it is shared and we must not shutdown it fun EventLoop.shutdownIfOio() { if (this is OioEventLoopGroup) { @Suppress("USELESS_CAST") (this as OioEventLoopGroup).shutdownGracefully(1L, 2L, TimeUnit.NANOSECONDS) } } // Event loop will be shut downed only if OIO fun Channel.closeAndShutdownEventLoop() { val eventLoop = eventLoop() try { close().awaitUninterruptibly() } finally { eventLoop.shutdownIfOio() } } @JvmOverloads fun Bootstrap.connect(remoteAddress: InetSocketAddress, promise: AsyncPromise<*>? = null, maxAttemptCount: Int = NettyUtil.DEFAULT_CONNECT_ATTEMPT_COUNT, stopCondition: Condition<Void>? = null): Channel? { try { return NettyUtil.doConnect(this, remoteAddress, promise, maxAttemptCount, stopCondition ?: Conditions.alwaysFalse<Void>()) } catch (e: Throwable) { promise?.setError(e) return null } }
apache-2.0
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/nbt/lang/psi/mixins/NbttDoubleMixin.kt
1
350
/* * 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.TagDouble interface NbttDoubleMixin : NbttElement { fun getDoubleTag(): TagDouble }
mit
imageprocessor/cv4j
app/src/main/java/com/cv4j/app/activity/pixels/ArithmeticAndLogicOperationActivity.kt
1
3344
package com.cv4j.app.activity.pixels import android.content.Intent import android.os.Bundle import com.cv4j.app.R import com.cv4j.app.app.BaseActivity import kotlinx.android.synthetic.main.activity_arithmetic_and_logic_operator.* /** * * @FileName: * com.cv4j.app.activity.pixels.ArithmeticAndLogicOperationActivity * @author: Tony Shen * @date: 2020-05-04 22:18 * @version: V1.0 <描述当前版本功能> */ class ArithmeticAndLogicOperationActivity : BaseActivity() { var title: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_arithmetic_and_logic_operator) intent.extras?.let { title = it.getString("Title","") }?:{ title = "" }() toolbar.setOnClickListener { finish() } text1.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text1.text.toString()) i.putExtra("Type", PixelOperatorActivity.ADD) startActivity(i) } text2.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text2.text.toString()) i.putExtra("Type", PixelOperatorActivity.SUBSTRACT) startActivity(i) } text3.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text3.text.toString()) i.putExtra("Type", PixelOperatorActivity.MULTIPLE) startActivity(i) } text4.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text4.text.toString()) i.putExtra("Type", PixelOperatorActivity.DIVISION) startActivity(i) } text5.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text5.text.toString()) i.putExtra("Type", PixelOperatorActivity.BITWISE_AND) startActivity(i) } text6.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text6.text.toString()) i.putExtra("Type", PixelOperatorActivity.BITWISE_OR) startActivity(i) } text7.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text7.text.toString()) i.putExtra("Type", PixelOperatorActivity.BITWISE_NOT) startActivity(i) } text8.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text8.text.toString()) i.putExtra("Type", PixelOperatorActivity.BITWISE_XOR) startActivity(i) } text9.setOnClickListener { val i = Intent(this, PixelOperatorActivity::class.java) i.putExtra("Title", text9!!.text.toString()) i.putExtra("Type", PixelOperatorActivity.ADD_WEIGHT) startActivity(i) } initData() } private fun initData() { toolbar.title = "< $title" } }
apache-2.0
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ArchiveDiskAction.kt
1
1345
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.objectweb.asm.Type @DependsOn(Node::class, ArchiveDisk::class) class ArchiveDiskAction : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Node>() } .and { it.instanceFields.any { it.type == type<ArchiveDisk>() } } @DependsOn(ArchiveDisk::class) class archiveDisk : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<ArchiveDisk>() } } @DependsOn(Archive::class) class archive : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<Archive>() } } class data : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == ByteArray::class.type } } class type : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == Type.INT_TYPE } } }
mit
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/TrailingCommaInspection.kt
2
11560
// 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.inspections import com.intellij.application.options.CodeStyle import com.intellij.codeInsight.intention.FileModifier import com.intellij.codeInspection.* import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel import com.intellij.codeInspection.util.InspectionMessage import com.intellij.codeInspection.util.IntentionFamilyName import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.CodeStyleSettingsManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.formatter.TrailingCommaVisitor import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaContext import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaState import org.jetbrains.kotlin.idea.formatter.trailingComma.addTrailingCommaIsAllowedFor import org.jetbrains.kotlin.idea.formatter.trailingCommaAllowedInModule import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.idea.util.isComma import org.jetbrains.kotlin.idea.util.isLineBreak import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import javax.swing.JComponent import kotlin.properties.Delegates class TrailingCommaInspection( @JvmField var addCommaWarning: Boolean = false ) : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : TrailingCommaVisitor() { override val recursively: Boolean = false private var useTrailingComma by Delegates.notNull<Boolean>() override fun process(trailingCommaContext: TrailingCommaContext) { val element = trailingCommaContext.ktElement val kotlinCustomSettings = element.containingKtFile.kotlinCustomSettings useTrailingComma = kotlinCustomSettings.addTrailingCommaIsAllowedFor(element) when (trailingCommaContext.state) { TrailingCommaState.MISSING, TrailingCommaState.EXISTS -> { checkCommaPosition(element) checkLineBreaks(element) } else -> Unit } checkTrailingComma(trailingCommaContext) } private fun checkLineBreaks(commaOwner: KtElement) { val first = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) if (first?.nextLeaf(true)?.isLineBreak() == false) { first.nextSibling?.let { registerProblemForLineBreak(commaOwner, it, ProblemHighlightType.INFORMATION) } } val last = TrailingCommaHelper.elementAfterLastElement(commaOwner) if (last?.prevLeaf(true)?.isLineBreak() == false) { registerProblemForLineBreak( commaOwner, last, if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION, ) } } private fun checkCommaPosition(commaOwner: KtElement) { for (invalidComma in TrailingCommaHelper.findInvalidCommas(commaOwner)) { reportProblem( invalidComma, KotlinBundle.message("inspection.trailing.comma.comma.loses.the.advantages.in.this.position"), KotlinBundle.message("inspection.trailing.comma.fix.comma.position") ) } } private fun checkTrailingComma(trailingCommaContext: TrailingCommaContext) { val commaOwner = trailingCommaContext.ktElement val trailingCommaOrLastElement = TrailingCommaHelper.trailingCommaOrLastElement(commaOwner) ?: return when (trailingCommaContext.state) { TrailingCommaState.MISSING -> { if (!trailingCommaAllowedInModule(commaOwner)) return reportProblem( trailingCommaOrLastElement, KotlinBundle.message("inspection.trailing.comma.missing.trailing.comma"), KotlinBundle.message("inspection.trailing.comma.add.trailing.comma"), if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION, ) } TrailingCommaState.REDUNDANT -> { reportProblem( trailingCommaOrLastElement, KotlinBundle.message("inspection.trailing.comma.useless.trailing.comma"), KotlinBundle.message("inspection.trailing.comma.remove.trailing.comma"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, checkTrailingCommaSettings = false, ) } else -> Unit } } private fun reportProblem( commaOrElement: PsiElement, @InspectionMessage message: String, @IntentionFamilyName fixMessage: String, highlightType: ProblemHighlightType = ProblemHighlightType.GENERIC_ERROR_OR_WARNING, checkTrailingCommaSettings: Boolean = true, ) { val commaOwner = commaOrElement.parent as KtElement // case for KtFunctionLiteral, where PsiWhiteSpace after KtTypeParameterList isn't included in this list val problemOwner = commonParent(commaOwner, commaOrElement) val highlightTypeWithAppliedCondition = highlightType.applyCondition(!checkTrailingCommaSettings || useTrailingComma) // INFORMATION shouldn't be reported in batch mode if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) { holder.registerProblem( problemOwner, message, highlightTypeWithAppliedCondition, commaOrElement.textRangeOfCommaOrSymbolAfter.shiftLeft(problemOwner.startOffset), createQuickFix(fixMessage, commaOwner), ) } } private fun registerProblemForLineBreak( commaOwner: KtElement, elementForTextRange: PsiElement, highlightType: ProblemHighlightType, ) { val problemElement = commonParent(commaOwner, elementForTextRange) val highlightTypeWithAppliedCondition = highlightType.applyCondition(useTrailingComma) // INFORMATION shouldn't be reported in batch mode if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) { holder.registerProblem( problemElement, KotlinBundle.message("inspection.trailing.comma.missing.line.break"), highlightTypeWithAppliedCondition, TextRange.from(elementForTextRange.startOffset, 1).shiftLeft(problemElement.startOffset), createQuickFix(KotlinBundle.message("inspection.trailing.comma.add.line.break"), commaOwner), ) } } private fun commonParent(commaOwner: PsiElement, elementForTextRange: PsiElement): PsiElement = PsiTreeUtil.findCommonParent(commaOwner, elementForTextRange) ?: throw KotlinExceptionWithAttachments("Common parent not found") .withPsiAttachment("commaOwner", commaOwner) .withAttachment("commaOwnerRange", commaOwner.textRange) .withPsiAttachment("elementForTextRange", elementForTextRange) .withAttachment("elementForTextRangeRange", elementForTextRange.textRange) .withPsiAttachment("parent", commaOwner.parent) .withAttachment("parentRange", commaOwner.parent.textRange) private fun ProblemHighlightType.applyCondition(condition: Boolean): ProblemHighlightType = when { isUnitTestMode() -> ProblemHighlightType.GENERIC_ERROR_OR_WARNING condition -> this else -> ProblemHighlightType.INFORMATION } private fun createQuickFix( @IntentionFamilyName fixMessage: String, commaOwner: KtElement, ): LocalQuickFix = ReformatTrailingCommaFix(commaOwner, fixMessage) private val PsiElement.textRangeOfCommaOrSymbolAfter: TextRange get() { val textRange = textRange if (isComma) return textRange return nextLeaf()?.leafIgnoringWhitespaceAndComments(false)?.endOffset?.takeIf { it > 0 }?.let { TextRange.create(it - 1, it).intersection(textRange) } ?: TextRange.create(textRange.endOffset - 1, textRange.endOffset) } } override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel( KotlinBundle.message("inspection.trailing.comma.report.also.a.missing.comma"), this, "addCommaWarning", ) class ReformatTrailingCommaFix(commaOwner: KtElement, @IntentionFamilyName private val fixMessage: String) : LocalQuickFix { val commaOwnerPointer = commaOwner.createSmartPointer() override fun getFamilyName(): String = fixMessage override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) { val element = commaOwnerPointer.element ?: return val range = createFormatterTextRange(element) val settings = CodeStyleSettingsManager.getInstance(project).cloneSettings(CodeStyle.getSettings(element.containingKtFile)) settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA = true settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA_ON_CALL_SITE = true CodeStyle.doWithTemporarySettings(project, settings, Runnable { CodeStyleManager.getInstance(project).reformatRange(element, range.startOffset, range.endOffset) }) } private fun createFormatterTextRange(commaOwner: KtElement): TextRange { val startElement = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) ?: commaOwner val endElement = TrailingCommaHelper.elementAfterLastElement(commaOwner) ?: commaOwner return TextRange.create(startElement.startOffset, endElement.endOffset) } override fun getFileModifierForPreview(target: PsiFile): FileModifier? { val element = commaOwnerPointer.element ?: return null return ReformatTrailingCommaFix(PsiTreeUtil.findSameElementInCopy(element, target), fixMessage) } } }
apache-2.0
boxtape/boxtape-cli
boxtape-cli/src/main/java/io/boxtape/cli/core/MavenDependencyCollector.kt
1
1741
package io.boxtape.cli.core import io.boxtape.core.LibraryArtifact import io.boxtape.cli.core.Project import org.apache.maven.cli.MavenCli import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import java.io.ByteArrayOutputStream import java.io.File import java.io.PrintStream import java.util.regex.Pattern @Component public class MavenDependencyCollector @Autowired constructor(val mvn: MavenCli):DependencyCollector { val ALPHA_CHARACTER = Pattern.compile("[a-zA-Z]"); val GROUP_ID = 0 val ARTIFACT_ID = 1 val VERSION = 3 override fun collect(project: Project):List<LibraryArtifact> { if (!project.hasFile("pom.xml")) { return listOf() } project.console.info("Reading your maven pom for dependencies") val outputStream = ByteArrayOutputStream() val printStream = PrintStream(outputStream) val outputFile = File.createTempFile("dependencies", ".txt") System.setProperty("maven.multiModuleProjectDirectory" , project.projectHome().canonicalPath) mvn.doMain(arrayOf("dependency:tree","-Dscope=compile", "-DoutputFile=${outputFile.getCanonicalPath()}"), project.projectHome().canonicalPath, printStream, printStream) val output = outputFile.readLines() .map { trimTreeSyntax(it) } .map { val parts = it.splitBy(":") LibraryArtifact(parts[GROUP_ID], parts[ARTIFACT_ID], parts[VERSION]) } return output } private fun trimTreeSyntax(line: String): String { val matcher = ALPHA_CHARACTER.matcher(line) return if (matcher.find()) line.substring(matcher.start()) else "" } }
apache-2.0
JetBrains/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/compilation/PortableCompilationCache.kt
1
11459
// 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.intellij.build.impl.compilation import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.NioFiles import org.jetbrains.intellij.build.CompilationContext import org.jetbrains.intellij.build.CompilationTasks import org.jetbrains.intellij.build.impl.JpsCompilationRunner import org.jetbrains.intellij.build.impl.compilation.cache.CommitsHistory import org.jetbrains.jps.incremental.storage.ProjectStamps import java.nio.file.Files import java.nio.file.Path import java.util.* class PortableCompilationCache(private val context: CompilationContext) { companion object { @JvmStatic val IS_ENABLED = ProjectStamps.PORTABLE_CACHES && IS_CONFIGURED private var isAlreadyUpdated = false } init { require(IS_ENABLED) { "JPS Caches are expected to be enabled" } } private val git = Git(context.paths.projectHome) /** * JPS data structures allowing incremental compilation for [CompilationOutput] */ private class JpsCaches(context: CompilationContext) { val skipDownload = bool(SKIP_DOWNLOAD_PROPERTY) val skipUpload = bool(SKIP_UPLOAD_PROPERTY) val dir: Path by lazy { context.compilationData.dataStorageRoot } val maybeAvailableLocally: Boolean by lazy { val files = dir.toFile().list() context.messages.info("$dir: ${files.joinToString()}") Files.isDirectory(dir) && files != null && files.isNotEmpty() } } /** * Server which stores [PortableCompilationCache] */ internal class RemoteCache(context: CompilationContext) { val url by lazy { require(URL_PROPERTY, "Remote Cache url", context) } val uploadUrl by lazy { require(UPLOAD_URL_PROPERTY, "Remote Cache upload url", context) } val authHeader by lazy { val username = System.getProperty("jps.auth.spaceUsername") val password = System.getProperty("jps.auth.spacePassword") when { password == null -> "" username == null -> "Bearer $password" else -> "Basic " + Base64.getEncoder().encodeToString("$username:$password".toByteArray()) } } } private val forceDownload = bool(FORCE_DOWNLOAD_PROPERTY) private val forceRebuild = bool(FORCE_REBUILD_PROPERTY) private val remoteCache = RemoteCache(context) private val jpsCaches by lazy { JpsCaches(context) } private val remoteGitUrl by lazy { val result = require(GIT_REPOSITORY_URL_PROPERTY, "Repository url", context) context.messages.info("Git remote url $result") result } private val downloader by lazy { val availableForHeadCommit = bool(AVAILABLE_FOR_HEAD_PROPERTY) PortableCompilationCacheDownloader(context, git, remoteCache, remoteGitUrl, availableForHeadCommit, jpsCaches.skipDownload) } private val uploader by lazy { val s3Folder = require(AWS_SYNC_FOLDER_PROPERTY, "AWS S3 sync folder", context) val commitHash = require(COMMIT_HASH_PROPERTY, "Repository commit", context) PortableCompilationCacheUploader(context, remoteCache, remoteGitUrl, commitHash, s3Folder, jpsCaches.skipUpload, forceRebuild) } /** * Download the latest available [PortableCompilationCache], * [org.jetbrains.intellij.build.CompilationTasks.resolveProjectDependencies] * and perform incremental compilation if necessary. * * When force rebuilding incremental compilation flag has to be set to false otherwise backward-refs won't be created. * During rebuild JPS checks condition [org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex.exists] || [org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.isRebuildInAllJavaModules] * and if incremental compilation is enabled JPS won't create [org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter]. * For more details see [org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.initialize] */ fun downloadCacheAndCompileProject() { synchronized(PortableCompilationCache) { if (isAlreadyUpdated) { context.messages.info("PortableCompilationCache is already updated") return } if (forceRebuild || forceDownload) { clean() } if (!forceRebuild && !isLocalCacheUsed()) { downloadCache() } CompilationTasks.create(context).resolveProjectDependencies() if (isCompilationRequired()) { context.options.incrementalCompilation = !forceRebuild context.messages.block("Compiling project") { compileProject(context) } } isAlreadyUpdated = true context.options.incrementalCompilation = true } } private fun isCompilationRequired() = forceRebuild || isLocalCacheUsed() || isRemoteCacheStale() private fun isLocalCacheUsed() = !forceRebuild && !forceDownload && jpsCaches.maybeAvailableLocally private fun isRemoteCacheStale() = !downloader.availableForHeadCommit /** * Upload local [PortableCompilationCache] to [PortableCompilationCache.RemoteCache] */ fun upload() { if (!forceRebuild && downloader.availableForHeadCommit) { context.messages.info("Nothing new to upload") } else { uploader.upload(context.messages) } val metadataFile = context.paths.artifactDir.resolve(COMPILATION_CACHE_METADATA_JSON) Files.createDirectories(metadataFile.parent) Files.writeString(metadataFile, "This is stub file required only for TeamCity artifact dependency. " + "Compiled classes will be resolved via ${remoteCache.url}") context.messages.artifactBuilt("$metadataFile") } /** * Publish already uploaded [PortableCompilationCache] to [PortableCompilationCache.RemoteCache] */ fun publish() { uploader.updateCommitHistory() } /** * Publish already uploaded [PortableCompilationCache] to [PortableCompilationCache.RemoteCache] overriding existing [CommitsHistory]. * Used in force rebuild and cleanup. */ fun overrideCommitHistory(forceRebuiltCommits: Set<String>) { uploader.updateCommitHistory(CommitsHistory(mapOf(remoteGitUrl to forceRebuiltCommits)), true) } private fun clean() { for (it in listOf(jpsCaches.dir, context.classesOutputDirectory)) { context.messages.info("Cleaning $it") NioFiles.deleteRecursively(it) } } private fun compileProject(context: CompilationContext) { // fail-fast in case of KTIJ-17296 if (SystemInfoRt.isWindows && git.lineBreaksConfig() != "input") { context.messages.error("PortableCompilationCache cannot be used with CRLF line breaks, " + "please execute `git config --global core.autocrlf input` before checkout " + "and upvote https://youtrack.jetbrains.com/issue/KTIJ-17296") } context.compilationData.statisticsReported = false val jps = JpsCompilationRunner(context) try { jps.buildAll() } catch (e: Exception) { if (!context.options.incrementalCompilation) { throw e } val successMessage: String if (forceDownload) { context.messages.warning("Incremental compilation using Remote Cache failed. Re-trying without any caches.") clean() context.options.incrementalCompilation = false successMessage = "Compilation successful after clean build retry" } else { // Portable Compilation Cache is rebuilt from scratch on CI and re-published every night to avoid possible incremental compilation issues. // If download isn't forced then locally available cache will be used which may suffer from those issues. // Hence, compilation failure. Replacing local cache with remote one may help. context.messages.warning("Incremental compilation using locally available caches failed. Re-trying using Remote Cache.") downloadCache() successMessage = "Compilation successful after retry with fresh Remote Cache" } context.compilationData.reset() jps.buildAll() context.messages.info(successMessage) println("##teamcity[buildStatus status='SUCCESS' text='$successMessage']") context.messages.reportStatisticValue("Incremental compilation failures", "1") } } private fun downloadCache() { context.messages.block("Downloading Portable Compilation Cache") { downloader.download() } } } /** * [PortableCompilationCache.JpsCaches] archive upload may be skipped if only [CompilationOutput]s are required * without any incremental compilation (for tests execution as an example) */ private const val SKIP_UPLOAD_PROPERTY = "intellij.jps.remote.cache.uploadCompilationOutputsOnly" /** * [PortableCompilationCache.JpsCaches] archive download may be skipped if only [CompilationOutput]s are required * without any incremental compilation (for tests execution as an example) */ private const val SKIP_DOWNLOAD_PROPERTY = "intellij.jps.remote.cache.downloadCompilationOutputsOnly" /** * URL for read/write operations */ private const val UPLOAD_URL_PROPERTY = "intellij.jps.remote.cache.upload.url" /** * URL for read-only operations */ private const val URL_PROPERTY = "intellij.jps.remote.cache.url" /** * If true then [PortableCompilationCache.RemoteCache] is configured to be used */ private val IS_CONFIGURED = !System.getProperty(URL_PROPERTY).isNullOrBlank() /** * IntelliJ repository git remote url */ private const val GIT_REPOSITORY_URL_PROPERTY = "intellij.remote.url" /** * If true then [PortableCompilationCache] for head commit is expected to exist and search in [CommitsHistory.JSON_FILE] is skipped. * Required for temporary branch caches which are uploaded but not published in [CommitsHistory.JSON_FILE]. */ private const val AVAILABLE_FOR_HEAD_PROPERTY = "intellij.jps.cache.availableForHeadCommit" /** * Download [PortableCompilationCache] even if there are caches available locally */ private const val FORCE_DOWNLOAD_PROPERTY = "intellij.jps.cache.download.force" /** * If true then [PortableCompilationCache] will be rebuilt from scratch */ private const val FORCE_REBUILD_PROPERTY = "intellij.jps.cache.rebuild.force" /** * Folder to store [PortableCompilationCache] for later upload to AWS S3 bucket. * Upload performed in a separate process on CI. */ private const val AWS_SYNC_FOLDER_PROPERTY = "jps.caches.aws.sync.folder" /** * Commit hash for which [PortableCompilationCache] is to be built/downloaded */ private const val COMMIT_HASH_PROPERTY = "build.vcs.number" private fun require(systemProperty: String, description: String, context: CompilationContext): String { val value = System.getProperty(systemProperty) if (value.isNullOrBlank()) { context.messages.error("$description is not defined. Please set '$systemProperty' system property.") } return value } private fun bool(systemProperty: String): Boolean { return System.getProperty(systemProperty).toBoolean() } /** * Compiled bytecode of project module, cannot be used for incremental compilation without [PortableCompilationCache.JpsCaches] */ internal class CompilationOutput( name: String, type: String, @JvmField val hash: String, // Some hash of compilation output, could be non-unique across different CompilationOutput's @JvmField val path: String, // Local path to compilation output ) { val remotePath = "$type/$name/$hash" }
apache-2.0
google/iosched
shared/src/main/java/com/google/samples/apps/iosched/shared/domain/FlowUseCase.kt
3
1415
/* * Copyright 2018 Google LLC * * 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.google.samples.apps.iosched.shared.domain import com.google.samples.apps.iosched.shared.result.Result import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flowOn /** * Executes business logic in its execute method and keep posting updates to the result as * [Result<R>]. * Handling an exception (emit [Result.Error] to the result) is the subclasses's responsibility. */ abstract class FlowUseCase<in P, R>(private val coroutineDispatcher: CoroutineDispatcher) { operator fun invoke(parameters: P): Flow<Result<R>> = execute(parameters) .catch { e -> emit(Result.Error(Exception(e))) } .flowOn(coroutineDispatcher) protected abstract fun execute(parameters: P): Flow<Result<R>> }
apache-2.0
apollographql/apollo-android
apollo-runtime/src/commonMain/kotlin/com/apollographql/apollo3/network/http/HttpNetworkTransport.kt
1
6587
package com.apollographql.apollo3.network.http import com.apollographql.apollo3.api.ApolloRequest import com.apollographql.apollo3.api.ApolloResponse import com.apollographql.apollo3.api.CustomScalarAdapters import com.apollographql.apollo3.api.Operation import com.apollographql.apollo3.api.http.DefaultHttpRequestComposer import com.apollographql.apollo3.api.http.HttpHeader import com.apollographql.apollo3.api.http.HttpRequest import com.apollographql.apollo3.api.http.HttpRequestComposer import com.apollographql.apollo3.api.http.HttpResponse import com.apollographql.apollo3.api.json.jsonReader import com.apollographql.apollo3.api.parseJsonResponse import com.apollographql.apollo3.exception.ApolloException import com.apollographql.apollo3.exception.ApolloHttpException import com.apollographql.apollo3.exception.ApolloParseException import com.apollographql.apollo3.internal.NonMainWorker import com.apollographql.apollo3.mpp.currentTimeMillis import com.apollographql.apollo3.network.NetworkTransport import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class HttpNetworkTransport private constructor( private val httpRequestComposer: HttpRequestComposer, val engine: HttpEngine, val interceptors: List<HttpInterceptor>, val exposeErrorBody: Boolean ) : NetworkTransport { private val worker = NonMainWorker() private val engineInterceptor = EngineInterceptor() override fun <D : Operation.Data> execute( request: ApolloRequest<D>, ): Flow<ApolloResponse<D>> { val customScalarAdapters = request.executionContext[CustomScalarAdapters]!! val httpRequest = httpRequestComposer.compose(request) return execute(request, httpRequest, customScalarAdapters) } fun <D : Operation.Data> execute( request: ApolloRequest<D>, httpRequest: HttpRequest, customScalarAdapters: CustomScalarAdapters, ): Flow<ApolloResponse<D>> { return flow { val millisStart = currentTimeMillis() val httpResponse = DefaultHttpInterceptorChain( interceptors = interceptors + engineInterceptor, index = 0 ).proceed(httpRequest) if (httpResponse.statusCode !in 200..299) { val maybeBody = if (exposeErrorBody) { httpResponse.body } else { httpResponse.body?.close() null } throw ApolloHttpException( statusCode = httpResponse.statusCode, headers = httpResponse.headers, body = maybeBody, message = "Http request failed with status code `${httpResponse.statusCode}`" ) } // do not capture request val operation = request.operation val response = worker.doWork { try { operation.parseJsonResponse( jsonReader = httpResponse.body!!.jsonReader(), customScalarAdapters = customScalarAdapters ) } catch (e: Exception) { throw wrapThrowableIfNeeded(e) } } emit( response.newBuilder() .requestUuid(request.requestUuid) .addExecutionContext( HttpInfo( millisStart = millisStart, millisEnd = currentTimeMillis(), statusCode = httpResponse.statusCode, headers = httpResponse.headers ) ) .build() ) } } inner class EngineInterceptor : HttpInterceptor { override suspend fun intercept(request: HttpRequest, chain: HttpInterceptorChain): HttpResponse { return engine.execute(request) } } override fun dispose() { interceptors.forEach { it.dispose() } engine.dispose() } /** * Creates a new Builder that shares the underlying resources * * Calling [dispose] on the original instance or the new one will terminate the [engine] for both instances */ fun newBuilder(): Builder { return Builder() .httpEngine(engine) .interceptors(interceptors) .httpRequestComposer(httpRequestComposer) } /** * A builder for [HttpNetworkTransport] */ class Builder { private var httpRequestComposer: HttpRequestComposer? = null private var serverUrl: String? = null private var engine: HttpEngine? = null private val interceptors: MutableList<HttpInterceptor> = mutableListOf() private var exposeErrorBody: Boolean = false fun httpRequestComposer(httpRequestComposer: HttpRequestComposer) = apply { this.httpRequestComposer = httpRequestComposer } fun serverUrl(serverUrl: String) = apply { this.serverUrl = serverUrl } /** * Configures whether to expose the error body in [ApolloHttpException]. * * If you're setting this to `true`, you **must** catch [ApolloHttpException] and close the body explicitly * to avoid sockets and other resources leaking. * * Default: false */ fun exposeErrorBody(exposeErrorBody: Boolean) = apply { this.exposeErrorBody = exposeErrorBody } fun httpHeaders(headers: List<HttpHeader>) = apply { interceptors.add(HeadersInterceptor(headers)) } fun httpEngine(httpEngine: HttpEngine) = apply { this.engine = httpEngine } fun interceptors(interceptors: List<HttpInterceptor>) = apply { this.interceptors.clear() this.interceptors.addAll(interceptors) } fun addInterceptor(interceptor: HttpInterceptor) = apply { this.interceptors.add(interceptor) } fun build(): HttpNetworkTransport { check (httpRequestComposer == null || serverUrl == null) { "It is an error to set both 'httpRequestComposer' and 'serverUrl'" } val composer = httpRequestComposer ?: serverUrl?.let { DefaultHttpRequestComposer(it) } ?: error("No HttpRequestComposer found. Use 'httpRequestComposer' or 'serverUrl'") return HttpNetworkTransport( httpRequestComposer = composer, engine = engine ?: DefaultHttpEngine(), interceptors = interceptors, exposeErrorBody = exposeErrorBody, ) } } companion object { private fun wrapThrowableIfNeeded(throwable: Throwable): ApolloException { return if (throwable is ApolloException) { throwable } else { // This happens for null pointer exceptions on missing fields ApolloParseException( message = "Failed to parse GraphQL http network response", cause = throwable ) } } } }
mit
camunda/camunda-process-test-coverage
extension/junit5-platform-7/src/test/kotlin/org/camunda/community/process_test_coverage/junit5/platform7/MultipleDeploymentsForIndividualTestsTest.kt
1
1810
package org.camunda.community.process_test_coverage.junit5.platform7 import org.assertj.core.api.HamcrestCondition import org.camunda.bpm.engine.test.Deployment import org.hamcrest.Matchers import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension class MultipleDeploymentsForIndividualTestsTest { companion object { private const val PROCESS_DEFINITION_KEY = "super-process-test-coverage" @JvmField @RegisterExtension var extension: ProcessEngineCoverageExtension = ProcessEngineCoverageExtension.builder().build() } @Test @Deployment(resources = ["superProcess.bpmn", "process.bpmn"]) fun testPathAAndSuperPathA() { val variables: MutableMap<String, Any> = HashMap() variables["path"] = "A" variables["superPath"] = "A" extension.processEngine.runtimeService.startProcessInstanceByKey(PROCESS_DEFINITION_KEY, variables) extension.addTestMethodCoverageCondition("testPathAAndSuperPathA", HamcrestCondition(Matchers.greaterThan(6.9 / 11.0))) extension.addTestMethodCoverageCondition("testPathAAndSuperPathA", HamcrestCondition(Matchers.lessThan(9 / 11.0))) } @Test @Deployment(resources = ["superProcess.bpmn", "process.bpmn"]) fun testPathBAndSuperPathB() { val variables: MutableMap<String, Any> = HashMap() variables["path"] = "B" variables["superPath"] = "B" extension.processEngine.runtimeService.startProcessInstanceByKey(PROCESS_DEFINITION_KEY, variables) extension.addTestMethodCoverageCondition("testPathBAndSuperPathB", HamcrestCondition(Matchers.greaterThan(6.9 / 11.0))) extension.addTestMethodCoverageCondition("testPathBAndSuperPathB", HamcrestCondition(Matchers.lessThan(9 / 11.0))) } }
apache-2.0
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldReturnToIfIntention.kt
1
3033
// 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.branchedTransformations.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.types.typeUtil.isNothing class UnfoldReturnToIfIntention : LowPriorityAction, SelfTargetingRangeIntention<KtReturnExpression>( KtReturnExpression::class.java, KotlinBundle.lazyMessage("replace.return.with.if.expression") ) { override fun applicabilityRange(element: KtReturnExpression): TextRange? { val ifExpression = element.returnedExpression as? KtIfExpression ?: return null return TextRange(element.startOffset, ifExpression.ifKeyword.endOffset) } override fun applyTo(element: KtReturnExpression, editor: Editor?) { val ifExpression = element.returnedExpression as KtIfExpression val thenExpr = ifExpression.then!!.lastBlockStatementOrThis() val elseExpr = ifExpression.`else`!!.lastBlockStatementOrThis() val newIfExpression = ifExpression.copied() val newThenExpr = newIfExpression.then!!.lastBlockStatementOrThis() val newElseExpr = newIfExpression.`else`!!.lastBlockStatementOrThis() val psiFactory = KtPsiFactory(element.project) val context = element.analyze() val labelName = element.getLabelName() newThenExpr.replace(createReturnExpression(thenExpr, labelName, psiFactory, context)) newElseExpr.replace(createReturnExpression(elseExpr, labelName, psiFactory, context)) element.replace(newIfExpression) } companion object { fun createReturnExpression( expr: KtExpression, labelName: String?, psiFactory: KtPsiFactory, context: BindingContext ): KtExpression { val label = labelName?.let { "@$it" } ?: "" val returnText = when (expr) { is KtBreakExpression, is KtContinueExpression, is KtReturnExpression, is KtThrowExpression -> "" else -> if (expr.getResolvedCall(context)?.resultingDescriptor?.returnType?.isNothing() == true) "" else "return$label " } return psiFactory.createExpressionByPattern("$returnText$0", expr) } } }
apache-2.0
fancylou/FancyFilePicker
fancyfilepickerlibrary/src/main/java/net/muliba/fancyfilepickerlibrary/ui/fragment/FileLocalStoragePickerFragment.kt
1
6833
package net.muliba.fancyfilepickerlibrary.ui.fragment import android.os.Bundle import android.os.Environment import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.TextView import kotlinx.android.synthetic.main.breadcrumbs.* import kotlinx.android.synthetic.main.fragment_file_picker.* import net.muliba.fancyfilepickerlibrary.FilePicker import net.muliba.fancyfilepickerlibrary.R import net.muliba.fancyfilepickerlibrary.adapter.FileAdapter import net.muliba.fancyfilepickerlibrary.adapter.FileViewHolder import net.muliba.fancyfilepickerlibrary.ext.friendlyFileLength import net.muliba.fancyfilepickerlibrary.ui.FileActivity import net.muliba.fancyfilepickerlibrary.util.Utils import org.jetbrains.anko.doAsync import org.jetbrains.anko.toast import org.jetbrains.anko.uiThread import java.io.File import java.util.regex.Pattern /** * Created by fancylou on 10/23/17. */ class FileLocalStoragePickerFragment: Fragment() { var mActivity: FileActivity? = null private val rootPath: String = Environment.getExternalStorageDirectory().absolutePath private var currentPath = rootPath override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if (activity != null) { mActivity = (activity as FileActivity) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.fragment_file_picker, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recycler_file_picker_list.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) recycler_file_picker_list.adapter = adapter constraint_file_picker_upper_level_button.setOnClickListener { upperLevel() } refreshList(currentPath) } fun onBackPressed():Boolean { if (rootPath == currentPath) { return false }else { upperLevel() return true } } /** * 向上一级 */ private fun upperLevel() { if (rootPath == currentPath) { activity?.toast(getString(R.string.message_already_on_top)) } else { refreshList(File(currentPath).parentFile.absolutePath) } } /** * 定义adapter */ val adapter: FileAdapter by lazy { object : FileAdapter() { override fun onBind(file: File, holder: FileViewHolder) { if (file.isDirectory) { holder.setText(R.id.tv_file_picker_folder_name, file.name) val folderDesc = holder.getView<TextView>(R.id.tv_file_picker_folder_description) doAsync { val size = file.list().size.toString() uiThread { folderDesc.text = getString(R.string.item_folder_description_label).format(size) } } holder.convertView.setOnClickListener { refreshList(file.absolutePath) } } else { holder.setText(R.id.tv_file_picker_file_name, file.name) .setImageByResource(R.id.image_file_picker_file, Utils.fileIcon(file.extension)) val fileDesc = holder.getView<TextView>(R.id.tv_file_picker_file_description) doAsync { val len = file.length().friendlyFileLength() uiThread { fileDesc.text = len } } val checkbox = holder.getView<CheckBox>(R.id.checkBox_file_picker_file) if (mActivity?.chooseType == FilePicker.CHOOSE_TYPE_SINGLE){ checkbox.visibility = View.GONE }else{ checkbox.visibility = View.VISIBLE checkbox.isChecked = false if (mActivity?.mSelected?.contains(file.absolutePath) == true) { checkbox.isChecked = true } //checkbox click checkbox.setOnClickListener { val check = checkbox.isChecked mActivity?.toggleChooseFile(file.absolutePath, check) } } holder.convertView.setOnClickListener { v -> if (mActivity?.chooseType == FilePicker.CHOOSE_TYPE_SINGLE){ mActivity?.chooseFileSingle(file.absolutePath) }else{ val filePickerCheckbox = v.findViewById(R.id.checkBox_file_picker_file) as CheckBox val check = filePickerCheckbox.isChecked filePickerCheckbox.isChecked = !check mActivity?.toggleChooseFile(file.absolutePath, !check) } } } } } } /** * 刷新list */ private fun refreshList(path: String) { doAsync { val list: List<File> = File(path).listFiles{ _, fileName -> val pattern = Pattern.compile("\\..*") !pattern.matcher(fileName).matches() }.map { it }.sortedWith(Comparator<File> { o1, o2 -> if (o1.isDirectory && o2.isDirectory) { o1.name.compareTo(o2.name, true) } else if (o1.isFile && o2.isFile) { o1.name.compareTo(o2.name, true) } else { when (o1.isDirectory && o2.isFile) { true -> -1 false -> 1 } } }) uiThread { currentPath = path if (currentPath.equals(rootPath)){ breadcrumbs.visibility = View.GONE }else { breadcrumbs.visibility = View.VISIBLE } tv_file_picker_folder_path.text = currentPath if (list.isNotEmpty()) { recycler_file_picker_list.visibility = View.VISIBLE file_picker_empty.visibility = View.GONE } else { recycler_file_picker_list.visibility = View.GONE file_picker_empty.visibility = View.VISIBLE } adapter.refreshItems(list) } } } }
apache-2.0
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/domain/retention/analytic/RetentionNotificationDismissed.kt
1
406
package org.stepik.android.domain.retention.analytic import org.stepik.android.domain.base.analytic.AnalyticEvent class RetentionNotificationDismissed( day: Int ) : AnalyticEvent { companion object { const val PARAM_DAY = "day" } override val name: String = "Retention notification dismissed" override val params: Map<String, Any> = mapOf(PARAM_DAY to day) }
apache-2.0
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/course_reviews/ui/adapter/delegates/CourseReviewDataDelegate.kt
2
4872
package org.stepik.android.view.course_reviews.ui.adapter.delegates import android.graphics.BitmapFactory import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.view.View import android.view.ViewGroup import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.PopupMenu import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory import androidx.core.view.isVisible import kotlinx.android.synthetic.main.view_course_reviews_item.view.* import org.stepic.droid.R import org.stepik.android.view.glide.ui.extension.wrapWithGlide import org.stepic.droid.util.DateTimeHelper import org.stepic.droid.util.resolveColorAttribute import org.stepik.android.domain.course_reviews.model.CourseReview import org.stepik.android.domain.course_reviews.model.CourseReviewItem import org.stepik.android.model.user.User import org.stepik.android.view.base.ui.mapper.DateMapper import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class CourseReviewDataDelegate( private val onUserClicked: (User) -> Unit, private val onEditReviewClicked: (CourseReview) -> Unit, private val onRemoveReviewClicked: (CourseReview) -> Unit ) : AdapterDelegate<CourseReviewItem, DelegateViewHolder<CourseReviewItem>>() { override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CourseReviewItem> = ViewHolder(createView(parent, R.layout.view_course_reviews_item)) override fun isForViewType(position: Int, data: CourseReviewItem): Boolean = data is CourseReviewItem.Data inner class ViewHolder(root: View) : DelegateViewHolder<CourseReviewItem>(root) { private val reviewIcon = root.reviewIcon private val reviewIconWrapper = reviewIcon.wrapWithGlide() private val reviewDate = root.reviewDate private val reviewName = root.reviewName private val reviewRating = root.reviewRating private val reviewText = root.reviewText private val reviewMenu = root.reviewMenu private val reviewMark = root.reviewMark private val reviewIconPlaceholder = with(context.resources) { val coursePlaceholderBitmap = BitmapFactory.decodeResource(this, R.drawable.general_placeholder) val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(this, coursePlaceholderBitmap) circularBitmapDrawable.cornerRadius = getDimension(R.dimen.corner_radius) circularBitmapDrawable } init { val userClickListener = View.OnClickListener { (itemData as? CourseReviewItem.Data)?.user?.let(onUserClicked) } reviewIcon.setOnClickListener(userClickListener) reviewName.setOnClickListener(userClickListener) reviewDate.setOnClickListener(userClickListener) reviewMenu.setOnClickListener(::showReviewMenu) } override fun onBind(data: CourseReviewItem) { data as CourseReviewItem.Data reviewIconWrapper.setImagePath(data.user.avatar ?: "", AppCompatResources.getDrawable(context, R.drawable.general_placeholder)) reviewName.text = data.user.fullName reviewDate.text = DateMapper.mapToRelativeDate(context, DateTimeHelper.nowUtc(), data.courseReview.updateDate?.time ?: 0) reviewRating.progress = data.courseReview.score reviewRating.total = 5 reviewText.text = data.courseReview.text reviewMenu.isVisible = data.isCurrentUserReview reviewMark.isVisible = data.isCurrentUserReview } private fun showReviewMenu(view: View) { val courseReview = (itemData as? CourseReviewItem.Data) ?.courseReview ?: return val popupMenu = PopupMenu(context, view) popupMenu.inflate(R.menu.course_review_menu) popupMenu .menu .findItem(R.id.course_review_menu_remove) ?.let { menuItem -> val title = SpannableString(menuItem.title) title.setSpan(ForegroundColorSpan(context.resolveColorAttribute(R.attr.colorError)), 0, title.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE) menuItem.title = title } popupMenu .setOnMenuItemClickListener { menuItem -> when (menuItem.itemId) { R.id.course_review_menu_edit -> onEditReviewClicked(courseReview) R.id.course_review_menu_remove -> onRemoveReviewClicked(courseReview) } true } popupMenu.show() } } }
apache-2.0
StepicOrg/stepik-android
app/src/main/java/org/stepic/droid/features/stories/ui/delegate/StoriesActivityDelegate.kt
1
3159
package org.stepic.droid.features.stories.ui.delegate import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.children import androidx.viewpager.widget.ViewPager import kotlinx.android.synthetic.main.activity_stories.* import org.stepic.droid.R import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.analytic.Analytic import org.stepik.android.domain.story.model.StoryReaction import ru.nobird.app.core.model.safeCast import ru.nobird.android.stories.model.Story import ru.nobird.android.stories.ui.adapter.StoriesPagerAdapter import ru.nobird.android.stories.ui.custom.DismissableLayout import ru.nobird.android.stories.ui.custom.StoryView import ru.nobird.android.stories.ui.delegate.StoriesActivityDelegateBase import ru.nobird.android.stories.ui.delegate.StoryPartViewDelegate class StoriesActivityDelegate( activity: AppCompatActivity, private val analytic: Analytic, storyReactionListener: (storyId: Long, storyPosition: Int, storyReaction: StoryReaction) -> Unit ) : StoriesActivityDelegateBase(activity) { private val storyReactions = mutableMapOf<Long, StoryReaction>() private val storyPartDelegate = PlainTextWithButtonStoryPartDelegate(analytic, activity, storyReactions, storyReactionListener) public override val dismissableLayout: DismissableLayout = activity.content public override val storiesViewPager: ViewPager = activity.storiesPager override val arguments: Bundle = activity.intent.extras ?: Bundle.EMPTY override val storyPartDelegates: List<StoryPartViewDelegate> = listOf(storyPartDelegate, FeedbackStoryPartDelegate(analytic, activity, dismissableLayout)) override fun onComplete() { super.onComplete() val story = getCurrentStory() ?: return analytic.reportAmplitudeEvent(AmplitudeAnalytic.Stories.STORY_CLOSED, mapOf( AmplitudeAnalytic.Stories.Values.STORY_ID to story.id, AmplitudeAnalytic.Stories.Values.CLOSE_TYPE to AmplitudeAnalytic.Stories.Values.CloseTypes.AUTO )) } fun getCurrentStory(): Story? = storiesViewPager.adapter .safeCast<StoriesPagerAdapter>() ?.stories ?.getOrNull(storiesViewPager.currentItem) fun setStoryVotes(votes: Map<Long, StoryReaction>) { val diff = votes - storyReactions // only this way as reactions can't be removed storyReactions.clear() storyReactions += votes val adapter = storiesViewPager.adapter .safeCast<StoriesPagerAdapter>() ?: return diff.forEach { (storyId, _) -> val position = adapter.stories .indexOfFirst { it.id == storyId } val story = adapter.stories .getOrNull(position) val storyPartPager = storiesViewPager .findViewWithTag<StoryView>(position) ?.findViewById<ViewPager>(R.id.storyViewPager) storyPartPager?.children?.forEach { view -> storyPartDelegate.setUpReactions(story, view, position) } } } }
apache-2.0
allotria/intellij-community
platform/elevation/client/src/com/intellij/execution/process/mediator/client/MediatedProcess.kt
2
8192
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("EXPERIMENTAL_API_USAGE") package com.intellij.execution.process.mediator.client import com.google.protobuf.ByteString import com.intellij.execution.process.SelfKiller import com.intellij.execution.process.mediator.daemon.QuotaExceededException import com.intellij.execution.process.mediator.util.ChannelInputStream import com.intellij.execution.process.mediator.util.ChannelOutputStream import com.intellij.execution.process.mediator.util.blockingGet import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlinx.coroutines.flow.* import kotlinx.coroutines.future.asCompletableFuture import java.io.* import java.lang.ref.Cleaner import java.util.concurrent.CompletableFuture import kotlin.coroutines.coroutineContext private val CLEANER = Cleaner.create() class MediatedProcess private constructor( private val handle: MediatedProcessHandle, command: List<String>, workingDir: File, environVars: Map<String, String>, inFile: File?, outFile: File?, errFile: File?, ) : Process(), SelfKiller { companion object { @Throws(IOException::class, QuotaExceededException::class, CancellationException::class) fun create(processMediatorClient: ProcessMediatorClient, processBuilder: ProcessBuilder): MediatedProcess { val workingDir = processBuilder.directory() ?: File(".").normalize() // defaults to current working directory val inFile = processBuilder.redirectInput().file() val outFile = processBuilder.redirectOutput().file() val errFile = processBuilder.redirectError().file() val handle = MediatedProcessHandle.create(processMediatorClient) return try { MediatedProcess(handle, processBuilder.command(), workingDir, processBuilder.environment(), inFile, outFile, errFile).apply { val cleanable = CLEANER.register(this, handle::releaseAsync) onExit().thenRun { cleanable.clean() } } } catch (e: Throwable) { handle.rpcScope.cancel(e as? CancellationException ?: CancellationException("Failed to create process", e)) throw e } } } private val pid = runBlocking { handle.rpc { handleId -> createProcess(handleId, command, workingDir, environVars, inFile, outFile, errFile) } } private val stdin: OutputStream = if (inFile == null) createOutputStream(0) else NullOutputStream private val stdout: InputStream = if (outFile == null) createInputStream(1) else NullInputStream private val stderr: InputStream = if (errFile == null) createInputStream(2) else NullInputStream private val termination: Deferred<Int> = handle.rpcScope.async { handle.rpc { handleId -> awaitTermination(handleId) } } override fun pid(): Long = pid override fun getOutputStream(): OutputStream = stdin override fun getInputStream(): InputStream = stdout override fun getErrorStream(): InputStream = stderr @Suppress("EXPERIMENTAL_API_USAGE") private fun createOutputStream(@Suppress("SameParameterValue") fd: Int): OutputStream { val ackFlow = MutableStateFlow<Long?>(0L) val channel = handle.rpcScope.actor<ByteString>(capacity = Channel.BUFFERED) { handle.rpc { handleId -> try { // NOTE: Must never consume the channel associated with the actor. In fact, the channel IS the actor coroutine, // and cancelling it makes the coroutine die in a horrible way leaving the remote call in a broken state. writeStream(handleId, fd, channel.receiveAsFlow()) .onCompletion { ackFlow.value = null } .fold(0L) { l, _ -> (l + 1).also { ackFlow.value = it } } } catch (e: IOException) { channel.cancel(CancellationException(e.message, e)) } } } val stream = ChannelOutputStream(channel, ackFlow) return BufferedOutputStream(stream) } @Suppress("EXPERIMENTAL_API_USAGE") private fun createInputStream(fd: Int): InputStream { val channel = handle.rpcScope.produce<ByteString>(capacity = Channel.BUFFERED) { handle.rpc { handleId -> try { readStream(handleId, fd).collect(channel::send) } catch (e: IOException) { channel.close(e) } } } val stream = ChannelInputStream(channel) return BufferedInputStream(stream) } override fun waitFor(): Int = termination.blockingGet() override fun onExit(): CompletableFuture<Process> = termination.asCompletableFuture().thenApply { this } override fun exitValue(): Int { return try { @Suppress("EXPERIMENTAL_API_USAGE") termination.getCompleted() } catch (e: IllegalStateException) { throw IllegalThreadStateException(e.message) } } override fun destroy() { destroy(false) } override fun destroyForcibly(): Process { destroy(true) return this } fun destroy(force: Boolean, destroyGroup: Boolean = false) { // In case this is called after releasing the handle (due to process termination), // it just does nothing, without throwing any error. handle.rpcScope.launch { handle.rpc { handleId -> destroyProcess(handleId, force, destroyGroup) } } } private object NullInputStream : InputStream() { override fun read(): Int = -1 override fun available(): Int = 0 } private object NullOutputStream : OutputStream() { override fun write(b: Int) = throw IOException("Stream closed") } } /** * All remote calls are performed using the provided [ProcessMediatorClient], * and the whole process lifecycle is contained within the coroutine scope of the client. * Normal remote calls (those besides process creation and release) are performed within the scope of the handle object. */ private class MediatedProcessHandle private constructor( private val client: ProcessMediatorClient, private val handleId: Long, private val lifetimeChannel: ReceiveChannel<*>, ) { companion object { fun create(client: ProcessMediatorClient): MediatedProcessHandle { val lifetimeChannel = client.openHandle().produceIn(client.coroutineScope) try { val handleId = runBlocking { lifetimeChannel.receiveOrNull() ?: throw IOException("Failed to receive handleId") } return MediatedProcessHandle(client, handleId, lifetimeChannel) } catch (e: Throwable) { lifetimeChannel.cancel(e as? CancellationException ?: CancellationException("Failed to initialize client-side handle", e)) throw e } } } private val parentScope: CoroutineScope = client.coroutineScope private val lifetimeJob = parentScope.launch { try { lifetimeChannel.receive() } catch (e: ClosedReceiveChannelException) { throw CancellationException("closed", e) } error("unreachable") } private val rpcJob: CompletableJob = SupervisorJob(lifetimeJob).apply { invokeOnCompletion { e -> lifetimeChannel.cancel(e as? CancellationException ?: CancellationException("Complete", e)) } } val rpcScope: CoroutineScope = parentScope + rpcJob suspend fun <R> rpc(block: suspend ProcessMediatorClient.(handleId: Long) -> R): R { rpcScope.ensureActive() coroutineContext.ensureActive() // Perform the call in the scope of this handle, so that it is dispatched in the same way as OpenHandle(). // This overrides the parent so that we can await for the call to complete before closing the lifetimeChannel; // at the same time we ensure the caller is still able to cancel it. val deferred = rpcScope.async { client.block(handleId) } return try { deferred.await() } catch (e: CancellationException) { deferred.cancel(e) throw e } } fun releaseAsync() { // let ongoing operations finish gracefully, // and once all of them finish don't accept new calls rpcJob.complete() } }
apache-2.0
deadpixelsociety/roto-ld34
core/src/com/thedeadpixelsociety/ld34/Sounds.kt
1
552
package com.thedeadpixelsociety.ld34 import com.badlogic.gdx.audio.Music import com.badlogic.gdx.audio.Sound import com.badlogic.gdx.utils.Disposable import kotlin.properties.Delegates object Sounds : Disposable { var bounce by Delegates.notNull<Sound>() var coin by Delegates.notNull<Sound>() var dead by Delegates.notNull<Sound>() var music by Delegates.notNull<Music>() var soundMuted = false override fun dispose() { //music.dispose() bounce.dispose() dead.dispose() coin.dispose() } }
mit
allotria/intellij-community
python/src/com/jetbrains/python/sdk/add/PyAddNewCondaEnvPanel.kt
3
6316
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.add import com.intellij.execution.ExecutionException import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.JBCheckBox import com.intellij.util.PathUtil import com.intellij.util.SystemProperties import com.intellij.util.ui.FormBuilder import com.jetbrains.python.PyBundle import com.jetbrains.python.packaging.PyCondaPackageManagerImpl import com.jetbrains.python.packaging.PyCondaPackageService import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.associateWithModule import com.jetbrains.python.sdk.basePath import com.jetbrains.python.sdk.conda.PyCondaSdkCustomizer import com.jetbrains.python.sdk.createSdkByGenerateTask import com.jetbrains.python.sdk.flavors.CondaEnvSdkFlavor import icons.PythonIcons import org.jetbrains.annotations.SystemIndependent import java.awt.BorderLayout import javax.swing.Icon import javax.swing.JComboBox import javax.swing.event.DocumentEvent /** * @author vlan */ open class PyAddNewCondaEnvPanel( private val project: Project?, private val module: Module?, private val existingSdks: List<Sdk>, newProjectPath: String? ) : PyAddNewEnvPanel() { override val envName: String = "Conda" override val panelName: String get() = PyBundle.message("python.add.sdk.panel.name.new.environment") override val icon: Icon = PythonIcons.Python.Anaconda protected val languageLevelsField: JComboBox<String> protected val condaPathField = TextFieldWithBrowseButton().apply { val path = PyCondaPackageService.getCondaExecutable(null) path?.let { text = it } addBrowseFolderListener(PyBundle.message("python.sdk.select.conda.path.title"), null, project, FileChooserDescriptorFactory.createSingleFileOrExecutableAppDescriptor()) textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { updatePathField() } }) } protected val pathField = TextFieldWithBrowseButton().apply { addBrowseFolderListener(PyBundle.message("python.sdk.select.location.for.conda.title"), null, project, FileChooserDescriptorFactory.createSingleFolderDescriptor()) } private val makeSharedField = JBCheckBox(PyBundle.message("available.to.all.projects")) override var newProjectPath: String? = newProjectPath set(value) { field = value updatePathField() } init { layout = BorderLayout() val supportedLanguageLevels = LanguageLevel.SUPPORTED_LEVELS .asReversed() .filter { it < LanguageLevel.PYTHON310 } .map { it.toPythonVersion() } languageLevelsField = ComboBox(supportedLanguageLevels.toTypedArray()).apply { selectedItem = if (itemCount > 0) getItemAt(0) else null } if (PyCondaSdkCustomizer.instance.sharedEnvironmentsByDefault) { makeSharedField.isSelected = true } updatePathField() @Suppress("LeakingThis") layoutComponents() } protected open fun layoutComponents() { layout = BorderLayout() val formPanel = FormBuilder.createFormBuilder() .addLabeledComponent(PyBundle.message("sdk.create.venv.conda.dialog.label.location"), pathField) .addLabeledComponent(PyBundle.message("sdk.create.venv.conda.dialog.label.python.version"), languageLevelsField) .addLabeledComponent(PyBundle.message("python.sdk.conda.path"), condaPathField) .addComponent(makeSharedField) .panel add(formPanel, BorderLayout.NORTH) } override fun validateAll(): List<ValidationInfo> = listOfNotNull(CondaEnvSdkFlavor.validateCondaPath(condaPathField.text), validateEnvironmentDirectoryLocation(pathField)) override fun getOrCreateSdk(): Sdk? { val condaPath = condaPathField.text val task = object : Task.WithResult<String, ExecutionException>(project, PyBundle.message("python.sdk.creating.conda.environment.title"), false) { override fun compute(indicator: ProgressIndicator): String { indicator.isIndeterminate = true return PyCondaPackageManagerImpl.createVirtualEnv(condaPath, pathField.text, selectedLanguageLevel) } } val shared = makeSharedField.isSelected val associatedPath = if (!shared) projectBasePath else null val sdk = createSdkByGenerateTask(task, existingSdks, null, associatedPath, null) ?: return null if (!shared) { sdk.associateWithModule(module, newProjectPath) } PyCondaPackageService.onCondaEnvCreated(condaPath) return sdk } override fun addChangeListener(listener: Runnable) { val documentListener = object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { listener.run() } } pathField.textField.document.addDocumentListener(documentListener) condaPathField.textField.document.addDocumentListener(documentListener) } private fun updatePathField() { val baseDir = defaultBaseDir ?: "${SystemProperties.getUserHome()}/.conda/envs" val dirName = PathUtil.getFileName(projectBasePath ?: "untitled") pathField.text = FileUtil.toSystemDependentName("$baseDir/$dirName") } private val defaultBaseDir: String? get() { val conda = condaPathField.text val condaFile = LocalFileSystem.getInstance().findFileByPath(conda) ?: return null return condaFile.parent?.parent?.findChild("envs")?.path } private val projectBasePath: @SystemIndependent String? get() = newProjectPath ?: module?.basePath ?: project?.basePath private val selectedLanguageLevel: String get() = languageLevelsField.getItemAt(languageLevelsField.selectedIndex) }
apache-2.0
spring-projects/spring-framework
spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/client/ClientResponseExtensionsTests.kt
1
5122
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.web.reactive.function.client import io.mockk.every import io.mockk.mockk import io.mockk.verify import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import reactor.core.publisher.Mono /** * Mock object based tests for [ClientResponse] Kotlin extensions. * * @author Sebastien Deleuze * @author Igor Manushin */ class ClientResponseExtensionsTests { private val response = mockk<ClientResponse>(relaxed = true) @Test fun `bodyToMono with reified type parameters`() { response.bodyToMono<List<Foo>>() verify { response.bodyToMono(object : ParameterizedTypeReference<List<Foo>>() {}) } } @Test fun `bodyToFlux with reified type parameters`() { response.bodyToFlux<List<Foo>>() verify { response.bodyToFlux(object : ParameterizedTypeReference<List<Foo>>() {}) } } @Test fun `bodyToFlow with reified type parameters`() { response.bodyToFlow<List<Foo>>() verify { response.bodyToFlux(object : ParameterizedTypeReference<List<Foo>>() {}) } } @Test fun `bodyToFlow with KClass parameter`() { response.bodyToFlow(Foo::class) verify { response.bodyToFlux(Foo::class.java) } } @Test fun `toEntity with reified type parameters`() { response.toEntity<List<Foo>>() verify { response.toEntity(object : ParameterizedTypeReference<List<Foo>>() {}) } } @Test fun `ResponseSpec#toEntityList with reified type parameters`() { response.toEntityList<List<Foo>>() verify { response.toEntityList(object : ParameterizedTypeReference<List<Foo>>() {}) } } @Test fun awaitBody() { val response = mockk<ClientResponse>() every { response.bodyToMono<String>() } returns Mono.just("foo") runBlocking { assertThat(response.awaitBody<String>()).isEqualTo("foo") } } @Test fun `awaitBody with KClass parameter`() { val response = mockk<ClientResponse>() every { response.bodyToMono(String::class.java) } returns Mono.just("foo") runBlocking { assertThat(response.awaitBody(String::class)).isEqualTo("foo") } } @Test fun awaitBodyOrNull() { val response = mockk<ClientResponse>() every { response.bodyToMono<String>() } returns Mono.empty() runBlocking { assertThat(response.awaitBodyOrNull<String>()).isNull() } } @Test fun `awaitBodyOrNullGeneric with KClass parameter`() { val response = mockk<ClientResponse>() every { response.bodyToMono(String::class.java) } returns Mono.empty() runBlocking { assertThat(response.awaitBodyOrNull(String::class)).isNull() } } @Test fun awaitEntity() { val response = mockk<ClientResponse>() val entity = ResponseEntity("foo", HttpStatus.OK) every { response.toEntity<String>() } returns Mono.just(entity) runBlocking { assertThat(response.awaitEntity<String>()).isEqualTo(entity) } } @Test fun `awaitEntity with KClass parameter`() { val response = mockk<ClientResponse>() val entity = ResponseEntity("foo", HttpStatus.OK) every { response.toEntity(String::class.java) } returns Mono.just(entity) runBlocking { assertThat(response.awaitEntity(String::class)).isEqualTo(entity) } } @Test fun awaitEntityList() { val response = mockk<ClientResponse>() val entity = ResponseEntity(listOf("foo"), HttpStatus.OK) every { response.toEntityList<String>() } returns Mono.just(entity) runBlocking { assertThat(response.awaitEntityList<String>()).isEqualTo(entity) } } @Test fun `awaitEntityList with KClass parameter`() { val response = mockk<ClientResponse>() val entity = ResponseEntity(listOf("foo"), HttpStatus.OK) every { response.toEntityList(String::class.java) } returns Mono.just(entity) runBlocking { assertThat(response.awaitEntityList(String::class)).isEqualTo(entity) } } @Test fun awaitBodilessEntity() { val response = mockk<ClientResponse>() val entity = mockk<ResponseEntity<Void>>() every { response.toBodilessEntity() } returns Mono.just(entity) runBlocking { assertThat(response.awaitBodilessEntity()).isEqualTo(entity) } } @Test fun createExceptionAndAwait() { val response = mockk<ClientResponse>() val exception = mockk<WebClientResponseException>() every { response.createException() } returns Mono.just(exception) runBlocking { assertThat(response.createExceptionAndAwait()).isEqualTo(exception) } } class Foo }
apache-2.0
grover-ws-1/http4k
http4k-testing-hamkrest/src/main/kotlin/org/http4k/hamkrest/response.kt
1
643
package org.http4k.hamkrest import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.has import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.cookie.Cookie import org.http4k.core.cookie.cookies fun hasStatus(expected: Status): Matcher<Response> = has(Response::status, equalTo(expected)) fun hasSetCookie(expected: Cookie): Matcher<Response> = hasSetCookie(expected.name, equalTo(expected)) fun hasSetCookie(name: String, expected: Matcher<Cookie>): Matcher<Response> = has("Cookie '$name'", { r: Response -> r.cookies().find { name == it.name }!! }, expected)
apache-2.0
kevindmoore/tasker
taskerlibrary/src/main/java/com/mastertechsoftware/tasker/Tasks.kt
1
814
package com.mastertechsoftware.tasker /** * Kotlin helper functions */ class KotlinTask(var runFunc : ((task: KotlinTask) -> Any?)) : DefaultTask<Any>() { override fun run(): Any? { return runFunc(this) } } class KotlinCondition(val condFun : () -> Boolean) : Condition { override fun shouldExecute(): Boolean { return condFun() } } /** * Extension to pass in a function instead of an object */ fun Tasker.addTask(runFunc: (task: KotlinTask) -> Any?) : Tasker { this.addTask(KotlinTask(runFunc)) return this } fun Tasker.addUITask(runFunc: (task: KotlinTask) -> Any?) : Tasker { this.addUITask(KotlinTask(runFunc)) return this } fun Tasker.withCondition(condFun: () -> Boolean) : Tasker { this.withCondition(KotlinCondition(condFun)) return this }
apache-2.0
zdary/intellij-community
xml/xml-psi-impl/src/com/intellij/html/embedding/HtmlTokenEmbeddedContentProvider.kt
12
1520
// 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.html.embedding import com.intellij.lexer.BaseHtmlLexer import com.intellij.lexer.Lexer import com.intellij.openapi.util.TextRange import com.intellij.psi.tree.IElementType import java.util.function.Supplier open class HtmlTokenEmbeddedContentProvider @JvmOverloads constructor(lexer: BaseHtmlLexer, private val token: IElementType, highlightingLexerSupplier: Supplier<Lexer?>, elementTypeOverrideSupplier: Supplier<IElementType?> = Supplier { token }) : BaseHtmlEmbeddedContentProvider(lexer) { private val info = object : HtmlEmbedmentInfo { override fun getElementType(): IElementType? = elementTypeOverrideSupplier.get() override fun createHighlightingLexer(): Lexer? = highlightingLexerSupplier.get() } override fun isStartOfEmbedment(tokenType: IElementType): Boolean = tokenType == this.token override fun createEmbedmentInfo(): HtmlEmbedmentInfo? = info override fun findTheEndOfEmbedment(): Pair<Int, Int> { val baseLexer = lexer.delegate val position = baseLexer.currentPosition baseLexer.advance() val result = Pair(baseLexer.tokenStart, baseLexer.state) baseLexer.restore(position) return result } override fun handleToken(tokenType: IElementType, range: TextRange) { embedment = tokenType == this.token } }
apache-2.0
code-helix/slatekit
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/conf/Config.kt
1
6469
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.common.conf import slatekit.common.* import slatekit.common.crypto.Encryptor //import java.time.* import org.threeten.bp.* import slatekit.common.convert.Conversions import slatekit.common.ext.decrypt import slatekit.common.ext.getEnv import slatekit.common.io.Uri import java.util.* /** * Conf is a wrapper around the typesafe config with additional support for: * 1. RESOURCES Use a prefix for indicating where to load config from. - "jars://" for the resources directory in the jar. - "user://" for the user.home directory. - "file://" for an explicit path to the file - "file://" for relative path to the file from working directory Examples: - jar://env.qa.conf - user://${company.dir}/${group.dir}/${app.id}/conf/env.qa.conf - file://c:/slatekit/${company.dir}/${group.dir}/${app.id}/conf/env.qa.conf - file://./conf/env.qa.conf 2. LOADING Use a short-hand syntax for specifying the files to merge and fallback with Examples: - primary - primary, fallback1 - primary, fallback1, fallback2 3. FUNCTIONS: Use functions in the config to resolve values dynamically. You can use the resolveString method to resolve the value dynamically. Note: This uses the slatekit.common.subs component. Examples: ( props inside your .conf file ) - tag : "@{today.yyyymmdd-hhmmss}" 4. DEFAULTS: Use optional default values for getting strings, int, doubles, bools. Examples: - getStringOrElse - getIntOrElse - getBoolOrElse - getDoubleOrElse - getDateOrElse 5. MAPPING Map slatekit objects automatically from the conf settings. Built in mappers for the Examples: - "env" : Environment selection ( dev, qa, stg, prod ) etc. - "login" : slatekit.common.Credentials object - "db" : database connection strings - "api" : standardized api keys * * @param fileName * @param enc * @param props */ class Config( cls: Class<*>, uri:Uri, val config: Properties, val enc: Encryptor? = null ) : Conf(cls, uri, { raw -> enc?.decrypt(raw) ?: raw }) { /** * Get or load the config object */ override val raw: Any = config override fun get(key: String): Any? = getInternal(key) override fun containsKey(key: String): Boolean = config.containsKey(key) override fun size(): Int = config.values.size override fun getString(key: String): String = interpret(key) override fun getBool(key: String): Boolean = Conversions.toBool(getStringRaw(key)) override fun getShort(key: String): Short = Conversions.toShort(getStringRaw(key)) override fun getInt(key: String): Int = Conversions.toInt(getStringRaw(key)) override fun getLong(key: String): Long = Conversions.toLong(getStringRaw(key)) override fun getFloat(key: String): Float = Conversions.toFloat(getStringRaw(key)) override fun getDouble(key: String): Double = Conversions.toDouble(getStringRaw(key)) override fun getInstant(key: String): Instant = Conversions.toInstant(getStringRaw(key)) override fun getDateTime(key: String): DateTime = Conversions.toDateTime(getStringRaw(key)) override fun getLocalDate(key: String): LocalDate = Conversions.toLocalDate(getStringRaw(key)) override fun getLocalTime(key: String): LocalTime = Conversions.toLocalTime(getStringRaw(key)) override fun getLocalDateTime(key: String): LocalDateTime = Conversions.toLocalDateTime(getStringRaw(key)) override fun getZonedDateTime(key: String): ZonedDateTime = Conversions.toZonedDateTime(getStringRaw(key)) override fun getZonedDateTimeUtc(key: String): ZonedDateTime = Conversions.toZonedDateTimeUtc(getStringRaw(key)) /** * Loads config from the file path supplied * * @param file * @return */ override fun loadFrom(file: String?): Conf? = Confs.load(cls, file, enc) /** * Extends the config by supporting decryption via marker tags. * e.g. * db.connection = "@{decrypt('8r4AbhQyvlzSeWnKsamowA')}" * db.connection = "@{env('APP1_DB_URL')}" * * @param key : key: The name of the config key * @return */ private fun interpret(key: String): String { val raw = getStringRaw(key) val value = if(raw.startsWith("@{env")) { raw.getEnv() } else if(raw.startsWith("@{decrypt")) { raw.decrypt(encryptor) } else { raw } return value } private fun getInternal(key: String): Any? { return if (containsKey(key)) { val value = config.getProperty(key) if (value != null && value is String) { value.trim() } else { value } } else { null } } private fun getStringRaw(key: String): String = config.getProperty(key)?.trim() ?: "" companion object { operator fun invoke(cls:Class<*>):Config { val info = Props.fromPath(cls, "") return Config(cls, info.first, info.second) } fun of(cls:Class<*>, configPath: String, enc: Encryptor? = null):Config { val info = Props.fromPath(cls, configPath) val conf = Config(cls, info.first, info.second, enc) return conf } fun of(cls:Class<*>, configPath: String, configParentPath: String, enc: Encryptor?):ConfigMulti { val parentInfo = Props.fromPath(cls, configParentPath) val parentConf = Config(cls, parentInfo.first, parentInfo.second, enc) val inheritInfo = Props.fromPath(cls, configPath) val inheritConf = Config(cls, inheritInfo.first, inheritInfo.second, enc) val conf = ConfigMulti(cls, inheritConf, parentConf, inheritInfo.first, enc) return conf } fun of(cls:Class<*>, configSource: Uri, configParent: Conf, enc: Encryptor?) :ConfigMulti { val inheritProps = Props.fromUri(cls, configSource) val inheritConf = Config(cls, configSource, inheritProps, enc) val conf = ConfigMulti(cls, inheritConf, configParent, configSource, enc) return conf } } }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/defaultArguments/function/extensionFunctionManyArgs.kt
5
6972
fun Int.foo(a: Int = 1, b: Int = 2, c: Int = 3, d: Int = 4, e: Int = 5, f: Int = 6, g: Int = 7, h: Int = 8, i: Int = 9, j: Int = 10, k: Int = 11, l: Int = 12, m: Int = 13, n: Int = 14, o: Int = 15, p: Int = 16, q: Int = 17, r: Int = 18, s: Int = 19, t: Int = 20, u: Int = 21, v: Int = 22, w: Int = 23, x: Int = 24, y: Int = 25, z: Int = 26, aa: Int = 27, bb: Int = 28, cc: Int = 29, dd: Int = 30, ee: Int = 31, ff: Int = 32): String { return "$a $b $c $d $e $f $g $h $i $j $k $l $m $n $o $p $q $r $s $t $u $v $w $x $y $z $aa $bb $cc $dd $ee $ff" } fun String.bar(a: Int = 1, b: Int = 2, c: Int = 3, d: Int = 4, e: Int = 5, f: Int = 6, g: Int = 7, h: Int = 8, i: Int = 9, j: Int = 10, k: Int = 11, l: Int = 12, m: Int = 13, n: Int = 14, o: Int = 15, p: Int = 16, q: Int = 17, r: Int = 18, s: Int = 19, t: Int = 20, u: Int = 21, v: Int = 22, w: Int = 23, x: Int = 24, y: Int = 25, z: Int = 26, aa: Int = 27, bb: Int = 28, cc: Int = 29, dd: Int = 30, ee: Int = 31, ff: Int = 32, gg: Int = 33, hh: Int = 34, ii: Int = 35, jj: Int = 36, kk: Int = 37, ll: Int = 38, mm: Int = 39, nn: Int = 40): String { return "$a $b $c $d $e $f $g $h $i $j $k $l $m $n $o $p $q $r $s $t $u $v $w $x $y $z $aa $bb $cc $dd $ee $ff " + "$gg $hh $ii $jj $kk $ll $mm $nn" } fun Char.baz(a: Int = 1, b: Int = 2, c: Int = 3, d: Int = 4, e: Int = 5, f: Int = 6, g: Int = 7, h: Int = 8, i: Int = 9, j: Int = 10, k: Int = 11, l: Int = 12, m: Int = 13, n: Int = 14, o: Int = 15, p: Int = 16, q: Int = 17, r: Int = 18, s: Int = 19, t: Int = 20, u: Int = 21, v: Int = 22, w: Int = 23, x: Int = 24, y: Int = 25, z: Int = 26, aa: Int = 27, bb: Int = 28, cc: Int = 29, dd: Int = 30, ee: Int = 31, ff: Int = 32, gg: Int = 33, hh: Int = 34, ii: Int = 35, jj: Int = 36, kk: Int = 37, ll: Int = 38, mm: Int = 39, nn: Int = 40, oo: Int = 41, pp: Int = 42, qq: Int = 43, rr: Int = 44, ss: Int = 45, tt: Int = 46, uu: Int = 47, vv: Int = 48, ww: Int = 49, xx: Int = 50, yy: Int = 51, zz: Int = 52, aaa: Int = 53, bbb: Int = 54, ccc: Int = 55, ddd: Int = 56, eee: Int = 57, fff: Int = 58, ggg: Int = 59, hhh: Int = 60, iii: Int = 61, jjj: Int = 62, kkk: Int = 63, lll: Int = 64, mmm: Int = 65, nnn: Int = 66, ooo: Int = 67, ppp: Int = 68, qqq: Int = 69, rrr: Int = 70): String { return "$a $b $c $d $e $f $g $h $i $j $k $l $m $n $o $p $q $r $s $t $u $v $w $x $y $z $aa $bb $cc $dd $ee $ff $gg $hh $ii $jj $kk " + "$ll $mm $nn $oo $pp $qq $rr $ss $tt $uu $vv $ww $xx $yy $zz $aaa $bbb $ccc $ddd $eee $fff $ggg $hhh $iii $jjj $kkk $lll " + "$mmm $nnn $ooo $ppp $qqq $rrr" } fun box(): String { val test1 = 1.foo(4, e = 8, f = 15, w = 16, aa = 23, ff = 42) val test2 = 1.foo() val test3 = 1.foo(32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, q = 16, r = 15, s = 14, t = 13, u = 12, v = 11, w = 10, x = 9, y = 8, z = 7, aa = 6, bb = 5, cc = 4, dd = 3, ee = 2, ff = 1) if (test1 != "4 2 3 4 8 15 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 16 24 25 26 23 28 29 30 31 42") { return "test1 = $test1" } if (test2 != "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32") { return "test2 = $test2" } if (test3 != "32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1") { return "test3 = $test3" } val test4 = "".bar(54, 217, h = 236, l = 18, q = 3216, u = 8, aa = 22, ff = 33, jj = 44, mm = 55) val test5 = "".bar() val test6 = "".bar(40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, u = 20, v = 19, w = 18, x = 17, y = 16, z = 15, aa = 14, bb = 13, cc = 12, dd = 11, ee = 10, ff = 9, gg = 8, hh = 7, ii = 6, jj = 5, kk = 4, ll = 3, mm = 2, nn = 1) if (test4 != "54 217 3 4 5 6 7 236 9 10 11 18 13 14 15 16 3216 18 19 20 8 22 23 24 25 26 22 28 29 30 31 33 33 34 35 44 37 38 55 40") { return "test4 = $test4" } if (test5 != "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40") { return "test5 = $test5" } if (test6 != "40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1") { return "test6 = $test6" } val test7 = 'a'.baz(5, f = 3, w = 1, aa = 71, nn = 2, qq = 15, ww = 97, aaa = 261258, iii = 3, nnn = 8, rrr = 7) val test8 = 'a'.baz() val test9 = 'a'.baz(70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, jj = 35, kk = 34, ll = 33, mm = 32, nn = 31, oo = 30, pp = 29, qq = 28, rr = 27, ss = 26, tt = 25, uu = 24, vv = 23, ww = 22, xx = 21, yy = 20, zz = 19, aaa = 18, bbb = 17, ccc = 16, ddd = 15, eee = 14, fff = 13, ggg = 12, hhh = 11, iii = 10, jjj = 9, kkk = 8, lll = 7, mmm = 6, nnn = 5, ooo = 4, ppp = 3, qqq = 2, rrr = 1) if (test7 != "5 2 3 4 5 3 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1 24 25 26 71 28 29 30 31 32 33 34 35 36 37 38 39 2 41 42 15 " + "44 45 46 47 48 97 50 51 52 261258 54 55 56 57 58 59 60 3 62 63 64 65 8 67 68 69 7") { return "test7 = $test7" } if (test8 != "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 " + "43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70") { return "test8 = $test8" } if (test9 != "70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 " + "31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1") { return "test9 = $test9" } return "OK" }
apache-2.0
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/inventory/SyncProviderLevel.kt
1
525
package net.ndrei.teslacorelib.inventory enum class SyncProviderLevel(private val syncWhenGuiOpened: Boolean, private val syncToClient: Boolean, private val store: Boolean) { TICK(true, true, true), GUI(true, false, true), SERVER_ONLY(false, false, true), GUI_ONLY(true, false, false), TICK_ONLY(false, true, false); fun shouldSync(hasGui: Boolean, isSyncing: Boolean, isSaving: Boolean) = (this.syncWhenGuiOpened && hasGui) || (this.syncToClient && isSyncing) || (this.store && isSaving) }
mit
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/suspendFunctionAsCoroutine/privateFunctions.kt
2
816
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* class X { var res = "" suspend fun execute() { a() b() } private suspend fun a() { res += suspendThere("O") res += suspendThere("K") } private suspend fun b() { res += suspendThere("5") res += suspendThere("6") } } suspend fun suspendThere(v: String): String = suspendCoroutineOrReturn { x -> x.resume(v) COROUTINE_SUSPENDED } fun builder(c: suspend X.() -> Unit) { c.startCoroutine(X(), EmptyContinuation) } fun box(): String { var result = "" builder { execute() result = res } if (result != "OK56") return "fail 1: $result" return "OK" }
apache-2.0
InventiDevelopment/AndroidSkeleton
app/src/main/java/cz/inventi/inventiskeleton/presentation/post/detail/PostDetailView.kt
1
464
package cz.inventi.inventiskeleton.presentation.post.detail import cz.inventi.inventiskeleton.data.comment.Comment import cz.inventi.inventiskeleton.data.post.Post import cz.inventi.inventiskeleton.presentation.common.BaseView /** * Created by ecnill on 6/7/2017. */ interface PostDetailView : BaseView { fun showDetailPost(post: Post) fun showProfilePicture(url: String) fun showComments(comments: List<Comment>) fun hideMoreCommentButton() }
apache-2.0
Pozo/threejs-kotlin
threejs/src/main/kotlin/three/helpers/GridHelper.kt
1
355
@file:JsQualifier("THREE") package three.helpers import three.objects.Line @JsName("GridHelper") external class GridHelper : Line { constructor(size: Int) constructor(size: Int, divisions: Int) constructor(size: Int, divisions: Int, colorCenterLine: Int) constructor(size: Int, divisions: Int, colorCenterLine: Int, colorGrid: Int) }
mit
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/ranges/contains/inPrimitiveProgression.kt
1
162
// WITH_RUNTIME val progression = 1 .. 3 step 2 fun box(): String = when { 0 in progression -> "fail 1" 1 !in progression -> "fail 2" else -> "OK" }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/bridges/fakeOverrideWithSeveralSuperDeclarations.kt
5
477
interface D1 { fun foo(): Any } interface D2 { fun foo(): Number } interface F3 : D1, D2 open class D4 { fun foo(): Int = 42 } class F5 : F3, D4() fun box(): String { val z = F5() var result = z.foo() val d4: D4 = z val f3: F3 = z val d2: D2 = z val d1: D1 = z result += d4.foo() result += f3.foo() as Int result += d2.foo() as Int result += d1.foo() as Int return if (result == 5 * 42) "OK" else "Fail: $result" }
apache-2.0
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/webview/events/TopLoadingStartEvent.kt
2
771
package abi44_0_0.host.exp.exponent.modules.api.components.webview.events import abi44_0_0.com.facebook.react.bridge.WritableMap import abi44_0_0.com.facebook.react.uimanager.events.Event import abi44_0_0.com.facebook.react.uimanager.events.RCTEventEmitter /** * Event emitted when loading has started */ class TopLoadingStartEvent(viewId: Int, private val mEventData: WritableMap) : Event<TopLoadingStartEvent>(viewId) { companion object { const val EVENT_NAME = "topLoadingStart" } override fun getEventName(): String = EVENT_NAME override fun canCoalesce(): Boolean = false override fun getCoalescingKey(): Short = 0 override fun dispatch(rctEventEmitter: RCTEventEmitter) = rctEventEmitter.receiveEvent(viewTag, eventName, mEventData) }
bsd-3-clause
AndroidX/androidx
work/work-runtime/src/main/java/androidx/work/impl/WorkDatabasePathHelper.kt
3
4325
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work.impl import android.content.Context import android.os.Build import androidx.annotation.DoNotInline import androidx.annotation.RequiresApi import androidx.annotation.RestrictTo import androidx.work.Logger import java.io.File private val TAG = Logger.tagWithPrefix("WrkDbPathHelper") /** * @return The name of the database. */ internal const val WORK_DATABASE_NAME = "androidx.work.workdb" // Supporting files for a SQLite database private val DATABASE_EXTRA_FILES = arrayOf("-journal", "-shm", "-wal") /** * Keeps track of {@link WorkDatabase} paths. * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) object WorkDatabasePathHelper { /** * Migrates [WorkDatabase] to the no-backup directory. * * @param context The application context. */ @JvmStatic fun migrateDatabase(context: Context) { val defaultDatabasePath = getDefaultDatabasePath(context) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && defaultDatabasePath.exists()) { Logger.get().debug(TAG, "Migrating WorkDatabase to the no-backup directory") migrationPaths(context).forEach { (source, destination) -> if (source.exists()) { if (destination.exists()) { Logger.get().warning(TAG, "Over-writing contents of $destination") } val renamed = source.renameTo(destination) val message = if (renamed) { "Migrated ${source}to $destination" } else { "Renaming $source to $destination failed" } Logger.get().debug(TAG, message) } } } } /** * Returns a [Map] of all paths which need to be migrated to the no-backup directory. * * @param context The application [Context] * @return a [Map] of paths to be migrated from source -> destination */ fun migrationPaths(context: Context): Map<File, File> { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val databasePath = getDefaultDatabasePath(context) val migratedPath = getDatabasePath(context) val map = DATABASE_EXTRA_FILES.associate { extra -> File(databasePath.path + extra) to File(migratedPath.path + extra) } map + (databasePath to migratedPath) } else emptyMap() } /** * @param context The application [Context] * @return The database path before migration to the no-backup directory. */ fun getDefaultDatabasePath(context: Context): File { return context.getDatabasePath(WORK_DATABASE_NAME) } /** * @param context The application [Context] * @return The the migrated database path. */ fun getDatabasePath(context: Context): File { return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // No notion of a backup directory exists. getDefaultDatabasePath(context) } else { getNoBackupPath(context) } } /** * Return the path for a [File] path in the [Context.getNoBackupFilesDir] * identified by the [String] fragment. * * @param context The application [Context] * @return the [File] */ @RequiresApi(23) private fun getNoBackupPath(context: Context): File { return File(Api21Impl.getNoBackupFilesDir(context), WORK_DATABASE_NAME) } } @RequiresApi(21) internal object Api21Impl { @DoNotInline fun getNoBackupFilesDir(context: Context): File { return context.noBackupFilesDir } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/rename/automaticRenamerParameterInExtension/after/main.kt
12
327
package testing interface Trait { open fun Int.foo(a: Int, b: String) { } } open class Super { open fun Int.foo(a: Int, b: String) { } } open class Middle : Super(), Trait { override fun Int.foo(aa: Int, b: String) { } } class Sub : Middle() { override fun Int.foo(aa: Int, b: String) { } }
apache-2.0
smmribeiro/intellij-community
plugins/editorconfig/src/org/editorconfig/language/codeinsight/quickfixes/EditorConfigConvertToPlainPatternQuickFix.kt
12
1501
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.codeinsight.quickfixes import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.codeStyle.CodeStyleManager import org.editorconfig.language.messages.EditorConfigBundle import org.editorconfig.language.psi.EditorConfigCharClass import org.editorconfig.language.services.EditorConfigElementFactory class EditorConfigConvertToPlainPatternQuickFix : LocalQuickFix { override fun getFamilyName() = EditorConfigBundle.get("quickfix.charclass.convert.to.plain.pattern.description") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val charClass = descriptor.psiElement as? EditorConfigCharClass ?: return val header = charClass.header val letter = charClass.charClassLetterList.first() val headerOffset = header.textOffset val range = charClass.textRange val actualRange = range.startOffset - headerOffset until range.endOffset - headerOffset val text = header.text val newText = text.replaceRange(actualRange, letter.text) val factory = EditorConfigElementFactory.getInstance(project) val newHeader = factory.createHeader(newText) CodeStyleManager.getInstance(project).performActionWithFormatterDisabled { header.replace(newHeader) } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/fromCompanion/isVariable/Main.kt
10
90
class Main { companion object { var isCompanion<caret>Variable = true } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/topLevel/extensionWithJvmOverloadsAndJvmName/WithoutAll.kt
10
78
fun test3() { with(true) { topLevelExtension("i", i3 = 42) } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/breadcrumbs/While.kt
13
190
fun foo() { while (true) { while (p) { while (x > 0) { do { <caret> } while (true) } } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/MoveConstructorsAfterFieldsConversion.kt
5
4850
// 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.nj2k.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.assignmentStatement import org.jetbrains.kotlin.nj2k.tree.* class MoveConstructorsAfterFieldsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClassBody) return recurse(element) if (element.declarations.none { it is JKInitDeclaration }) return recurse(element) moveInitBlocks(element, isStatic = false) moveInitBlocks(element, isStatic = true) return recurse(element) } private fun moveInitBlocks(element: JKClassBody, isStatic: Boolean) { val data = computeDeclarationsData(element, isStatic) element.declarations = collectNewDeclarations(element, data, isStatic) } private fun computeDeclarationsData( element: JKClassBody, isStatic: Boolean, ): DeclarationsData { val moveAfter = mutableMapOf<JKDeclaration, JKDeclaration>() val forwardlyReferencedFields = mutableSetOf<JKField>() val declarationsToAdd = mutableListOf<JKDeclaration>() val order = element.declarations.withIndex().associateTo(mutableMapOf()) { (index, value) -> value to index } for (declaration in element.declarations) { when { declaration is JKInitDeclaration && declaration.isStatic == isStatic -> { declarationsToAdd += declaration val fields = findAllUsagesOfFieldsIn(declaration, element) { it.hasOtherModifier(OtherModifier.STATIC) == isStatic } moveAfter[declaration] = declaration val lastDependentField = fields.maxByOrNull(order::getValue) ?: continue val initDeclarationIndex = order.getValue(declaration) if (order.getValue(lastDependentField) < initDeclarationIndex) continue moveAfter[declaration] = lastDependentField for (field in fields) { if (order.getValue(field) > initDeclarationIndex) { forwardlyReferencedFields += field } } } declaration is JKField && declaration.hasOtherModifier(OtherModifier.STATIC) == isStatic -> { if (declaration.initializer !is JKStubExpression && declaration in forwardlyReferencedFields) { val assignment = createFieldAssignmentInitDeclaration(declaration, isStatic) moveAfter[assignment] = declarationsToAdd.last() order[assignment] = order.getValue(declarationsToAdd.last()) declarationsToAdd += assignment } } } } return DeclarationsData(order, moveAfter, declarationsToAdd) } @OptIn(ExperimentalStdlibApi::class) private fun collectNewDeclarations( element: JKClassBody, data: DeclarationsData, isStatic: Boolean, ): List<JKDeclaration> { var index = 0 val newDeclarations = buildList { for (declaration in element.declarations) { if (declaration !is JKInitDeclaration || declaration.isStatic != isStatic) { add(declaration) } val declarationIndex = data.order.getValue(declaration) while (index <= data.declarationsToAdd.lastIndex) { val initDeclaration = data.declarationsToAdd[index] val moveAfterIndex = data.order.getValue(data.moveAfter.getValue(initDeclaration)) if (declarationIndex >= moveAfterIndex) { add(initDeclaration) index++ } else { break } } } } return newDeclarations } private data class DeclarationsData( val order: Map<JKDeclaration, Int>, val moveAfter: Map<JKDeclaration, JKDeclaration>, val declarationsToAdd: List<JKDeclaration>, ) private fun createFieldAssignmentInitDeclaration(field: JKField, isStatic: Boolean): JKInitDeclaration { val initializer = field.initializer field.initializer = JKStubExpression() val block = JKBlockImpl(assignmentStatement(field, initializer, symbolProvider)) return if (isStatic) JKJavaStaticInitDeclaration(block) else JKKtInitDeclaration(block) } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/implement/sealedWithConflictAfter15.kt
9
303
// "Implement sealed class" "true" // WITH_STDLIB // SHOULD_BE_AVAILABLE_AFTER_EXECUTION // COMPILER_ARGUMENTS: -XXLanguage:+SealedInterfaces sealed class <caret>Base { abstract fun foo(): Int class BaseImpl : Base() { override fun foo() = throw UnsupportedOperationException() } }
apache-2.0
mglukhikh/intellij-community
python/src/com/jetbrains/python/inspections/PyNamedTupleInspection.kt
1
4034
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import com.jetbrains.python.codeInsight.stdlib.PyStdlibTypeProvider import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyTargetExpression import com.jetbrains.python.psi.types.TypeEvalContext import java.util.* class PyNamedTupleInspection : PyInspection() { companion object { fun inspectFieldsOrder(cls: PyClass, context: TypeEvalContext, callback: (PsiElement, String, ProblemHighlightType) -> Unit) { val fieldsProcessor = FieldsProcessor(context) cls.processClassLevelDeclarations(fieldsProcessor) registerErrorOnTargetsAboveBound(fieldsProcessor.lastFieldWithoutDefaultValue, fieldsProcessor.fieldsWithDefaultValue, "Fields with a default value must come after any fields without a default.", callback) } private fun registerErrorOnTargetsAboveBound(bound: PyTargetExpression?, targets: TreeSet<PyTargetExpression>, message: String, callback: (PsiElement, String, ProblemHighlightType) -> Unit) { if (bound != null) { targets .headSet(bound) .forEach { callback(it, message, ProblemHighlightType.GENERIC_ERROR) } } } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session) private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) { override fun visitPyClass(node: PyClass?) { super.visitPyClass(node) if (node != null && LanguageLevel.forElement(node).isAtLeast(LanguageLevel.PYTHON36) && PyStdlibTypeProvider.isTypingNamedTupleDirectInheritor(node, myTypeEvalContext)) { inspectFieldsOrder(node, myTypeEvalContext, this::registerProblem) } } } private class FieldsProcessor(private val context: TypeEvalContext) : PsiScopeProcessor { val lastFieldWithoutDefaultValue: PyTargetExpression? get() = lastFieldWithoutDefaultValueBox.result val fieldsWithDefaultValue: TreeSet<PyTargetExpression> private val lastFieldWithoutDefaultValueBox: MaxBy<PyTargetExpression> init { val offsetComparator = compareBy(PyTargetExpression::getTextOffset) lastFieldWithoutDefaultValueBox = MaxBy(offsetComparator) fieldsWithDefaultValue = TreeSet(offsetComparator) } override fun execute(element: PsiElement, state: ResolveState): Boolean { if (element is PyTargetExpression) { val annotation = element.annotation if (annotation != null && PyTypingTypeProvider.isClassVarAnnotation(annotation, context)) { return true } when { element.findAssignedValue() != null -> fieldsWithDefaultValue.add(element) else -> lastFieldWithoutDefaultValueBox.apply(element) } } return true } } private class MaxBy<T>(private val comparator: Comparator<T>) { var result: T? = null private set fun apply(t: T) { if (result == null || comparator.compare(result, t) < 0) { result = t } } } }
apache-2.0
google/intellij-community
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/ReplaceBySourceTest.kt
1
53826
// 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.workspaceModel.storage import com.intellij.testFramework.UsefulTestCase.assertEmpty import com.intellij.testFramework.UsefulTestCase.assertOneElement import com.intellij.workspaceModel.storage.entities.test.addSampleEntity import com.intellij.workspaceModel.storage.entities.test.api.* import com.intellij.workspaceModel.storage.impl.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.RepeatedTest import org.junit.jupiter.api.RepetitionInfo import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class ReplaceBySourceTest { private lateinit var builder: MutableEntityStorageImpl private lateinit var replacement: MutableEntityStorageImpl @BeforeEach fun setUp(info: RepetitionInfo) { builder = createEmptyBuilder() replacement = createEmptyBuilder() builder.useNewRbs = true builder.keepLastRbsEngine = true builder.upgradeEngine = { (it as ReplaceBySourceAsTree).shuffleEntities = info.currentRepetition.toLong() } } @RepeatedTest(10) fun `add entity`() { builder add NamedEntity("hello2", SampleEntitySource("2")) replacement = createEmptyBuilder() replacement add NamedEntity("hello1", SampleEntitySource("1")) builder.replaceBySource({ it == SampleEntitySource("1") }, replacement) assertEquals(setOf("hello1", "hello2"), builder.entities(NamedEntity::class.java).mapTo(HashSet()) { it.myName }) builder.assertConsistency() } @RepeatedTest(10) fun `remove entity`() { val source1 = SampleEntitySource("1") builder add NamedEntity("hello1", source1) builder add NamedEntity("hello2", SampleEntitySource("2")) builder.replaceBySource({ it == source1 }, createEmptyBuilder()) assertEquals("hello2", builder.entities(NamedEntity::class.java).single().myName) builder.assertConsistency() } @RepeatedTest(10) fun `remove and add entity`() { val source1 = SampleEntitySource("1") builder add NamedEntity("hello1", source1) builder add NamedEntity("hello2", SampleEntitySource("2")) replacement = createEmptyBuilder() replacement add NamedEntity("updated", source1) builder.replaceBySource({ it == source1 }, replacement) assertEquals(setOf("hello2", "updated"), builder.entities(NamedEntity::class.java).mapTo(HashSet()) { it.myName }) builder.assertConsistency() } @RepeatedTest(10) fun `multiple sources`() { val sourceA1 = SampleEntitySource("a1") val sourceA2 = SampleEntitySource("a2") val sourceB = SampleEntitySource("b") val parent1 = builder add NamedEntity("a", sourceA1) builder add NamedEntity("b", sourceB) replacement = createEmptyBuilder() val parent3 = replacement add NamedEntity("new", sourceA2) builder.replaceBySource({ it is SampleEntitySource && it.name.startsWith("a") }, replacement) assertEquals(setOf("b", "new"), builder.entities(NamedEntity::class.java).mapTo(HashSet()) { it.myName }) builder.assertConsistency() thisStateCheck { parent1 assert ReplaceState.Remove } replaceWithCheck { parent3 assert ReplaceWithState.ElementMoved } } @RepeatedTest(10) fun `work with different entity sources`() { val sourceA1 = SampleEntitySource("a1") val sourceA2 = SampleEntitySource("a2") val parentEntity = builder add NamedEntity("hello", sourceA1) replacement = createBuilderFrom(builder) replacement add NamedChildEntity("child", sourceA2) { this.parentEntity = parentEntity } builder.replaceBySource({ it == sourceA2 }, replacement) assertEquals(1, builder.toSnapshot().entities(NamedEntity::class.java).toList().size) assertEquals(1, builder.toSnapshot().entities(NamedChildEntity::class.java).toList().size) assertEquals("child", builder.toSnapshot().entities(NamedEntity::class.java).single().children.single().childProperty) builder.assertConsistency() } @RepeatedTest(10) fun `empty storages`() { val builder2 = createEmptyBuilder() builder.replaceBySource({ true }, builder2) assertTrue(builder.collectChanges(createEmptyBuilder()).isEmpty()) builder.assertConsistency() } @RepeatedTest(10) fun `replace with empty storage`() { val parent1 = builder add NamedEntity("data1", MySource) val parent2 = builder add NamedEntity("data2", MySource) resetChanges() val originalStorage = builder.toSnapshot() builder.replaceBySource({ true }, createEmptyBuilder()) val collectChanges = builder.collectChanges(originalStorage) assertEquals(1, collectChanges.size) assertEquals(2, collectChanges.values.single().size) assertTrue(collectChanges.values.single().all { it is EntityChange.Removed<*> }) builder.assertConsistency() assertNoNamedEntities() thisStateCheck { parent1 assert ReplaceState.Remove parent2 assert ReplaceState.Remove } } @RepeatedTest(10) fun `add entity with false source`() { builder add NamedEntity("hello2", SampleEntitySource("2")) resetChanges() replacement = createEmptyBuilder() replacement add NamedEntity("hello1", SampleEntitySource("1")) builder.replaceBySource({ false }, replacement) assertEquals(setOf("hello2"), builder.entities(NamedEntity::class.java).mapTo(HashSet()) { it.myName }) assertTrue(builder.collectChanges(createEmptyBuilder()).isEmpty()) builder.assertConsistency() } @RepeatedTest(10) fun `entity modification`() { val entity = builder add NamedEntity("hello2", MySource) replacement = createBuilderFrom(builder) val modified = replacement.modifyEntity(entity) { myName = "Hello Alex" } rbsAllSources() builder.assertConsistency() assertSingleNameEntity("Hello Alex") thisStateCheck { entity assert ReplaceState.Remove } replaceWithCheck { modified assert ReplaceWithState.ElementMoved } } @RepeatedTest(10) fun `adding entity in builder`() { replacement = createBuilderFrom(builder) replacement add NamedEntity("myEntity", MySource) rbsAllSources() assertEquals(setOf("myEntity"), builder.entities(NamedEntity::class.java).mapTo(HashSet()) { it.myName }) builder.assertConsistency() } @RepeatedTest(10) fun `removing entity in builder`() { val entity = builder add NamedEntity("myEntity", MySource) replacement = createBuilderFrom(builder) replacement.removeEntity(entity) rbsAllSources() builder.assertConsistency() assertNoNamedEntities() thisStateCheck { entity assert ReplaceState.Remove } } @RepeatedTest(10) fun `child and parent - modify parent`() { val parent = builder add NamedEntity("myProperty", MySource) builder add NamedChildEntity("myChild", MySource) { this.parentEntity = parent } replacement = createBuilderFrom(builder) replacement.modifyEntity(parent) { myName = "newProperty" } rbsAllSources() val child = assertOneElement(builder.entities(NamedChildEntity::class.java).toList()) assertEquals("newProperty", child.parentEntity.myName) assertOneElement(builder.entities(NamedEntity::class.java).toList()) builder.assertConsistency() } @RepeatedTest(10) fun `child and parent - modify child`() { val parent = builder add NamedEntity("myProperty", MySource) val child = builder add NamedChildEntity("myChild", MySource) { this.parentEntity = parent } replacement = createBuilderFrom(builder) replacement.modifyEntity(child) { childProperty = "newProperty" } rbsAllSources() val updatedChild = assertOneElement(builder.entities(NamedChildEntity::class.java).toList()) assertEquals("newProperty", updatedChild.childProperty) assertEquals(updatedChild, assertOneElement(builder.entities(NamedEntity::class.java).toList()).children.single()) builder.assertConsistency() } @RepeatedTest(10) fun `child and parent - remove parent`() { val parent = builder add NamedEntity("myProperty", MySource) { children = listOf(NamedChildEntity("myChild", MySource)) } replacement = createBuilderFrom(builder) replacement.removeEntity(parent) rbsAllSources() builder.assertConsistency() assertNoNamedEntities() assertNoNamedChildEntities() thisStateCheck { parent assert ReplaceState.Remove } } @RepeatedTest(10) fun `child and parent - change parent for child`() { val parent = builder add NamedEntity("myProperty", MySource) val parent2 = builder add NamedEntity("anotherProperty", MySource) val child = builder add NamedChildEntity("myChild", MySource) { this.parentEntity = parent } replacement = createBuilderFrom(builder) replacement.modifyEntity(child) { this.parentEntity = parent2 } rbsAllSources() builder.assertConsistency() val parents = builder.entities(NamedEntity::class.java).toList() assertTrue(parents.single { it.myName == "myProperty" }.children.none()) assertEquals(child.childProperty, parents.single { it.myName == "anotherProperty" }.children.single().childProperty) thisStateCheck { parent assert ReplaceState.Relabel(parent.base.id) parent2 assert ReplaceState.Relabel(parent2.base.id) child assert ReplaceState.Remove } replaceWithCheck { child assert ReplaceWithState.ElementMoved parent2 assert ReplaceWithState.Relabel(parent2.base.id) } } @RepeatedTest(10) fun `child and parent - change parent for child - 2`() { val parent = builder add NamedEntity("myProperty", AnotherSource) val parent2 = builder add NamedEntity("anotherProperty", MySource) val child = builder add NamedChildEntity("myChild", AnotherSource) { this.parentEntity = parent2 } replacement = createBuilderFrom(builder) replacement.modifyEntity(child) { this.parentEntity = parent } builder.replaceBySource({ it is MySource }, replacement) builder.assertConsistency() } @RepeatedTest(10) fun `child and parent - change parent for child - 3`() { // Difference with the test above: different initial parent val parent = builder add NamedEntity("myProperty", AnotherSource) val parent2 = builder add NamedEntity("anotherProperty", MySource) val child = builder add NamedChildEntity("myChild", AnotherSource) { this.parentEntity = parent } replacement = createBuilderFrom(builder) replacement.modifyEntity(child) { this.parentEntity = parent2 } builder.replaceBySource({ it is MySource }, replacement) builder.assertConsistency() val parents = builder.entities(NamedEntity::class.java).toList() assertTrue(parents.single { it.myName == "anotherProperty" }.children.none()) assertEquals(child, parents.single { it.myName == "myProperty" }.children.single()) } @RepeatedTest(10) fun `child and parent - remove child`() { val parent = builder add NamedEntity("myProperty", MySource) val child = builder add NamedChildEntity("myChild", MySource) { this.parentEntity = parent } replacement = createBuilderFrom(builder) replacement.removeEntity(child) rbsAllSources() assertEmpty(builder.entities(NamedChildEntity::class.java).toList()) assertOneElement(builder.entities(NamedEntity::class.java).toList()) assertEmpty(builder.entities(NamedEntity::class.java).single().children.toList()) builder.assertConsistency() } @RepeatedTest(10) fun `fail - child and parent - different source for parent`() { replacement = createBuilderFrom(builder) val parent = replacement add NamedEntity("myProperty", AnotherSource) replacement add NamedChildEntity("myChild", MySource) { this.parentEntity = parent } builder.replaceBySource({ it is MySource }, replacement) assertTrue(builder.entities(NamedEntity::class.java).toList().isEmpty()) assertTrue(builder.entities(NamedChildEntity::class.java).toList().isEmpty()) } @RepeatedTest(10) fun `child and parent - two children of different sources`() { val parent = builder add NamedEntity("Property", AnotherSource) builder add NamedChildEntity("MySourceChild", MySource) { this.parentEntity = parent } replacement = createBuilderFrom(builder) replacement add NamedChildEntity("AnotherSourceChild", AnotherSource) { this.parentEntity = parent } builder.replaceBySource({ it is MySource }, replacement) builder.assertConsistency() assertOneElement(builder.entities(NamedEntity::class.java).toList()) val child = assertOneElement(builder.entities(NamedChildEntity::class.java).toList()) assertEquals("MySourceChild", child.childProperty) } @RepeatedTest(10) fun `child and parent - trying to remove parent and leave child`() { val parentEntity = builder add NamedEntity("prop", AnotherSource) builder add NamedChildEntity("data", MySource) { this.parentEntity = parentEntity } replacement = createBuilderFrom(builder) replacement.removeEntity(parentEntity) builder.replaceBySource({ it is AnotherSource }, replacement) builder.assertConsistency() assertNoNamedEntities() assertNoNamedChildEntities() thisStateCheck { parentEntity assert ReplaceState.Remove } } @RepeatedTest(10) fun `child and parent - different source for child`() { replacement = createBuilderFrom(builder) val parent = replacement add NamedEntity("myProperty", MySource) replacement add NamedChildEntity("myChild", AnotherSource) { this.parentEntity = parent } builder.replaceBySource({ it is MySource }, replacement) assertEmpty(builder.entities(NamedChildEntity::class.java).toList()) assertOneElement(builder.entities(NamedEntity::class.java).toList()) assertEmpty(builder.entities(NamedEntity::class.java).single().children.toList()) builder.assertConsistency() } @RepeatedTest(10) fun `remove child of different source`() { val parent = builder add NamedEntity("data", AnotherSource) val child = builder add NamedChildEntity("data", MySource) { this.parentEntity = parent } replacement = createBuilderFrom(builder) replacement.removeEntity(child) builder.replaceBySource({ it is MySource }, replacement) } @RepeatedTest(10) fun `entity with soft reference`() { val named = builder.addNamedEntity("MyName") builder.addWithSoftLinkEntity(named.persistentId) resetChanges() builder.assertConsistency() replacement = createBuilderFrom(builder) replacement.modifyEntity(named) { this.myName = "NewName" } replacement.assertConsistency() rbsAllSources() assertEquals("NewName", assertOneElement(builder.entities(NamedEntity::class.java).toList()).myName) assertEquals("NewName", assertOneElement(builder.entities(WithSoftLinkEntity::class.java).toList()).link.presentableName) builder.assertConsistency() } @RepeatedTest(10) fun `entity with soft reference remove reference`() { val named = builder.addNamedEntity("MyName") val linked = builder.addWithListSoftLinksEntity("name", listOf(named.persistentId)) resetChanges() builder.assertConsistency() replacement = createBuilderFrom(builder) replacement.modifyEntity(linked) { this.links = mutableListOf() } replacement.assertConsistency() rbsAllSources() builder.assertConsistency() } @RepeatedTest(10) fun `replace by source with composite id`() { replacement = createEmptyBuilder() val namedEntity = replacement.addNamedEntity("MyName") val composedEntity = replacement.addComposedIdSoftRefEntity("AnotherName", namedEntity.persistentId) replacement.addComposedLinkEntity(composedEntity.persistentId) replacement.assertConsistency() rbsAllSources() builder.assertConsistency() assertOneElement(builder.entities(NamedEntity::class.java).toList()) assertOneElement(builder.entities(ComposedIdSoftRefEntity::class.java).toList()) assertOneElement(builder.entities(ComposedLinkEntity::class.java).toList()) } @RepeatedTest(10) fun `trying to create two similar persistent ids`() { val namedEntity = builder.addNamedEntity("MyName", source = AnotherSource) replacement = createBuilderFrom(builder) replacement.modifyEntity(namedEntity) { this.myName = "AnotherName" } replacement.addNamedEntity("MyName", source = MySource) rbsMySources() assertEquals(MySource, builder.entities(NamedEntity::class.java).single().entitySource) } @RepeatedTest(10) fun `changing parent`() { val parentEntity = builder add NamedEntity("data", MySource) val childEntity = builder add NamedChildEntity("data", AnotherSource) { this.parentEntity = parentEntity } replacement = createBuilderFrom(builder) val anotherParent = replacement add NamedEntity("Another", MySource) replacement.modifyEntity(childEntity) { this.parentEntity = anotherParent } builder.replaceBySource({ it is MySource }, replacement) } @RepeatedTest(10) fun `replace same entity with persistent id and different sources`() { val name = "Hello" builder.addNamedEntity(name, source = MySource) replacement = createEmptyBuilder() replacement.addNamedEntity(name, source = AnotherSource) builder.replaceBySource({ it is AnotherSource }, replacement) assertEquals(1, builder.entities(NamedEntity::class.java).toList().size) assertEquals(AnotherSource, builder.entities(NamedEntity::class.java).single().entitySource) } @RepeatedTest(10) fun `replace dummy parent entity by real entity`() { val namedParent = builder.addNamedEntity("name", "foo", MyDummyParentSource) builder.addNamedChildEntity(namedParent, "fooChild", AnotherSource) replacement = createEmptyBuilder() replacement.addNamedEntity("name", "bar", MySource) builder.replaceBySource({ it is MySource || it is MyDummyParentSource }, replacement) assertEquals("bar", builder.entities(NamedEntity::class.java).single().additionalProperty) val child = builder.entities(NamedChildEntity::class.java).single() assertEquals("fooChild", child.childProperty) assertEquals("bar", child.parentEntity.additionalProperty) } @RepeatedTest(10) fun `do not replace real parent entity by dummy entity`() { val namedParent = builder.addNamedEntity("name", "foo", MySource) builder.addNamedChildEntity(namedParent, "fooChild", AnotherSource) replacement = createEmptyBuilder() replacement.addNamedEntity("name", "bar", MyDummyParentSource) builder.replaceBySource({ it is MySource || it is MyDummyParentSource }, replacement) assertEquals("foo", builder.entities(NamedEntity::class.java).single().additionalProperty) val child = builder.entities(NamedChildEntity::class.java).single() assertEquals("fooChild", child.childProperty) assertEquals("foo", child.parentEntity.additionalProperty) } @RepeatedTest(10) fun `do not replace real parent entity by dummy entity but replace children`() { val namedParent = builder.addNamedEntity("name", "foo", MySource) builder.addNamedChildEntity(namedParent, "fooChild", MySource) replacement = createEmptyBuilder() val newParent = replacement.addNamedEntity("name", "bar", MyDummyParentSource) replacement.addNamedChildEntity(newParent, "barChild", MySource) builder.replaceBySource({ it is MySource || it is MyDummyParentSource }, replacement) assertEquals("foo", builder.entities(NamedEntity::class.java).single().additionalProperty) val child = builder.entities(NamedChildEntity::class.java).single() assertEquals("barChild", child.childProperty) assertEquals("foo", child.parentEntity.additionalProperty) } @RepeatedTest(10) fun `replace parents with completely different children 1`() { builder add NamedEntity("PrimaryName", MySource) { additionalProperty = "Initial" children = listOf( NamedChildEntity("PrimaryChild", MySource) ) } replacement = createEmptyBuilder() replacement add NamedEntity("PrimaryName", MySource) { additionalProperty = "Update" children = listOf( NamedChildEntity("PrimaryChild", MySource) ) } rbsAllSources() val parentEntity = builder.entities(NamedEntity::class.java).single() assertEquals("Update", parentEntity.additionalProperty) assertEquals("PrimaryChild", parentEntity.children.single().childProperty) } @RepeatedTest(10) fun `replace parents with completely different children`() { val parentEntity = builder.addNamedEntity("PrimaryParent", additionalProperty = "Initial", source = AnotherSource) builder.addNamedChildEntity(parentEntity, "PrimaryChild", source = MySource) builder.addNamedEntity("SecondaryParent", source = AnotherSource) replacement = createEmptyBuilder() replacement.addNamedEntity("PrimaryParent", additionalProperty = "New", source = AnotherSource) val anotherParentEntity = replacement.addNamedEntity("SecondaryParent2", source = AnotherSource) replacement.addNamedChildEntity(anotherParentEntity, source = MySource) builder.replaceBySource({ it is AnotherSource }, replacement) val primaryChild = builder.entities(NamedChildEntity::class.java).find { it.childProperty == "PrimaryChild" }!! assertEquals("PrimaryParent", primaryChild.parentEntity.myName) assertEquals("New", primaryChild.parentEntity.additionalProperty) } @RepeatedTest(10) fun `replace oneToOne connection with partial move`() { val parentEntity = builder.addOoParentEntity() builder.addOoChildEntity(parentEntity) replacement = createEmptyBuilder() val anotherParent = replacement.addOoParentEntity(source = AnotherSource) replacement.addOoChildEntity(anotherParent) builder.replaceBySource({ it is MySource }, replacement) builder.assertConsistency() } @RepeatedTest(10) fun `replace oneToOne connection with partial move and pid`() { val parentEntity = builder.addOoParentWithPidEntity(source = AnotherSource) builder.addOoChildForParentWithPidEntity(parentEntity, source = MySource) val anotherParent = replacement.addOoParentWithPidEntity(source = MySource) replacement.addOoChildForParentWithPidEntity(anotherParent, source = MySource) builder.replaceBySource({ it is MySource }, replacement) builder.assertConsistency() assertNotNull(builder.entities(OoParentWithPidEntity::class.java).single().childOne) thisStateCheck { parentEntity assert ReplaceState.Relabel(anotherParent.base.id) parentEntity.childOne!! assert ReplaceState.Relabel(anotherParent.childOne!!.base.id, setOf(ParentsRef.TargetRef(parentEntity.base.id))) } replaceWithCheck { anotherParent assert ReplaceWithState.Relabel(parentEntity.base.id) } } @RepeatedTest(10) fun `replace with unmatching tree`() { val entity = builder add NamedEntity("Data", MySource) { children = listOf( NamedChildEntity("ChildData", MySource), NamedChildEntity("AnotherChildData", MySource), ) } val newEntity = replacement add NamedEntity("Data", AnotherSource) { children = listOf( NamedChildEntity("ChildData", AnotherSource), NamedChildEntity("AnotherChildData", AnotherSource), ) } rbsMySources() builder.assertConsistency() assertNoNamedEntities() assertNoNamedChildEntities() thisStateCheck { entity assert ReplaceState.Remove entity.children.forEach { child -> child assert ReplaceState.Remove } } replaceWithCheck { newEntity assert ReplaceWithState.NoChangeTraceLost } } @RepeatedTest(10) fun `no changes in root`() { val entity = builder add NamedEntity("Data", AnotherSource) { children = listOf( NamedChildEntity("data", MySource) ) } val newEntity = replacement add NamedEntity("Data", AnotherSource) rbsMySources() builder.assertConsistency() assertSingleNameEntity("Data") assertNoNamedChildEntities() thisStateCheck { entity assert ReplaceState.NoChange(newEntity.base.id) } replaceWithCheck { newEntity assert ReplaceWithState.NoChange(entity.base.id) } } @RepeatedTest(10) fun `move two children`() { builder add NamedEntity("Data", AnotherSource) replacement add NamedEntity("Data", AnotherSource) { children = listOf( NamedChildEntity("data1", MySource), NamedChildEntity("data2", MySource), ) } rbsMySources() builder.assertConsistency() val parentEntity = assertSingleNameEntity("Data") assertEquals(setOf("data1", "data2"), parentEntity.children.map { it.childProperty }.toSet()) } @RepeatedTest(10) fun `remove two children`() { builder add NamedEntity("Data", AnotherSource) { children = listOf( NamedChildEntity("data1", MySource), NamedChildEntity("data2", MySource), ) } replacement add NamedEntity("Data", AnotherSource) rbsMySources() builder.assertConsistency() assertSingleNameEntity("Data") assertNoNamedChildEntities() } @RepeatedTest(10) fun `rbs for multiple parents but no actual multiple parents`() { builder add TreeMultiparentRootEntity("data", MySource) { children = listOf( TreeMultiparentLeafEntity("info1", MySource), TreeMultiparentLeafEntity("info2", MySource), ) } replacement add TreeMultiparentRootEntity("data", MySource) { children = listOf( TreeMultiparentLeafEntity("info1", MySource), TreeMultiparentLeafEntity("info2", MySource), ) } rbsAllSources() builder.assertConsistency() } @RepeatedTest(10) fun `rbs for deep chain`() { builder add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity("internal", MySource)) }, ) } val thisRoot = builder.toSnapshot().entities(TreeMultiparentRootEntity::class.java).single() val replaceRoot = replacement add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity("internal2", MySource)) }, ) } rbsMySources() builder.assertConsistency() assertEquals("internal2", builder.entities(TreeMultiparentRootEntity::class.java).single().children.single().children.single().data) thisStateCheck { thisRoot assert ReplaceState.NoChange(replaceRoot.base.id) thisRoot.children.single() assert ReplaceState.NoChange(replaceRoot.children.single().base.id) thisRoot.children.single().children.single() assert ReplaceState.Remove } replaceWithCheck { replaceRoot assert ReplaceWithState.NoChange(thisRoot.base.id) replaceRoot.children.single() assert ReplaceWithState.NoChange(thisRoot.children.single().base.id) replaceRoot.children.single().children.single() assert ReplaceWithState.ElementMoved } } @RepeatedTest(10) fun `rbs for deep chain 2`() { builder add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity("internal", AnotherSource)) }, ) } val thisRoot = builder.toSnapshot().entities(TreeMultiparentRootEntity::class.java).single() val replaceRoot = replacement add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity("internal2", MySource)) }, ) } rbsMySources() builder.assertConsistency() val endChildren = builder.entities(TreeMultiparentRootEntity::class.java).single().children.single().children assertTrue(endChildren.any { it.data == "internal2" }) assertTrue(endChildren.any { it.data == "internal" }) thisStateCheck { thisRoot assert ReplaceState.NoChange(replaceRoot.base.id) } replaceWithCheck { replaceRoot assert ReplaceWithState.NoChange(thisRoot.base.id) replaceRoot.children.single() assert ReplaceWithState.NoChange(thisRoot.children.single().base.id) replaceRoot.children.single().children.single() assert ReplaceWithState.ElementMoved } } @RepeatedTest(10) fun `rbs for deep chain 3`() { builder add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity("internal", MySource)) }, ) } val thisRoot = builder.toSnapshot().entities(TreeMultiparentRootEntity::class.java).single() val replaceRoot = replacement add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity("internal2", AnotherSource)) }, ) } rbsMySources() builder.assertConsistency() val endChildren = builder.entities(TreeMultiparentRootEntity::class.java).single().children.single().children assertTrue(endChildren.isEmpty()) thisStateCheck { thisRoot assert ReplaceState.NoChange(replaceRoot.base.id) thisRoot.children.single() assert ReplaceState.NoChange(replaceRoot.children.single().base.id) thisRoot.children.single().children.single() assert ReplaceState.Remove } replaceWithCheck { replaceRoot assert ReplaceWithState.NoChange(thisRoot.base.id) } } @RepeatedTest(10) fun `rbs for deep chain 4`() { builder add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", MySource) { this.children = listOf(TreeMultiparentLeafEntity("internal", AnotherSource)) }, ) } val thisRoot = builder.toSnapshot().entities(TreeMultiparentRootEntity::class.java).single() val replaceRoot = replacement add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", MySource) { this.children = listOf(TreeMultiparentLeafEntity("internal2", AnotherSource)) }, ) } rbsMySources() builder.assertConsistency() val endChildren = builder.entities(TreeMultiparentRootEntity::class.java).single().children.single().children assertEquals("internal", endChildren.single().data) thisStateCheck { thisRoot assert ReplaceState.NoChange(replaceRoot.base.id) thisRoot.children.single() assert ReplaceState.Relabel(replaceRoot.children.single().base.id, setOf(ParentsRef.TargetRef(thisRoot.base.id))) } replaceWithCheck { replaceRoot assert ReplaceWithState.NoChange(thisRoot.base.id) replaceRoot.children.single() assert ReplaceWithState.Relabel(thisRoot.children.single().base.id) } } @RepeatedTest(10) fun `rbs lot of children`() { builder add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("internal", MySource), ) }, TreeMultiparentLeafEntity("info2", AnotherSource), TreeMultiparentLeafEntity("info3", AnotherSource), TreeMultiparentLeafEntity("info4", AnotherSource), TreeMultiparentLeafEntity("info5", AnotherSource), ) } builder.toSnapshot().entities(TreeMultiparentRootEntity::class.java).single() replacement add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("internal", MySource), ) }, ) } rbsMySources() builder.assertConsistency() val endChildren = builder.entities(TreeMultiparentRootEntity::class.java).single().children assertEquals(5, endChildren.size) } @RepeatedTest(10) fun `rbs for deep chain 5`() { builder add ModuleTestEntity("data", AnotherSource) { this.contentRoots = listOf( ContentRootTestEntity(AnotherSource) { this.sourceRootOrder = SourceRootTestOrderEntity("info", MySource) this.sourceRoots = listOf( SourceRootTestEntity("data", MySource) ) } ) } builder.toSnapshot().entities(ModuleTestEntity::class.java).single() replacement add ModuleTestEntity("data", AnotherSource) { this.contentRoots = listOf( ContentRootTestEntity(AnotherSource) { this.sourceRootOrder = SourceRootTestOrderEntity("info", MySource) this.sourceRoots = listOf( SourceRootTestEntity("data", MySource) ) } ) } rbsMySources() builder.assertConsistency() val contentRoot = builder.entities(ModuleTestEntity::class.java).single().contentRoots.single() assertEquals("info", contentRoot.sourceRootOrder!!.data) assertEquals("data", contentRoot.sourceRoots.single().data) } @RepeatedTest(10) fun `rbs for multiple parents`() { builder add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity("internal", MySource)) }, TreeMultiparentLeafEntity("info2", AnotherSource), ) } replacement add TreeMultiparentRootEntity("data", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("info1", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity("internal2", MySource)) }, TreeMultiparentLeafEntity("info2", AnotherSource), ) } rbsMySources() builder.assertConsistency() } @RepeatedTest(10) fun `abstract entity`() { builder add HeadAbstractionEntity("Data", AnotherSource) { this.child = LeftEntity(AnotherSource) { this.children = listOf( LeftEntity(MySource), RightEntity(MySource), ) } } replacement add HeadAbstractionEntity("Data", AnotherSource) { this.child = LeftEntity(AnotherSource) { this.children = listOf( MiddleEntity("info1", MySource), MiddleEntity("info1", MySource), ) } } rbsMySources() builder.assertConsistency() } @RepeatedTest(10) fun `non persistent id root`() { val targetEntity = builder.addSampleEntity("data", MySource) val replaceWithEntity = replacement.addSampleEntity("data", MySource) rbsMySources() builder.assertConsistency() thisStateCheck { targetEntity assert ReplaceState.Relabel(replaceWithEntity.base.id) } replaceWithCheck { replaceWithEntity assert ReplaceWithState.Relabel(targetEntity.base.id) } } @RepeatedTest(10) fun `different source on parent`() { builder add TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( TreeMultiparentLeafEntity("data", MySource) { this.children = listOf(TreeMultiparentLeafEntity ("internal", MySource)) } ) } replacement add TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( TreeMultiparentLeafEntity("data", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity ("internal", MySource)) } ) } rbsMySources() builder.assertConsistency() val children = builder.entities(TreeMultiparentRootEntity::class.java).single().children assertTrue(children.isEmpty()) } @RepeatedTest(10) fun `detach root parent`() { val internalChild = TreeMultiparentLeafEntity("internal", MySource) val leafsStructure = TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( TreeMultiparentLeafEntity("data", AnotherSource) { this.children = listOf(internalChild) } ) } builder add leafsStructure builder.modifyEntity(internalChild) { this.mainParent = leafsStructure } val replaceWithEntity = replacement add TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( TreeMultiparentLeafEntity("data", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity ("internal", MySource)) } ) } var rootEntity = builder.entities(TreeMultiparentRootEntity::class.java).single() assertEquals(2, rootEntity.children.size) rbsMySources() builder.assertConsistency() rootEntity = builder.entities(TreeMultiparentRootEntity::class.java).single() assertEquals(1, rootEntity.children.size) val childAbove = rootEntity.children.single() assertEquals("data", childAbove.data) val child = childAbove.children.single() assertTrue(child.mainParent == null) thisStateCheck { leafsStructure assert ReplaceState.NoChange(replaceWithEntity.base.id) leafsStructure.children.single() assert ReplaceState.NoChange(replaceWithEntity.children.single().base.id) internalChild assert ReplaceState.Relabel(replaceWithEntity.children.single().children.single().base.id, setOf(ParentsRef.TargetRef(leafsStructure.children.single().base.id))) } replaceWithCheck { replaceWithEntity assert ReplaceWithState.NoChange(leafsStructure.base.id) replaceWithEntity.children.single() assert ReplaceWithState.NoChange(leafsStructure.children.single().base.id) replaceWithEntity.children.single().children.single() assert ReplaceWithState.Relabel(leafsStructure.children.single().children.single().base.id) } } @RepeatedTest(10) fun `detach internal parent`() { val internalChild = TreeMultiparentLeafEntity("internal", MySource) val leafsStructure = TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( TreeMultiparentLeafEntity("data", AnotherSource) { this.children = listOf(internalChild) } ) } builder add leafsStructure builder.modifyEntity(internalChild) { this.mainParent = leafsStructure } val root = builder.toSnapshot().entities(TreeMultiparentRootEntity::class.java).single() val replaceChild1 = TreeMultiparentLeafEntity("data", AnotherSource) val replaceChild2 = TreeMultiparentLeafEntity("internal", MySource) val replaceWithEntity = replacement add TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( replaceChild1, replaceChild2, ) } var rootEntity = builder.entities(TreeMultiparentRootEntity::class.java).single() assertEquals(2, rootEntity.children.size) rbsMySources() builder.assertConsistency() rootEntity = builder.entities(TreeMultiparentRootEntity::class.java).single() assertEquals(2, rootEntity.children.size) val childAbove = rootEntity.children.single { it.data == "data" } assertEquals("data", childAbove.data) val noChildren = childAbove.children.isEmpty() assertTrue(noChildren) thisStateCheck { root assert ReplaceState.NoChange(replaceWithEntity.base.id) root.children.single { it.data == "data" } assert ReplaceState.NoChange(replaceChild1.base.id) internalChild assert ReplaceState.Relabel(replaceChild2.base.id, setOf(ParentsRef.TargetRef(root.base.id))) } replaceWithCheck { replaceWithEntity assert ReplaceWithState.NoChange(root.base.id) replaceChild1 assert ReplaceWithState.NoChange(root.children.single { it.data == "data" }.base.id) replaceChild2 assert ReplaceWithState.Relabel(internalChild.base.id) } } @RepeatedTest(10) fun `detach both parents`() { val internalChild = TreeMultiparentLeafEntity("internal", MySource) val leafsStructure = TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( TreeMultiparentLeafEntity("data", AnotherSource) { this.children = listOf(internalChild) } ) } builder add leafsStructure builder.modifyEntity(internalChild) { this.mainParent = leafsStructure } val root = builder.toSnapshot().entities(TreeMultiparentRootEntity::class.java).single() val replaceWithDataElement = TreeMultiparentLeafEntity("data", AnotherSource) val replaceWithEntity = replacement add TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( replaceWithDataElement, ) } var rootEntity = builder.entities(TreeMultiparentRootEntity::class.java).single() assertEquals(2, rootEntity.children.size) rbsMySources() builder.assertConsistency() rootEntity = builder.entities(TreeMultiparentRootEntity::class.java).single() assertEquals(1, rootEntity.children.size) val childAbove = rootEntity.children.single { it.data == "data" } assertEquals("data", childAbove.data) val noChildren = childAbove.children.isEmpty() assertTrue(noChildren) thisStateCheck { root assert ReplaceState.NoChange(replaceWithEntity.base.id) root.children.single { it.data == "data" } assert ReplaceState.NoChange(replaceWithDataElement.base.id) internalChild assert ReplaceState.Remove } replaceWithCheck { replaceWithEntity assert ReplaceWithState.NoChange(root.base.id) replaceWithDataElement assert ReplaceWithState.NoChange(root.children.single { it.data == "data" }.base.id) } } @RepeatedTest(10) fun `attach to root entity`() { val internalChild = TreeMultiparentLeafEntity("internal", MySource) val leafsStructure = TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( TreeMultiparentLeafEntity("data", AnotherSource) { this.children = listOf(internalChild) } ) } builder add leafsStructure val root = builder.toSnapshot().entities(TreeMultiparentRootEntity::class.java).single() val replaceWithDataElement = TreeMultiparentLeafEntity("data", AnotherSource) val replaceWithEntity = replacement add TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( replaceWithDataElement, ) } val internalReplacement = replacement add TreeMultiparentLeafEntity("internal", MySource) { this.mainParent = replaceWithEntity this.leafParent = replaceWithDataElement } var rootEntity = builder.entities(TreeMultiparentRootEntity::class.java).single() assertEquals(1, rootEntity.children.size) rbsMySources() builder.assertConsistency() rootEntity = builder.entities(TreeMultiparentRootEntity::class.java).single() assertEquals(2, rootEntity.children.size) val childAbove = rootEntity.children.single { it.data == "data" } rootEntity.children.single { it.data == "internal" } assertEquals("data", childAbove.data) val myInternalChild = childAbove.children.single() assertTrue(myInternalChild.data == "internal") thisStateCheck { root assert ReplaceState.NoChange(replaceWithEntity.base.id) root.children.single { it.data == "data" } assert ReplaceState.NoChange(replaceWithDataElement.base.id) internalChild assert ReplaceState.Relabel( internalReplacement.base.id, parents = setOf(ParentsRef.TargetRef(leafsStructure.base.id), ParentsRef.TargetRef(root.children.single().base.id)) ) } replaceWithCheck { replaceWithEntity assert ReplaceWithState.NoChange(root.base.id) replaceWithDataElement assert ReplaceWithState.NoChange(root.children.single { it.data == "data" }.base.id) } } @RepeatedTest(10) fun `add new root`() { val leafsStructure = TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( TreeMultiparentLeafEntity("data", MySource) ) } builder add leafsStructure builder.toSnapshot().entities(TreeMultiparentRootEntity::class.java).single() val doubleRooted = TreeMultiparentLeafEntity("data", MySource) replacement add TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( doubleRooted ) } replacement add TreeMultiparentRootEntity("data2", MySource) { children = listOf( TreeMultiparentLeafEntity("SomeEntity", MySource) { this.children = listOf(doubleRooted) } ) } rbsMySources() builder.assertConsistency() val parents = builder.entities(TreeMultiparentRootEntity::class.java).toList() assertEquals(2, parents.size) val targetLeaf = parents.single { it.data == "data" }.children.single() val targetLeafFromOtherSide = parents.single { it.data == "data2" }.children.single().children.single() assertEquals(targetLeaf.base.id, targetLeafFromOtherSide.base.id) assertEquals("data", targetLeaf.data) } @RepeatedTest(10) fun `transfer new store`() { val doubleRooted = TreeMultiparentLeafEntity("data", MySource) replacement add TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( doubleRooted ) } replacement add TreeMultiparentRootEntity("data2", MySource) { children = listOf( TreeMultiparentLeafEntity("SomeEntity", MySource) { this.children = listOf(doubleRooted) } ) } rbsAllSources() builder.assertConsistency() val parents = builder.entities(TreeMultiparentRootEntity::class.java).toList() assertEquals(2, parents.size) val targetLeaf = parents.single { it.data == "data" }.children.single() val targetLeafFromOtherSide = parents.single { it.data == "data2" }.children.single().children.single() assertEquals(targetLeaf.base.id, targetLeafFromOtherSide.base.id) assertEquals("data", targetLeaf.data) } @RepeatedTest(10) fun `do not transfer to new store`() { val doubleRooted = TreeMultiparentLeafEntity("data", MySource) replacement add TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( doubleRooted ) } replacement add TreeMultiparentRootEntity("data2", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("SomeEntity", AnotherSource) { this.children = listOf(doubleRooted) } ) } rbsMySources() builder.assertConsistency() val parents = builder.entities(TreeMultiparentRootEntity::class.java).toList() assertEquals(0, parents.size) val leafs = builder.entities(TreeMultiparentLeafEntity::class.java).toList() assertEquals(0, leafs.size) } @RepeatedTest(10) fun `unbind ref`() { val doubleRooted = TreeMultiparentLeafEntity("data", MySource) builder add TreeMultiparentRootEntity("data", AnotherSource) { this.children = listOf( doubleRooted ) } builder add TreeMultiparentRootEntity("data2", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("SomeEntity", AnotherSource) { this.children = listOf(doubleRooted) } ) } replacement add TreeMultiparentRootEntity("data2", AnotherSource) { children = listOf( TreeMultiparentLeafEntity("SomeEntity", AnotherSource) { this.children = listOf(TreeMultiparentLeafEntity("data", MySource)) } ) } rbsAllSources() builder.assertConsistency() val parent = builder.entities(TreeMultiparentRootEntity::class.java).single() assertEquals("data2", parent.data) val single = parent.children.single().children.single() assertEquals("data", single.data) } @RepeatedTest(10) fun `same child`() { builder add NamedEntity("data", MySource) { children = listOf( NamedChildEntity("Info1", SampleEntitySource("a")), NamedChildEntity("Info1", SampleEntitySource("a")), ) } replacement add NamedEntity("data", MySource) { children = listOf( NamedChildEntity("Info1", SampleEntitySource("x")), NamedChildEntity("Info1", SampleEntitySource("x")), ) } builder.replaceBySource({ it is SampleEntitySource }, replacement) builder.assertConsistency() val sources = builder.entities(NamedEntity::class.java).single().children .map { (it.entitySource as SampleEntitySource).name } .toSet() .single() assertEquals("x", sources) } @RepeatedTest(10) fun `persistent id in the middle`() { builder add ModuleTestEntity("data", AnotherSource) { facets = listOf( FacetTestEntity("facet", "MyData", MySource) ) } replacement add ModuleTestEntity("data", AnotherSource) { facets = listOf( FacetTestEntity("facet", "Very other data", MySource) ) } rbsMySources() builder.assertConsistency() assertEquals("Very other data", builder.entities(ModuleTestEntity::class.java).single().facets.single().moreData) } @RepeatedTest(10) fun `persistent id in the middle 2`() { builder add ModuleTestEntity("data", AnotherSource) { facets = listOf( FacetTestEntity("facet", "MyData", AnotherSource) ) } replacement add ModuleTestEntity("data", MySource) { facets = listOf( FacetTestEntity("facet", "Very other data", MySource) ) } rbsAllSources() builder.assertConsistency() val module = builder.entities(ModuleTestEntity::class.java).single() assertEquals(MySource, module.entitySource) val facet = module.facets.single() assertEquals(MySource, facet.entitySource) assertEquals("Very other data", facet.moreData) } @RepeatedTest(10) fun `replace root entities without persistent id`() { builder add LeftEntity(AnotherSource) builder add LeftEntity(AnotherSource) replacement add LeftEntity(MySource) replacement add LeftEntity(MySource) rbsAllSources() builder.assertConsistency() val leftEntities = builder.entities(LeftEntity::class.java).toList() assertEquals(2, leftEntities.size) assertTrue(leftEntities.all { it.entitySource == MySource }) } @RepeatedTest(10) fun `replace same entities should produce no events`() { builder add NamedEntity("name", MySource) { children = listOf( NamedChildEntity("info1", MySource), NamedChildEntity("info2", MySource), ) } replacement add NamedEntity("name", MySource) { children = listOf( NamedChildEntity("info1", MySource), NamedChildEntity("info2", MySource), ) } builder.changeLog.clear() rbsAllSources() builder.assertConsistency() assertEquals(0, builder.changeLog.changeLog.size) } @RepeatedTest(10) fun `replace same entities should produce in case of source change`() { builder add NamedEntity("name", MySource) { children = listOf( NamedChildEntity("info1", MySource), NamedChildEntity("info2", MySource), ) } replacement add NamedEntity("name", MySource) { children = listOf( NamedChildEntity("info1", AnotherSource), NamedChildEntity("info2", MySource), ) } builder.changeLog.clear() rbsAllSources() builder.assertConsistency() assertEquals(1, builder.changeLog.changeLog.size) } private inner class ThisStateChecker { infix fun WorkspaceEntity.assert(state: ReplaceState) { val thisState = engine.targetState[this.base.id] assertNotNull(thisState) assertEquals(state, thisState) } } private inner class ReplaceStateChecker { infix fun WorkspaceEntity.assert(state: ReplaceWithState) { assertEquals(state, engine.replaceWithState[this.base.id]) } } private fun thisStateCheck(checks: ThisStateChecker.() -> Unit) { ThisStateChecker().checks() } private fun replaceWithCheck(checks: ReplaceStateChecker.() -> Unit) { ReplaceStateChecker().checks() } private val WorkspaceEntity.base: WorkspaceEntityBase get() = this as WorkspaceEntityBase private fun assertNoNamedEntities() { assertTrue(builder.entities(NamedEntity::class.java).toList().isEmpty()) } private fun assertSingleNameEntity(name: String): NamedEntity { val entities = builder.entities(NamedEntity::class.java).toList() assertEquals(1, entities.size) assertEquals(name, entities.single().myName) return entities.single() } private fun assertNoNamedChildEntities() { assertTrue(builder.entities(NamedChildEntity::class.java).toList().isEmpty()) } private fun rbsAllSources() { builder.replaceBySource({ true }, replacement) } private fun rbsMySources() { builder.replaceBySource({ it is MySource }, replacement) } private fun resetChanges() { builder = builder.toSnapshot().toBuilder() as MutableEntityStorageImpl builder.useNewRbs = true builder.keepLastRbsEngine = true } private val engine: ReplaceBySourceAsTree get() = builder.engine as ReplaceBySourceAsTree private infix fun <T : WorkspaceEntity> MutableEntityStorage.add(entity: T): T { this.addEntity(entity) return entity } }
apache-2.0
Flank/flank
test_runner/src/main/kotlin/ftl/shard/TestMethodDuration.kt
1
1109
package ftl.shard import ftl.api.JUnitTest import ftl.args.AndroidArgs import ftl.args.IArgs import ftl.domain.junit.empty fun createTestMethodDurationMap(junitResult: JUnitTest.Result, args: IArgs): Map<String, Double> { val junitMap = mutableMapOf<String, Double>() // Create a map with information from previous junit run junitResult.testsuites?.forEach { testsuite -> testsuite.testcases?.forEach { testcase -> if (!testcase.empty() && testcase.time != null) { val key = if (args is AndroidArgs) testcase.androidKey() else testcase.iosKey() val time = testcase.time.toDouble() if (time >= 0) junitMap[key] = time } } } return junitMap } private fun JUnitTest.Case.androidKey(): String { return "class $classname#$name" } private fun JUnitTest.Case.iosKey(): String { // FTL iOS XML appends `()` to each test name. ex: `testBasicSelection()` // xctestrun file requires classname/name with no `()` val testName = name?.substringBefore('(') return "$classname/$testName" }
apache-2.0
viartemev/requestmapper
src/main/kotlin/com/viartemev/requestmapper/utils/CommonUtils.kt
1
619
package com.viartemev.requestmapper.utils fun String.unquote(): String = if (length >= 2 && first() == '"' && last() == '"') substring(1, this.length - 1) else this fun String.inCurlyBrackets(): Boolean = length >= 2 && first() == '{' && last() == '}' fun String.unquoteCurlyBrackets(): String = if (this.inCurlyBrackets()) this.drop(1).dropLast(1) else this fun String.addCurlyBrackets(): String = "{$this}" fun List<String>.dropFirstEmptyStringIfExists(): List<String> = if (this.isNotEmpty() && this.first().isEmpty()) this.drop(1) else this fun String.isNumeric(): Boolean = this.toBigDecimalOrNull() != null
mit
chickenbane/workshop-jb
test/i_introduction/_8_Smart_Casts/_08_Smart_Casts.kt
3
484
package i_introduction._8_Smart_Casts import org.junit.Assert import org.junit.Test class _08_Smart_Casts { @Test fun testNum() { Assert.assertEquals("'eval' on Num should work:", 2, eval(Num(2))) } @Test fun testSum() { Assert.assertEquals("'eval' on Sum should work:", 3, eval(Sum(Num(2), Num(1)))) } @Test fun testRecursion() { Assert.assertEquals("'eval' should work recursively:", 6, eval(Sum(Sum(Num(1), Num(2)), Num(3)))) } }
mit
FuturemanGaming/FutureBot-Discord
src/main/kotlin/com/futuremangaming/futurebot/music/PlayerSendHandler.kt
1
1392
/* * 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 import com.sedmelluq.discord.lavaplayer.player.AudioPlayer import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame import net.dv8tion.jda.core.audio.AudioSendHandler class PlayerSendHandler(private val player: AudioPlayer) : AudioSendHandler { private var lastFrame: AudioFrame? = null override fun provide20MsAudio(): ByteArray? { if (lastFrame === null) { lastFrame = player.provide() } val data = lastFrame?.data lastFrame = null return data } override fun canProvide(): Boolean { if (lastFrame === null) { lastFrame = player.provide() } return lastFrame !== null } override fun isOpus(): Boolean = true }
apache-2.0
kickstarter/android-oss
app/src/main/java/com/kickstarter/viewmodels/ProjectCardHolderViewModel.kt
1
25817
package com.kickstarter.viewmodels import android.util.Pair import androidx.annotation.NonNull import com.kickstarter.R import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.libs.utils.NumberUtils import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.ProgressBarUtils import com.kickstarter.libs.utils.extensions.ProjectMetadata import com.kickstarter.libs.utils.extensions.deadlineCountdownValue import com.kickstarter.libs.utils.extensions.isCompleted import com.kickstarter.libs.utils.extensions.metadataForProject import com.kickstarter.libs.utils.extensions.negate import com.kickstarter.models.Category import com.kickstarter.models.Project import com.kickstarter.models.User import com.kickstarter.models.extensions.replaceSmallImageWithMediumIfEmpty import com.kickstarter.services.DiscoveryParams import com.kickstarter.ui.data.Editorial import com.kickstarter.ui.viewholders.ProjectCardViewHolder import org.joda.time.DateTime import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject interface ProjectCardHolderViewModel { interface Inputs { /** Call to configure view model with a project and current discovery params. */ fun configureWith(projectAndDiscoveryParams: Pair<Project, DiscoveryParams>) /** Call when the project card has been clicked. */ fun projectCardClicked() /** Call when the heart button is clicked. */ fun heartButtonClicked() } interface Outputs { /** Emits the project's number of backers. */ fun backersCountTextViewText(): Observable<String> /** Emits to determine if backing view should be shown. */ fun backingViewGroupIsGone(): Observable<Boolean> /** Emits the a string representing how much time the project has remaining. */ fun deadlineCountdownText(): Observable<String> /** Emits to determine if featured view should be shown. */ fun featuredViewGroupIsGone(): Observable<Boolean> /** Emits list of friends who have also backed this project. */ fun friendsForNamepile(): Observable<List<User>> /** Emits to determine if second face in facepile should be shown. */ fun friendAvatar2IsGone(): Observable<Boolean> /** Emits to determine if third face in facepile should be shown. */ fun friendAvatar3IsGone(): Observable<Boolean> /** Emits URL string of first friend's avatar. */ fun friendAvatarUrl1(): Observable<String> /** Emits URL string of second friend's avatar. */ fun friendAvatarUrl2(): Observable<String> /** Emits URL string of third friend's avatar. */ fun friendAvatarUrl3(): Observable<String> /** Emits to determine if project has a photo to display. */ fun imageIsInvisible(): Observable<Boolean> /** Emits to determine if friends who have also backed should be shown. */ fun friendBackingViewIsHidden(): Observable<Boolean> /** Emits to determine if successful funding state should be shown. */ fun fundingSuccessfulViewGroupIsGone(): Observable<Boolean> /** Emits to determine if unsuccessful funding state should be shown. */ fun fundingUnsuccessfulViewGroupIsGone(): Observable<Boolean> /** Emits a Boolean determining if the project's location should be shown. */ fun locationContainerIsGone(): Observable<Boolean> /** Emits the displayable name of the location of the project. */ fun locationName(): Observable<String> /** Emits to determine if metadata container should be shown. */ fun metadataViewGroupIsGone(): Observable<Boolean> /** Emits background drawable resource ID of metadata container. */ fun metadataViewGroupBackgroundDrawable(): Observable<Int> /** Emits project to be used for calculating countdown. */ fun projectForDeadlineCountdownDetail(): Observable<Project> /** Emits percentage representing project funding. */ fun percentageFundedForProgressBar(): Observable<Int> /** Emits to determine if funded progress bar should be shown. */ fun percentageFundedProgressBarIsGone(): Observable<Boolean> /** Emits string representation of project funding percentage. */ fun percentageFundedTextViewText(): Observable<String> /** Emits URL string of project cover photo. */ fun photoUrl(): Observable<String> /** Emits project name and blurb. */ fun nameAndBlurbText(): Observable<Pair<String, String>> /** Emits when project card is clicked. */ fun notifyDelegateOfProjectClick(): Observable<Project> /** Emits time project was canceled. */ fun projectCanceledAt(): Observable<DateTime> /** Emits to determine if stats container should be shown. */ fun projectCardStatsViewGroupIsGone(): Observable<Boolean> /** Emits time project was unsuccessfully funded. */ fun projectFailedAt(): Observable<DateTime> /** Emits to determine if state container should be shown. */ fun projectStateViewGroupIsGone(): Observable<Boolean> /** Emits to determine if project (sub)category tag should be shown. */ fun projectSubcategoryIsGone(): Observable<Boolean> /** Emits project (sub)category. */ fun projectSubcategoryName(): Observable<String> /** Emits time project was successfully funded. */ fun projectSuccessfulAt(): Observable<DateTime> /** Emits time project was suspended. */ fun projectSuspendedAt(): Observable<DateTime> /** Emits to determine if project tags container should be shown. */ fun projectTagContainerIsGone(): Observable<Boolean> /** Emits to determine if project we love tag container should be shown. */ fun projectWeLoveIsGone(): Observable<Boolean> /** Emits project's root category. */ fun rootCategoryNameForFeatured(): Observable<String> /** Emits to determine if saved container should shown. */ fun savedViewGroupIsGone(): Observable<Boolean> /** Emits to determine if padding should be added to top of view. */ fun setDefaultTopPadding(): Observable<Boolean> /** Emits a drawable id that corresponds to whether the project is saved. */ fun heartDrawableId(): Observable<Int> /** Emits the current [Project] to Toggle save */ fun notifyDelegateOfHeartButtonClicked(): Observable<Project> } class ViewModel(environment: Environment) : ActivityViewModel<ProjectCardViewHolder?>(environment), Inputs, Outputs { private fun shouldShowLocationTag(params: DiscoveryParams): Boolean { return params.tagId() != null && params.tagId() == Editorial.LIGHTS_ON.tagId } private fun areParamsAllOrSameCategoryAsProject(categoryPair: Pair<Category?, Category>): Boolean { return ObjectUtils.isNotNull(categoryPair.first) && categoryPair.first?.id() == categoryPair.second.id() } private val heartButtonClicked = PublishSubject.create<Void>() private val discoveryParams = PublishSubject.create<DiscoveryParams?>() private val project = PublishSubject.create<Project?>() private val projectCardClicked = PublishSubject.create<Void?>() private val backersCountTextViewText: Observable<String> private val backingViewGroupIsGone: Observable<Boolean> private val deadlineCountdownText: Observable<String> private val featuredViewGroupIsGone: Observable<Boolean> private val friendAvatar2IsGone: Observable<Boolean> private val friendAvatar3IsGone: Observable<Boolean> private val friendAvatarUrl1: Observable<String> private val friendAvatarUrl2: Observable<String> private val friendAvatarUrl3: Observable<String> private val friendBackingViewIsHidden: Observable<Boolean> private val friendsForNamepile: Observable<List<User>> private val fundingSuccessfulViewGroupIsGone: Observable<Boolean> private val fundingUnsuccessfulViewGroupIsGone: Observable<Boolean> private val imageIsInvisible: Observable<Boolean> private val locationName = BehaviorSubject.create<String>() private val locationContainerIsGone = BehaviorSubject.create<Boolean>() private val metadataViewGroupBackground: Observable<Int> private val metadataViewGroupIsGone: Observable<Boolean> private val nameAndBlurbText: Observable<Pair<String, String>> private val notifyDelegateOfProjectClick: Observable<Project> private val percentageFundedForProgressBar: Observable<Int> private val percentageFundedProgressBarIsGone: Observable<Boolean> private val percentageFundedTextViewText: Observable<String> private val photoUrl: Observable<String> private val projectForDeadlineCountdownDetail: Observable<Project> private val projectCardStatsViewGroupIsGone: Observable<Boolean> private val projectStateViewGroupIsGone: Observable<Boolean> private val projectCanceledAt: Observable<DateTime> private val projectFailedAt: Observable<DateTime> private val projectSubcategoryName: Observable<String> private val projectSubcategoryIsGone: Observable<Boolean> private val projectSuccessfulAt: Observable<DateTime> private val projectSuspendedAt: Observable<DateTime> private val projectTagContainerIsGone: Observable<Boolean> private val projectWeLoveIsGone: Observable<Boolean> private val rootCategoryNameForFeatured: Observable<String> private val savedViewGroupIsGone: Observable<Boolean> private val setDefaultTopPadding: Observable<Boolean> private val heartDrawableId = BehaviorSubject.create<Int>() private val notifyDelegateOfHeartButtonClicked = BehaviorSubject.create<Project>() @JvmField val inputs: Inputs = this @JvmField val outputs: Outputs = this override fun configureWith(projectAndDiscoveryParams: Pair<Project, DiscoveryParams>) { project.onNext(projectAndDiscoveryParams.first) discoveryParams.onNext(projectAndDiscoveryParams.second) } override fun heartButtonClicked() { this.heartButtonClicked.onNext(null) } override fun projectCardClicked() { projectCardClicked.onNext(null) } @NonNull override fun heartDrawableId(): Observable<Int> = this.heartDrawableId override fun backersCountTextViewText(): Observable<String> = backersCountTextViewText override fun backingViewGroupIsGone(): Observable<Boolean> = backingViewGroupIsGone override fun deadlineCountdownText(): Observable<String> = deadlineCountdownText override fun featuredViewGroupIsGone(): Observable<Boolean> = featuredViewGroupIsGone override fun friendAvatar2IsGone(): Observable<Boolean> = friendAvatar2IsGone override fun friendAvatar3IsGone(): Observable<Boolean> = friendAvatar3IsGone override fun friendAvatarUrl1(): Observable<String> = friendAvatarUrl1 override fun friendAvatarUrl2(): Observable<String> = friendAvatarUrl2 override fun friendAvatarUrl3(): Observable<String> = friendAvatarUrl3 override fun friendBackingViewIsHidden(): Observable<Boolean> = friendBackingViewIsHidden override fun friendsForNamepile(): Observable<List<User>> = friendsForNamepile override fun fundingSuccessfulViewGroupIsGone(): Observable<Boolean> = fundingSuccessfulViewGroupIsGone override fun fundingUnsuccessfulViewGroupIsGone(): Observable<Boolean> = fundingUnsuccessfulViewGroupIsGone override fun imageIsInvisible(): Observable<Boolean> = imageIsInvisible override fun locationContainerIsGone(): Observable<Boolean> = locationContainerIsGone override fun locationName(): Observable<String> = locationName override fun metadataViewGroupBackgroundDrawable(): Observable<Int> = metadataViewGroupBackground override fun metadataViewGroupIsGone(): Observable<Boolean> = metadataViewGroupIsGone override fun nameAndBlurbText(): Observable<Pair<String, String>> = nameAndBlurbText override fun notifyDelegateOfProjectClick(): Observable<Project> = notifyDelegateOfProjectClick override fun percentageFundedForProgressBar(): Observable<Int> = percentageFundedForProgressBar override fun percentageFundedProgressBarIsGone(): Observable<Boolean> = percentageFundedProgressBarIsGone override fun percentageFundedTextViewText(): Observable<String> = percentageFundedTextViewText override fun photoUrl(): Observable<String> = photoUrl override fun projectCardStatsViewGroupIsGone(): Observable<Boolean> = projectCardStatsViewGroupIsGone override fun projectForDeadlineCountdownDetail(): Observable<Project> = projectForDeadlineCountdownDetail override fun projectStateViewGroupIsGone(): Observable<Boolean> = projectStateViewGroupIsGone override fun projectSubcategoryIsGone(): Observable<Boolean> = projectSubcategoryIsGone override fun projectSubcategoryName(): Observable<String> = projectSubcategoryName override fun projectCanceledAt(): Observable<DateTime> = projectCanceledAt override fun projectFailedAt(): Observable<DateTime> = projectFailedAt override fun projectSuccessfulAt(): Observable<DateTime> = projectSuccessfulAt override fun projectSuspendedAt(): Observable<DateTime> = projectSuspendedAt override fun projectTagContainerIsGone(): Observable<Boolean> = projectTagContainerIsGone override fun projectWeLoveIsGone(): Observable<Boolean> = projectWeLoveIsGone override fun rootCategoryNameForFeatured(): Observable<String> = rootCategoryNameForFeatured override fun setDefaultTopPadding(): Observable<Boolean> = setDefaultTopPadding override fun savedViewGroupIsGone(): Observable<Boolean> = savedViewGroupIsGone override fun notifyDelegateOfHeartButtonClicked(): Observable<Project> = this.notifyDelegateOfHeartButtonClicked init { projectForDeadlineCountdownDetail = project backersCountTextViewText = project .map { it?.backersCount() } .map { value -> value?.let { it -> NumberUtils.format( it ) } } backingViewGroupIsGone = project .map { it?.metadataForProject() !== ProjectMetadata.BACKING } deadlineCountdownText = project .map { it.deadlineCountdownValue() } .map { NumberUtils.format(it) } project .map { p -> if (p.isStarred()) R.drawable.icon__heart else R.drawable.icon__heart_outline } .subscribe(this.heartDrawableId) project .compose(Transformers.takeWhen(heartButtonClicked)) .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .compose(bindToLifecycle()) .subscribe { notifyDelegateOfHeartButtonClicked.onNext(it) } featuredViewGroupIsGone = project .map { it?.metadataForProject() !== ProjectMetadata.CATEGORY_FEATURED } friendAvatarUrl1 = project .filter(Project::isFriendBacking) .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } .map { it[0].avatar().replaceSmallImageWithMediumIfEmpty() } .filter { it.isNotEmpty() } friendAvatarUrl2 = project .filter(Project::isFriendBacking) .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } .filter { it.size > 1 } .map { it[1].avatar().replaceSmallImageWithMediumIfEmpty() } .filter { it.isNotEmpty() } friendAvatarUrl3 = project .filter(Project::isFriendBacking) .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } .filter { it.size > 2 } .map { it[2].avatar().replaceSmallImageWithMediumIfEmpty() } .filter { it.isNotEmpty() } friendAvatar2IsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } .map { it != null && it.size > 1 } .map { it.negate() } friendAvatar3IsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } .map { it != null && it.size > 2 } .map { it.negate() } friendBackingViewIsHidden = project .map(Project::isFriendBacking) .map { it.negate() } friendsForNamepile = project .filter(Project::isFriendBacking) .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.friends() } fundingUnsuccessfulViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { ( it.state() != Project.STATE_CANCELED && it.state() != Project.STATE_FAILED && it.state() != Project.STATE_SUSPENDED ) } fundingSuccessfulViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.state() != Project.STATE_SUCCESSFUL } imageIsInvisible = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.photo() } .map { ObjectUtils.isNull(it) } project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.location() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.displayableName() } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe { locationName.onNext(it) } discoveryParams .map { shouldShowLocationTag(it) } .compose(Transformers.combineLatestPair(project)) .map { distanceSortAndProject: Pair<Boolean, Project>? -> distanceSortAndProject?.first == true && ObjectUtils.isNotNull( distanceSortAndProject.second.location() ) } .map { it.negate() } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe { locationContainerIsGone.onNext(it) } metadataViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.metadataForProject() == null } metadataViewGroupBackground = backingViewGroupIsGone .map { gone: Boolean -> if (gone) R.drawable.rect_white_grey_stroke else R.drawable.rect_green_grey_stroke } nameAndBlurbText = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { Pair.create( it.name(), it.blurb() ) } notifyDelegateOfProjectClick = project .compose(Transformers.takeWhen(projectCardClicked)) percentageFundedForProgressBar = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { if (it.state() == Project.STATE_LIVE || it.state() == Project.STATE_SUCCESSFUL) it.percentageFunded() else 0.0f }.map { ProgressBarUtils.progress(it) } percentageFundedProgressBarIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.state() == Project.STATE_CANCELED } percentageFundedTextViewText = project .map { it.percentageFunded() } .map { NumberUtils.flooredPercentage(it) } photoUrl = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { if (it.photo() == null) null else it.photo()?.full() } projectCanceledAt = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .filter { it.state() == Project.STATE_CANCELED } .map { it.stateChangedAt() } .compose(Transformers.coalesce(DateTime())) projectCardStatsViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.state() != Project.STATE_LIVE } projectFailedAt = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .filter { it.state() == Project.STATE_FAILED } .map { it.stateChangedAt() } .compose(Transformers.coalesce(DateTime())) projectStateViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.isCompleted() } .map { it.negate() } val projectCategory = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.category() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } projectSubcategoryIsGone = discoveryParams .map { it.category() } .compose(Transformers.combineLatestPair(projectCategory)) .map { areParamsAllOrSameCategoryAsProject(it) }.distinctUntilChanged() projectSubcategoryName = projectCategory .map { it.name() } projectSuccessfulAt = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .filter { it.state() == Project.STATE_SUCCESSFUL } .map { it.stateChangedAt() } .compose(Transformers.coalesce(DateTime())) projectSuspendedAt = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .filter { it.state() == Project.STATE_SUSPENDED } .map { it.stateChangedAt() } .compose(Transformers.coalesce(DateTime())) projectWeLoveIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.staffPick() } .compose(Transformers.coalesce(false)) .compose( Transformers.combineLatestPair( discoveryParams.map { it.staffPicks() } .compose(Transformers.coalesce(false)) ) ) .map { it.first == true && it.second == false } .map { it.negate() } .distinctUntilChanged() projectTagContainerIsGone = Observable.combineLatest<Boolean, Boolean, Pair<Boolean, Boolean>>( projectSubcategoryIsGone, projectWeLoveIsGone ) { a: Boolean?, b: Boolean? -> Pair.create(a, b) } .map { it.first && it.second } .distinctUntilChanged() rootCategoryNameForFeatured = projectCategory .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.root() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.name() } savedViewGroupIsGone = project .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { it.metadataForProject() !== ProjectMetadata.SAVING } setDefaultTopPadding = metadataViewGroupIsGone } } }
apache-2.0
Flank/flank
tool/shard/dump/src/main/kotlin/flank/shard/Dump.kt
1
333
package flank.shard import flank.shard.mapper.prettyGson import java.io.Writer /** * Dump shards as json formatted string. * * @receiver List of shards to dump. * @param writer Writer that will receive formatted json. */ infix fun Shards.dumpTo( writer: Writer ) { prettyGson.toJson(this, writer) writer.flush() }
apache-2.0
mdaniel/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inline/inlineVariableOrProperty/explicateTypeArgument/InStringTemplate.kt
13
61
fun f() { val v : List<Int> = listOf() "$<caret>v" }
apache-2.0
mdaniel/intellij-community
plugins/kotlin/code-insight/inspections-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/inspections/diagnosticBased/UnusedVariableInspection.kt
1
1957
// 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.k2.codeinsight.inspections.diagnosticBased import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicators.* import org.jetbrains.kotlin.idea.codeinsight.utils.isExplicitTypeReferenceNeededForTypeInference import org.jetbrains.kotlin.idea.codeinsight.utils.removeProperty import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtProperty import kotlin.reflect.KClass internal class UnusedVariableInspection : AbstractKotlinDiagnosticBasedInspection<KtNamedDeclaration, KtFirDiagnostic.UnusedVariable, KotlinApplicatorInput.Empty>( elementType = KtNamedDeclaration::class, ) { override fun getDiagnosticType() = KtFirDiagnostic.UnusedVariable::class override fun getInputByDiagnosticProvider() = inputByDiagnosticProvider<_, KtFirDiagnostic.UnusedVariable, _> { diagnostic -> val ktProperty = diagnostic.psi as? KtProperty ?: return@inputByDiagnosticProvider null if (ktProperty.isExplicitTypeReferenceNeededForTypeInference()) return@inputByDiagnosticProvider null KotlinApplicatorInput } override fun getApplicabilityRange() = ApplicabilityRanges.DECLARATION_NAME override fun getApplicator() = applicator<KtNamedDeclaration, KotlinApplicatorInput.Empty> { familyName(KotlinBundle.lazyMessage("remove.element")) actionName { psi, _ -> KotlinBundle.message("remove.variable.0", psi.name.toString()) } applyTo { psi, _ -> removeProperty(psi as KtProperty) } } }
apache-2.0
mdaniel/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/classBodyDeclarations/class/classWithoutBody1.kt
13
128
// MOVE: down // class A <caret>class A // class D class D { } // class C class C { } // SET_FALSE: KEEP_FIRST_COLUMN_COMMENT
apache-2.0
bitsydarel/DBWeather
dbweatherweather/src/main/java/com/dbeginc/dbweatherweather/viewmodels/WeatherMapper.kt
1
6421
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweatherweather.viewmodels import com.dbeginc.dbweathercommon.utils.round import com.dbeginc.dbweatherdomain.entities.weather.* import com.dbeginc.dbweatherweather.R import org.threeten.bp.Instant import org.threeten.bp.ZoneId import org.threeten.bp.format.DateTimeFormatter import java.util.* /** * Created by darel on 18.09.17. * * Weather ViewModel Mapper */ fun Weather.toUi(): WeatherModel { val unit = if (flags.units == "us") "F" else "C" val currentDayName = Calendar.getInstance().getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault()) val today = daily.data.mapIndexed { index, day -> index to day } .first { (_, day) -> day.time.dayOfWeek(timezone) == currentDayName } .second return WeatherModel( location = location.toUi(), current = currently.toUi( location = location.name, timeZone = timezone, unit = unit, sunrise = today.sunriseTime, sunset = today.sunsetTime ), hourly = hourly.data.map { hour -> hour.toUi(unit, timezone) }, daily = daily.data.map { day -> day.toUi( dayName = day.time.dayOfWeek(timezone), timeZone = timezone, unit = unit ) }, alerts = alerts?.map { alert -> alert.toUi(timezone) } ) } fun Currently.toUi(location: String, sunrise: Long, sunset: Long, unit: String, timeZone: String?): CurrentWeatherModel { return CurrentWeatherModel( location = location, temperature = temperature.round(), apparentTemperature = apparentTemperature?.round() ?: 0, icon = icon.getId(), summary = summary, time = time, windSpeed = windSpeed.toMps(), humidity = humidity.toPercent(), cloudCover = cloudCover.toPercent(), precipitationProbability = precipProbability.toPercent(), sunrise = sunrise.toFormattedTime(timeZone), sunset = sunset.toFormattedTime(timeZone), temperatureUnit = unit ) } fun DailyData.toUi(dayName: String, timeZone: String?, unit: String): DayWeatherModel { return DayWeatherModel( dayName = dayName, time = time, summary = summary, icon = icon.getId(), temperatureUnit = unit, temperatureHigh = temperatureHigh.round(), temperatureHighTime = temperatureHighTime, temperatureLow = temperatureLow.round(), temperatureLowTime = temperatureLowTime, apparentTemperatureHigh = apparentTemperatureHigh.round(), apparentTemperatureLow = apparentTemperatureLow.round(), dewPoint = dewPoint, humidity = humidity.toPercent(), pressure = pressure, windSpeed = windSpeed.toPercent(), windGust = windGust, windGustTime = windGustTime, windBearing = windBearing, moonPhase = moonPhase, uvIndex = uvIndex, uvIndexTime = uvIndexTime, sunsetTime = sunsetTime.toFormattedTime(timeZone), sunriseTime = sunriseTime.toFormattedTime(timeZone), precipIntensity = precipIntensity, precipIntensityMax = precipIntensityMax, precipProbability = precipProbability, precipType = precipType ) } fun HourlyData.toUi(unit: String, timeZone: String?): HourWeatherModel { return HourWeatherModel( hourlyTime = time.toHour(timeZone), time = time, icon = icon.getId(), temperature = temperature.round(), temperatureUnit = unit ) } fun Alert.toUi(timeZone: String?): AlertWeatherModel { return AlertWeatherModel( time = time.toFormattedTime(timeZone), title = title, description = description, uri = uri, expires = expires.toFormattedTime(timeZone), severity = severity, regions = regions ) } fun Location.toUi(): WeatherLocationModel { return WeatherLocationModel( name = name, latitude = latitude, longitude = longitude, countryName = countryName, countryCode = countryCode ) } fun Long.dayOfWeek(timeZone: String?): String { val format = DateTimeFormatter.ofPattern("EEEE") return Instant.ofEpochSecond(this) .atZone(ZoneId.of(timeZone ?: TimeZone.getDefault().id)) .format(format) } fun Long.toHour(timeZone: String?) : String { val format = DateTimeFormatter.ofPattern("h a") return Instant.ofEpochSecond(this) .atZone(ZoneId.of(timeZone ?: TimeZone.getDefault().id)) .format(format) } fun Double.toMps() : String = "%d mps".format(this.round()) fun Double.toPercent() : String = "%d%%".format(this.round()) fun Long.toFormattedTime(timeZone: String?) : String { val format = DateTimeFormatter.ofPattern("h:mm a") return Instant.ofEpochSecond(this) .atZone(ZoneId.of(timeZone ?: TimeZone.getDefault().id)) .format(format) } fun String.getId(): Int { return when (this) { "clear-night" -> R.drawable.clear_night "rain" -> R.drawable.rain "snow" -> R.drawable.snow "sleet" -> R.drawable.sleet "wind" -> R.drawable.wind "fog" -> R.drawable.fog "cloudy" -> R.drawable.cloudy "partly-cloudy-day" -> R.drawable.partly_cloudy "partly-cloudy-night" -> R.drawable.cloudy_night else -> R.drawable.clear_day } }
gpl-3.0
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueFragment.kt
1
15739
package eu.kanade.tachiyomi.ui.catalogue import android.content.res.Configuration import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.SearchView import android.support.v7.widget.Toolbar import android.view.* import android.view.animation.AnimationUtils import android.widget.ArrayAdapter import android.widget.ProgressBar import android.widget.Spinner import com.afollestad.materialdialogs.MaterialDialog import com.f2prateek.rx.preferences.Preference import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.source.online.LoginSource import eu.kanade.tachiyomi.ui.base.adapter.FlexibleViewHolder import eu.kanade.tachiyomi.ui.base.fragment.BaseRxFragment import eu.kanade.tachiyomi.ui.main.MainActivity import eu.kanade.tachiyomi.ui.manga.MangaActivity import eu.kanade.tachiyomi.util.getResourceDrawable import eu.kanade.tachiyomi.util.snack import eu.kanade.tachiyomi.util.toast import eu.kanade.tachiyomi.widget.DividerItemDecoration import eu.kanade.tachiyomi.widget.EndlessScrollListener import eu.kanade.tachiyomi.widget.IgnoreFirstSpinnerListener import kotlinx.android.synthetic.main.fragment_catalogue.* import kotlinx.android.synthetic.main.toolbar.* import nucleus.factory.RequiresPresenter import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.subjects.PublishSubject import timber.log.Timber import java.util.concurrent.TimeUnit.MILLISECONDS /** * Fragment that shows the manga from the catalogue. * Uses R.layout.fragment_catalogue. */ @RequiresPresenter(CataloguePresenter::class) open class CatalogueFragment : BaseRxFragment<CataloguePresenter>(), FlexibleViewHolder.OnListItemClickListener { /** * Spinner shown in the toolbar to change the selected source. */ private var spinner: Spinner? = null /** * Adapter containing the list of manga from the catalogue. */ private lateinit var adapter: CatalogueAdapter /** * Scroll listener for grid mode. It loads next pages when the end of the list is reached. */ private lateinit var gridScrollListener: EndlessScrollListener /** * Scroll listener for list mode. It loads next pages when the end of the list is reached. */ private lateinit var listScrollListener: EndlessScrollListener /** * Query of the search box. */ private val query: String get() = presenter.query /** * Selected index of the spinner (selected source). */ private var selectedIndex: Int = 0 /** * Time in milliseconds to wait for input events in the search query before doing network calls. */ private val SEARCH_TIMEOUT = 1000L /** * Subject to debounce the query. */ private val queryDebouncerSubject = PublishSubject.create<String>() /** * Subscription of the debouncer subject. */ private var queryDebouncerSubscription: Subscription? = null /** * Subscription of the number of manga per row. */ private var numColumnsSubscription: Subscription? = null /** * Search item. */ private var searchItem: MenuItem? = null /** * Property to get the toolbar from the containing activity. */ private val toolbar: Toolbar get() = (activity as MainActivity).toolbar companion object { /** * Creates a new instance of this fragment. * * @return a new instance of [CatalogueFragment]. */ fun newInstance(): CatalogueFragment { return CatalogueFragment() } } override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View? { return inflater.inflate(R.layout.fragment_catalogue, container, false) } override fun onViewCreated(view: View, savedState: Bundle?) { // If the source list is empty or it only has unlogged sources, return to main screen. val sources = presenter.sources if (sources.isEmpty() || sources.all { it is LoginSource && !it.isLogged() }) { context.toast(R.string.no_valid_sources) activity.onBackPressed() return } // Initialize adapter, scroll listener and recycler views adapter = CatalogueAdapter(this) val glm = catalogue_grid.layoutManager as GridLayoutManager gridScrollListener = EndlessScrollListener(glm, { requestNextPage() }) catalogue_grid.setHasFixedSize(true) catalogue_grid.adapter = adapter catalogue_grid.addOnScrollListener(gridScrollListener) val llm = LinearLayoutManager(activity) listScrollListener = EndlessScrollListener(llm, { requestNextPage() }) catalogue_list.setHasFixedSize(true) catalogue_list.adapter = adapter catalogue_list.layoutManager = llm catalogue_list.addOnScrollListener(listScrollListener) catalogue_list.addItemDecoration( DividerItemDecoration(context.theme.getResourceDrawable(R.attr.divider_drawable))) if (presenter.isListMode) { switcher.showNext() } numColumnsSubscription = getColumnsPreferenceForCurrentOrientation().asObservable() .doOnNext { catalogue_grid.spanCount = it } .skip(1) // Set again the adapter to recalculate the covers height .subscribe { catalogue_grid.adapter = adapter } switcher.inAnimation = AnimationUtils.loadAnimation(activity, android.R.anim.fade_in) switcher.outAnimation = AnimationUtils.loadAnimation(activity, android.R.anim.fade_out) // Create toolbar spinner val themedContext = activity.supportActionBar?.themedContext ?: activity val spinnerAdapter = ArrayAdapter(themedContext, android.R.layout.simple_spinner_item, presenter.sources) spinnerAdapter.setDropDownViewResource(R.layout.spinner_item) val onItemSelected = IgnoreFirstSpinnerListener { position -> val source = spinnerAdapter.getItem(position) if (!presenter.isValidSource(source)) { spinner?.setSelection(selectedIndex) context.toast(R.string.source_requires_login) } else if (source != presenter.source) { selectedIndex = position showProgressBar() glm.scrollToPositionWithOffset(0, 0) llm.scrollToPositionWithOffset(0, 0) presenter.setActiveSource(source) activity.invalidateOptionsMenu() } } selectedIndex = presenter.sources.indexOf(presenter.source) spinner = Spinner(themedContext).apply { adapter = spinnerAdapter setSelection(selectedIndex) onItemSelectedListener = onItemSelected } setToolbarTitle("") toolbar.addView(spinner) showProgressBar() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.catalogue_list, menu) // Initialize search menu searchItem = menu.findItem(R.id.action_search).apply { val searchView = actionView as SearchView if (!query.isBlank()) { expandActionView() searchView.setQuery(query, true) searchView.clearFocus() } searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { onSearchEvent(query, true) return true } override fun onQueryTextChange(newText: String): Boolean { onSearchEvent(newText, false) return true } }) } // Setup filters button menu.findItem(R.id.action_set_filter).apply { if (presenter.source.filters.isEmpty()) { isEnabled = false icon.alpha = 128 } else { isEnabled = true icon.alpha = 255 } } // Show next display mode menu.findItem(R.id.action_display_mode).apply { val icon = if (presenter.isListMode) R.drawable.ic_view_module_white_24dp else R.drawable.ic_view_list_white_24dp setIcon(icon) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_display_mode -> swapDisplayMode() R.id.action_set_filter -> showFiltersDialog() else -> return super.onOptionsItemSelected(item) } return true } override fun onResume() { super.onResume() queryDebouncerSubscription = queryDebouncerSubject.debounce(SEARCH_TIMEOUT, MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe { searchWithQuery(it) } } override fun onPause() { queryDebouncerSubscription?.unsubscribe() super.onPause() } override fun onDestroyView() { numColumnsSubscription?.unsubscribe() searchItem?.let { if (it.isActionViewExpanded) it.collapseActionView() } spinner?.let { toolbar.removeView(it) } super.onDestroyView() } /** * Called when the input text changes or is submitted. * * @param query the new query. * @param now whether to send the network call now or debounce it by [SEARCH_TIMEOUT]. */ private fun onSearchEvent(query: String, now: Boolean) { if (now) { searchWithQuery(query) } else { queryDebouncerSubject.onNext(query) } } /** * Restarts the request with a new query. * * @param newQuery the new query. */ private fun searchWithQuery(newQuery: String) { // If text didn't change, do nothing if (query == newQuery) return showProgressBar() catalogue_grid.layoutManager.scrollToPosition(0) catalogue_list.layoutManager.scrollToPosition(0) presenter.restartPager(newQuery) } /** * Requests the next page (if available). Called from scroll listeners when they reach the end. */ private fun requestNextPage() { if (presenter.hasNextPage()) { showGridProgressBar() presenter.requestNext() } } /** * Called from the presenter when the network request is received. * * @param page the current page. * @param mangas the list of manga of the page. */ fun onAddPage(page: Int, mangas: List<Manga>) { hideProgressBar() if (page == 1) { adapter.clear() gridScrollListener.resetScroll() listScrollListener.resetScroll() } adapter.addItems(mangas) } /** * Called from the presenter when the network request fails. * * @param error the error received. */ fun onAddPageError(error: Throwable) { hideProgressBar() Timber.e(error) catalogue_view.snack(error.message ?: "", Snackbar.LENGTH_INDEFINITE) { setAction(R.string.action_retry) { showProgressBar() presenter.requestNext() } } } /** * Called from the presenter when a manga is initialized. * * @param manga the manga initialized */ fun onMangaInitialized(manga: Manga) { getHolder(manga)?.setImage(manga) } /** * Swaps the current display mode. */ fun swapDisplayMode() { presenter.swapDisplayMode() val isListMode = presenter.isListMode activity.invalidateOptionsMenu() switcher.showNext() if (!isListMode) { // Initialize mangas if going to grid view presenter.initializeMangas(adapter.items) } } /** * Returns a preference for the number of manga per row based on the current orientation. * * @return the preference. */ fun getColumnsPreferenceForCurrentOrientation(): Preference<Int> { return if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) presenter.prefs.portraitColumns() else presenter.prefs.landscapeColumns() } /** * Returns the view holder for the given manga. * * @param manga the manga to find. * @return the holder of the manga or null if it's not bound. */ private fun getHolder(manga: Manga): CatalogueGridHolder? { return catalogue_grid.findViewHolderForItemId(manga.id!!) as? CatalogueGridHolder } /** * Shows the progress bar. */ private fun showProgressBar() { progress.visibility = ProgressBar.VISIBLE } /** * Shows the progress bar at the end of the screen. */ private fun showGridProgressBar() { progress_grid.visibility = ProgressBar.VISIBLE } /** * Hides active progress bars. */ private fun hideProgressBar() { progress.visibility = ProgressBar.GONE progress_grid.visibility = ProgressBar.GONE } /** * Called when a manga is clicked. * * @param position the position of the element clicked. * @return true if the item should be selected, false otherwise. */ override fun onListItemClick(position: Int): Boolean { val item = adapter.getItem(position) ?: return false val intent = MangaActivity.newIntent(activity, item, true) startActivity(intent) return false } /** * Called when a manga is long clicked. * * @param position the position of the element clicked. */ override fun onListItemLongClick(position: Int) { val manga = adapter.getItem(position) ?: return val textRes = if (manga.favorite) R.string.remove_from_library else R.string.add_to_library MaterialDialog.Builder(activity) .items(getString(textRes)) .itemsCallback { dialog, itemView, which, text -> when (which) { 0 -> { presenter.changeMangaFavorite(manga) adapter.notifyItemChanged(position) } } }.show() } /** * Show the filter dialog for the source. */ private fun showFiltersDialog() { val allFilters = presenter.source.filters val selectedFilters = presenter.filters .map { filter -> allFilters.indexOf(filter) } .toTypedArray() MaterialDialog.Builder(context) .title(R.string.action_set_filter) .items(allFilters.map { it.name }) .itemsCallbackMultiChoice(selectedFilters) { dialog, positions, text -> val newFilters = positions.map { allFilters[it] } showProgressBar() presenter.setSourceFilter(newFilters) true } .positiveText(android.R.string.ok) .negativeText(android.R.string.cancel) .show() } }
gpl-3.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/indexOf/indexOfFirst_mustBeNoIndexInCondition.kt
4
260
// WITH_RUNTIME // IS_APPLICABLE: false // IS_APPLICABLE_2: false fun foo(list: List<String>) { var result = -1 <caret>for ((index, s) in list.withIndex()) { if (s.length > index) { result = index break } } }
apache-2.0
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapter.kt
2
575
package eu.kanade.tachiyomi.ui.recent_updates import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.MangaChapter import eu.kanade.tachiyomi.data.download.model.Download class RecentChapter(mc: MangaChapter) : Chapter by mc.chapter { val manga = mc.manga private var _status: Int = 0 var status: Int get() = download?.status ?: _status set(value) { _status = value } @Transient var download: Download? = null val isDownloaded: Boolean get() = status == Download.DOWNLOADED }
gpl-3.0
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/notifications/NotificationsApi.kt
1
687
package io.github.feelfreelinux.wykopmobilny.api.notifications import io.github.feelfreelinux.wykopmobilny.models.dataclass.Notification import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.NotificationsCountResponse import io.reactivex.Single interface NotificationsApi { fun getNotificationCount(): Single<NotificationsCountResponse> fun getHashTagNotificationCount(): Single<NotificationsCountResponse> fun getHashTagNotifications(page: Int): Single<List<Notification>> fun getNotifications(page: Int): Single<List<Notification>> fun readNotifications(): Single<List<Notification>> fun readHashTagNotifications(): Single<List<Notification>> }
mit
idea4bsd/idea4bsd
platform/lang-impl/src/com/intellij/reporting/ReportExcessiveInlineHint.kt
2
4679
/* * 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 com.intellij.reporting import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager 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.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import java.io.File class ReportExcessiveInlineHint : AnAction() { private val text = "Report Excessive Inline Hint" private val description = "Text line at caret will be anonymously reported to our servers" companion object { private val LOG = Logger.getInstance(ReportExcessiveInlineHint::class.java) } init { val presentation = templatePresentation presentation.text = text presentation.description = description } private val recorderId = "inline-hints-reports" private val file = File(PathManager.getTempPath(), recorderId) override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = false if (!isHintsEnabled()) return CommonDataKeys.PROJECT.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val range = getCurrentLineRange(editor) if (editor.getInlays(range).isNotEmpty()) { e.presentation.isEnabledAndVisible = true } } override fun actionPerformed(e: AnActionEvent) { val project = CommonDataKeys.PROJECT.getData(e.dataContext)!! val editor = CommonDataKeys.EDITOR.getData(e.dataContext)!! val document = editor.document val range = getCurrentLineRange(editor) val inlays = editor.getInlays(range) if (inlays.isNotEmpty()) { val line = document.getText(range) reportInlays(line.trim(), inlays) showHint(project) } } private fun reportInlays(text: String, inlays: List<Inlay>) { val hintManager = ParameterHintsPresentationManager.getInstance() val hints = inlays.mapNotNull { hintManager.getHintText(it) } trySend(text, hints) } private fun trySend(text: String, inlays: List<String>) { val report = InlayReport(text, inlays) writeToFile(createReportLine(recorderId, report)) trySendFileInBackground() } private fun trySendFileInBackground() { LOG.debug("File: ${file.path} Length: ${file.length()}") if (!file.exists() || file.length() == 0L) return ApplicationManager.getApplication().executeOnPooledThread { val text = file.readText() LOG.debug("File text $text") if (StatsSender.send(text, compress = false)) { file.delete() LOG.debug("File deleted") } } } private fun showHint(project: Project) { val notification = Notification( "Inline Hints", "Inline Hints Reporting", "Problematic inline hint was reported", NotificationType.INFORMATION ) notification.notify(project) } private fun writeToFile(line: String) { if (!file.exists()) { file.createNewFile() } file.appendText(line) } private fun getCurrentLineRange(editor: Editor): TextRange { val offset = editor.caretModel.currentCaret.offset val document = editor.document val line = document.getLineNumber(offset) return TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line)) } } private fun isHintsEnabled() = EditorSettingsExternalizable.getInstance().isShowParameterNameHints private fun Editor.getInlays(range: TextRange): List<Inlay> { return inlayModel.getInlineElementsInRange(range.startOffset, range.endOffset) } private class InlayReport(@JvmField var text: String, @JvmField var inlays: List<String>)
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/formatter/WhenEntry.kt
2
629
fun a() { when { true && true -> { } false -> { } else -> { } } } fun b() { val sealed: Sealed = Sealed.Foo() when (val a = sealed) { is Sealed.Foo -> println("Foo") is Sealed.A -> println("A") Sealed.A() -> print(1) else -> { } } } fun c() { val sealed: Sealed = Sealed.Foo() when (sealed) { is Sealed.Foo -> println("Foo") is Sealed.A -> println("A") Sealed.A() -> print(1) else -> { } } } // SET_TRUE: ALIGN_IN_COLUMNS_CASE_BRANCH
apache-2.0
vovagrechka/fucking-everything
alraune/alkjs/src/alraune/alkjs-2.kt
1
1087
package alraune import org.w3c.dom.HTMLElement import vgrechka.* import kotlin.browser.document import kotlin.coroutines.experimental.* import kotlin.js.Promise class ResolvablePromise<T> { var resolve by notNullOnce<(T) -> Unit>() var reject by notNullOnce<(Throwable) -> Unit>() val promise = Promise<T> {resolve, reject -> this.resolve = resolve this.reject = reject } } suspend fun <T> await(p: Promise<T>): T = suspendCoroutine {cont-> p.then({cont.resume(it)}, {cont.resumeWithException(it)}) } fun <T> async(block: suspend () -> T): Promise<T> { val rep = ResolvablePromise<T>() block.startCoroutine(object : Continuation<T> { override val context: CoroutineContext get() = EmptyCoroutineContext override fun resume(value: T) {rep.resolve(value)} override fun resumeWithException(exception: Throwable) {rep.reject(exception)} }) return rep.promise } fun elbyid(domid: String): HTMLElement = document.getElementById(domid) as HTMLElement? ?: bitch("I want element #$domid")
apache-2.0
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/create/CreateThinLvExecutor.kt
2
999
package com.github.kerubistan.kerub.planner.steps.storage.lvm.create import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LogicalVolume import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LvmLv class CreateThinLvExecutor( hostCommandExecutor: HostCommandExecutor, virtualDiskDynDao: VirtualStorageDeviceDynamicDao ) : AbstractCreateLvExecutor<CreateThinLv>(hostCommandExecutor, virtualDiskDynDao) { override fun perform(step: CreateThinLv): LogicalVolume = hostCommandExecutor.execute(step.host) { session -> LvmLv.create( session = session, vgName = step.volumeGroupName, size = step.disk.size, poolName = step.poolName, name = step.disk.id.toString() ) LvmLv.list(session = session, volName = step.disk.id.toString()) .single { it.name == step.disk.id.toString() } } }
apache-2.0
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/support/recycler/RecyclerItem.kt
1
206
package com.maubis.scarlet.base.support.recycler abstract class RecyclerItem { abstract val type: Type enum class Type { NOTE, EMPTY, FILE, FOLDER, INFORMATION, TOOLBAR } }
gpl-3.0
jwren/intellij-community
plugins/kotlin/compiler-plugins/parcelize/common/src/org/jetbrains/kotlin/idea/compilerPlugin/parcelize/quickfixes/ParcelizeAddIgnoreOnParcelAnnotationQuickFix.kt
4
968
// 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.compilerPlugin.parcelize.quickfixes import org.jetbrains.kotlin.idea.compilerPlugin.parcelize.KotlinParcelizeBundle import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory class ParcelizeAddIgnoreOnParcelAnnotationQuickFix(property: KtProperty) : AbstractParcelizeQuickFix<KtProperty>(property) { object Factory : AbstractFactory({ findElement<KtProperty>()?.let(::ParcelizeAddIgnoreOnParcelAnnotationQuickFix) }) override fun getText() = KotlinParcelizeBundle.message("parcelize.fix.add.ignored.on.parcel.annotation") override fun invoke(ktPsiFactory: KtPsiFactory, element: KtProperty) { element.addAnnotationEntry(ktPsiFactory.createAnnotationEntry("@kotlinx.parcelize.IgnoredOnParcel")).shortenReferences() } }
apache-2.0
jwren/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/VersionColumn.kt
2
2624
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns import com.intellij.util.ui.ColumnInfo import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.PackagesTableItem import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.editors.PackageVersionTableCellEditor import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers.PackageVersionTableCellRenderer import javax.swing.table.TableCellEditor import javax.swing.table.TableCellRenderer internal class VersionColumn( private val versionSetter: (uiPackageModel: UiPackageModel<*>, newVersion: NormalizedPackageVersion<*>) -> Unit ) : ColumnInfo<PackagesTableItem<*>, UiPackageModel<*>>( PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.columns.versions") ) { private val cellRenderer = PackageVersionTableCellRenderer() private val cellEditor = PackageVersionTableCellEditor() private var onlyStable: Boolean = false private var targetModules: TargetModules = TargetModules.None override fun getRenderer(item: PackagesTableItem<*>): TableCellRenderer = cellRenderer override fun getEditor(item: PackagesTableItem<*>): TableCellEditor = cellEditor override fun isCellEditable(item: PackagesTableItem<*>?) = item?.uiPackageModel?.sortedVersions?.isNotEmpty() ?: false fun updateData(onlyStable: Boolean, targetModules: TargetModules) { this.onlyStable = onlyStable this.targetModules = targetModules cellRenderer.updateData(onlyStable) cellEditor.updateData(onlyStable) } override fun valueOf(item: PackagesTableItem<*>): UiPackageModel<*> = when (item) { is PackagesTableItem.InstalledPackage -> item.uiPackageModel is PackagesTableItem.InstallablePackage -> item.uiPackageModel } override fun setValue(item: PackagesTableItem<*>?, value: UiPackageModel<*>?) { val selectedVersion = value?.selectedVersion if (selectedVersion == null) return if (selectedVersion == item?.uiPackageModel?.selectedVersion) return versionSetter(value, selectedVersion) } }
apache-2.0
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/yesod/hamlet/psi/Comment.kt
1
211
package org.jetbrains.yesod.hamlet.psi /** * @author Leyla H */ import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode class Comment(node: ASTNode) : ASTWrapperPsiElement(node)
apache-2.0
JetBrains/intellij-community
plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/KotlinMavenImporter.kt
1
25249
// 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.maven import com.intellij.notification.BrowseNotificationAction import com.intellij.notification.Notification import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.notificationGroup import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.util.PathUtil import org.jdom.Element import org.jdom.Text import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.idea.maven.execution.MavenRunner import org.jetbrains.idea.maven.importing.MavenImporter import org.jetbrains.idea.maven.importing.MavenRootModelAdapter import org.jetbrains.idea.maven.model.MavenPlugin import org.jetbrains.idea.maven.project.* import org.jetbrains.idea.maven.utils.resolved import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments import org.jetbrains.kotlin.compilerRunner.ArgumentUtils import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.extensions.ProjectExtensionDescriptor import org.jetbrains.kotlin.idea.base.codeInsight.tooling.tooling import org.jetbrains.kotlin.idea.base.platforms.detectLibraryKind import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.facet.* import org.jetbrains.kotlin.idea.framework.KotlinSdkType import org.jetbrains.kotlin.idea.maven.configuration.KotlinMavenConfigurator import org.jetbrains.kotlin.platform.IdePlatformKind import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind import org.jetbrains.kotlin.platform.impl.isCommon import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addIfNotNull import java.io.File import java.lang.ref.WeakReference import java.util.* interface MavenProjectImportHandler { companion object : ProjectExtensionDescriptor<MavenProjectImportHandler>( "org.jetbrains.kotlin.mavenProjectImportHandler", MavenProjectImportHandler::class.java ) operator fun invoke(facet: KotlinFacet, mavenProject: MavenProject) } class KotlinMavenImporter : MavenImporter(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ARTIFACT_ID) { companion object { const val KOTLIN_PLUGIN_GROUP_ID = "org.jetbrains.kotlin" const val KOTLIN_PLUGIN_ARTIFACT_ID = "kotlin-maven-plugin" const val KOTLIN_PLUGIN_SOURCE_DIRS_CONFIG = "sourceDirs" private val KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED = Key<Boolean>("KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED") private val KOTLIN_JPS_VERSION_ACCUMULATOR = Key<IdeKotlinVersion>("KOTLIN_JPS_VERSION_ACCUMULATOR") } override fun preProcess( module: Module, mavenProject: MavenProject, changes: MavenProjectChanges, modifiableModelsProvider: IdeModifiableModelsProvider ) { KotlinJpsPluginSettings.getInstance(module.project)?.dropExplicitVersion() module.project.putUserData(KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED, null) module.project.putUserData(KOTLIN_JPS_VERSION_ACCUMULATOR, null) } override fun process( modifiableModelsProvider: IdeModifiableModelsProvider, module: Module, rootModel: MavenRootModelAdapter, mavenModel: MavenProjectsTree, mavenProject: MavenProject, changes: MavenProjectChanges, mavenProjectToModuleName: MutableMap<MavenProject, String>, postTasks: MutableList<MavenProjectsProcessorTask> ) { if (changes.hasPluginsChanges()) { contributeSourceDirectories(mavenProject, module, rootModel) } val mavenPlugin = mavenProject.findKotlinMavenPlugin() ?: return val currentVersion = mavenPlugin.compilerVersion val accumulatorVersion = module.project.getUserData(KOTLIN_JPS_VERSION_ACCUMULATOR) module.project.putUserData(KOTLIN_JPS_VERSION_ACCUMULATOR, maxOf(accumulatorVersion ?: currentVersion, currentVersion)) } override fun postProcess( module: Module, mavenProject: MavenProject, changes: MavenProjectChanges, modifiableModelsProvider: IdeModifiableModelsProvider ) { super.postProcess(module, mavenProject, changes, modifiableModelsProvider) val project = module.project project.getUserData(KOTLIN_JPS_VERSION_ACCUMULATOR)?.let { version -> KotlinJpsPluginSettings.importKotlinJpsVersionFromExternalBuildSystem( project, version.rawVersion, isDelegatedToExtBuild = MavenRunner.getInstance(project).settings.isDelegateBuildToMaven ) project.putUserData(KOTLIN_JPS_VERSION_ACCUMULATOR, null) } if (changes.hasDependencyChanges()) { scheduleDownloadStdlibSources(mavenProject, module) val targetLibraryKind = detectPlatformByExecutions(mavenProject)?.tooling?.libraryKind if (targetLibraryKind != null) { modifiableModelsProvider.getModifiableRootModel(module).orderEntries().forEachLibrary { library -> if ((library as LibraryEx).kind == null) { val model = modifiableModelsProvider.getModifiableLibraryModel(library) as LibraryEx.ModifiableModelEx detectLibraryKind(library, project)?.let { model.kind = it } } true } } } configureFacet(mavenProject, modifiableModelsProvider, module) } private fun scheduleDownloadStdlibSources(mavenProject: MavenProject, module: Module) { // TODO: here we have to process all kotlin libraries but for now we only handle standard libraries val artifacts = mavenProject.dependencyArtifactIndex.data[KOTLIN_PLUGIN_GROUP_ID]?.values?.flatMap { it.filter { it.resolved() } } ?: emptyList() val libraryNames = mutableSetOf<String?>() OrderEnumerator.orderEntries(module).forEachLibrary { library -> val model = library.modifiableModel try { if (model.getFiles(OrderRootType.SOURCES).isEmpty()) { libraryNames.add(library.name) } } finally { Disposer.dispose(model) } true } val toBeDownloaded = artifacts.filter { it.libraryName in libraryNames } if (toBeDownloaded.isNotEmpty()) { MavenProjectsManager.getInstance(module.project) .scheduleArtifactsDownloading(listOf(mavenProject), toBeDownloaded, true, false, AsyncPromise()) } } private fun configureJSOutputPaths( mavenProject: MavenProject, modifiableRootModel: ModifiableRootModel, facetSettings: KotlinFacetSettings, mavenPlugin: MavenPlugin ) { fun parentPath(path: String): String = File(path).absoluteFile.parentFile.absolutePath val sharedOutputFile = mavenPlugin.configurationElement?.getChild("outputFile")?.text val compilerModuleExtension = modifiableRootModel.getModuleExtension(CompilerModuleExtension::class.java) ?: return val buildDirectory = mavenProject.buildDirectory val executions = mavenPlugin.executions executions.forEach { val explicitOutputFile = it.configurationElement?.getChild("outputFile")?.text ?: sharedOutputFile if (PomFile.KotlinGoals.Js in it.goals) { // see org.jetbrains.kotlin.maven.K2JSCompilerMojo val outputFilePath = PathUtil.toSystemDependentName(explicitOutputFile ?: "$buildDirectory/js/${mavenProject.mavenId.artifactId}.js") compilerModuleExtension.setCompilerOutputPath(parentPath(outputFilePath)) facetSettings.productionOutputPath = outputFilePath } if (PomFile.KotlinGoals.TestJs in it.goals) { // see org.jetbrains.kotlin.maven.KotlinTestJSCompilerMojo val outputFilePath = PathUtil.toSystemDependentName( explicitOutputFile ?: "$buildDirectory/test-js/${mavenProject.mavenId.artifactId}-tests.js" ) compilerModuleExtension.setCompilerOutputPathForTests(parentPath(outputFilePath)) facetSettings.testOutputPath = outputFilePath } } } private data class ImportedArguments(val args: List<String>, val jvmTarget6IsUsed: Boolean) private fun getCompilerArgumentsByConfigurationElement( mavenProject: MavenProject, configuration: Element?, platform: TargetPlatform, project: Project ): ImportedArguments { val arguments = platform.createArguments() var jvmTarget6IsUsed = false arguments.apiVersion = configuration?.getChild("apiVersion")?.text ?: mavenProject.properties["kotlin.compiler.apiVersion"]?.toString() arguments.languageVersion = configuration?.getChild("languageVersion")?.text ?: mavenProject.properties["kotlin.compiler.languageVersion"]?.toString() arguments.multiPlatform = configuration?.getChild("multiPlatform")?.text?.trim()?.toBoolean() ?: false arguments.suppressWarnings = configuration?.getChild("nowarn")?.text?.trim()?.toBoolean() ?: false when (arguments) { is K2JVMCompilerArguments -> { arguments.classpath = configuration?.getChild("classpath")?.text arguments.jdkHome = configuration?.getChild("jdkHome")?.text arguments.javaParameters = configuration?.getChild("javaParameters")?.text?.toBoolean() ?: false val jvmTarget = configuration?.getChild("jvmTarget")?.text ?: mavenProject.properties["kotlin.compiler.jvmTarget"]?.toString() if (jvmTarget == JvmTarget.JVM_1_6.description && KotlinJpsPluginSettings.getInstance(project)?.settings?.version?.isBlank() != false ) { // Load JVM target 1.6 in Maven projects as 1.8, for IDEA platforms <= 222. // The reason is that JVM target 1.6 is no longer supported by the latest Kotlin compiler, yet we'd like JPS projects imported from // Maven to be compilable by IDEA, to avoid breaking local development. // (Since IDEA 222, JPS plugin is unbundled from the Kotlin IDEA plugin, so this change is not needed there in case // when explicit version is specified in kotlinc.xml) arguments.jvmTarget = JvmTarget.JVM_1_8.description jvmTarget6IsUsed = true } else { arguments.jvmTarget = jvmTarget } } is K2JSCompilerArguments -> { arguments.sourceMap = configuration?.getChild("sourceMap")?.text?.trim()?.toBoolean() ?: false arguments.sourceMapPrefix = configuration?.getChild("sourceMapPrefix")?.text?.trim() ?: "" arguments.sourceMapEmbedSources = configuration?.getChild("sourceMapEmbedSources")?.text?.trim() ?: "inlining" arguments.outputFile = configuration?.getChild("outputFile")?.text arguments.metaInfo = configuration?.getChild("metaInfo")?.text?.trim()?.toBoolean() ?: false arguments.moduleKind = configuration?.getChild("moduleKind")?.text arguments.main = configuration?.getChild("main")?.text } } val additionalArgs = SmartList<String>().apply { val argsElement = configuration?.getChild("args") argsElement?.content?.forEach { argElement -> when (argElement) { is Text -> { argElement.text?.let { addAll(splitArgumentString(it)) } } is Element -> { if (argElement.name == "arg") { addIfNotNull(argElement.text) } } } } } parseCommandLineArguments(additionalArgs, arguments) return ImportedArguments(ArgumentUtils.convertArgumentsToStringList(arguments), jvmTarget6IsUsed) } private fun displayJvmTarget6UsageNotification(project: Project) { NotificationGroupManager.getInstance() .getNotificationGroup("Kotlin Maven project import") .createNotification( KotlinMavenBundle.message("configuration.maven.jvm.target.1.6.title"), KotlinMavenBundle.message("configuration.maven.jvm.target.1.6.content"), NotificationType.WARNING, ) .setImportant(true) .notify(project) } private val compilationGoals = listOf( PomFile.KotlinGoals.Compile, PomFile.KotlinGoals.TestCompile, PomFile.KotlinGoals.Js, PomFile.KotlinGoals.TestJs, PomFile.KotlinGoals.MetaData ) private val MavenPlugin.compilerVersion: IdeKotlinVersion get() = version?.let(IdeKotlinVersion::opt) ?: KotlinPluginLayout.standaloneCompilerVersion private fun MavenProject.findKotlinMavenPlugin(): MavenPlugin? = findPlugin( KotlinMavenConfigurator.GROUP_ID, KotlinMavenConfigurator.MAVEN_PLUGIN_ID, ) private var kotlinJsCompilerWarning = WeakReference<Notification>(null) private fun configureFacet(mavenProject: MavenProject, modifiableModelsProvider: IdeModifiableModelsProvider, module: Module) { val mavenPlugin = mavenProject.findKotlinMavenPlugin() ?: return val compilerVersion = mavenPlugin.compilerVersion val kotlinFacet = module.getOrCreateFacet( modifiableModelsProvider, false, ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID ) // TODO There should be a way to figure out the correct platform version val platform = detectPlatform(mavenProject)?.defaultPlatform kotlinFacet.configureFacet(compilerVersion, platform, modifiableModelsProvider) val facetSettings = kotlinFacet.configuration.settings val configuredPlatform = kotlinFacet.configuration.settings.targetPlatform!! val configuration = mavenPlugin.configurationElement val sharedArguments = getCompilerArgumentsByConfigurationElement(mavenProject, configuration, configuredPlatform, module.project) val executionArguments = mavenPlugin.executions ?.firstOrNull { it.goals.any { s -> s in compilationGoals } } ?.configurationElement?.let { getCompilerArgumentsByConfigurationElement(mavenProject, it, configuredPlatform, module.project) } parseCompilerArgumentsToFacet(sharedArguments.args, emptyList(), kotlinFacet, modifiableModelsProvider) if (executionArguments != null) { parseCompilerArgumentsToFacet(executionArguments.args, emptyList(), kotlinFacet, modifiableModelsProvider) } if (facetSettings.compilerArguments is K2JSCompilerArguments) { configureJSOutputPaths(mavenProject, modifiableModelsProvider.getModifiableRootModel(module), facetSettings, mavenPlugin) deprecatedKotlinJsCompiler(module.project, compilerVersion.kotlinVersion) } MavenProjectImportHandler.getInstances(module.project).forEach { it(kotlinFacet, mavenProject) } setImplementedModuleName(kotlinFacet, mavenProject, module) kotlinFacet.noVersionAutoAdvance() if ((sharedArguments.jvmTarget6IsUsed || executionArguments?.jvmTarget6IsUsed == true) && module.project.getUserData(KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED) != true ) { module.project.putUserData(KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED, true) displayJvmTarget6UsageNotification(module.project) } } private fun deprecatedKotlinJsCompiler( project: Project, kotlinVersion: KotlinVersion, ) { if (!kotlinVersion.isAtLeast(1, 7)) return if (kotlinJsCompilerWarning.get() != null) return NotificationGroupManager.getInstance() .getNotificationGroup("Kotlin/JS compiler Maven") .createNotification( KotlinMavenBundle.message("notification.text.kotlin.js.compiler.title"), KotlinMavenBundle.message("notification.text.kotlin.js.compiler.body"), NotificationType.WARNING ) .addAction( BrowseNotificationAction( KotlinMavenBundle.message("notification.text.kotlin.js.compiler.learn.more"), KotlinMavenBundle.message("notification.text.kotlin.js.compiler.link"), ) ) .also { kotlinJsCompilerWarning = WeakReference(it) } .notify(project) } private fun detectPlatform(mavenProject: MavenProject) = detectPlatformByExecutions(mavenProject) ?: detectPlatformByLibraries(mavenProject) private fun detectPlatformByExecutions(mavenProject: MavenProject): IdePlatformKind? { return mavenProject.findPlugin(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ARTIFACT_ID)?.executions?.flatMap { it.goals } ?.mapNotNull { goal -> when (goal) { PomFile.KotlinGoals.Compile, PomFile.KotlinGoals.TestCompile -> JvmIdePlatformKind PomFile.KotlinGoals.Js, PomFile.KotlinGoals.TestJs -> JsIdePlatformKind PomFile.KotlinGoals.MetaData -> CommonIdePlatformKind else -> null } }?.distinct()?.singleOrNull() } private fun detectPlatformByLibraries(mavenProject: MavenProject): IdePlatformKind? { for (kind in IdePlatformKind.ALL_KINDS) { val mavenLibraryIds = kind.tooling.mavenLibraryIds if (mavenLibraryIds.any { mavenProject.findDependencies(KOTLIN_PLUGIN_GROUP_ID, it).isNotEmpty() }) { // TODO we could return here the correct version return kind } } return null } // TODO in theory it should work like this but it doesn't as it couldn't unmark source roots that are not roots anymore. // I believe this is something should be done by the underlying maven importer implementation or somewhere else in the IDEA // For now there is a contributeSourceDirectories implementation that deals with the issue // see https://youtrack.jetbrains.com/issue/IDEA-148280 // override fun collectSourceRoots(mavenProject: MavenProject, result: PairConsumer<String, JpsModuleSourceRootType<*>>) { // for ((type, dir) in collectSourceDirectories(mavenProject)) { // val jpsType: JpsModuleSourceRootType<*> = when (type) { // SourceType.PROD -> JavaSourceRootType.SOURCE // SourceType.TEST -> JavaSourceRootType.TEST_SOURCE // } // // result.consume(dir, jpsType) // } // } private fun contributeSourceDirectories(mavenProject: MavenProject, module: Module, rootModel: MavenRootModelAdapter) { val directories = collectSourceDirectories(mavenProject) val toBeAdded = directories.map { it.second }.toSet() val state = module.kotlinImporterComponent val isNonJvmModule = mavenProject .plugins .asSequence() .filter { it.isKotlinPlugin() } .flatMap { it.executions.asSequence() } .flatMap { it.goals.asSequence() } .any { it in PomFile.KotlinGoals.CompileGoals && it !in PomFile.KotlinGoals.JvmGoals } val prodSourceRootType: JpsModuleSourceRootType<*> = if (isNonJvmModule) SourceKotlinRootType else JavaSourceRootType.SOURCE val testSourceRootType: JpsModuleSourceRootType<*> = if (isNonJvmModule) TestSourceKotlinRootType else JavaSourceRootType.TEST_SOURCE for ((type, dir) in directories) { if (rootModel.getSourceFolder(File(dir)) == null) { val jpsType: JpsModuleSourceRootType<*> = when (type) { SourceType.TEST -> testSourceRootType SourceType.PROD -> prodSourceRootType } rootModel.addSourceFolder(dir, jpsType) } } if (isNonJvmModule) { mavenProject.sources.forEach { rootModel.addSourceFolder(it, SourceKotlinRootType) } mavenProject.testSources.forEach { rootModel.addSourceFolder(it, TestSourceKotlinRootType) } mavenProject.resources.forEach { rootModel.addSourceFolder(it.directory, ResourceKotlinRootType) } mavenProject.testResources.forEach { rootModel.addSourceFolder(it.directory, TestResourceKotlinRootType) } KotlinSdkType.setUpIfNeeded() } state.addedSources.filter { it !in toBeAdded }.forEach { rootModel.unregisterAll(it, true, true) state.addedSources.remove(it) } state.addedSources.addAll(toBeAdded) } private fun collectSourceDirectories(mavenProject: MavenProject): List<Pair<SourceType, String>> = mavenProject.plugins.filter { it.isKotlinPlugin() }.flatMap { plugin -> plugin.configurationElement.sourceDirectories().map { SourceType.PROD to it } + plugin.executions.flatMap { execution -> execution.configurationElement.sourceDirectories().map { execution.sourceType() to it } } }.distinct() private fun setImplementedModuleName(kotlinFacet: KotlinFacet, mavenProject: MavenProject, module: Module) { if (kotlinFacet.configuration.settings.targetPlatform.isCommon()) { kotlinFacet.configuration.settings.implementedModuleNames = emptyList() } else { val manager = MavenProjectsManager.getInstance(module.project) val mavenDependencies = mavenProject.dependencies.mapNotNull { manager?.findProject(it) } val implemented = mavenDependencies.filter { detectPlatformByExecutions(it).isCommon } kotlinFacet.configuration.settings.implementedModuleNames = implemented.map { manager.findModule(it)?.name ?: it.displayName } } } } private fun MavenPlugin.isKotlinPlugin() = groupId == KotlinMavenImporter.KOTLIN_PLUGIN_GROUP_ID && artifactId == KotlinMavenImporter.KOTLIN_PLUGIN_ARTIFACT_ID private fun Element?.sourceDirectories(): List<String> = this?.getChildren(KotlinMavenImporter.KOTLIN_PLUGIN_SOURCE_DIRS_CONFIG)?.flatMap { it.children ?: emptyList() }?.map { it.textTrim } ?: emptyList() private fun MavenPlugin.Execution.sourceType() = goals.map { if (isTestGoalName(it)) SourceType.TEST else SourceType.PROD } .distinct() .singleOrNull() ?: SourceType.PROD private fun isTestGoalName(goalName: String) = goalName.startsWith("test-") private enum class SourceType { PROD, TEST } @State( name = "AutoImportedSourceRoots", storages = [(Storage(StoragePathMacros.MODULE_FILE))] ) class KotlinImporterComponent : PersistentStateComponent<KotlinImporterComponent.State> { class State(var directories: List<String> = ArrayList()) val addedSources: MutableSet<String> = Collections.synchronizedSet(HashSet<String>()) override fun loadState(state: State) { addedSources.clear() addedSources.addAll(state.directories) } override fun getState(): State { return State(addedSources.sorted()) } } internal val Module.kotlinImporterComponent: KotlinImporterComponent get() = getService(KotlinImporterComponent::class.java) ?: error("Service ${KotlinImporterComponent::class.java} not found")
apache-2.0
myhau/kotlin-unwrap
src/test/kotlin/com/myhau/unwrap/test_unwrap.kt
1
1674
package com.myhau.unwrap import org.junit.Test import kotlin.test.assertEquals class UnwrapTest { class Dummy1(val value: Int) class Dummy2(val value: String) @Test fun testNotNull() { val _a = Dummy1(10) val _b = Dummy2("1") var count = 0 notnull(_a, _b) { ++count } assertEquals(1, count) } @Test fun testNotNullManyArgs() { val _a = Dummy1(10) val _b = Dummy2("1") val _c = null val _d = null var count = 0 notnull(_a, _b, _c, _d) { ++count } assertEquals(0, count) } @Test fun testUnwrapWithNull() { val _a = Dummy1(1) val _b = null var validCount = 0 var invalidCount = 0 val res = unwrap(_a, _b) { a, b -> ++validCount } ?: ++invalidCount assertEquals(0, validCount) assertEquals(1, invalidCount) assertEquals(res, invalidCount) } @Test fun testUnwrapWithoutNull() { val _a = Dummy1(1) val _b = Dummy1(2) var validCount = 0 var invalidCount = 0 unwrap(_a, _b) { a, b -> validCount++ assertEquals(a.value, 1) assertEquals(b.value, 2) } ?: ++invalidCount assertEquals(1, validCount) assertEquals(0, invalidCount) } @Test fun testUnwrapWithoutNullMoreParams() { val _a = Dummy1(1) val _b = Dummy1(2) val _c = Dummy2("unwrap") val _d = Dummy2("unwrap123") var validCount = 0 var invalidCount = 0 unwrap(_a, _b, _c, _d) { a, b, c, _d -> validCount++ assertEquals(a.value, 1) assertEquals(b.value, 2) assertEquals(c.value, "unwrap") } assertEquals(1, validCount) assertEquals(0, invalidCount) } }
apache-2.0
holisticon/ranked
backend/views/leaderboard/src/main/kotlin/PlayerRankingBySets.kt
1
4684
@file:Suppress("UNUSED") package de.holisticon.ranked.view.leaderboard import de.holisticon.ranked.model.Team import de.holisticon.ranked.model.TeamColor import de.holisticon.ranked.model.TimedMatchSet import de.holisticon.ranked.model.UserName import de.holisticon.ranked.model.event.MatchCreated import org.axonframework.config.ProcessingGroup import org.axonframework.eventhandling.EventHandler import org.springframework.stereotype.Component import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.time.temporal.ChronoUnit /** * The rest controller provides getters for key figures based on the played sets */ @RestController @RequestMapping(value = ["/view/sets"]) class PlayerRankingBySetsView( private val playerRankingBySets: PlayerRankingBySets ) { @GetMapping(path = ["/player/{userName}"]) fun setStatsByPlayer(@PathVariable("userName") userName: String): PlayerSetStats = playerRankingBySets.getSetStatsForPlayer(userName) } @Component @ProcessingGroup(PROCESSING_GROUP) class PlayerRankingBySets { private val setStats = mutableMapOf<UserName, PlayerSetStats>() @EventHandler fun on(e: MatchCreated) { ensurePlayerStatExists(e.teamBlue); ensurePlayerStatExists(e.teamRed); var lastSetEndTime = e.startTime.toLocalTime(); e.matchSets.forEach { if (it is TimedMatchSet) { val endTime = it.goals.last().second.toLocalTime() val setTime = ChronoUnit.SECONDS.between(lastSetEndTime, endTime) setAvgSetTimeForPlayersOfTeam(e.teamRed, setTime) setAvgSetTimeForPlayersOfTeam(e.teamBlue, setTime) lastSetEndTime = endTime } if (it.winner() === TeamColor.RED) { incWonSetsForPlayersOfTeam(e.teamRed, it.offenseRed) incLostSetsForPlayersOfTeam(e.teamBlue, it.offenseBlue) } else { incWonSetsForPlayersOfTeam(e.teamBlue, it.offenseBlue) incLostSetsForPlayersOfTeam(e.teamRed, it.offenseRed) } } } private fun ensurePlayerStatExists(team: Team) { setStats.putIfAbsent(team.player1, PlayerSetStats(team.player1, 0, 0, 0, 0, 0.0)) setStats.putIfAbsent(team.player2, PlayerSetStats(team.player2, 0, 0, 0, 0, 0.0)) } private fun incWonSetsForPlayersOfTeam(team: Team, offense: UserName) { if (team.player1 == offense) { setStats[team.player1]!!.incWonSetsInOffense() setStats[team.player2]!!.incWonSetsInDefense() } else if (team.player2 == offense) { setStats[team.player1]!!.incWonSetsInDefense() setStats[team.player2]!!.incWonSetsInOffense() } } private fun incLostSetsForPlayersOfTeam(team: Team, offense: UserName) { if (team.player1 == offense) { setStats[team.player1]!!.incLostSetsInOffense() setStats[team.player2]!!.incLostSetsInDefense() } else if (team.player2 == offense) { setStats[team.player1]!!.incLostSetsInDefense() setStats[team.player2]!!.incLostSetsInOffense() } } private fun setAvgSetTimeForPlayersOfTeam(team: Team, setTime: Long) { setAvgSetTimeForPlayer(team.player1, setTime); setAvgSetTimeForPlayer(team.player2, setTime); } private fun setAvgSetTimeForPlayer(player: UserName, setTime: Long) { val stats = setStats[player]!!; val totalSets = stats.lostSets.whenInOffense + stats.lostSets.whenInDefense + stats.wonSets.whenInOffense + stats.wonSets.whenInDefense; stats.averageSetTime = calcAvgSetTime(totalSets, stats.averageSetTime, setTime); } private fun calcAvgSetTime(setCount: Int, averageSetTime: Double, setTime: Long): Double { return (averageSetTime * setCount + setTime) / (setCount + 1); } fun getSetStatsForPlayer(playerName: String) = setStats[UserName(playerName)] ?: PlayerSetStats(UserName(playerName), 0, 0, 0, 0, 0.0) } data class PlayerSetStats(val userName: UserName, val wonSets: InPosition<Int>, val lostSets: InPosition<Int>, var averageSetTime: Double) { constructor(userName: UserName, wonSetsInOffense: Int, wonSetsInDefense: Int, lostSetsInOffense: Int, lostSetsInDefense: Int, averageSetTime: Double) : this(userName, InPosition(wonSetsInOffense, wonSetsInDefense), InPosition(lostSetsInOffense, lostSetsInDefense), averageSetTime) fun incWonSetsInOffense() { wonSets.whenInOffense++ } fun incWonSetsInDefense() { wonSets.whenInDefense++ } fun incLostSetsInOffense() { lostSets.whenInOffense++ } fun incLostSetsInDefense() { lostSets.whenInDefense++ } }
bsd-3-clause
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/formatter/SafeCast.after.kt
13
37
fun main(a: Any) { a as? String }
apache-2.0
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/data/GHCommit.kt
2
1003
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api.data import com.fasterxml.jackson.annotation.JsonProperty import com.intellij.collaboration.api.dto.GraphQLFragment import com.intellij.collaboration.api.dto.GraphQLNodesDTO import com.intellij.openapi.util.NlsSafe @GraphQLFragment("/graphql/fragment/commit.graphql") class GHCommit(id: String, oid: String, abbreviatedOid: String, url: String, @NlsSafe val messageHeadline: String, @NlsSafe messageHeadlineHTML: String, @NlsSafe val messageBodyHTML: String, author: GHGitActor?, val committer: GHGitActor?, @JsonProperty("parents") parents: GraphQLNodesDTO<GHCommitHash>) : GHCommitShort(id, oid, abbreviatedOid, url, messageHeadlineHTML, author) { val parents = parents.nodes }
apache-2.0
lnr0626/cfn-templates
base-models/src/main/kotlin/com/lloydramey/cfn/model/resources/attributes/ResourceDefinitionAttribute.kt
1
793
/* * Copyright 2017 Lloyd Ramey <[email protected]> * * 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.lloydramey.cfn.model.resources.attributes import com.fasterxml.jackson.annotation.JsonIgnore abstract class ResourceDefinitionAttribute(@JsonIgnore val name: String)
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/multiplatform/diamondModuleDependency1/common-2-2/common-2-2.kt
9
363
@file:Suppress("UNUSED_PARAMETER") package sample actual interface <!LINE_MARKER("descr='Has expects in common-1 module'"), LINE_MARKER("descr='Is implemented by B Click or press ... to navigate'")!>A<!> { actual fun <!LINE_MARKER("descr='Has expects in common-1 module'")!>foo<!>() fun baz() } fun take_A_common_2_2(x: A) { x.foo() x.baz() }
apache-2.0
tginsberg/advent-2016-kotlin
src/test/kotlin/com/ginsberg/advent2016/Day15Spec.kt
1
1130
/* * Copyright (c) 2016 by Todd Ginsberg */ package com.ginsberg.advent2016 import com.ginsberg.advent2016.utils.Common import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it class Day15Spec : Spek({ describe("day 15") { val sampleInput = listOf( "Disc #1 has 5 positions; at time=0, it is at position 4.", "Disc #2 has 2 positions; at time=0, it is at position 1." ) describe("part 1") { it("should answer example inputs properly") { assertThat(Day15(sampleInput).solvePart1()).isEqualTo(5) } it("should answer the question with provided input") { assertThat(Day15(Common.readFile("day_15_input.txt")).solvePart1()).isEqualTo(317371) } } describe("part 2") { it("should answer the question with provided input") { assertThat(Day15(Common.readFile("day_15_input.txt")).solvePart2()).isEqualTo(2080951) } } } })
mit
jwren/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/autoImports/kt21515/constructorFromDeprecated.kt
10
197
// "Import" "true" // LANGUAGE_VERSION: 1.3 package foo open class Bar { companion object { class FromBarCompanion } } class Foo : Bar() { val a = <caret>FromBarCompanion() }
apache-2.0
jwren/intellij-community
platform/statistics/src/com/intellij/internal/statistic/local/LanguageUsageStatisticsProvider.kt
8
802
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.statistic.local import com.intellij.lang.Language interface LanguageUsageStatisticsProvider { fun getStatisticsForLanguage(language: Language): LanguageUsageStatistics /** * @return Map of languages (represented by their IDs) and their usage statistics */ fun getStatistics(): Map<String, LanguageUsageStatistics> fun updateLanguageStatistics(language: Language) } data class LanguageUsageStatistics(val useCount: Int, val isMostUsed: Boolean, val lastUsed: Long, val isMostRecent: Boolean) { companion object { val NEVER_USED = LanguageUsageStatistics(0, false, Long.MAX_VALUE, false) } }
apache-2.0
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/share/iscsi/tgtd/TgtdIscsiUnshare.kt
2
888
package com.github.kerubistan.kerub.planner.steps.storage.share.iscsi.tgtd import com.fasterxml.jackson.annotation.JsonTypeName import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.VirtualStorageDevice import com.github.kerubistan.kerub.model.dynamic.VirtualStorageAllocation import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep import com.github.kerubistan.kerub.planner.steps.InvertibleStep import com.github.kerubistan.kerub.planner.steps.storage.share.iscsi.AbstractIscsiUnshare @JsonTypeName("tgtd-iscsi-unshare") data class TgtdIscsiUnshare( override val host: Host, override val vstorage: VirtualStorageDevice, override val allocation: VirtualStorageAllocation ) : AbstractIscsiUnshare, InvertibleStep { override fun isInverseOf(other: AbstractOperationalStep) = other is TgtdIscsiShare && other.isInverseOf(this) }
apache-2.0
moshbit/Kotlift
src/com/moshbit/kotlift/Main.kt
2
3827
package com.moshbit.kotlift import java.io.File import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardOpenOption import java.util.* import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import com.fasterxml.jackson.module.kotlin.readValue data class Replacement(val from: String, val to: String, val multiple: Boolean) fun main(args: Array<String>) { if (args.count() < 3 || args.count() > 4) { println("Usage: kotlift src/kotlin dest/swift replacementFile.json") println("or: kotlift src/kotlin dest/swift replacementFile.json dest/test/swift") println("calling with a test path validates all files") return } val sourcePath = args[0] val destinationPath = args[1] // Replacement array val replacements: List<Replacement> = loadReplacementList((Paths.get(args[2]).toFile())) if (replacements.isEmpty()) { println("replacementFile empty: ${Paths.get(args[2]).toFile().absoluteFile}") return } val sourceFiles = ArrayList<File>() val destinationFiles = ArrayList<File>() listFiles(sourcePath, sourceFiles, ".kt") println(replacements) println(sourceFiles) val transpiler = Transpiler(replacements) print("Parsing... ") // Parse each file for (file in sourceFiles) { val lines = Files.readAllLines(Paths.get(file.path), Charsets.UTF_8) transpiler.parse(lines) } print(" finished\nTranspiling...") // Transpile each file for (file in sourceFiles) { val lines = Files.readAllLines(Paths.get(file.path), Charsets.UTF_8) val destLines = transpiler.transpile(lines) val destPath = Paths.get(file.path.replace(sourcePath, destinationPath).replace(".kt", ".swift")) destinationFiles.add(destPath.toFile()) val parentDir = destPath.parent.toFile() if(!parentDir.exists()) { parentDir.mkdirs() } Files.write(destPath, destLines, Charsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING) } // Validate if (args.count() == 4) { print(" finished\nValidating... ") var errorCount = 0 val testDestinationPath = args[3] val testDestFiles = ArrayList<File>() listFiles(testDestinationPath, testDestFiles, ".swift") if (destinationFiles.count() != testDestFiles.count()) { println("ERROR: INVALID TEST FOLDER:") println(destinationFiles) println(testDestFiles) return } // Validate each file for (i in 0..sourceFiles.count() - 1) { val linesDest = Files.readAllLines(Paths.get(destinationFiles[i].path), Charsets.UTF_8) val linesTest = Files.readAllLines(Paths.get(testDestFiles[i].path), Charsets.UTF_8) // Check for same line count if (linesDest.count() != linesTest.count()) { errorCount++ validateError(destinationFiles[i].path, "Invalid line count: dest=${linesDest.count()} test=${linesTest.count()}") } else { // Compare each line for (j in 0..linesDest.count() - 1) { if (linesDest[j] != linesTest[j]) { errorCount++ validateError(destinationFiles[i].path, "\n \"${linesDest[j]}\"\n \"${linesTest[j]}\"") } } } } if (errorCount == 0) { println("finished - everything OK") } else { println("finished - $errorCount ERRORS") } } else { println(" finished") } } // A very simple json parser. Could also be implemented with jackson json parser, but omitted to reduce dependencies. fun loadReplacementList(file: File): List<Replacement> { val mapper = ObjectMapper().registerModule(KotlinModule()) val result: List<Replacement> = mapper.readValue(file); return result; } fun validateError(fileName: String, hint: String) { println("$fileName: $hint") }
apache-2.0
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vscode/mappings/KeyBindingsMappings.kt
3
5585
package com.intellij.ide.customize.transferSettings.providers.vscode.mappings object KeyBindingsMappings { fun commandIdMap(commandId: String) = when (commandId) { "editor.action.clipboardPasteAction" -> "\$Paste" "editor.action.deleteLines" -> "EditorDeleteLine" "editor.action.insertLineAfter" -> "EditorStartNewLine" "editor.action.insertLineBefore" -> "EditorStartNewLineBefore" "editor.action.moveLinesDownAction" -> "MoveLineDown" "editor.action.moveLinesUpAction" -> "MoveLineUp" "editor.action.copyLinesDownAction" -> "EditorDuplicate" "undo" -> "\$Undo" "redo" -> "\$Redo" "editor.action.clipboardCutAction" -> "\$Cut" "editor.action.addSelectionToNextFindMatch" -> "SelectNextOccurrence" "editor.action.insertCursorAtEndOfEachLineSelected" -> "EditorToggleColumnMode" "editor.action.selectHighlights" -> "SelectAllOccurrences" "editor.action.changeAll" -> "SelectAllOccurrences" "editor.action.insertCursorBelow" -> "EditorCloneCaretBelow" "editor.action.insertCursorAbove" -> "EditorCloneCaretAbove" "editor.action.jumpToBracket" -> "EditorMatchBrace" "editor.action.indentLines" -> "EditorIndentLineOrSelection" "editor.action.outdentLines" -> "EditorUnindentSelection" "cursorHome" -> "EditorLineStart" "cursorEnd" -> "EditorLineEnd" "cursorBottom" -> "EditorTextEnd" "cursorTop" -> "EditorTextStart" "scrollLineDown" -> "EditorScrollDown" "scrollLineUp" -> "EditorScrollUp" "scrollPageDown" -> "ScrollPane-scrollDown" "scrollPageUp" -> "ScrollPane-scrollUp" "editor.fold" -> "CollapseRegion" "editor.unfold" -> "ExpandRegion" "editor.foldRecursively" -> "CollapseRegionRecursively" "editor.unfoldRecursively" -> "ExpandRegionRecursively" "editor.foldAll" -> "CollapseAllRegions" "editor.unfoldAll" -> "ExpandAllRegions" "editor.action.addCommentLine" -> "CommentByLineComment" "editor.action.removeCommentLine" -> "CommentByLineComment" "editor.action.commentLine" -> "CommentByLineComment" "editor.action.blockComment" -> "CommentByBlockComment" "actions.find" -> "Find" "editor.action.startFindReplaceAction" -> "Replace" "editor.action.triggerParameterHints" -> "ParameterInfo" "editor.action.formatDocument" -> "ReformatCode" "editor.action.revealDefinition" -> "GotoDeclaration" "editor.action.peekDefinition" -> "QuickImplementations" "editor.action.quickFix" -> "ShowIntentionActions" "editor.action.goToReferences" -> "ShowUsages" "editor.action.rename" -> "RenameElement" "workbench.action.showAllSymbols" -> "GotoSymbol" "workbench.action.gotoLine" -> "GotoLine" "workbench.action.quickOpen" -> "GotoFile" "editor.action.marker.nextInFiles" -> "GotoNextError" "editor.action.marker.prevInFiles" -> "GotoPreviousError" "workbench.action.navigateBack" -> "Back" "workbench.action.navigateForward" -> "Forward" "workbench.action.closeActiveEditor" -> "CloseContent" "workbench.action.closeAllEditors" -> "CloseAllEditors" "workbench.action.closeFolder" -> "CloseProject" "workbench.action.splitEditor" -> "SplitVertically" "workbench.action.files.newUntitledFile" -> "FileChooser.NewFile" "workbench.action.files.openFileFolder" -> "OpenFile" "workbench.action.files.save" -> "SaveAll" "workbench.action.files.saveAll" -> "SaveAll" "workbench.action.reopenClosedEditor" -> "ReopenClosedTab" "workbench.action.files.revealActiveFileInWindows" -> "RevealIn" "workbench.action.files.showOpenedFileInNewWindow" -> "EditSourceInNewWindow" "workbench.action.toggleZenMode" -> "ToggleDistractionFreeMode" "workbench.action.zoomIn" -> "EditorIncreaseFontSize" "workbench.action.zoomOut" -> "EditorDecreaseFontSize" "workbench.action.zoomReset" -> "EditorResetFontSize" "workbench.action.toggleSidebarVisibility" -> "HideSideWindows" "workbench.view.explorer" -> "ActivateProjectToolWindow" "workbench.view.scm" -> "ActivateVersionControlToolWindow" "workbench.view.debug" -> "ActivateDebugToolWindow" "workbench.view.extensions" -> "WelcomeScreen.Plugins" "workbench.action.output.toggleOutput" -> "ActivateRunToolWindow" "markdown.showPreview" -> "org.intellij.plugins.markdown.ui.actions.editorLayout.PreviewOnlyLayoutChangeAction" "markdown.showPreviewToSide" -> "org.intellij.plugins.markdown.ui.actions.editorLayout.EditorAndPreviewLayoutChangeAction" "workbench.action.terminal.toggleTerminal" -> "ActivateTerminalToolWindow" "workbench.action.replaceInFiles" -> "ReplaceInPath" "workbench.action.openSettings" -> "ShowSettings" "workbench.action.selectTheme" -> "QuickChangeScheme" "editor.debug.action.toggleBreakpoint" -> "ToggleLineBreakpoint" "workbench.action.debug.start" -> "Debug" "workbench.action.debug.run" -> "Run" "workbench.action.debug.stepOver" -> "StepOver" "workbench.action.debug.stepOut" -> "StepOut" "workbench.action.debug.stepInto" -> "StepInto" "workbench.action.tasks.build" -> "CompileDirty" else -> null } fun shortcutMap(shortcut: String) = when (shortcut) { "SHIFT" -> "shift" "ALT" -> "alt" "CMD" -> "meta" "CTRL" -> "ctrl" "-" -> "MINUS" "=" -> "EQUALS" "BACKSPACE" -> "BACK_SPACE" "," -> "COMMA" ";" -> "SEMICOLON" "." -> "PERIOD" "/" -> "SLASH" "\\" -> "BACK_SLASH" "PAGEDOWN" -> "PAGE_DOWN" "PAGEUP" -> "PAGE_UP" "[" -> "OPEN_BRACKET" "]" -> "CLOSE_BRACKET" "'" -> "AMPERSAND" else -> shortcut } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinPropertyWithSetterJvmNameByGetterRef/after/test/test.kt
26
121
package test class A { @set:JvmName("setBar") var second = 1 } fun test() { A().second A().second = 1 }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/editor/enterHandler/SplitStringByEnter.after.kt
9
76
// WITHOUT_CUSTOM_LINE_INDENT_PROVIDER val s = "foo" + "<caret>bar"
apache-2.0
smmribeiro/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInspection/enhancedSwitch/SwitchLabeledRuleCanBeCodeBlockFixTest.kt
9
768
// 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.java.codeInspection.enhancedSwitch import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.enhancedSwitch.SwitchLabeledRuleCanBeCodeBlockInspection /** * @author Pavel.Dolgov */ class SwitchLabeledRuleCanBeCodeBlockFixTest : LightQuickFixParameterizedTestCase() { override fun configureLocalInspectionTools(): Array<LocalInspectionTool> = arrayOf( SwitchLabeledRuleCanBeCodeBlockInspection()) override fun getBasePath() = "/inspection/switchLabeledRuleCanBeCodeBlockFix" }
apache-2.0
android/compose-samples
Crane/app/src/main/java/androidx/compose/samples/crane/base/BaseUserInput.kt
1
5916
/* * 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 androidx.compose.samples.crane.base import androidx.annotation.DrawableRes import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.LocalContentColor import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.samples.crane.R import androidx.compose.samples.crane.ui.CraneTheme import androidx.compose.samples.crane.ui.captionTextStyle import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun SimpleUserInput( text: String? = null, caption: String? = null, @DrawableRes vectorImageId: Int? = null ) { CraneUserInput( caption = if (text == null) caption else null, text = text ?: "", vectorImageId = vectorImageId ) } @Composable fun CraneUserInput( text: String, modifier: Modifier = Modifier, onClick: () -> Unit = { }, caption: String? = null, @DrawableRes vectorImageId: Int? = null, tint: Color = LocalContentColor.current ) { CraneBaseUserInput( modifier = modifier, onClick = onClick, caption = caption, vectorImageId = vectorImageId, tintIcon = { text.isNotEmpty() }, tint = tint ) { Text(text = text, style = MaterialTheme.typography.body1.copy(color = tint)) } } @Composable fun CraneEditableUserInput( hint: String, caption: String? = null, @DrawableRes vectorImageId: Int? = null, onInputChanged: (String) -> Unit ) { var textFieldState by remember { mutableStateOf(TextFieldValue()) } CraneBaseUserInput( caption = caption, tintIcon = { textFieldState.text.isNotEmpty() }, showCaption = { textFieldState.text.isNotEmpty() }, vectorImageId = vectorImageId ) { BasicTextField( value = textFieldState, onValueChange = { textFieldState = it onInputChanged(textFieldState.text) }, textStyle = MaterialTheme.typography.body1.copy(color = LocalContentColor.current), cursorBrush = SolidColor(LocalContentColor.current), decorationBox = { innerTextField -> if (hint.isNotEmpty() && textFieldState.text.isEmpty()) { Text( text = hint, style = captionTextStyle.copy(color = LocalContentColor.current) ) } innerTextField() } ) } } @OptIn(ExperimentalMaterialApi::class) @Composable private fun CraneBaseUserInput( modifier: Modifier = Modifier, onClick: () -> Unit = { }, caption: String? = null, @DrawableRes vectorImageId: Int? = null, showCaption: () -> Boolean = { true }, tintIcon: () -> Boolean, tint: Color = LocalContentColor.current, content: @Composable () -> Unit ) { Surface( modifier = modifier, onClick = onClick, color = MaterialTheme.colors.primaryVariant ) { Row(Modifier.padding(all = 12.dp)) { if (vectorImageId != null) { Icon( modifier = Modifier.size(24.dp, 24.dp), painter = painterResource(id = vectorImageId), tint = if (tintIcon()) tint else Color(0x80FFFFFF), contentDescription = null ) Spacer(Modifier.width(8.dp)) } if (caption != null && showCaption()) { Text( modifier = Modifier.align(Alignment.CenterVertically), text = caption, style = (captionTextStyle).copy(color = tint) ) Spacer(Modifier.width(8.dp)) } Row( Modifier .weight(1f) .align(Alignment.CenterVertically) ) { content() } } } } @Preview @Composable fun PreviewInput() { CraneTheme { Surface { CraneBaseUserInput( tintIcon = { true }, vectorImageId = R.drawable.ic_plane, caption = "Caption", showCaption = { true } ) { Text(text = "text", style = MaterialTheme.typography.body1) } } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/tooLongCharLiteralToString/startWithBackslash.kt
13
121
// "Convert too long character literal to string" "true" // ERROR: Illegal escape: '\ ' fun foo() { '\ bar<caret>' }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/completion/tests/testData/basic/codeFragments/elementAt.kt
13
132
fun foo() { val aaaB = 1 <caret>val aaaC = 1 val aaaD = 1 } // INVOCATION_COUNT: 1 // EXIST: aaaB // ABSENT: aaaC, aaaD
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/codeVision/InterfaceMethodUsages.kt
12
487
// MODE: usages <# block [ 1 Usage] #> interface SomeInterface { <# block [ 3 Usages] #> fun someFun(): String fun someOtherFun() = someFun() // <== (1): delegation from another interface method val someProperty = someFun() // <== (2): property initializer } fun main() { val instance = object: SomeInterface { <# block [ 1 Usage] #> override fun someFun(): String {} // <== (): used below } instance.someFun() <== (3): call on an instance }
apache-2.0
smmribeiro/intellij-community
plugins/stream-debugger/src/com/intellij/debugger/streams/trace/dsl/MapVariable.kt
23
759
// Copyright 2000-2017 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.debugger.streams.trace.dsl import com.intellij.debugger.streams.trace.impl.handler.type.MapType /** * @author Vitaliy.Bibaev */ interface MapVariable : Variable { override val type: MapType fun get(key: Expression): Expression fun set(key: Expression, newValue: Expression): Expression fun contains(key: Expression): Expression fun size(): Expression fun keys(): Expression fun computeIfAbsent(key: Expression, supplier: Lambda): Expression fun defaultDeclaration(isMutable: Boolean = true): VariableDeclaration fun convertToArray(dsl: Dsl, arrayName: String): CodeBlock }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/mayBeConstant/getterWithInitializer.kt
13
62
// PROBLEM: none val <caret>withGetter = 42 get() = field
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/navigation/implementations/DefaultImplFunction.kt
13
258
package testing interface I { fun <caret>f() { } } class A : I class B : I { override fun f() { } } class C : I interface II: I interface III: I { override fun f() { } } // REF: (in testing.B).f() // REF: (in testing.III).f()
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/CompletionBenchmarkSink.kt
5
3409
// 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.completion import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel.Factory.CONFLATED import kotlinx.coroutines.channels.onClosed import java.lang.System.currentTimeMillis interface CompletionBenchmarkSink { fun onCompletionStarted(completionSession: CompletionSession) fun onCompletionEnded(completionSession: CompletionSession, canceled: Boolean) fun onFlush(completionSession: CompletionSession) companion object { fun enableAndGet(): Impl = Impl().also { _instance = it } fun disable() { _instance.let { (it as? Impl)?.channel?.close() } _instance = Empty } val instance get() = _instance private var _instance: CompletionBenchmarkSink = Empty } private object Empty : CompletionBenchmarkSink { override fun onCompletionStarted(completionSession: CompletionSession) {} override fun onCompletionEnded(completionSession: CompletionSession, canceled: Boolean) {} override fun onFlush(completionSession: CompletionSession) {} } class Impl : CompletionBenchmarkSink { private val pendingSessions = mutableListOf<CompletionSession>() val channel = Channel<CompletionBenchmarkResults>(capacity = CONFLATED) private val perSessionResults = LinkedHashMap<CompletionSession, PerSessionResults>() private var start: Long = 0 override fun onCompletionStarted(completionSession: CompletionSession) = synchronized(this) { if (pendingSessions.isEmpty()) start = currentTimeMillis() pendingSessions += completionSession perSessionResults[completionSession] = PerSessionResults() } override fun onCompletionEnded(completionSession: CompletionSession, canceled: Boolean) = synchronized(this) { pendingSessions -= completionSession perSessionResults[completionSession]?.onEnd(canceled) if (pendingSessions.isEmpty()) { val firstFlush = perSessionResults.values.filterNot { results -> results.canceled }.minOfOrNull { it.firstFlush } ?: 0 val full = perSessionResults.values.maxOfOrNull { it.full } ?: 0 channel.trySend(CompletionBenchmarkResults(firstFlush, full)).onClosed { throw IllegalStateException(it) } reset() } } override fun onFlush(completionSession: CompletionSession) = synchronized(this) { perSessionResults[completionSession]?.onFirstFlush() Unit } fun reset() = synchronized(this) { pendingSessions.clear() perSessionResults.clear() } data class CompletionBenchmarkResults(var firstFlush: Long = 0, var full: Long = 0) private inner class PerSessionResults { var firstFlush = 0L var full = 0L var canceled = false fun onFirstFlush() { firstFlush = currentTimeMillis() - start } fun onEnd(canceled: Boolean) { full = currentTimeMillis() - start this.canceled = canceled } } } }
apache-2.0
tlaukkan/kotlin-web-vr
client/src/vr/webvr/model/NDCScaleOffset.kt
1
140
package vr.webvr.model data class NDCScaleOffset(val pxscale: Double, val pyscale: Double, val pxoffset: Double, val pyoffset: Double) { }
mit
TimePath/launcher
src/main/kotlin/com/timepath/swing/ObjectBasedTableModel.kt
1
2749
package com.timepath.swing import java.util.ArrayList import java.util.Arrays import javax.swing.table.AbstractTableModel /** * @param <E> */ public abstract class ObjectBasedTableModel<E> protected constructor() : AbstractTableModel() { private val columns = Arrays.asList<String>(*columns()) private var rows: MutableList<E> = ArrayList() public fun getRows(): List<E> { return rows } public fun setRows(rows: MutableList<E>) { fireTableRowsDeleted(0, Math.max(this.rows.size() - 1, 0)) this.rows = rows fireTableRowsInserted(0, Math.max(this.rows.size() - 1, 0)) } /** * Add Object o to the model * * @param o the Object * @return true if added */ public fun add(o: E): Boolean { val idx = rows.indexOf(o) if (idx >= 0) { return false } rows.add(o) fireTableRowsInserted(rows.size() - 1, rows.size() - 1) return true } public abstract fun columns(): Array<String> override fun getColumnName(column: Int): String { if (column < columns.size()) { val name = columns[column] if (name != null) return name } return super.getColumnName(column) } override fun getRowCount(): Int { return rows.size() } override fun getColumnCount(): Int { return columns.size() } override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? { return get(rows[rowIndex], columnIndex) } /** * Gets a property from an Object based on an index * * @param o the Object * @param columnIndex index to Object property * @return the property */ public abstract fun get(o: E, columnIndex: Int): Any? /** * Remove Object o from the model * * @param o the Object * @return true if removed */ public fun remove(o: E): Boolean { val idx = rows.indexOf(o) if (idx < 0) { return false } rows.remove(idx) fireTableRowsDeleted(idx, idx) return true } override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean { return isCellEditable(rows[rowIndex], columnIndex) } protected open fun isCellEditable(e: E, columnIndex: Int): Boolean { return false } /** * Fire update for Object o in the model * * @param o the Object * @return true if not updated (because the Object isn't in the model) */ public fun update(o: E): Boolean { val idx = rows.indexOf(o) if (idx < 0) { return false } fireTableRowsUpdated(idx, idx) return true } }
artistic-2.0
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/instance/tasks/InstanceTail.kt
1
811
package com.cognifide.gradle.aem.instance.tasks import com.cognifide.gradle.aem.common.tasks.Instance import kotlinx.coroutines.ExperimentalCoroutinesApi import org.gradle.api.tasks.TaskAction @OptIn(ExperimentalCoroutinesApi::class) open class InstanceTail : Instance() { @TaskAction fun tail() { logger.lifecycle("Tailing logs from:\n${anyInstances.joinToString("\n") { "Instance '${it.name}' at URL '${it.httpUrl}'" }}") logger.lifecycle("Filter incidents using file: ${instanceManager.tailer.incidentFilter.get()}") instanceManager.tailer.tail(anyInstances) } init { description = "Tails logs from all configured instances (local & remote) and notifies about unknown errors." } companion object { const val NAME = "instanceTail" } }
apache-2.0
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/api/java/util/test/SourceTester.kt
1
4274
package xyz.nulldev.ts.api.java.util.test import eu.kanade.tachiyomi.source.CatalogueSource import xyz.nulldev.ts.api.java.TachiyomiAPI class SourceTester { val api = TachiyomiAPI fun test(source: CatalogueSource, eventHandler: (Event) -> Unit) { fun debug(message: String) { eventHandler(Event.Debug(message)) } fun fail(message: String, e: Throwable? = null) { eventHandler(Event.Error(message, e)) } fun warn(message: String, e: Throwable? = null) { eventHandler(Event.Warning(message, e)) } //Test catalogue (3 pages) debug("Testing catalogue...") debug("Testing page 1 of catalogue...") val catalogueContent = try { api.catalogue.getCatalogueContent(1, source) } catch(e: Exception) { fail("Could not get page 1 of catalogue!", e) return } val mergedCatalogues = catalogueContent.manga.toMutableList() if(catalogueContent.nextPage != null) { debug("Testing page 2 of catalogue...") val catalogueContent2 = try { api.catalogue.getCatalogueContent(2, source) } catch (e: Exception) { fail("Could not get page 2 of catalogue!", e) return } mergedCatalogues += catalogueContent2.manga if(catalogueContent2.nextPage != null) { debug("Testing page 3 of catalogue...") val catalogueContent3 = try { api.catalogue.getCatalogueContent(3, source) } catch (e: Exception) { fail("Could not get page 3 of catalogue!", e) return } mergedCatalogues += catalogueContent3.manga } } else warn("Catalogue appears to only have one page, please confirm that this is intended!") //Verify that there are no duplicates in the catalogue if(mergedCatalogues.any { a -> mergedCatalogues.any { b -> //Not same object but same URL? a !== b && a.url == b.url } }) { fail("Duplicate manga detected in catalogue!") return } debug("Testing update manga info/chapters...") catalogueContent.manga.take(10).forEachIndexed { index, manga -> debug("Testing manga $index (${manga.url})...") debug("Testing update manga $index info...") try { api.catalogue.updateMangaInfo(manga) } catch(e: Exception) { fail("Could not update manga $index info...", e) return } debug("Testing update manga $index chapters...") try { api.catalogue.updateMangaChapters(manga) } catch(e: Exception) { warn("Could not update manga $index chapters...", e) } debug("Testing get cover of manga $index...") val cover = try { api.images.fetchCover(manga, NOOPOutputStream()) } catch(e: Exception) { warn("Could not get cover of manga $index...", e) } debug("Testing get page list of chapter 1...") val chapter = api.database.getChapters(manga).executeAsBlocking().getOrNull(0) if(chapter != null) { val pageList = try { api.catalogue.getPageList(chapter) } catch (e: Exception) { warn("Could not get page list of chapter 1...", e) null } if (pageList != null) { if(pageList.isNotEmpty()) { debug("Testing get image of page 1...") val image = try { api.images.fetchImage(chapter, pageList[0], NOOPOutputStream()) } catch (e: Exception) { warn("Could not get image of page 1...", e) } } else warn("Page list empty!") } } else warn("Chapter 1 does not exist!") } } }
apache-2.0
fkorotkov/k8s-kotlin-dsl
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/autoscaling/v2beta2/ClassBuilders.kt
1
7747
// GENERATE package com.fkorotkov.kubernetes.autoscaling.v2beta2 import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ContainerResourceMetricSource as v2beta2_ContainerResourceMetricSource import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ContainerResourceMetricStatus as v2beta2_ContainerResourceMetricStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.CrossVersionObjectReference as v2beta2_CrossVersionObjectReference import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ExternalMetricSource as v2beta2_ExternalMetricSource import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ExternalMetricStatus as v2beta2_ExternalMetricStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HPAScalingPolicy as v2beta2_HPAScalingPolicy import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HPAScalingRules as v2beta2_HPAScalingRules import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscaler as v2beta2_HorizontalPodAutoscaler import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerBehavior as v2beta2_HorizontalPodAutoscalerBehavior import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerCondition as v2beta2_HorizontalPodAutoscalerCondition import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerList as v2beta2_HorizontalPodAutoscalerList import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerSpec as v2beta2_HorizontalPodAutoscalerSpec import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerStatus as v2beta2_HorizontalPodAutoscalerStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricIdentifier as v2beta2_MetricIdentifier import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricSpec as v2beta2_MetricSpec import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricStatus as v2beta2_MetricStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricTarget as v2beta2_MetricTarget import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricValueStatus as v2beta2_MetricValueStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ObjectMetricSource as v2beta2_ObjectMetricSource import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ObjectMetricStatus as v2beta2_ObjectMetricStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.PodsMetricSource as v2beta2_PodsMetricSource import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.PodsMetricStatus as v2beta2_PodsMetricStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ResourceMetricSource as v2beta2_ResourceMetricSource import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ResourceMetricStatus as v2beta2_ResourceMetricStatus fun newContainerResourceMetricSource(block : v2beta2_ContainerResourceMetricSource.() -> Unit = {}): v2beta2_ContainerResourceMetricSource { val instance = v2beta2_ContainerResourceMetricSource() instance.block() return instance } fun newContainerResourceMetricStatus(block : v2beta2_ContainerResourceMetricStatus.() -> Unit = {}): v2beta2_ContainerResourceMetricStatus { val instance = v2beta2_ContainerResourceMetricStatus() instance.block() return instance } fun newCrossVersionObjectReference(block : v2beta2_CrossVersionObjectReference.() -> Unit = {}): v2beta2_CrossVersionObjectReference { val instance = v2beta2_CrossVersionObjectReference() instance.block() return instance } fun newExternalMetricSource(block : v2beta2_ExternalMetricSource.() -> Unit = {}): v2beta2_ExternalMetricSource { val instance = v2beta2_ExternalMetricSource() instance.block() return instance } fun newExternalMetricStatus(block : v2beta2_ExternalMetricStatus.() -> Unit = {}): v2beta2_ExternalMetricStatus { val instance = v2beta2_ExternalMetricStatus() instance.block() return instance } fun newHPAScalingPolicy(block : v2beta2_HPAScalingPolicy.() -> Unit = {}): v2beta2_HPAScalingPolicy { val instance = v2beta2_HPAScalingPolicy() instance.block() return instance } fun newHPAScalingRules(block : v2beta2_HPAScalingRules.() -> Unit = {}): v2beta2_HPAScalingRules { val instance = v2beta2_HPAScalingRules() instance.block() return instance } fun newHorizontalPodAutoscaler(block : v2beta2_HorizontalPodAutoscaler.() -> Unit = {}): v2beta2_HorizontalPodAutoscaler { val instance = v2beta2_HorizontalPodAutoscaler() instance.block() return instance } fun newHorizontalPodAutoscalerBehavior(block : v2beta2_HorizontalPodAutoscalerBehavior.() -> Unit = {}): v2beta2_HorizontalPodAutoscalerBehavior { val instance = v2beta2_HorizontalPodAutoscalerBehavior() instance.block() return instance } fun newHorizontalPodAutoscalerCondition(block : v2beta2_HorizontalPodAutoscalerCondition.() -> Unit = {}): v2beta2_HorizontalPodAutoscalerCondition { val instance = v2beta2_HorizontalPodAutoscalerCondition() instance.block() return instance } fun newHorizontalPodAutoscalerList(block : v2beta2_HorizontalPodAutoscalerList.() -> Unit = {}): v2beta2_HorizontalPodAutoscalerList { val instance = v2beta2_HorizontalPodAutoscalerList() instance.block() return instance } fun newHorizontalPodAutoscalerSpec(block : v2beta2_HorizontalPodAutoscalerSpec.() -> Unit = {}): v2beta2_HorizontalPodAutoscalerSpec { val instance = v2beta2_HorizontalPodAutoscalerSpec() instance.block() return instance } fun newHorizontalPodAutoscalerStatus(block : v2beta2_HorizontalPodAutoscalerStatus.() -> Unit = {}): v2beta2_HorizontalPodAutoscalerStatus { val instance = v2beta2_HorizontalPodAutoscalerStatus() instance.block() return instance } fun newMetricIdentifier(block : v2beta2_MetricIdentifier.() -> Unit = {}): v2beta2_MetricIdentifier { val instance = v2beta2_MetricIdentifier() instance.block() return instance } fun newMetricSpec(block : v2beta2_MetricSpec.() -> Unit = {}): v2beta2_MetricSpec { val instance = v2beta2_MetricSpec() instance.block() return instance } fun newMetricStatus(block : v2beta2_MetricStatus.() -> Unit = {}): v2beta2_MetricStatus { val instance = v2beta2_MetricStatus() instance.block() return instance } fun newMetricTarget(block : v2beta2_MetricTarget.() -> Unit = {}): v2beta2_MetricTarget { val instance = v2beta2_MetricTarget() instance.block() return instance } fun newMetricValueStatus(block : v2beta2_MetricValueStatus.() -> Unit = {}): v2beta2_MetricValueStatus { val instance = v2beta2_MetricValueStatus() instance.block() return instance } fun newObjectMetricSource(block : v2beta2_ObjectMetricSource.() -> Unit = {}): v2beta2_ObjectMetricSource { val instance = v2beta2_ObjectMetricSource() instance.block() return instance } fun newObjectMetricStatus(block : v2beta2_ObjectMetricStatus.() -> Unit = {}): v2beta2_ObjectMetricStatus { val instance = v2beta2_ObjectMetricStatus() instance.block() return instance } fun newPodsMetricSource(block : v2beta2_PodsMetricSource.() -> Unit = {}): v2beta2_PodsMetricSource { val instance = v2beta2_PodsMetricSource() instance.block() return instance } fun newPodsMetricStatus(block : v2beta2_PodsMetricStatus.() -> Unit = {}): v2beta2_PodsMetricStatus { val instance = v2beta2_PodsMetricStatus() instance.block() return instance } fun newResourceMetricSource(block : v2beta2_ResourceMetricSource.() -> Unit = {}): v2beta2_ResourceMetricSource { val instance = v2beta2_ResourceMetricSource() instance.block() return instance } fun newResourceMetricStatus(block : v2beta2_ResourceMetricStatus.() -> Unit = {}): v2beta2_ResourceMetricStatus { val instance = v2beta2_ResourceMetricStatus() instance.block() return instance }
mit
sksamuel/ktest
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io.kotest.engine/spec/SpecExecutionOrder.kt
1
1014
package io.kotest.engine.spec import io.kotest.core.spec.Order import io.kotest.core.spec.SpecExecutionOrder import io.kotest.core.spec.Spec import io.kotest.mpp.annotation import kotlin.reflect.KClass interface SpecSorter { fun sort(classes: List<KClass<out Spec>>): List<KClass<out Spec>> } /** * An implementation of [SpecExecutionOrder] which will run specs in * a lexicographic order. */ object LexicographicSpecSorter : SpecSorter { override fun sort(classes: List<KClass<out Spec>>) = classes.sortedBy { it.simpleName } } /** * An implementation of [SpecExecutionOrder] which will run specs in * a different random order each time the are executed. */ object RandomSpecSorter : SpecSorter { override fun sort(classes: List<KClass<out Spec>>): List<KClass<out Spec>> = classes.shuffled() } object AnnotatedSpecSorter : SpecSorter { override fun sort(classes: List<KClass<out Spec>>): List<KClass<out Spec>> = classes.sortedBy { it.annotation<Order>()?.value ?: Int.MAX_VALUE } }
mit
mapzen/eraser-map
app/src/main/kotlin/com/mapzen/erasermap/model/IntentQuery.kt
1
232
package com.mapzen.erasermap.model import com.mapzen.tangram.LngLat /** * Represents components of an implicit intent query string that has been parsed. */ data class IntentQuery(val queryString: String, val focusPoint: LngLat)
gpl-3.0