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 |
---|---|---|---|---|---|
Yubico/yubioath-desktop | android/app/src/main/kotlin/com/yubico/authenticator/oath/AppLinkMethodChannel.kt | 1 | 1312 | /*
* Copyright (C) 2022 Yubico.
*
* 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.yubico.authenticator.oath
import android.net.Uri
import androidx.annotation.UiThread
import com.yubico.authenticator.logging.Log
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodChannel
import org.json.JSONObject
class AppLinkMethodChannel(messenger: BinaryMessenger) {
private val methodChannel = MethodChannel(messenger, "app.link.methods")
@UiThread
fun handleUri(uri: Uri) {
Log.t(TAG, "Handling URI: $uri")
methodChannel.invokeMethod(
"handleOtpAuthLink",
JSONObject(mapOf("link" to uri.toString())).toString()
)
}
companion object {
const val TAG = "AppLinkMethodChannel"
}
} | apache-2.0 |
AcornUI/Acorn | acornui-core/src/test/kotlin/com/acornui/component/LinearGradientTest.kt | 1 | 1302 | /*
* Copyright 2020 Poly Forest, 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
*
* 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.acornui.component
import com.acornui.graphic.Color
import com.acornui.serialization.jsonParse
import com.acornui.serialization.jsonStringify
import kotlin.test.Test
import kotlin.test.assertEquals
class LinearGradientTest {
@Test fun toCssString() {
assertEquals("linear-gradient(to bottom, rgba(255, 0, 0, 1) 0px)", LinearGradient(GradientDirection.BOTTOM, ColorStop(Color.RED, dp = 0.0)).toCssString())
}
@Test fun serialize() {
val g = LinearGradient(GradientDirection.ANGLE, Color.RED, Color.BLACK, Color.BLUE)
val json = jsonStringify(LinearGradient.serializer(), g)
assertEquals(g, jsonParse(LinearGradient.serializer(), json))
}
} | apache-2.0 |
Turbo87/intellij-rust | src/main/kotlin/org/rust/ide/codestyle/RustLanguageCodeStyleSettingsProvider.kt | 1 | 1183 | package org.rust.ide.codestyle
import com.intellij.openapi.util.io.StreamUtil
import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizable
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider
import org.rust.lang.RustLanguage
class RustLanguageCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() {
override fun getLanguage() = RustLanguage
override fun customizeSettings(consumer: CodeStyleSettingsCustomizable,
settingsType: LanguageCodeStyleSettingsProvider.SettingsType) {
if (settingsType == SettingsType.WRAPPING_AND_BRACES_SETTINGS) {
consumer.showStandardOptions("RIGHT_MARGIN");
}
}
override fun getDefaultCommonSettings() = CommonCodeStyleSettings(language).apply {
RIGHT_MARGIN = 99
}
override fun getCodeSample(settingsType: LanguageCodeStyleSettingsProvider.SettingsType) = CODE_SAMPLE
private val CODE_SAMPLE by lazy {
val stream = javaClass.classLoader.getResourceAsStream("org/rust/ide/codestyle/code_sample.rs")
StreamUtil.readText(stream, "UTF-8")
}
}
| mit |
edwardharks/Aircraft-Recognition | recognition/src/test/kotlin/com/edwardharker/aircraftrecognition/filter/results/RepositoryFilterResultsUseCaseTest.kt | 1 | 1195 | package com.edwardharker.aircraftrecognition.filter.results
import com.edwardharker.aircraftrecognition.filter.FakeSelectedFilterOptions
import com.edwardharker.aircraftrecognition.model.Aircraft
import com.edwardharker.aircraftrecognition.repository.FakeAircraftRepository
import org.junit.Test
import rx.observers.TestSubscriber
class RepositoryFilterResultsUseCaseTest {
private val fakeSelectedFilterOptions = FakeSelectedFilterOptions()
private val fakeAircraftRepository = FakeAircraftRepository()
private val testSubscriber = TestSubscriber<List<Aircraft>>()
@Test
fun filterEmissionsEmitFilteredAircraft() {
val aircraft = listOf(Aircraft())
val filters = mapOf(Pair("key", "value"))
fakeAircraftRepository.thatEmits(aircraft, filters)
val repositoryFilterResultsUseCase = RepositoryFilterResultsUseCase(
selectedFilterOptions = fakeSelectedFilterOptions,
aircraftRepository = fakeAircraftRepository
)
repositoryFilterResultsUseCase.filteredAircraft().subscribe(testSubscriber)
fakeSelectedFilterOptions.subject.onNext(filters)
testSubscriber.assertValues(aircraft)
}
}
| gpl-3.0 |
ingokegel/intellij-community | plugins/markdown/test/src/org/intellij/plugins/markdown/formatter/MarkdownFormatterTest.kt | 1 | 2573 | // 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.intellij.plugins.markdown.formatter
import com.intellij.application.options.CodeStyle
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import org.intellij.plugins.markdown.MarkdownTestingUtil
import org.intellij.plugins.markdown.lang.MarkdownLanguage
import org.intellij.plugins.markdown.lang.formatter.settings.MarkdownCustomCodeStyleSettings
class MarkdownFormatterTest: LightPlatformCodeInsightTestCase() {
fun `test smoke`() = doTest()
fun `test headers`() = doTest()
fun `test paragraphs`() = doTest()
fun `test lists`() = doTest()
//For now alignment of fence parts is not supported
fun `test fences`() = doTest()
fun `test blockquotes`() = doTest()
fun `test codeblocks`() = doTest()
fun `test tables`() = doTest()
fun `test reflow`() = doTest()
fun `test long table`() = doTest()
fun `test punctuation`() = doTest()
override fun getTestDataPath(): String {
return MarkdownTestingUtil.TEST_DATA_PATH + "/formatter/"
}
override fun getTestName(lowercaseFirstLetter: Boolean): String {
val name = super.getTestName(lowercaseFirstLetter)
return name.trimStart().replace(' ', '_')
}
private fun doTest() {
val before = getTestName(true) + "_before.md"
val after = getTestName(true) + "_after.md"
runWithTemporaryStyleSettings { settings ->
settings.apply {
WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN = true
getCommonSettings(MarkdownLanguage.INSTANCE).apply {
RIGHT_MARGIN = 40
}
getCustomSettings(MarkdownCustomCodeStyleSettings::class.java).apply {
WRAP_TEXT_IF_LONG = true
KEEP_LINE_BREAKS_INSIDE_TEXT_BLOCKS = false
}
}
doReformatTest(before, after)
//check idempotence of formatter
doReformatTest(after, after)
}
}
private fun runWithTemporaryStyleSettings(block: (CodeStyleSettings) -> Unit) {
val settings = CodeStyle.getSettings(project)
CodeStyle.doWithTemporarySettings(project, settings, block)
}
private fun doReformatTest(before: String, after: String) {
configureByFile(before)
WriteCommandAction.runWriteCommandAction(project) {
CodeStyleManager.getInstance(project).reformat(file)
}
checkResultByFile(after)
}
}
| apache-2.0 |
mdaniel/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/fromIntellij/InlineWithTry.kt | 13 | 314 | // ERROR: Cannot perform refactoring.\nInline Function is not supported for functions with return statements not at the end of the body.
class A {
init {
g()
}
fun <caret>g(): Int {
try {
return 0
}
catch (e: Error) {
throw e
}
}
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/intentions/removeArgumentName/noExpression.kt | 13 | 96 | // IS_APPLICABLE: false
fun foo(s: String, b: Boolean){}
fun bar() {
foo("", <caret>b = )
} | apache-2.0 |
PKRoma/PocketHub | app/src/main/java/com/github/pockethub/android/ui/item/commit/CommitCommentItem.kt | 6 | 1234 | package com.github.pockethub.android.ui.item.commit
import com.github.pockethub.android.R
import com.github.pockethub.android.util.AvatarLoader
import com.github.pockethub.android.util.HttpImageGetter
import com.github.pockethub.android.util.TimeUtils
import com.meisolsson.githubsdk.model.git.GitComment
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.comment.*
class CommitCommentItem @JvmOverloads constructor(
private val avatarLoader: AvatarLoader,
private val imageGetter: HttpImageGetter,
val comment: GitComment,
private val isLineComment: Boolean = false
) : Item(comment.id()!!) {
override fun getLayout() = if (isLineComment) {
R.layout.diff_comment_item
} else {
R.layout.commit_comment_item
}
override fun bind(holder: ViewHolder, position: Int) {
avatarLoader.bind(holder.iv_avatar, comment.user())
holder.tv_comment_author.text = comment.user()!!.login()
holder.tv_comment_date.text = TimeUtils.getRelativeTime(comment.updatedAt())
imageGetter.bind(holder.tv_comment_body, comment.bodyHtml(), comment.id())
}
}
| apache-2.0 |
ingokegel/intellij-community | platform/script-debugger/backend/src/debugger/sourcemap/SourceMapDataImpl.kt | 13 | 534 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.debugger.sourcemap
data class SourceMapDataImpl(override val file: String?,
override val sources: List<String>,
override val sourcesContent: List<String?>?,
override val hasNameMappings: Boolean,
override val mappings: List<MappingEntry>) : SourceMapData | apache-2.0 |
benjamin-bader/thrifty | thrifty-java-codegen/src/main/kotlin/com/microsoft.thrifty.gen/GenerateReaderVisitor.kt | 1 | 9496 | /*
* Thrifty
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.thrifty.gen
import com.microsoft.thrifty.Adapter
import com.microsoft.thrifty.schema.BuiltinType
import com.microsoft.thrifty.schema.EnumType
import com.microsoft.thrifty.schema.ListType
import com.microsoft.thrifty.schema.MapType
import com.microsoft.thrifty.schema.NamespaceScope
import com.microsoft.thrifty.schema.ServiceType
import com.microsoft.thrifty.schema.SetType
import com.microsoft.thrifty.schema.StructType
import com.microsoft.thrifty.schema.ThriftType
import com.microsoft.thrifty.schema.TypedefType
import com.microsoft.thrifty.schema.UserType
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterizedTypeName
import java.util.ArrayDeque
import java.util.Deque
/**
* Generates Java code to read a field's value from an open Protocol object.
*
* Assumptions:
* We are inside of [Adapter.read]. Further, we are
* inside of a single case block for a single field. There are variables
* in scope named "protocol" and "builder", representing the connection and
* the struct builder.
*/
internal open class GenerateReaderVisitor(
private val resolver: TypeResolver,
private val read: MethodSpec.Builder,
private val fieldName: String,
private val fieldType: ThriftType,
private val failOnUnknownEnumValues: Boolean = true
) : ThriftType.Visitor<Unit> {
private val nameStack: Deque<String> = ArrayDeque<String>()
private var scope: Int = 0
fun generate() {
val fieldTypeCode = resolver.getTypeCode(fieldType)
val codeName = TypeNames.getTypeCodeName(fieldTypeCode)
read.beginControlFlow("if (field.typeId == \$T.\$L)", TypeNames.TTYPE, codeName)
nameStack.push("value")
fieldType.accept(this)
nameStack.pop()
useReadValue("value")
read.nextControlFlow("else")
read.addStatement("\$T.skip(protocol, field.typeId)", TypeNames.PROTO_UTIL)
read.endControlFlow()
}
protected open fun useReadValue(localName: String) {
if (failOnUnknownEnumValues || !fieldType.isEnum) {
read.addStatement("builder.\$N(\$N)", fieldName, localName)
} else {
read.beginControlFlow("if (\$N != null)", localName)
read.addStatement("builder.\$N(\$N)", fieldName, localName)
read.endControlFlow()
}
}
override fun visitBool(boolType: BuiltinType) {
read.addStatement("\$T \$N = protocol.readBool()", TypeNames.BOOLEAN.unbox(), nameStack.peek())
}
override fun visitByte(byteType: BuiltinType) {
read.addStatement("\$T \$N = protocol.readByte()", TypeNames.BYTE.unbox(), nameStack.peek())
}
override fun visitI16(i16Type: BuiltinType) {
read.addStatement("\$T \$N = protocol.readI16()", TypeNames.SHORT.unbox(), nameStack.peek())
}
override fun visitI32(i32Type: BuiltinType) {
read.addStatement("\$T \$N = protocol.readI32()", TypeNames.INTEGER.unbox(), nameStack.peek())
}
override fun visitI64(i64Type: BuiltinType) {
read.addStatement("\$T \$N = protocol.readI64()", TypeNames.LONG.unbox(), nameStack.peek())
}
override fun visitDouble(doubleType: BuiltinType) {
read.addStatement("\$T \$N = protocol.readDouble()", TypeNames.DOUBLE.unbox(), nameStack.peek())
}
override fun visitString(stringType: BuiltinType) {
read.addStatement("\$T \$N = protocol.readString()", TypeNames.STRING, nameStack.peek())
}
override fun visitBinary(binaryType: BuiltinType) {
read.addStatement("\$T \$N = protocol.readBinary()", TypeNames.BYTE_STRING, nameStack.peek())
}
override fun visitVoid(voidType: BuiltinType) {
throw AssertionError("Cannot read void")
}
override fun visitEnum(enumType: EnumType) {
val target = nameStack.peek()
val qualifiedJavaName = getFullyQualifiedJavaName(enumType)
val intName = "i32_$scope"
read.addStatement("int \$L = protocol.readI32()", intName)
read.addStatement("$1L $2N = $1L.findByValue($3L)", qualifiedJavaName, target, intName)
if (failOnUnknownEnumValues) {
read.beginControlFlow("if (\$N == null)", target!!)
read.addStatement(
"throw new $1T($2T.PROTOCOL_ERROR, $3S + $4L)",
TypeNames.THRIFT_EXCEPTION,
TypeNames.THRIFT_EXCEPTION_KIND,
"Unexpected value for enum-type " + enumType.name + ": ",
intName)
read.endControlFlow()
}
}
override fun visitList(listType: ListType) {
val elementType = resolver.getJavaClass(listType.elementType.trueType)
val genericListType = ParameterizedTypeName.get(TypeNames.LIST, elementType)
val listImplType = resolver.listOf(elementType)
val listInfo = "listMetadata$scope"
val idx = "i$scope"
val item = "item$scope"
read.addStatement("\$T \$N = protocol.readListBegin()", TypeNames.LIST_META, listInfo)
read.addStatement("\$T \$N = new \$T(\$N.size)", genericListType, nameStack.peek(), listImplType, listInfo)
read.beginControlFlow("for (int $1N = 0; $1N < $2N.size; ++$1N)", idx, listInfo)
pushScope {
nameStack.push(item)
listType.elementType.trueType.accept(this)
nameStack.pop()
}
read.addStatement("\$N.add(\$N)", nameStack.peek(), item)
read.endControlFlow()
read.addStatement("protocol.readListEnd()")
}
override fun visitSet(setType: SetType) {
val elementType = resolver.getJavaClass(setType.elementType.trueType)
val genericSetType = ParameterizedTypeName.get(TypeNames.SET, elementType)
val setImplType = resolver.setOf(elementType)
val setInfo = "setMetadata$scope"
val idx = "i$scope"
val item = "item$scope"
read.addStatement("\$T \$N = protocol.readSetBegin()", TypeNames.SET_META, setInfo)
read.addStatement("\$T \$N = new \$T(\$N.size)", genericSetType, nameStack.peek(), setImplType, setInfo)
read.beginControlFlow("for (int $1N = 0; $1N < $2N.size; ++$1N)", idx, setInfo)
pushScope {
nameStack.push(item)
setType.elementType.accept(this)
nameStack.pop()
}
read.addStatement("\$N.add(\$N)", nameStack.peek(), item)
read.endControlFlow()
read.addStatement("protocol.readSetEnd()")
}
override fun visitMap(mapType: MapType) {
val keyType = resolver.getJavaClass(mapType.keyType.trueType)
val valueType = resolver.getJavaClass(mapType.valueType.trueType)
val genericMapType = ParameterizedTypeName.get(TypeNames.MAP, keyType, valueType)
val mapImplType = resolver.mapOf(keyType, valueType)
val mapInfo = "mapMetadata$scope"
val idx = "i$scope"
val key = "key$scope"
val value = "value$scope"
pushScope {
read.addStatement("\$T \$N = protocol.readMapBegin()", TypeNames.MAP_META, mapInfo)
read.addStatement("\$T \$N = new \$T(\$N.size)", genericMapType, nameStack.peek(), mapImplType, mapInfo)
read.beginControlFlow("for (int $1N = 0; $1N < $2N.size; ++$1N)", idx, mapInfo)
nameStack.push(key)
mapType.keyType.accept(this)
nameStack.pop()
pushScope {
nameStack.push(value)
mapType.valueType.accept(this)
nameStack.pop()
}
read.addStatement("\$N.put(\$N, \$N)", nameStack.peek(), key, value)
read.endControlFlow()
read.addStatement("protocol.readMapEnd()")
}
}
override fun visitStruct(structType: StructType) {
val qualifiedJavaName = getFullyQualifiedJavaName(structType)
read.addStatement("$1L $2N = $1L.ADAPTER.read(protocol)", qualifiedJavaName, nameStack.peek())
}
override fun visitTypedef(typedefType: TypedefType) {
// throw AssertionError?
typedefType.trueType.accept(this)
}
override fun visitService(serviceType: ServiceType) {
throw AssertionError("Cannot read a service")
}
private fun getFullyQualifiedJavaName(type: UserType): String {
if (type.isBuiltin || type.isList || type.isMap || type.isSet || type.isTypedef) {
throw AssertionError("Only user and enum types are supported")
}
val packageName = type.getNamespaceFor(NamespaceScope.JAVA)
return packageName + "." + type.name
}
private inline fun pushScope(fn: () -> Unit) {
++scope
try {
fn()
} finally {
--scope
}
}
}
| apache-2.0 |
hzsweers/CatchUp | libraries/util/src/main/kotlin/io/sweers/catchup/util/data/adapters/UnescapeJsonAdapter.kt | 1 | 1925 | /*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.util.data.adapters
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonAdapter.Factory
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Types
import org.unbescape.java.JavaEscape
/**
* [JsonAdapter] that defaults the given element if it is a collection to an empty form
* if it is null, denoted via [UnEscape].
*/
class UnescapeJsonAdapter(private val delegate: JsonAdapter<String>) : JsonAdapter<String>() {
override fun fromJson(reader: JsonReader): String? {
val fromJson: String? = delegate.fromJson(reader)
return JavaEscape.unescapeJava(fromJson)
}
override fun toJson(writer: JsonWriter, value: String?) {
delegate.toJson(writer, value)
}
override fun toString() = "$delegate.unescaping()"
companion object {
@JvmField
val FACTORY = Factory { type, annotations, moshi ->
if (annotations.size > 1) {
// save the iterator
return@Factory null
}
annotations
.find { it is UnEscape }
?.let {
UnescapeJsonAdapter(
moshi.adapter(
type,
Types.nextAnnotations(
annotations,
UnEscape::class.java
)!!
)
)
}
}
}
}
| apache-2.0 |
florent37/Flutter-AssetsAudioPlayer | android/src/main/kotlin/com/github/florent37/assets_audio_player/notification/NotificationSettings.kt | 1 | 1603 | package com.github.florent37.assets_audio_player.notification
import java.io.Serializable
class NotificationSettings(
val nextEnabled: Boolean,
val playPauseEnabled: Boolean,
val prevEnabled: Boolean,
val seekBarEnabled: Boolean,
//android only
val stopEnabled: Boolean,
val previousIcon: String?,
val stopIcon: String?,
val playIcon: String?,
val nextIcon: String?,
val pauseIcon: String?
) : Serializable {
fun numberEnabled() : Int {
var number = 0
if(playPauseEnabled) number++
if(prevEnabled) number++
if(nextEnabled) number++
if(stopEnabled) number++
return number
}
}
fun fetchNotificationSettings(from: Map<*, *>) : NotificationSettings {
return NotificationSettings(
nextEnabled= from["notif.settings.nextEnabled"] as? Boolean ?: true,
stopEnabled= from["notif.settings.stopEnabled"] as? Boolean ?: true,
playPauseEnabled = from["notif.settings.playPauseEnabled"] as? Boolean ?: true,
prevEnabled = from["notif.settings.prevEnabled"] as? Boolean ?: true,
seekBarEnabled = from["notif.settings.seekBarEnabled"] as? Boolean ?: true,
previousIcon = from["notif.settings.previousIcon"] as? String,
nextIcon = from["notif.settings.nextIcon"] as? String,
pauseIcon = from["notif.settings.pauseIcon"] as? String,
playIcon = from["notif.settings.playIcon"] as? String,
stopIcon = from["notif.settings.stopIcon"] as? String
)
} | apache-2.0 |
Turbo87/intellij-emberjs | src/main/kotlin/com/emberjs/yaml/YAMLKeyValueExt.kt | 1 | 435 | package com.emberjs.yaml
import com.emberjs.utils.parents
import org.jetbrains.yaml.psi.YAMLDocument
import org.jetbrains.yaml.psi.YAMLKeyValue
val YAMLKeyValue.keyPath: String
get() = this.parents.takeWhile { it !is YAMLDocument }
.filterIsInstance(YAMLKeyValue::class.java)
.let { listOf(this, *it.toTypedArray()) }
.map { it.keyText }
.reversed()
.joinToString(".")
| apache-2.0 |
hzsweers/CatchUp | services/github/src/main/kotlin/io/sweers/catchup/service/github/model/TrendingItem.kt | 1 | 880 | /*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.service.github.model
data class TrendingItem(
val author: String,
val repoName: String,
val url: String,
val description: String,
val stars: Int,
val forks: Int?,
val starsToday: Int?,
val language: String,
val languageColor: String?
)
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/intentions/branched/unfolding/returnToIf/ifWithNothing.kt | 9 | 115 | // WITH_STDLIB
fun test(b: Boolean): Int {
<caret>return if (b) {
1
} else {
TODO()
}
} | apache-2.0 |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/main/kotlin/entities/identifiers/ImmutableIntSequenceIdentifierEntity.kt | 1 | 606 | package entities.identifiers
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.annotations.Attribute
import com.onyx.persistence.annotations.Entity
import com.onyx.persistence.annotations.Identifier
import com.onyx.persistence.annotations.values.IdentifierGenerator
import entities.AbstractEntity
/**
* Created by timothy.osborn on 11/3/14.
*/
@Entity
class ImmutableIntSequenceIdentifierEntity : AbstractEntity(), IManagedEntity {
@Attribute
@Identifier(generator = IdentifierGenerator.SEQUENCE)
var identifier: Int = 0
@Attribute
var correlation: Int = 0
}
| agpl-3.0 |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinReferenceData.kt | 4 | 2458 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.codeInsight
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import java.awt.datatransfer.DataFlavor
import java.io.Serializable
data class KotlinReferenceData(
var startOffset: Int,
var endOffset: Int,
val fqName: String,
val isQualifiable: Boolean,
val kind: Kind
) : Cloneable, Serializable {
enum class Kind {
CLASS,
PACKAGE,
FUNCTION,
PROPERTY;
companion object {
fun fromDescriptor(descriptor: DeclarationDescriptor) = when (descriptor.getImportableDescriptor()) {
is ClassDescriptor -> CLASS
is PackageViewDescriptor -> PACKAGE
is FunctionDescriptor -> FUNCTION
is PropertyDescriptor -> PROPERTY
else -> null
}
}
}
public override fun clone(): KotlinReferenceData {
try {
return super.clone() as KotlinReferenceData
} catch (e: CloneNotSupportedException) {
throw RuntimeException()
}
}
companion object {
fun isQualifiable(refElement: KtElement, descriptor: DeclarationDescriptor): Boolean {
refElement.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference }?.let {
val receiverExpression = it.receiverExpression
if (receiverExpression != null) {
val lhs = it.analyze(BodyResolveMode.PARTIAL)[BindingContext.DOUBLE_COLON_LHS, receiverExpression]
if (lhs is DoubleColonLHS.Expression) return false
}
return descriptor.containingDeclaration is ClassifierDescriptor
}
return !descriptor.isExtension
}
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/compiler-plugins/parcelize/common/src/org/jetbrains/kotlin/idea/compilerPlugin/parcelize/quickfixes/ParcelRemoveCustomCreatorProperty.kt | 4 | 989 | // 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.compilerPlugin.parcelize.quickfixes
import org.jetbrains.kotlin.idea.compilerPlugin.parcelize.KotlinParcelizeBundle
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
class ParcelRemoveCustomCreatorProperty(property: KtProperty) : AbstractParcelizeQuickFix<KtProperty>(property) {
object Factory : AbstractFactory(f@ {
// KtProperty or its name identifier
psiElement as? KtProperty ?: (psiElement.parent as? KtProperty) ?: return@f null
findElement<KtProperty>()?.let(::ParcelRemoveCustomCreatorProperty)
})
override fun getText() = KotlinParcelizeBundle.message("parcelize.fix.remove.custom.creator.property")
override fun invoke(ktPsiFactory: KtPsiFactory, element: KtProperty) {
element.delete()
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/code-insight/kotlin.code-insight.k2/testData/structureView/fileStructure/InheritedSynthesizedFromDataClass.kt | 4 | 72 | data class TestData(val a: Int) {
fun some() {}
}
// WITH_INHERITED | apache-2.0 |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/find/impl/FindPopupHeader.kt | 8 | 5061 | // 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.find.impl
import com.intellij.find.FindBundle
import com.intellij.find.FindUsagesCollector
import com.intellij.find.impl.FindPopupPanel.ToggleOptionName
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.StateRestoringCheckBox
import com.intellij.ui.dsl.builder.IntelliJSpacingConfiguration
import com.intellij.ui.dsl.builder.RightGap
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.MathUtil
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.Dimension
import javax.swing.Box
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.JLabel
import kotlin.math.max
internal class FindPopupHeader(project: Project, filterContextButton: ActionButton, pinAction: ToggleAction) {
@JvmField
val panel: DialogPanel
lateinit var titleLabel: JLabel
lateinit var infoLabel: JLabel
lateinit var loadingIcon: JLabel
lateinit var cbFileFilter: StateRestoringCheckBox
lateinit var fileMaskField: ComboBox<String>
init {
panel = panel {
customizeSpacingConfiguration(spacingConfiguration = object : IntelliJSpacingConfiguration() {
// Remove default vertical gap around cells, so the header can be smaller
override val verticalComponentGap: Int
get() = if (ExperimentalUI.isNewUI()) 0 else super.verticalComponentGap
}) {
row {
val titleCell = label(FindBundle.message("find.in.path.dialog.title"))
.bold()
titleLabel = titleCell.component
infoLabel = label("")
.gap(RightGap.SMALL)
.component
if (ExperimentalUI.isNewUI()) {
val headerInsets = JBUI.CurrentTheme.ComplexPopup.headerInsets()
titleCell.customize(Gaps(top = headerInsets.top, bottom = headerInsets.bottom, right = JBUI.scale(12)))
infoLabel.foreground = JBUI.CurrentTheme.ContextHelp.FOREGROUND
}
else {
titleCell.gap(RightGap.SMALL)
UIUtil.applyStyle(UIUtil.ComponentStyle.SMALL, infoLabel)
}
loadingIcon = icon(EmptyIcon.ICON_16)
.resizableColumn()
.component
cbFileFilter = cell(createCheckBox(project))
.gap(RightGap.SMALL)
.component
fileMaskField = cell(createFileFilter()).component
cell(filterContextButton)
.gap(RightGap.SMALL)
if (!ExperimentalUI.isNewUI()) {
cell(createSeparator())
.gap(RightGap.SMALL)
}
actionButton(pinAction)
}
}
}
}
private fun createCheckBox(project: Project): StateRestoringCheckBox {
val checkBox = StateRestoringCheckBox(FindBundle.message("find.popup.filemask"))
checkBox.addActionListener {
FindUsagesCollector.CHECK_BOX_TOGGLED.log(project, FindUsagesCollector.FIND_IN_PATH, ToggleOptionName.FileFilter, checkBox.isSelected)
}
return checkBox
}
private fun createFileFilter(): ComboBox<String> {
val result = object : ComboBox<String>() {
override fun getPreferredSize(): Dimension {
var width = 0
var buttonWidth = 0
val components = components
for (component in components) {
val size = component.preferredSize
val w = size?.width ?: 0
if (component is JButton) {
buttonWidth = w
}
width += w
}
val editor = getEditor()
if (editor != null) {
val editorComponent = editor.editorComponent
if (editorComponent != null) {
val fontMetrics = editorComponent.getFontMetrics(editorComponent.font)
val item: Any? = selectedItem
width = max(width, fontMetrics.stringWidth(item.toString()) + buttonWidth)
// Let's reserve some extra space for just one 'the next' letter
width += fontMetrics.stringWidth("m")
}
}
val size = super.getPreferredSize()
val insets = insets
width += insets.left + insets.right
size.width = MathUtil.clamp(width, JBUIScale.scale(80), JBUIScale.scale(500))
return size
}
}
result.isEditable = true
result.maximumRowCount = 8
return result
}
private fun createSeparator(): JComponent {
val result = Box.createRigidArea(JBDimension(1, 24)) as JComponent
result.isOpaque = true
result.background = JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground()
return result
}
}
| apache-2.0 |
KotlinBy/bkug.by | webapp/src/main/kotlin/by/bkug/webapp/App.kt | 1 | 2860 | package by.bkug.webapp
import by.bkug.calendar.IcsCalendarGenerator
import by.bkug.common.DefaultShutdownManager
import by.bkug.data.calendar
import by.bkug.data.internalCalendar
import by.bkug.data.model.Calendar
import by.bkug.shortener.URLShortenerHandler
import io.undertow.Undertow
import io.undertow.server.HttpHandler
import io.undertow.server.HttpServerExchange
import io.undertow.server.RoutingHandler
import io.undertow.server.handlers.PathHandler
import io.undertow.server.handlers.resource.ClassPathResourceManager
import io.undertow.server.handlers.resource.PathResourceManager
import io.undertow.server.handlers.resource.ResourceHandler
import io.undertow.util.Headers
import io.undertow.util.StatusCodes
import java.nio.file.Paths
/**
* Runs web app:
*
* - authentication
* - forms
* - shortener
* - storage
*
* @author Ruslan Ibragimov
* @since 1.0.0
*/
fun main() {
val rootHandler = PathHandler(100)
.addPrefixPath("/", ResourceHandler(
ClassPathResourceManager(
ClassPathResourceManager::class.java.classLoader,
"public"
), ResourceHandler(
PathResourceManager(
Paths.get("web-theme", "dist")
)
)
))
.addPrefixPath("/auth", NoopHandler)
.addPrefixPath("/form", NoopHandler)
.addPrefixPath("/to", URLShortenerHandler())
.addPrefixPath("/files", NoopHandler)
.addPrefixPath("/api", ApiHandler())
.addExactPath("/calendar.ics", CalendarHandler(calendar))
.addExactPath("/calendar-internal.ics", CalendarHandler(internalCalendar))
val server = Undertow.builder()
.addHttpListener(8080, "0.0.0.0")
.setHandler(rootHandler)
.build()
val manager = DefaultShutdownManager()
manager.onShutdown("Undertow") {
server.stop()
}
server.start()
}
class CalendarHandler(
calendarData: Calendar
) : HttpHandler {
private val data = IcsCalendarGenerator().generate(calendarData)
override fun handleRequest(exchange: HttpServerExchange) {
exchange.responseHeaders.put(Headers.CONTENT_TYPE, "text/calendar")
exchange.responseSender.send(data)
}
}
class HealthCheckHandler : HttpHandler {
override fun handleRequest(exchange: HttpServerExchange) {
exchange.statusCode = StatusCodes.OK
exchange.responseSender.send("ok")
}
}
class ApiHandler : HttpHandler {
private val pathHandler = RoutingHandler()
.get("/healthcheck", HealthCheckHandler())
override fun handleRequest(exchange: HttpServerExchange) {
pathHandler.handleRequest(exchange)
}
}
object NoopHandler : HttpHandler {
override fun handleRequest(exchange: HttpServerExchange) {
exchange.responseSender.send(exchange.requestPath)
}
}
| gpl-3.0 |
yongce/AndroidLib | baseLib/src/main/java/me/ycdev/android/lib/common/net/HttpClient.kt | 1 | 5467 | package me.ycdev.android.lib.common.net
import me.ycdev.android.lib.common.utils.IoUtils
import me.ycdev.android.lib.common.utils.LibLogger
import java.io.DataOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.util.HashMap
import java.util.zip.GZIPInputStream
import java.util.zip.InflaterInputStream
@Suppress("unused")
class HttpClient {
private val charset = "UTF-8"
private var connectTimeout: Int = 10_000 // ms
private var readTimeout: Int = 10_1000 // ms
fun setTimeout(connectTimeout: Int, readTimeout: Int) {
this.connectTimeout = connectTimeout
this.readTimeout = readTimeout
}
@Throws(IOException::class)
operator fun get(
url: String,
requestHeaders: HashMap<String, String>
): String {
val httpConn = getHttpConnection(url, false, requestHeaders)
try {
httpConn.connect()
} catch (e: Exception) {
throw IOException(e.toString())
}
try {
return getResponse(httpConn)
} finally {
httpConn.disconnect()
}
}
@Throws(IOException::class)
fun post(url: String, body: String): String {
val httpConn = getHttpConnection(url, true, null)
var os: DataOutputStream? = null
// Send the "POST" request
try {
os = DataOutputStream(httpConn.outputStream)
os.write(body.toByteArray(charset(charset)))
os.flush()
return getResponse(httpConn)
} catch (e: Exception) {
// should not be here, but.....
throw IOException(e.toString())
} finally {
// Must be called before calling HttpURLConnection.disconnect()
IoUtils.closeQuietly(os)
httpConn.disconnect()
}
}
@Throws(IOException::class)
fun post(url: String, body: ByteArray): String {
val httpConn = getHttpConnection(url, true, null)
var os: DataOutputStream? = null
// Send the "POST" request
try {
os = DataOutputStream(httpConn.outputStream)
os.write(body)
os.flush()
return getResponse(httpConn)
} catch (e: Exception) {
// prepare for any unexpected exceptions
throw IOException(e.toString())
} finally {
// Must be called before calling HttpURLConnection.disconnect()
IoUtils.closeQuietly(os)
httpConn.disconnect()
}
}
@Throws(IOException::class)
private fun getHttpConnection(
url: String,
post: Boolean,
requestHeaders: HashMap<String, String>?
): HttpURLConnection {
val httpConn = NetworkUtils.openHttpURLConnection(url)
httpConn.connectTimeout = connectTimeout
httpConn.readTimeout = readTimeout
httpConn.doInput = true
httpConn.useCaches = false
httpConn.setRequestProperty("Accept-Encoding", "gzip,deflate")
httpConn.setRequestProperty("Charset", charset)
if (requestHeaders != null) {
addRequestHeaders(httpConn, requestHeaders)
}
if (post) {
httpConn.doOutput = true
httpConn.requestMethod = "POST"
} else {
httpConn.requestMethod = "GET" // by default
}
return httpConn
}
private fun addRequestHeaders(
httpConn: HttpURLConnection,
requestHeaders: HashMap<String, String>
) {
val allHeaders = requestHeaders.entries
for ((key, value) in allHeaders) {
httpConn.addRequestProperty(key, value)
}
}
@Throws(IOException::class)
private fun getResponse(httpConn: HttpURLConnection): String {
val contentEncoding = httpConn.contentEncoding
LibLogger.d(
TAG, "response code: " + httpConn.responseCode +
", encoding: " + contentEncoding + ", method: " + httpConn.requestMethod
)
var httpInputStream: InputStream? = null
try {
httpInputStream = httpConn.inputStream
} catch (e: IOException) {
// ignore
} catch (e: IllegalStateException) {
}
if (httpInputStream == null) {
// If httpConn.getInputStream() throws IOException,
// we can get the error message from the error stream.
// For example, the case when the response code is 4xx.
httpInputStream = httpConn.errorStream
}
if (httpInputStream == null) {
throw IOException("HttpURLConnection.getInputStream() returned null")
}
val input: InputStream
if (contentEncoding != null && contentEncoding.contains("gzip")) {
input = GZIPInputStream(httpInputStream)
} else if (contentEncoding != null && contentEncoding.contains("deflate")) {
input = InflaterInputStream(httpInputStream)
} else {
input = httpInputStream
}
// Read the response content
try {
val responseContent = input.readBytes()
return String(responseContent, charset(charset))
} finally {
// Must be called before calling HttpURLConnection.disconnect()
IoUtils.closeQuietly(input)
}
}
companion object {
private const val TAG = "HttpClient"
}
}
| apache-2.0 |
jk1/intellij-community | java/java-impl/src/com/intellij/psi/impl/JavaPlatformModuleSystem.kt | 1 | 11070 | // 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.psi.impl
import com.intellij.codeInsight.JavaModuleSystemEx
import com.intellij.codeInsight.JavaModuleSystemEx.ErrorWithFixes
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.JavaErrorMessages
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AddExportsDirectiveFix
import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiresDirectiveFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.JdkOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightJavaModule
import com.intellij.psi.impl.source.PsiJavaModuleReference
import com.intellij.psi.util.PsiUtil
/**
* Checks package accessibility according to JLS 7 "Packages and Modules".
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-7.html">JLS 7 "Packages and Modules"</a>
* @see <a href="http://openjdk.java.net/jeps/261">JEP 261: Module System</a>
*/
class JavaPlatformModuleSystem : JavaModuleSystemEx {
override fun getName(): String = "Java Platform Module System"
override fun isAccessible(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): Boolean =
checkAccess(targetPackageName, targetFile?.originalFile, place, quick = true) == null
override fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): ErrorWithFixes? =
checkAccess(targetPackageName, targetFile?.originalFile, place, quick = false)
private fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement, quick: Boolean): ErrorWithFixes? {
val useFile = place.containingFile?.originalFile
if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) {
val useVFile = useFile.virtualFile
val index = ProjectFileIndex.getInstance(useFile.project)
if (useVFile == null || !index.isInLibrarySource(useVFile)) {
if (targetFile != null && targetFile.isPhysical) {
return checkAccess(targetFile, useFile, targetPackageName, quick)
}
else if (useVFile != null) {
val target = JavaPsiFacade.getInstance(useFile.project).findPackage(targetPackageName)
if (target != null) {
val module = index.getModuleForFile(useVFile)
if (module != null) {
val test = index.isInTestSourceContent(useVFile)
val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test))
if (dirs.isEmpty()) {
return if (quick) ERR else ErrorWithFixes(JavaErrorMessages.message("package.not.found", target.qualifiedName))
}
val error = checkAccess(dirs[0], useFile, target.qualifiedName, quick)
return when {
error == null -> null
dirs.size == 1 -> error
dirs.asSequence().drop(1).any { checkAccess(it, useFile, target.qualifiedName, true) == null } -> null
else -> error
}
}
}
}
}
}
return null
}
private val ERR = ErrorWithFixes("-")
private fun checkAccess(target: PsiFileSystemItem, place: PsiFileSystemItem, packageName: String, quick: Boolean): ErrorWithFixes? {
val targetModule = JavaModuleGraphUtil.findDescriptorByElement(target)
val useModule = JavaModuleGraphUtil.findDescriptorByElement(place)
if (targetModule != null) {
if (targetModule == useModule) {
return null
}
val targetName = targetModule.name
val useName = useModule?.name ?: "ALL-UNNAMED"
val module = place.virtualFile?.let { ProjectFileIndex.getInstance(place.project).getModuleForFile(it) }
if (useModule == null) {
val origin = targetModule.containingFile?.virtualFile
if (origin == null || module == null || ModuleRootManager.getInstance(module).fileIndex.getOrderEntryForFile(origin) !is JdkOrderEntry) {
return null // a target is not on the mandatory module path
}
val root = PsiJavaModuleReference.resolve(place, "java.se", false)
if (!(root == null || JavaModuleGraphUtil.reads(root, targetModule) || inAddedModules(module, targetName))) {
return if (quick) ERR else ErrorWithFixes(
JavaErrorMessages.message("module.access.not.in.graph", packageName, targetName),
listOf(AddModulesOptionFix(module, targetName)))
}
}
if (!(targetModule is LightJavaModule ||
JavaModuleGraphUtil.exports(targetModule, packageName, useModule) ||
module != null && inAddedExports(module, targetName, packageName, useName))) {
if (quick) return ERR
val fixes = when {
packageName.isEmpty() -> emptyList()
targetModule is PsiCompiledElement && module != null -> listOf(AddExportsOptionFix(module, targetName, packageName, useName))
targetModule !is PsiCompiledElement && useModule != null -> listOf(AddExportsDirectiveFix(targetModule, packageName, useName))
else -> emptyList()
}
return when (useModule) {
null -> ErrorWithFixes(JavaErrorMessages.message("module.access.from.unnamed", packageName, targetName), fixes)
else -> ErrorWithFixes(JavaErrorMessages.message("module.access.from.named", packageName, targetName, useName), fixes)
}
}
if (useModule != null && !(targetName == PsiJavaModule.JAVA_BASE || JavaModuleGraphUtil.reads(useModule, targetModule))) {
return when {
quick -> ERR
PsiNameHelper.isValidModuleName(targetName, useModule) -> ErrorWithFixes(
JavaErrorMessages.message("module.access.does.not.read", packageName, targetName, useName),
listOf(AddRequiresDirectiveFix(useModule, targetName)))
else -> ErrorWithFixes(JavaErrorMessages.message("module.access.bad.name", packageName, targetName))
}
}
}
else if (useModule != null) {
return if (quick) ERR else ErrorWithFixes(JavaErrorMessages.message("module.access.to.unnamed", packageName, useModule.name))
}
return null
}
private fun inAddedExports(module: Module, targetName: String, packageName: String, useName: String): Boolean {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module)
if (options.isEmpty()) return false
val prefix = "${targetName}/${packageName}="
return optionValues(options, "--add-exports")
.filter { it.startsWith(prefix) }
.map { it.substring(prefix.length) }
.flatMap { it.splitToSequence(",") }
.any { it == useName }
}
private fun inAddedModules(module: Module, moduleName: String): Boolean {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module)
return optionValues(options, "--add-modules")
.flatMap { it.splitToSequence(",") }
.any { it == moduleName || it == "ALL-SYSTEM" }
}
private fun optionValues(options: List<String>, name: String) =
if (options.isEmpty()) emptySequence()
else {
var useValue = false
options.asSequence()
.map {
when {
it == name -> { useValue = true; "" }
useValue -> { useValue = false; it }
it.startsWith(name) && it[name.length] == '=' -> it.substring(name.length + 1)
else -> ""
}
}
.filterNot { it.isEmpty() }
}
private abstract class CompilerOptionFix(private val module: Module) : IntentionAction {
override fun getFamilyName() = "dfd4a2c1-da18-4651-9aa8-d7d31cae10be" // random string; never visible
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = !module.isDisposed
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (isAvailable(project, editor, file)) {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module).toMutableList()
update(options)
JavaCompilerConfigurationProxy.setAdditionalOptions(module.project, module, options)
PsiManager.getInstance(project).dropPsiCaches()
DaemonCodeAnalyzer.getInstance(project).restart()
}
}
protected abstract fun update(options: MutableList<String>)
override fun startInWriteAction() = true
}
private class AddExportsOptionFix(module: Module, targetName: String, packageName: String, private val useName: String) : CompilerOptionFix(module) {
private val qualifier = "${targetName}/${packageName}"
override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-exports=${qualifier}=${useName}")
override fun update(options: MutableList<String>) {
var idx = -1; var candidate = -1; var offset = 0
for ((i, option) in options.withIndex()) {
if (option.startsWith("--add-exports")) {
if (option.length == 13) { candidate = i + 1 ; offset = 0 }
else if (option[13] == '=') { candidate = i; offset = 14 }
}
if (i == candidate && option.startsWith(qualifier, offset)) {
val qualifierEnd = qualifier.length + offset
if (option.length == qualifierEnd || option[qualifierEnd] == '=') {
idx = i
}
}
}
when {
idx == -1 -> options += "--add-exports=${qualifier}=${useName}"
candidate == options.size -> options[idx - 1] = "--add-exports=${qualifier}=${useName}"
else -> {
val value = options[idx]
options[idx] = if (value.endsWith('=') || value.endsWith(',')) value + useName else "${value},${useName}"
}
}
}
}
private class AddModulesOptionFix(module: Module, private val moduleName: String) : CompilerOptionFix(module) {
override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-modules=${moduleName}")
override fun update(options: MutableList<String>) {
var idx = -1
for ((i, option) in options.withIndex()) {
if (option.startsWith("--add-modules")) {
if (option.length == 13) idx = i + 1
else if (option[13] == '=') idx = i
}
}
when (idx) {
-1 -> options += "--add-modules=${moduleName}"
options.size -> options[idx - 1] = "--add-modules=${moduleName}"
else -> {
val value = options[idx]
options[idx] = if (value.endsWith('=') || value.endsWith(',')) value + moduleName else "${value},${moduleName}"
}
}
}
}
} | apache-2.0 |
ktorio/ktor | ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/Android.kt | 1 | 1309 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.android
import io.ktor.client.*
import io.ktor.client.engine.*
/**
* A JVM/Android client engine that uses `HttpURLConnection` under the hood.
* You can use this engine if your application targets old Android versions (1.x+).
*
* To create the client with this engine, pass it to the `HttpClient` constructor:
* ```kotlin
* val client = HttpClient(Android)
* ```
* To configure the engine, pass settings exposed by [AndroidEngineConfig] to the `engine` method:
* ```kotlin
* val client = HttpClient(Android) {
* engine {
* // this: AndroidEngineConfig
* }
* }
* ```
*
* You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html).
*/
public object Android : HttpClientEngineFactory<AndroidEngineConfig> {
override fun create(block: AndroidEngineConfig.() -> Unit): HttpClientEngine =
AndroidClientEngine(AndroidEngineConfig().apply(block))
}
@Suppress("KDocMissingDocumentation")
public class AndroidEngineContainer : HttpClientEngineContainer {
override val factory: HttpClientEngineFactory<*> = Android
override fun toString(): String = "Android"
}
| apache-2.0 |
seirion/code | google/2019/qualification_round/4/small.kt | 1 | 820 | import java.util.*
fun main(args: Array<String>) {
val t = readLine()!!.toInt()
(1..t).forEach {
solve()
}
}
fun solve() {
val (N, B, F) = readLine()!!.split("\\s".toRegex()).map { it.toInt() }
val response = ArrayList<String>()
(0 until F).forEach {
println(bitFlag(N, 1 shl it))
readLine()!!.let { s -> response.add(s) }
}
val s = ArrayList<Int>(N - B).apply {
repeat(N - B) { add(0) }
}
response.forEachIndexed { row, value ->
value.forEachIndexed { col, v -> if (v == '1') s[col] += (1 shl row) }
}
println((0 until N).toSet().minus(s).joinToString(" "))
readLine()
}
fun bitFlag(size: Int, gap: Int) =
("0".repeat(gap) + "1".repeat(gap))
.repeat(size / gap + gap)
.take(size)
| apache-2.0 |
ktorio/ktor | ktor-http/common/src/io/ktor/http/Cookie.kt | 1 | 7636 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http
import io.ktor.util.*
import io.ktor.util.date.*
import kotlin.jvm.*
/**
* Represents a cookie with name, content and a set of settings such as expiration, visibility and security.
* A cookie with neither [expires] nor [maxAge] is a session cookie.
*
* @property name
* @property value
* @property encoding - cookie encoding type [CookieEncoding]
* @property maxAge number of seconds to keep cookie
* @property expires date when it expires
* @property domain for which it is set
* @property path for which it is set
* @property secure send it via secure connection only
* @property httpOnly only transfer cookie over HTTP, no access from JavaScript
* @property extensions additional cookie extensions
*/
public data class Cookie(
val name: String,
val value: String,
val encoding: CookieEncoding = CookieEncoding.URI_ENCODING,
@get:JvmName("getMaxAgeInt")
val maxAge: Int = 0,
val expires: GMTDate? = null,
val domain: String? = null,
val path: String? = null,
val secure: Boolean = false,
val httpOnly: Boolean = false,
val extensions: Map<String, String?> = emptyMap()
)
/**
* Cooke encoding strategy
*/
public enum class CookieEncoding {
/**
* No encoding (could be dangerous)
*/
RAW,
/**
* Double quotes with slash-escaping
*/
DQUOTES,
/**
* URI encoding
*/
URI_ENCODING,
/**
* BASE64 encoding
*/
BASE64_ENCODING
}
private val loweredPartNames = setOf("max-age", "expires", "domain", "path", "secure", "httponly", "\$x-enc")
/**
* Parse server's `Set-Cookie` header value
*/
public fun parseServerSetCookieHeader(cookiesHeader: String): Cookie {
val asMap = parseClientCookiesHeader(cookiesHeader, false)
val first = asMap.entries.first { !it.key.startsWith("$") }
val encoding = asMap["\$x-enc"]?.let { CookieEncoding.valueOf(it) } ?: CookieEncoding.RAW
val loweredMap = asMap.mapKeys { it.key.toLowerCasePreservingASCIIRules() }
return Cookie(
name = first.key,
value = decodeCookieValue(first.value, encoding),
encoding = encoding,
maxAge = loweredMap["max-age"]?.toIntClamping() ?: 0,
expires = loweredMap["expires"]?.fromCookieToGmtDate(),
domain = loweredMap["domain"],
path = loweredMap["path"],
secure = "secure" in loweredMap,
httpOnly = "httponly" in loweredMap,
extensions = asMap.filterKeys {
it.toLowerCasePreservingASCIIRules() !in loweredPartNames && it != first.key
}
)
}
private val clientCookieHeaderPattern = """(^|;)\s*([^;=\{\}\s]+)\s*(=\s*("[^"]*"|[^;]*))?""".toRegex()
/**
* Parse client's `Cookie` header value
*/
public fun parseClientCookiesHeader(cookiesHeader: String, skipEscaped: Boolean = true): Map<String, String> =
clientCookieHeaderPattern.findAll(cookiesHeader)
.map { (it.groups[2]?.value ?: "") to (it.groups[4]?.value ?: "") }
.filter { !skipEscaped || !it.first.startsWith("$") }
.map { cookie ->
if (cookie.second.startsWith("\"") && cookie.second.endsWith("\"")) {
cookie.copy(second = cookie.second.removeSurrounding("\""))
} else {
cookie
}
}
.toMap()
/**
* Format `Set-Cookie` header value
*/
public fun renderSetCookieHeader(cookie: Cookie): String = with(cookie) {
renderSetCookieHeader(
name,
value,
encoding,
maxAge,
expires,
domain,
path,
secure,
httpOnly,
extensions
)
}
/**
* Format `Cookie` header value
*/
public fun renderCookieHeader(cookie: Cookie): String = with(cookie) {
"$name=${encodeCookieValue(value, encoding)}"
}
/**
* Format `Set-Cookie` header value
*/
public fun renderSetCookieHeader(
name: String,
value: String,
encoding: CookieEncoding = CookieEncoding.URI_ENCODING,
maxAge: Int = 0,
expires: GMTDate? = null,
domain: String? = null,
path: String? = null,
secure: Boolean = false,
httpOnly: Boolean = false,
extensions: Map<String, String?> = emptyMap(),
includeEncoding: Boolean = true
): String = (
listOf(
cookiePart(name.assertCookieName(), value, encoding),
cookiePartUnencoded("Max-Age", if (maxAge > 0) maxAge else null),
cookiePartUnencoded("Expires", expires?.toHttpDate()),
cookiePart("Domain", domain, CookieEncoding.RAW),
cookiePart("Path", path, CookieEncoding.RAW),
cookiePartFlag("Secure", secure),
cookiePartFlag("HttpOnly", httpOnly)
) + extensions.map { cookiePartExt(it.key.assertCookieName(), it.value) } +
if (includeEncoding) cookiePartExt("\$x-enc", encoding.name) else ""
).filter { it.isNotEmpty() }
.joinToString("; ")
/**
* Encode cookie value using the specified [encoding]
*/
public fun encodeCookieValue(value: String, encoding: CookieEncoding): String = when (encoding) {
CookieEncoding.RAW -> when {
value.any { it.shouldEscapeInCookies() } ->
throw IllegalArgumentException(
"The cookie value contains characters that cannot be encoded in RAW format. " +
" Consider URL_ENCODING mode"
)
else -> value
}
CookieEncoding.DQUOTES -> when {
value.contains('"') -> throw IllegalArgumentException(
"The cookie value contains characters that cannot be encoded in DQUOTES format. " +
"Consider URL_ENCODING mode"
)
value.any { it.shouldEscapeInCookies() } -> "\"$value\""
else -> value
}
CookieEncoding.BASE64_ENCODING -> value.encodeBase64()
CookieEncoding.URI_ENCODING -> value.encodeURLParameter(spaceToPlus = true)
}
/**
* Decode cookie value using the specified [encoding]
*/
public fun decodeCookieValue(encodedValue: String, encoding: CookieEncoding): String = when (encoding) {
CookieEncoding.RAW, CookieEncoding.DQUOTES -> when {
encodedValue.trimStart().startsWith("\"") && encodedValue.trimEnd().endsWith("\"") ->
encodedValue.trim().removeSurrounding("\"")
else -> encodedValue
}
CookieEncoding.URI_ENCODING -> encodedValue.decodeURLQueryComponent(plusIsSpace = true)
CookieEncoding.BASE64_ENCODING -> encodedValue.decodeBase64String()
}
private fun String.assertCookieName() = when {
any { it.shouldEscapeInCookies() } -> throw IllegalArgumentException("Cookie name is not valid: $this")
else -> this
}
private val cookieCharsShouldBeEscaped = setOf(';', ',', '"')
private fun Char.shouldEscapeInCookies() = isWhitespace() || this < ' ' || this in cookieCharsShouldBeEscaped
@Suppress("NOTHING_TO_INLINE")
private inline fun cookiePart(name: String, value: Any?, encoding: CookieEncoding) =
if (value != null) "$name=${encodeCookieValue(value.toString(), encoding)}" else ""
@Suppress("NOTHING_TO_INLINE")
private inline fun cookiePartUnencoded(name: String, value: Any?) =
if (value != null) "$name=$value" else ""
@Suppress("NOTHING_TO_INLINE")
private inline fun cookiePartFlag(name: String, value: Boolean) =
if (value) name else ""
@Suppress("NOTHING_TO_INLINE")
private inline fun cookiePartExt(name: String, value: String?) =
if (value == null) cookiePartFlag(name, true) else cookiePart(name, value, CookieEncoding.RAW)
private fun String.toIntClamping(): Int = toLong().coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
| apache-2.0 |
Novatec-Consulting-GmbH/testit-testutils | logrecorder/logrecorder-assertions/src/main/kotlin/info/novatec/testit/logrecorder/assertion/blocks/MessagesAssertionBlock.kt | 1 | 6330 | /*
* Copyright 2017-2021 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 info.novatec.testit.logrecorder.assertion.blocks
import info.novatec.testit.logrecorder.api.LogLevel
import info.novatec.testit.logrecorder.api.LogLevel.*
import info.novatec.testit.logrecorder.assertion.DslContext
import info.novatec.testit.logrecorder.assertion.matchers.LogLevelMatcher
import info.novatec.testit.logrecorder.assertion.matchers.MessageMatcher
import info.novatec.testit.logrecorder.assertion.matchers.level.AnyLogLevelMatcher
import info.novatec.testit.logrecorder.assertion.matchers.level.EqualLogLevelMatcher
import info.novatec.testit.logrecorder.assertion.matchers.message.*
@DslContext
interface MessagesAssertionBlock : AssertionBlock {
fun addExpectation(logLevelMatcher: LogLevelMatcher, messageMatchers: List<MessageMatcher>)
// message expectation factories
/**
* Define the expectation of a [TRACE] message equal to the provided `message`.
*/
fun trace(message: String) = trace(equalTo(message))
/**
* Define the expectation of a [TRACE] message that complies with _all_ specified [MessageMatcher].
*
* Will match any [TRACE] if not at least one [MessageMatcher] is specified.
*/
fun trace(vararg messageMatchers: MessageMatcher) = addExpectation(equalTo(TRACE), messageMatchers.toList())
/**
* Define the expectation of a [DEBUG] message equal to the provided `message`.
*/
fun debug(message: String) = debug(equalTo(message))
/**
* Define the expectation of a [DEBUG] message that complies with _all_ specified [MessageMatcher].
*
* Will match any [DEBUG] if not at least one [MessageMatcher] is specified.
*/
fun debug(vararg messageMatchers: MessageMatcher) = addExpectation(equalTo(DEBUG), messageMatchers.toList())
/**
* Define the expectation of a [INFO] message equal to the provided `message`.
*/
fun info(message: String) = info(equalTo(message))
/**
* Define the expectation of a [INFO] message that complies with _all_ specified [MessageMatcher].
*
* Will match any [INFO] if not at least one [MessageMatcher] is specified.
*/
fun info(vararg messageMatchers: MessageMatcher) = addExpectation(equalTo(INFO), messageMatchers.toList())
/**
* Define the expectation of a [WARN] message equal to the provided `message`.
*/
fun warn(message: String) = warn(equalTo(message))
/**
* Define the expectation of a [WARN] message that complies with _all_ specified [MessageMatcher].
*
* Will match any [WARN] if not at least one [MessageMatcher] is specified.
*/
fun warn(vararg messageMatchers: MessageMatcher) = addExpectation(equalTo(WARN), messageMatchers.toList())
/**
* Define the expectation of a [ERROR] message equal to the provided `message`.
*/
fun error(message: String) = error(equalTo(message))
/**
* Define the expectation of a [ERROR] message that complies with _all_ specified [MessageMatcher].
*
* Will match any [WARN] if not at least one [MessageMatcher] is specified.
*/
fun error(vararg messageMatchers: MessageMatcher) = addExpectation(equalTo(ERROR), messageMatchers.toList())
/**
* Define the expectation of a message, with any log level, and a value equal to the provided `message`.
*/
fun any(message: String) = any(equalTo(message))
/**
* Define the expectation of a message, with any log level, that complies with _all_ specified [MessageMatcher].
*
* Will match any message if not at least one [MessageMatcher] is specified.
*/
fun any(vararg messageMatchers: MessageMatcher) = addExpectation(anyLogLevel(), messageMatchers.toList())
/**
* This matcher can be used to skip log messages, that are not of any interest.
* It will match any massage with any log level.
*/
fun anything() = any()
// message value matcher factories
/**
* Will match if the actual message is equal to the expected message.
*
* @see EqualMessageMatcher
*/
fun equalTo(message: String): MessageMatcher = EqualMessageMatcher(message)
/**
* Will match if the actual message matches the provided regular expression.
*
* @see RegexMessageMatcher
*/
fun matches(regex: String): MessageMatcher = RegexMessageMatcher(regex)
/**
* Will match if the actual message contains all the provided parts in _any order_.
*
* @see ContainsMessageMatcher
*/
fun contains(vararg parts: String): MessageMatcher = ContainsMessageMatcher(parts.toList())
/**
* Will match if the actual message contains all the provided parts in that _exact order_.
*
* @see ContainsInOrderMessageMatcher
*/
fun containsInOrder(vararg parts: String): MessageMatcher = ContainsInOrderMessageMatcher(parts.toList())
/**
* Will match if the actual message starts with the provided _prefix_.
*
* @see StartsWithMessageMatcher
*/
fun startsWith(prefix: String): MessageMatcher = StartsWithMessageMatcher(prefix)
/**
* Will match if the actual message ends with the provided _suffix_.
*
* @see EndsWithMessageMatcher
*/
fun endsWith(suffix: String): MessageMatcher = EndsWithMessageMatcher(suffix)
// log level matcher factories
/**
* Will match if the actual log level is equal to the expected level.
*
* @see EqualLogLevelMatcher
*/
fun equalTo(logLevel: LogLevel): LogLevelMatcher = EqualLogLevelMatcher(logLevel)
/**
* Will match for all log levels.
*
* @see AnyLogLevelMatcher
*/
fun anyLogLevel(): LogLevelMatcher = AnyLogLevelMatcher()
}
| apache-2.0 |
airbnb/lottie-android | sample/src/main/kotlin/com/airbnb/lottie/samples/LottiefilesFragment.kt | 1 | 6546 | package com.airbnb.lottie.samples
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingDataAdapter
import androidx.paging.PagingSource
import androidx.paging.PagingState
import androidx.paging.cachedIn
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.samples.api.LottiefilesApi
import com.airbnb.lottie.samples.databinding.LottiefilesFragmentBinding
import com.airbnb.lottie.samples.model.AnimationData
import com.airbnb.lottie.samples.model.AnimationResponse
import com.airbnb.lottie.samples.model.CompositionArgs
import com.airbnb.lottie.samples.utils.MvRxViewModel
import com.airbnb.lottie.samples.utils.hideKeyboard
import com.airbnb.lottie.samples.utils.viewBinding
import com.airbnb.lottie.samples.views.AnimationItemView
import com.airbnb.mvrx.BaseMvRxFragment
import com.airbnb.mvrx.MvRxState
import com.airbnb.mvrx.MvRxViewModelFactory
import com.airbnb.mvrx.ViewModelContext
import com.airbnb.mvrx.fragmentViewModel
import com.airbnb.mvrx.withState
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
data class LottiefilesState(
val mode: LottiefilesMode = LottiefilesMode.Recent,
val query: String = ""
) : MvRxState
class LottiefilesViewModel(initialState: LottiefilesState, private val api: LottiefilesApi) : MvRxViewModel<LottiefilesState>(initialState) {
private var mode = initialState.mode
private var query = initialState.query
private var dataSource: LottiefilesDataSource? = null
val pager = Pager(PagingConfig(pageSize = 16)) {
LottiefilesDataSource(api, mode, query).also { dataSource = it }
}.flow.cachedIn(viewModelScope)
init {
selectSubscribe(LottiefilesState::mode, LottiefilesState::query) { mode, query ->
this.mode = mode
this.query = query
dataSource?.invalidate()
}
}
fun setMode(mode: LottiefilesMode) = setState { copy(mode = mode) }
fun setQuery(query: String) = setState { copy(query = query) }
companion object : MvRxViewModelFactory<LottiefilesViewModel, LottiefilesState> {
override fun create(viewModelContext: ViewModelContext, state: LottiefilesState): LottiefilesViewModel {
val service = viewModelContext.app<LottieApplication>().lottiefilesService
return LottiefilesViewModel(state, service)
}
}
}
class LottiefilesDataSource(
private val api: LottiefilesApi,
val mode: LottiefilesMode,
private val query: String
) : PagingSource<Int, AnimationData>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, AnimationData> {
val page = params.key ?: 1
return try {
val response = when (mode) {
LottiefilesMode.Popular -> api.getPopular(page)
LottiefilesMode.Recent -> api.getRecent(page)
LottiefilesMode.Search -> {
if (query.isBlank()) {
AnimationResponse(page, emptyList(), "", page, null, "", 0, "", 0, 0)
} else {
api.search(query, page)
}
}
}
LoadResult.Page(
response.data,
if (page == 1) null else page + 1,
(page + 1).takeIf { page < response.lastPage }
)
} catch (e: Exception) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Int, AnimationData>): Int? {
return state.closestItemToPosition(state.anchorPosition ?: return null)?.id as Int?
}
}
class LottiefilesFragment : BaseMvRxFragment(R.layout.lottiefiles_fragment) {
private val binding: LottiefilesFragmentBinding by viewBinding()
private val viewModel: LottiefilesViewModel by fragmentViewModel()
private object AnimationItemDataDiffCallback : DiffUtil.ItemCallback<AnimationData>() {
override fun areItemsTheSame(oldItem: AnimationData, newItem: AnimationData) = oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: AnimationData, newItem: AnimationData) = oldItem == newItem
}
private class AnimationItemViewHolder(context: Context) : RecyclerView.ViewHolder(AnimationItemView(context)) {
fun bind(data: AnimationData?) {
val view = itemView as AnimationItemView
view.setTitle(data?.title)
view.setPreviewUrl(data?.preview)
view.setPreviewBackgroundColor(data?.bgColorInt)
view.setOnClickListener {
val intent = PlayerActivity.intent(view.context, CompositionArgs(animationData = data))
view.context.startActivity(intent)
}
}
}
private val adapter = object : PagingDataAdapter<AnimationData, AnimationItemViewHolder>(AnimationItemDataDiffCallback) {
override fun onBindViewHolder(holder: AnimationItemViewHolder, position: Int) = holder.bind(getItem(position))
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = AnimationItemViewHolder(parent.context)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.recyclerView.adapter = adapter
viewLifecycleOwner.lifecycleScope.launch {
viewModel.pager.collectLatest(adapter::submitData)
}
binding.tabBar.setRecentClickListener {
viewModel.setMode(LottiefilesMode.Recent)
requireContext().hideKeyboard()
}
binding.tabBar.setPopularClickListener {
viewModel.setMode(LottiefilesMode.Popular)
requireContext().hideKeyboard()
}
binding.tabBar.setSearchClickListener {
viewModel.setMode(LottiefilesMode.Search)
requireContext().hideKeyboard()
}
binding.searchView.query.onEach { query ->
viewModel.setQuery(query)
}.launchIn(viewLifecycleOwner.lifecycleScope)
}
override fun invalidate(): Unit = withState(viewModel) { state ->
binding.searchView.isVisible = state.mode == LottiefilesMode.Search
binding.tabBar.setMode(state.mode)
}
} | apache-2.0 |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/block/BlockData.kt | 1 | 2677 | /*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.block
import com.mcmoonlake.api.packet.PacketOutBlockChange
import com.mcmoonlake.api.util.ComparisonChain
/**
* ## BlockData (方块数据)
*
* @author lgou2w
* @since 2.0
* @constructor BlockData
* @param type Type id of this block data.
* @param type 此方块数据的类型 Id
* @param data Data value of this block.
* @param data 此方块数据的数据值.
*/
data class BlockData(
/**
* * The type id of this block data.
* * 此方块数据的类型 Id.
*/
val type: Int,
/**
* * The data value of this block data.
* * 此方块数据的数据值.
*/
val data: Int
) : Comparable<BlockData> {
override fun compareTo(other: BlockData): Int {
return ComparisonChain.start()
.compare(type, other.type)
.compare(data, other.data)
.result
}
/**
* * Get the block data for the id of the packet.
* * 获取此方块数据用于数据包的 Id.
*
* @see [PacketOutBlockChange]
*/
fun toId(): Int
= toId(this)
companion object {
/**
* * Air Block Data.
* * 空气方块数据.
*/
@JvmField
val AIR = BlockData(0, 0)
/**
* * Get the block data from the given id.
* * 从给定的 Id 获取方块数据.
*
* @param id Id
*/
@JvmStatic
@JvmName("fromId")
fun fromId(id: Int): BlockData
= BlockData(id shr 4, id and 15)
/**
* * Get id from given block data.
* * 从给定的方块数据获取 Id.
*
* @param data Block data.
* @param data 方块数据.
*/
@JvmStatic
@JvmName("toId")
fun toId(data: BlockData): Int
= (data.type shl 4) or (data.data and 15)
}
}
| gpl-3.0 |
Kerooker/rpg-npc-generator | app/src/main/java/me/kerooker/rpgnpcgenerator/view/random/npc/RandomNpcElementListview.kt | 1 | 1299 | package me.kerooker.rpgnpcgenerator.view.random.npc
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import androidx.cardview.widget.CardView
import kotlinx.android.synthetic.main.randomnpc_element_list_view_item.view.*
import kotlinx.android.synthetic.main.randomnpc_element_view.view.random_field_dice
class RandomNpcElementListview(context: Context, attrs: AttributeSet) : CardView(context, attrs) {
var onDeleteClick = { }
var onRandomClick = { }
var onManualInput = object : ManualInputListener {
override fun onManualInput(text: String) { }
}
override fun onFinishInflate() {
super.onFinishInflate()
prepareEventListeners()
}
private fun prepareEventListeners() {
random_npc_minus.setOnClickListener { onDeleteClick() }
random_npc_list_item_element.onRandomClick = { onRandomClick() }
random_npc_list_item_element.onManualInput = object : ManualInputListener {
override fun onManualInput(text: String) {
onManualInput.onManualInput(text)
}
}
}
fun setText(text: String) { random_npc_list_item_element.text = text }
fun setHint(hint: String) { random_npc_list_item_element.setHint(hint) }
}
| apache-2.0 |
Tickaroo/tikxml | annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/element/ServerConfigDataClass.kt | 1 | 1075 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tickaroo.tikxml.annotationprocessing.element
import com.tickaroo.tikxml.annotation.Attribute
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.Xml
/**
* @author Hannes Dorfmann
*/
@Xml(name = "serverConfig")
data class ServerConfigDataClass(
@field:Attribute
var enabled: Boolean = false,
@field:PropertyElement
var ip: String? = null
)
| apache-2.0 |
meik99/CoffeeList | app/src/main/java/rynkbit/tk/coffeelist/ui/item/ItemAdapter.kt | 1 | 1864 | package rynkbit.tk.coffeelist.ui.item
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import rynkbit.tk.coffeelist.R
import rynkbit.tk.coffeelist.contract.entity.Item
/**
* Created by michael on 13/11/16.
*/
class ItemAdapter : RecyclerView.Adapter<ItemAdapter.ViewHolder>() {
private var items = mutableListOf<Item>()
var onClickListener: ((item: Item) -> Unit)? = null
fun updateItems(itemList: List<Item>) {
items.clear()
items.addAll(itemList)
this.notifyDataSetChanged()
}
class ViewHolder(internal var view: View) : RecyclerView.ViewHolder(view) {
internal var txtItemName: TextView = view.findViewById<View>(R.id.txtItemName) as TextView
internal var txtItemPrice: TextView = view.findViewById<View>(R.id.txtItemPrice) as TextView
internal var txtItemStock: TextView = view.findViewById<View>(R.id.txtItemStock) as TextView
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemAdapter.ViewHolder {
val itemView = View.inflate(parent.context, R.layout.item_card, null)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
holder.txtItemName.text = item.name
holder.txtItemStock.text = String.format(
holder.view.context.getString(R.string.item_stock),
item.stock
)
holder.txtItemPrice.text = String.format(
holder.view.context.getString(R.string.item_price),
item.price
)
holder.view.setOnClickListener {
onClickListener?.apply { this(item) }
}
}
override fun getItemCount(): Int {
return items.size
}
}
| mit |
iSoron/uhabits | uhabits-android/src/test/java/org/isoron/uhabits/receivers/ReminderControllerTest.kt | 1 | 2553 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.receivers
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import org.isoron.uhabits.BaseAndroidJVMTest
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.Timestamp
import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.reminders.ReminderScheduler
import org.isoron.uhabits.core.ui.NotificationTray
import org.junit.Test
class ReminderControllerTest : BaseAndroidJVMTest() {
private lateinit var controller: ReminderController
private lateinit var reminderScheduler: ReminderScheduler
private lateinit var notificationTray: NotificationTray
private lateinit var preferences: Preferences
override fun setUp() {
super.setUp()
reminderScheduler = mock()
notificationTray = mock()
preferences = mock()
controller = ReminderController(
reminderScheduler,
notificationTray,
preferences
)
}
@Test
@Throws(Exception::class)
fun testOnDismiss() {
verifyNoMoreInteractions(reminderScheduler)
verifyNoMoreInteractions(notificationTray)
verifyNoMoreInteractions(preferences)
}
@Test
@Throws(Exception::class)
fun testOnShowReminder() {
val habit: Habit = mock()
controller.onShowReminder(habit, Timestamp.ZERO.plus(100), 456)
verify(notificationTray).show(habit, Timestamp.ZERO.plus(100), 456)
verify(reminderScheduler).scheduleAll()
}
@Test
@Throws(Exception::class)
fun testOnBootCompleted() {
controller.onBootCompleted()
verify(reminderScheduler).scheduleAll()
}
}
| gpl-3.0 |
mdanielwork/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/completion/providers/EditorConfigComplexKeyTemplateCompletionProvider.kt | 1 | 1741 | // 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.completion.providers
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.template.impl.LiveTemplateLookupElementImpl
import com.intellij.patterns.PsiElementPattern
import com.intellij.psi.PsiElement
import com.intellij.util.ProcessingContext
import org.editorconfig.language.psi.EditorConfigSection
import org.editorconfig.language.services.EditorConfigOptionDescriptorManager
import org.editorconfig.language.util.EditorConfigPsiTreeUtil.getParentOfType
import org.editorconfig.language.util.EditorConfigTemplateUtil
object EditorConfigComplexKeyTemplateCompletionProvider : EditorConfigCompletionProviderBase() {
override val destination: PsiElementPattern.Capture<PsiElement>
get() = EditorConfigSimpleOptionKeyCompletionProvider.destination
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val section = parameters.position.getParentOfType<EditorConfigSection>() ?: return
val descriptors = EditorConfigOptionDescriptorManager.instance.getQualifiedKeys(true)
EditorConfigTemplateUtil
.buildSameStartClasses(descriptors)
.filter { (_, sameStartClass) -> EditorConfigTemplateUtil.checkStructuralEquality(sameStartClass) }
.map { (string, list) -> EditorConfigTemplateUtil.buildTemplate(string, list, section, initialNewLine = false) }
.map { LiveTemplateLookupElementImpl(it, true) }
.forEach(result::addElement)
}
}
| apache-2.0 |
cdietze/klay | klay-jvm/src/main/kotlin/klay/jvm/JavaSound.kt | 1 | 1640 | package klay.jvm
import euklid.f.MathUtil
import klay.core.Exec
import klay.core.SoundImpl
import javax.sound.sampled.Clip
import javax.sound.sampled.FloatControl
import kotlin.math.log10
class JavaSound(exec: Exec) : SoundImpl<Clip>(exec) {
override fun playingImpl(): Boolean {
return impl!!.isActive
}
override fun playImpl(): Boolean {
impl!!.framePosition = 0
if (_looping) {
impl!!.loop(Clip.LOOP_CONTINUOUSLY)
} else {
impl!!.start()
}
return true
}
override fun stopImpl() {
impl!!.stop()
impl!!.flush()
}
override fun setLoopingImpl(looping: Boolean) {
// nothing to do here, we pass looping to impl.play()
}
override fun setVolumeImpl(volume: Float) {
if (impl!!.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
val volctrl = impl!!.getControl(FloatControl.Type.MASTER_GAIN) as FloatControl
volctrl.value = toGain(volume, volctrl.minimum, volctrl.maximum)
}
}
override fun releaseImpl() {
impl!!.close()
}
companion object {
// @Override
// public float volume() {
// FloatControl volctrl = (FloatControl) impl.getControl(FloatControl.Type.MASTER_GAIN);
// return toVolume(volctrl.getValue());
// }
// protected static float toVolume (float gain) {
// return MathUtil.pow(10, gain/20);
// }
private fun toGain(volume: Float, min: Float, max: Float): Float {
return MathUtil.clamp(20 * log10(volume), min, max)
}
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/old/tests/testData/fileOrElement/enum/runnableImplementation.kt | 25 | 216 | internal enum class Color : Runnable {
WHITE, BLACK, RED, YELLOW, BLUE;
override fun run() {
println(
"name()=" + name +
", toString()=" + toString()
)
}
} | apache-2.0 |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/factory/Factories.kt | 1 | 29609 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
@file:JvmName("Factories")
package com.github.jonathanxd.kores.factory
import com.github.jonathanxd.kores.*
import com.github.jonathanxd.kores.base.*
import com.github.jonathanxd.kores.base.Annotation
import com.github.jonathanxd.kores.base.Retention
import com.github.jonathanxd.kores.base.comment.Comments
import com.github.jonathanxd.kores.common.KoresNothing
import com.github.jonathanxd.kores.common.Void
import com.github.jonathanxd.kores.literal.Literals
import com.github.jonathanxd.kores.operator.Operator
import com.github.jonathanxd.kores.operator.Operators
import com.github.jonathanxd.kores.type.PlainKoresType
import java.lang.reflect.Type
import java.util.*
// Access
/**
* @see Access
*/
fun accessStatic(): Access = Defaults.ACCESS_STATIC
/**
* @see Access
*/
fun accessLocal(): Access = Defaults.ACCESS_LOCAL
/**
* @see Access
*/
fun accessThis(): Access = Defaults.ACCESS_THIS
/**
* @see Access
*/
fun accessSuper(): Access = Defaults.ACCESS_SUPER
// Annotations
/**
* @see Annotation
*/
@JvmOverloads
fun annotation(
retention: com.github.jonathanxd.kores.base.Retention,
type: Type,
values: Map<String, Any> = emptyMap()
): Annotation =
Annotation(type, values, retention)
/**
* @see Annotation
*/
@JvmOverloads
fun runtimeAnnotation(type: Type, values: Map<String, Any> = emptyMap()): Annotation =
annotation(Retention.RUNTIME, type, values)
/**
* @see Annotation
*/
@JvmOverloads
fun classAnnotation(type: Type, values: Map<String, Any> = emptyMap()): Annotation =
annotation(Retention.CLASS, type, values)
/**
* @see Annotation
*/
@JvmOverloads
fun sourceAnnotation(type: Type, values: Map<String, Any> = emptyMap()): Annotation =
annotation(Retention.SOURCE, type, values)
/**
* @see Annotation
*/
fun overrideAnnotation(): Annotation = sourceAnnotation(Override::class.java, mapOf())
/**
* @see Annotation
*/
fun deprecatedAnnotation(): Annotation = sourceAnnotation(Deprecated::class.java, mapOf())
/**
* @see Annotation
*/
@JvmOverloads
fun annotationProperty(
comments: Comments = Comments.Absent,
annotations: List<Annotation> = emptyList(),
type: Type,
name: String,
defaultValue: Any?
): AnnotationProperty =
AnnotationProperty(comments, annotations, type, name, defaultValue)
// Arrays
/**
* @see ArrayConstructor
*/
fun createArray(
arrayType: Type,
dimensions: List<Instruction>,
arguments: List<Instruction>
): ArrayConstructor =
ArrayConstructor(arrayType, dimensions, arguments)
/**
* @see ArrayConstructor
*/
fun createArray1D(arrayType: Type, arguments: List<Instruction>): ArrayConstructor =
ArrayConstructor(arrayType, listOf(Literals.INT(arguments.size)), arguments)
/**
* Creates array of type [arrayType] with [dimension] for receiver instructions.
*
* @see ArrayConstructor
*/
fun List<Instruction>.createArray(
arrayType: Type,
dimensions: List<Instruction>
): ArrayConstructor =
ArrayConstructor(arrayType = arrayType, dimensions = dimensions, arguments = this)
/**
* @see ArrayStore
*/
fun setArrayValue(
arrayType: Type,
target: Instruction,
index: Instruction,
valueType: Type,
valueToStore: Instruction
): ArrayStore =
ArrayStore(arrayType, target, index, valueType, valueToStore)
/**
* Sets value at [index] of [receiver array][Instruction] of type [arrayType] to [valueToStore].
*
* @see ArrayStore
*/
fun Instruction.setArrayValue(
arrayType: Type,
index: Instruction,
valueType: Type,
valueToStore: Instruction
): ArrayStore =
ArrayStore(
arrayType = arrayType,
target = this,
index = index,
valueType = valueType,
valueToStore = valueToStore
)
/**
* Sets value at [index] of [receiver array][TypedInstruction] of type [arrayType][TypedInstruction.type] to [valueToStore].
*
* @see ArrayStore
*/
fun TypedInstruction.setArrayValue(
index: Instruction,
valueType: Type,
valueToStore: Instruction
): ArrayStore =
ArrayStore(
arrayType = this.type,
target = this,
index = index,
valueType = valueType,
valueToStore = valueToStore
)
/**
* @see ArrayLoad
*/
fun accessArrayValue(
arrayType: Type,
target: Instruction,
index: Instruction,
valueType: Type
): ArrayLoad =
ArrayLoad(arrayType, target, index, valueType)
/**
* @see ArrayLoad
*/
fun TypedInstruction.accessArrayValue(
index: Instruction,
valueType: Type
): ArrayLoad =
ArrayLoad(this.type, this, index, valueType)
/**
* Accesses the value of [valueType] of [receiver array][Instruction] at [index].
*
* @see ArrayLoad
*/
fun Instruction.accessArrayValue(
arrayType: Type,
index: Instruction,
valueType: Type
): ArrayLoad =
ArrayLoad(arrayType = arrayType, target = this, index = index, valueType = valueType)
/**
* @see ArrayLength
*/
fun arrayLength(arrayType: Type, target: Instruction): ArrayLength =
ArrayLength(arrayType, target)
/**
* Accesses the length of [receiver array][Instruction] of type [arrayType].
* @see ArrayLength
*/
fun Instruction.arrayLength(arrayType: Type): ArrayLength =
ArrayLength(arrayType, target = this)
/**
* Accesses the length of [receiver array][Instruction] of type [arrayType].
* @see ArrayLength
*/
fun TypedInstruction.arrayLength(): ArrayLength =
ArrayLength(this.type, target = this)
// Enum
/**
* @see EnumEntry
*/
fun enumEntry(name: String): EnumEntry =
EnumEntry.Builder.builder()
.name(name)
.build()
/**
* @see EnumValue
*/
fun enumValue(enumType: Type, enumEntry: String): EnumValue =
EnumValue(enumType, enumEntry)
// Variable
/**
* @see VariableAccess
*/
fun accessVariable(type: Type, name: String): VariableAccess =
VariableAccess(type, name)
/**
* @see VariableAccess
*/
fun accessVariable(variable: VariableBase): VariableAccess =
accessVariable(variable.type, variable.name)
/**
* @see VariableDefinition
*/
fun setVariableValue(type: Type, name: String, value: Instruction): VariableDefinition =
VariableDefinition(type, name, value)
/**
* @see VariableDefinition
*/
fun setVariableValue(name: String, value: TypedInstruction): VariableDefinition =
VariableDefinition(value.type, name, value)
/**
* @see VariableDefinition
*/
fun setVariableValue(variable: VariableBase, value: Instruction): VariableDefinition =
VariableDefinition(variable.type, variable.name, value)
// Field
/**
* @see FieldAccess
*/
fun accessField(
localization: Type,
target: Instruction,
type: Type,
name: String
): FieldAccess =
FieldAccess(localization, target, type, name)
/**
* Access field with [name] and [type] of [receiver][Instruction] in [localization].
*
* @see FieldAccess
*/
fun Instruction.accessField(
localization: Type,
type: Type,
name: String
): FieldAccess =
FieldAccess(localization = localization, target = this, type = type, name = name)
/**
* Access field with [name] and [type][TypedInstruction.type] of [receiver][Instruction] in [localization].
*
* @see FieldAccess
*/
fun TypedInstruction.accessField(
localization: Type,
name: String
): FieldAccess =
FieldAccess(localization = localization, target = this, type = this.type, name = name)
/**
* @see FieldAccess
*/
fun accessThisField(type: Type, name: String): FieldAccess =
accessField(Alias.THIS, accessThis(), type, name)
/**
* @see FieldAccess
*/
@JvmOverloads
fun accessStaticField(localization: Type = Alias.THIS, type: Type, name: String): FieldAccess =
accessField(localization, accessStatic(), type, name)
/**
* @see FieldDefinition
*/
fun setFieldValue(
localization: Type,
target: Instruction,
type: Type,
name: String,
value: Instruction
): FieldDefinition =
FieldDefinition(localization, target, type, name, value)
/**
* Sets field [name] of [type] of [receiver][Instruction] in [localization].
*
* @see FieldDefinition
*/
fun Instruction.setFieldValue(
localization: Type,
type: Type,
name: String,
value: Instruction
): FieldDefinition =
FieldDefinition(
localization = localization,
target = this,
type = type,
name = name,
value = value
)
/**
* Sets field [name] of [receiver type][TypedInstruction.type] of [receiver][TypedInstruction] in [localization].
*
* @see FieldDefinition
*/
fun TypedInstruction.setFieldValue(
localization: Type,
name: String,
value: Instruction
): FieldDefinition =
FieldDefinition(
localization = localization,
target = this,
type = this.type,
name = name,
value = value
)
/**
* @see FieldDefinition
*/
fun setThisFieldValue(type: Type, name: String, value: Instruction): FieldDefinition =
setFieldValue(Alias.THIS, Access.THIS, type, name, value)
/**
* @see FieldDefinition
*/
fun TypedInstruction.setToThisFieldValue(name: String): FieldDefinition =
setFieldValue(Alias.THIS, Access.THIS, this.type, name, this)
/**
* @see FieldDefinition
*/
@JvmOverloads
fun setStaticFieldValue(
localization: Type = Alias.THIS,
type: Type,
name: String,
value: Instruction
): FieldDefinition =
setFieldValue(localization, Access.STATIC, type, name, value)
/**
* @see FieldDefinition
*/
@JvmOverloads
fun setStaticFieldValue(
localization: Type = Alias.THIS,
name: String,
value: TypedInstruction
): FieldDefinition =
setFieldValue(localization, Access.STATIC, value.type, name, value)
/**
* Invoke getter of a field (`get`+`capitalize(fieldName)`).
*
* @param invokeType Type of invocation
* @param localization Localization of getter
* @param target Target of invocation
* @param type Type of field.
* @param name Name of field.
*/
fun invokeFieldGetter(
invokeType: InvokeType,
localization: Type,
target: Instruction,
type: Type,
name: String
): MethodInvocation =
invoke(invokeType, localization, target, "get${name.capitalize()}", TypeSpec(type), emptyList())
/**
* Invoke getter of a field (`get`+`capitalize(fieldName)`) of [receiver][Instruction].
*
* @param invokeType Type of invocation
* @param localization Localization of getter
* @param type Type of field.
* @param name Name of field.
*/
fun Instruction.invokeFieldGetter(
invokeType: InvokeType,
localization: Type,
type: Type,
name: String
): MethodInvocation =
invoke(
invokeType = invokeType,
localization = localization,
target = this,
name = "get${name.capitalize()}",
spec = TypeSpec(type),
arguments = emptyList()
)
/**
* Invoke getter of a field (`get`+`capitalize(fieldName)`) of [receiver][TypedInstruction] and [receiver type][TypedInstruction.type].
*
* @param invokeType Type of invocation
* @param localization Localization of getter
* @param type Type of field.
* @param name Name of field.
*/
fun TypedInstruction.invokeFieldGetter(
invokeType: InvokeType,
localization: Type,
name: String
): MethodInvocation =
invoke(
invokeType = invokeType,
localization = localization,
target = this,
name = "get${name.capitalize()}",
spec = TypeSpec(this.type),
arguments = emptyList()
)
/**
* Invoke setter of a field (`set`+`capitalize(fieldName)`) with [value].
*
* @param invokeType Type of invocation
* @param localization Localization of setter
* @param target Target of invocation
* @param type Type of field.
* @param name Name of field.
* @param value Value to pass to setter
*/
fun invokeFieldSetter(
invokeType: InvokeType,
localization: Type,
target: Instruction,
type: Type,
name: String,
value: Instruction
): MethodInvocation =
invoke(
invokeType,
localization,
target,
"set${name.capitalize()}",
TypeSpec(Void.type, listOf(type)),
listOf(value)
)
/**
* Invoke setter of a field (`set`+`capitalize(fieldName)`) of [receiver][Instruction] with [value].
*
* @param invokeType Type of invocation
* @param localization Localization of setter
* @param type Type of field.
* @param name Name of field.
* @param value Value to pass to setter
*/
fun Instruction.invokeFieldSetter(
invokeType: InvokeType,
localization: Type,
type: Type,
name: String,
value: Instruction
): MethodInvocation =
invoke(
invokeType = invokeType,
localization = localization,
target = this,
name = "set${name.capitalize()}",
spec = TypeSpec(Void.type, listOf(type)),
arguments = listOf(value)
)
/**
* Invoke setter of a field (`set`+`capitalize(fieldName)`) of [receiver][Instruction] of [receiver type][Instruction.type] with [value].
*
* @param invokeType Type of invocation
* @param localization Localization of setter
* @param type Type of field.
* @param name Name of field.
* @param value Value to pass to setter
*/
fun TypedInstruction.invokeFieldSetter(
invokeType: InvokeType,
localization: Type,
name: String,
value: Instruction
): MethodInvocation =
invoke(
invokeType = invokeType,
localization = localization,
target = this,
name = "set${name.capitalize()}",
spec = TypeSpec(Void.type, listOf(this.type)),
arguments = listOf(value)
)
// Return
/**
* @see Return
*/
fun returnValue(type: Type, value: Instruction) = Return(type, value)
/**
* @see Return
*/
fun returnValue(value: TypedInstruction) = Return(value.type, value)
/**
* Void return (Java: `return;`)
* @see Return
*/
fun returnVoid(): Return = returnValue(Void.type, Void)
/**
* Creates a [Return] of receiver instruction of type [type].
*/
fun Instruction.returnValue(type: Type) =
returnValue(type, this)
/**
* Creates a [Return] of receiver instruction of type [type].
*/
fun TypedInstruction.returnSelfValue() =
returnValue(this.type, this)
// Parameter
/**
* @see KoresParameter
*/
@JvmOverloads
fun parameter(
annotations: List<Annotation> = emptyList(),
modifiers: Set<KoresModifier> = emptySet(),
type: Type,
name: String
) = KoresParameter(annotations, modifiers, type, name)
/**
* @see KoresParameter
*/
@JvmOverloads
fun finalParameter(annotations: List<Annotation> = emptyList(), type: Type, name: String) =
KoresParameter(annotations, EnumSet.of(KoresModifier.FINAL), type, name)
// Operate
/**
* @see Operate
*/
fun operate(target: Instruction, operation: Operator.Math, value: Instruction): Operate =
Operate(target, operation, value)
/**
* Operate variable value and assign the result to the variable
*
* @see Operate
*/
fun operateAndAssign(
variable: VariableBase,
operation: Operator.Math,
value: Instruction
): VariableDefinition =
setVariableValue(
variable.variableType,
variable.name,
operate(accessVariable(variable.variableType, variable.name), operation, value)
)
/**
* Operate variable value and assign the result to the variable
*
* @see Operate
*/
fun operateAndAssign(
type: Type,
name: String,
operation: Operator.Math,
value: Instruction
): VariableDefinition =
setVariableValue(type, name, operate(accessVariable(type, name), operation, value))
/**
* Operate field value and assign the result to the field
*
* @see Operate
*/
fun operateAndAssign(
field: FieldBase,
operation: Operator.Math,
value: Instruction
): FieldDefinition =
setFieldValue(
field.localization,
field.target,
field.type,
field.name,
operate(
accessField(field.localization, field.target, field.type, field.name),
operation,
value
)
)
/**
* Operate field value and assign the result to the field
*
* @see Operate
*/
fun operateAndAssign(
localization: Type,
target: Instruction,
type: Type,
name: String,
operation: Operator.Math,
value: Instruction
): FieldDefinition =
setFieldValue(
localization,
target,
type,
name,
operate(accessField(localization, target, type, name), operation, value)
)
// Throw
/**
* @see ThrowException
*/
fun throwException(part: Instruction) = ThrowException(part)
/**
* Throws [receiver][Instruction] as exception.
*
* @see ThrowException
*/
fun Instruction.throwThisException() = ThrowException(this)
// Cast
/**
* @see Cast
*/
fun cast(from: Type?, to: Type, part: Instruction): Cast =
Cast(from, to, part)
/**
* @see Cast
*/
fun cast(to: Type, part: TypedInstruction): Cast =
Cast(part.type, to, part)
/**
* Creates a cast of receiver from type [from] to type [to].
*/
fun Instruction.cast(from: Type?, to: Type) =
cast(from, to, this)
/**
* Creates a cast of receiver from type [from] to type [to].
*/
fun TypedInstruction.cast(to: Type) =
cast(this.type, to, this)
// IfExpr
/**
* @see IfExpr
*/
fun ifExpr(
expr1: Instruction,
operation: Operator.Conditional,
expr2: Instruction
): IfExpr =
IfExpr(expr1, operation, expr2)
/**
* @see IfExpr
*/
fun check(expr1: Instruction, operation: Operator.Conditional, expr2: Instruction): IfExpr =
ifExpr(expr1, operation, expr2)
/**
* Helper function to create if expressions. This function converts a sequence of: [IfExpr],
* [Operator], [IfGroup], [List] and [KoresPart] into a list of expressions (which for the three first types
* no conversion is done), if a [List] is found, it will be converted to a [IfGroup]. If a [KoresPart] is found
* it will be converted to a [IfExpr] that checks if the `codePart` is equal to `true`.
*
* @param objects Sequence of operations.
* @return Sequence of if expressions.
* @throws IllegalArgumentException If an element is not of a valid type.
*/
fun ifExprs(vararg objects: Any): List<Instruction> {
val list = ArrayList<Instruction>()
for (any in objects) {
if (any is IfExpr || any is Operator || any is IfGroup) {
if (any is Operator)
if (any != Operators.OR
&& any != Operators.AND
&& any != Operators.BITWISE_INCLUSIVE_OR
&& any != Operators.BITWISE_EXCLUSIVE_OR
&& any != Operators.BITWISE_AND
)
throw IllegalArgumentException("Input object is not a valid operator, it must be: OR or AND or short-circuit BITWISE_INCLUSIVE_OR, BITWISE_EXCLUSIVE_OR or BITWISE_AND. Current: $any")
list.add(any as Instruction)
} else if (any is Instruction) {
list.add(checkTrue(any))
} else if (any is List<*>) {
@Suppress("UNCHECKED_CAST")
val other = any as List<Instruction>
list.add(IfGroup(other))
} else {
throw IllegalArgumentException("Illegal input object: '$any'.")
}
}
return list
}
/**
* [IfExpr] that checks if [part] is not `null`
*/
fun checkNotNull(part: Instruction) = ifExpr(part, Operators.NOT_EQUAL_TO, Literals.NULL)
/**
* [IfExpr] that checks if [receiver][Instruction] is not `null`
*/
fun Instruction.checkThisNotNull() = ifExpr(this, Operators.NOT_EQUAL_TO, Literals.NULL)
/**
* [IfExpr] that checks if [part] is `null`
*/
fun checkNull(part: Instruction) = ifExpr(part, Operators.EQUAL_TO, Literals.NULL)
/**
* [IfExpr] that checks if [receiver][Instruction] is `null`
*/
fun Instruction.checkThisNull() = ifExpr(this, Operators.EQUAL_TO, Literals.NULL)
/**
* [IfExpr] that checks if [part] is `true`
*/
fun checkTrue(part: Instruction) = ifExpr(part, Operators.EQUAL_TO, Literals.TRUE)
/**
* [IfExpr] that checks if [receiver][Instruction] is `true`
*/
fun Instruction.checThiskTrue() = ifExpr(this, Operators.EQUAL_TO, Literals.TRUE)
/**
* [IfExpr] that checks if [part] is `false`
*/
fun checkFalse(part: Instruction) = ifExpr(part, Operators.EQUAL_TO, Literals.FALSE)
/**
* [IfExpr] that checks if [receiver][Instruction] is `false`
*/
fun Instruction.checkThisFalse() = ifExpr(this, Operators.EQUAL_TO, Literals.FALSE)
// IfStatement
/**
* @see IfStatement
*/
@JvmOverloads
fun ifStatement(
expressions: List<Instruction>,
body: Instructions,
elseStatement: Instructions = Instructions.empty()
): IfStatement =
IfStatement(expressions, body, elseStatement)
/**
* @see IfStatement
*/
@JvmOverloads
fun ifStatement(
ifExpr: IfExpr,
body: Instructions,
elseStatement: Instructions = Instructions.empty()
): IfStatement =
IfStatement(listOf(ifExpr), body, elseStatement)
// Label
/**
* @see Label
*/
@JvmOverloads
fun label(name: String, body: Instructions = Instructions.empty()): Label =
Label(name, body)
// ControlFlow
/**
* @see ControlFlow
*/
@JvmOverloads
fun controlFlow(type: ControlFlow.Type, at: Label? = null): ControlFlow =
ControlFlow(type, at)
/**
* `break`
*
* `break @at`
*
* @see ControlFlow
*/
@JvmOverloads
fun breakFlow(at: Label? = null) = controlFlow(ControlFlow.Type.BREAK, at)
/**
* `continue`
*
* `continue @at`
*
* @see ControlFlow
*/
@JvmOverloads
fun continueFlow(at: Label? = null) = controlFlow(ControlFlow.Type.CONTINUE, at)
// InstanceOfCheck
/**
* Checks if [part] is instance of [type]
*
* @see InstanceOfCheck
*/
fun isInstanceOf(part: Instruction, type: Type): InstanceOfCheck = InstanceOfCheck(part, type)
/**
* Checks if [receiver][Instruction] is instance of [type]
*
* @see InstanceOfCheck
*/
fun Instruction.isThisInstanceOf(type: Type): InstanceOfCheck = InstanceOfCheck(this, type)
// TryStatement
/**
* @see TryStatement
*/
@JvmOverloads
fun tryStatement(
body: Instructions,
catchStatements: List<CatchStatement>,
finallyStatement: Instructions = Instructions.empty()
): TryStatement =
TryStatement(body, catchStatements, finallyStatement)
// CatchStatement
/**
* @see CatchStatement
*/
fun catchStatement(
exceptionTypes: List<Type>,
variable: VariableDeclaration,
body: Instructions
): CatchStatement =
CatchStatement(exceptionTypes, variable, body)
/**
* @see CatchStatement
*/
fun catchStatement(
exceptionType: Type,
variable: VariableDeclaration,
body: Instructions
): CatchStatement =
catchStatement(listOf(exceptionType), variable, body)
// TryWithResources
/**
* @see TryWithResources
*/
@JvmOverloads
fun tryWithResources(
variable: VariableDeclaration,
body: Instructions,
catchStatements: List<CatchStatement> = emptyList(),
finallyStatement: Instructions = Instructions.empty()
): TryWithResources =
TryWithResources(variable, body, catchStatements, finallyStatement)
// WhileStatement
/**
* @see [WhileStatement]
*/
@JvmOverloads
fun whileStatement(
type: WhileStatement.Type = WhileStatement.Type.WHILE,
expressions: List<Instruction>,
body: Instructions
): WhileStatement =
WhileStatement(type, expressions, body)
/**
* @see [WhileStatement]
*/
fun doWhileStatement(expressions: List<Instruction>, body: Instructions): WhileStatement =
WhileStatement(WhileStatement.Type.DO_WHILE, expressions, body)
// ForStatement
/**
* @see ForStatement
*/
fun forStatement(
forInit: Instruction,
forExpression: List<Instruction>,
forUpdate: Instruction,
body: Instructions
): ForStatement =
ForStatement(listOf(forInit), forExpression, listOf(forUpdate), body)
/**
* @see ForStatement
*/
fun forStatement(
forInit: List<Instruction>,
forExpression: List<Instruction>,
forUpdate: List<Instruction>,
body: Instructions
): ForStatement =
ForStatement(forInit, forExpression, forUpdate, body)
/**
* @see ForStatement
*/
fun forStatement(
forInit: Instruction,
forExpression: IfExpr,
forUpdate: Instruction,
body: Instructions
): ForStatement =
forStatement(forInit, listOf(forExpression), forUpdate, body)
// ForEachStatement
/**
* @see ForEachStatement
*/
fun forEachStatement(
variable: VariableDeclaration,
iterationType: IterationType,
iterableElement: Instruction,
body: Instructions
): ForEachStatement =
ForEachStatement(variable, iterationType, iterableElement, body)
/**
* Loop elements of an iterable element.
*
* @see ForEachStatement
*/
fun forEachIterable(
variable: VariableDeclaration,
iterableElement: Instruction,
body: Instructions
): ForEachStatement =
forEachStatement(variable, IterationType.ITERABLE_ELEMENT, iterableElement, body)
/**
* Loop elements of an array.
*
* @see ForEachStatement
*/
fun forEachArray(
variable: VariableDeclaration,
iterableElement: Instruction,
body: Instructions
): ForEachStatement =
forEachStatement(variable, IterationType.ARRAY, iterableElement, body)
// Switch & Case
/**
* @see SwitchStatement
*/
fun switchStatement(
value: Instruction,
switchType: SwitchType,
cases: List<Case>
): SwitchStatement =
SwitchStatement(value, switchType, cases)
/**
* Switch [receiver][Instruction]
*
* @see SwitchStatement
*/
fun Instruction.switchThisStatement(
switchType: SwitchType,
cases: List<Case>
): SwitchStatement =
SwitchStatement(this, switchType, cases)
/**
* @see SwitchStatement
*/
fun switchInt(value: Instruction, cases: List<Case>): SwitchStatement =
switchStatement(value, SwitchType.NUMERIC, cases)
/**
* Case [receiver][Instruction] int.
*
* @see SwitchStatement
*/
fun Instruction.switchThisInt(cases: List<Case>): SwitchStatement =
switchStatement(this, SwitchType.NUMERIC, cases)
/**
* @see SwitchStatement
*/
fun switchString(value: Instruction, cases: List<Case>): SwitchStatement =
switchStatement(value, SwitchType.STRING, cases)
/**
* Case [receiver][Instruction] string.
* @see SwitchStatement
*/
fun Instruction.switchThisString(cases: List<Case>): SwitchStatement =
switchStatement(this, SwitchType.STRING, cases)
/**
* @see SwitchStatement
*/
fun switchEnum(value: Instruction, cases: List<Case>): SwitchStatement =
switchStatement(value, SwitchType.ENUM, cases)
/**
* Case [receiver][Instruction] enum.
* @see SwitchStatement
*/
fun Instruction.switchThisEnum(cases: List<Case>): SwitchStatement =
switchStatement(this, SwitchType.ENUM, cases)
/**
* @see Case
*/
fun caseStatement(value: Instruction, body: Instructions): Case =
Case(value, body)
/**
* Case [receiver][Instruction] value.
* @see Case
*/
fun Instruction.caseThis(body: Instructions): Case =
Case(this, body)
/**
* @see Case
*/
fun defaultCase(body: Instructions): Case =
caseStatement(KoresNothing, body)
// PlainKoresType
/**
* @see PlainKoresType
*/
fun plainType(name: String, isInterface: Boolean): PlainKoresType =
PlainKoresType(name, isInterface)
/**
* @see PlainKoresType
*/
fun plainInterfaceType(name: String): PlainKoresType =
plainType(name, true)
/**
* @see PlainKoresType
*/
fun plainClassType(name: String): PlainKoresType =
plainType(name, false)
// TypeSpec
/**
* @see TypeSpec
*/
fun typeSpec(rtype: Type) =
TypeSpec(rtype, emptyList())
/**
* @see TypeSpec
*/
fun typeSpec(rtype: Type, ptypes: List<Type>) =
TypeSpec(rtype, ptypes.toList())
/**
* @see TypeSpec
*/
fun typeSpec(rtype: Type, ptype: Type) =
typeSpec(rtype, listOf(ptype))
/**
* @see TypeSpec
*/
fun typeSpec(rtype: Type, vararg ptypes: Type) =
typeSpec(rtype, ptypes.toList())
/**
* @see TypeSpec
*/
fun voidTypeSpec(vararg ptypes: Type) =
typeSpec(Types.VOID, ptypes.toList())
/**
* @see TypeSpec
*/
fun constructorTypeSpec(vararg ptypes: Type) =
typeSpec(Types.VOID, ptypes.toList())
/**
* Creates a [Line] instance linking [value] to [line number][line].
*/
fun line(line: Int, value: Instruction): Line =
if (value is Typed) Line.TypedLine(line, value, value.type) else Line.NormalLine(line, value)
/**
* Creates a [Line] of number [line]
*/
fun Instruction.line(line: Int) =
line(line, this) | mit |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findFunctionUsages/javaAndKotlinOverrides.2.kt | 9 | 76 | open class Bawdaw : A<String>() {
override fun foo(t: String) {
}
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/intentions/insertCurlyBracesToTemplate/insertBrackets5.kt | 9 | 127 | // IS_APPLICABLE: true
// AFTER-WARNING: Variable 'y' is never used
fun foo() {
val x = 4
val y = """$x$<caret>x$x"""
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/nestedObject/staticLateinit/KotlinObject.kt | 9 | 137 | package one.two
object KotlinObject {
object Nested {
@JvmStatic
lateinit var staticLateinit<caret>: Nested
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/copyPaste/plainTextConversion/PostProcessing.expected.kt | 13 | 290 | package to
import java.io.File
import java.util.ArrayList
internal class JavaClass {
fun foo(file: File?, target: MutableList<String>?) {
val list = ArrayList<String>()
if (file != null) {
list.add(file.name)
}
target?.addAll(list)
}
}
| apache-2.0 |
dkandalov/katas | kotlin/src/katas/kotlin/binarysearch/binary-search6.kt | 1 | 1113 | package katas.kotlin.binarysearch
import datsok.shouldEqual
import org.junit.Test
class BinarySearchTests {
@Test fun `find index of an element in the sorted list`() {
listOf(1).findIndexOf(0) shouldEqual -1
listOf(1).findIndexOf(1) shouldEqual 0
listOf(1).findIndexOf(2) shouldEqual -1
listOf(1, 2).findIndexOf(0) shouldEqual -1
listOf(1, 2).findIndexOf(1) shouldEqual 0
listOf(1, 2).findIndexOf(2) shouldEqual 1
listOf(1, 2).findIndexOf(3) shouldEqual -1
listOf(1, 2, 3).findIndexOf(0) shouldEqual -1
listOf(1, 2, 3).findIndexOf(1) shouldEqual 0
listOf(1, 2, 3).findIndexOf(2) shouldEqual 1
listOf(1, 2, 3).findIndexOf(3) shouldEqual 2
listOf(1, 2, 3).findIndexOf(4) shouldEqual -1
}
}
private fun <E: Comparable<E>> List<E>.findIndexOf(element: E): Int {
var from = 0
var to = size
while (from < to) {
val index = (from + to) / 2
if (element < this[index]) to = index
else if (this[index] < element) from = index + 1
else return index
}
return -1
}
| unlicense |
TheMrMilchmann/lwjgl3 | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/NV_dedicated_allocation.kt | 1 | 6096 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val NV_dedicated_allocation = "NVDedicatedAllocation".nativeClassVK("NV_dedicated_allocation", type = "device", postfix = "NV") {
documentation =
"""
This extension allows device memory to be allocated for a particular buffer or image resource, which on some devices can significantly improve the performance of that resource. Normal device memory allocations must support memory aliasing and sparse binding, which could interfere with optimizations like framebuffer compression or efficient page table usage. This is important for render targets and very large resources, but need not (and probably should not) be used for smaller resources that can benefit from suballocation.
This extension adds a few small structures to resource creation and memory allocation: a new structure that flags whether am image/buffer will have a dedicated allocation, and a structure indicating the image or buffer that an allocation will be bound to.
<h5>Examples</h5>
<pre><code>
// Create an image with
// VkDedicatedAllocationImageCreateInfoNV::dedicatedAllocation
// set to VK_TRUE
VkDedicatedAllocationImageCreateInfoNV dedicatedImageInfo =
{
VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_IMAGE_CREATE_INFO_NV, // sType
NULL, // pNext
VK_TRUE, // dedicatedAllocation
};
VkImageCreateInfo imageCreateInfo =
{
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // sType
&dedicatedImageInfo // pNext
// Other members set as usual
};
VkImage image;
VkResult result = vkCreateImage(
device,
&imageCreateInfo,
NULL, // pAllocator
&image);
VkMemoryRequirements memoryRequirements;
vkGetImageMemoryRequirements(
device,
image,
&memoryRequirements);
// Allocate memory with VkDedicatedAllocationMemoryAllocateInfoNV::image
// pointing to the image we are allocating the memory for
VkDedicatedAllocationMemoryAllocateInfoNV dedicatedInfo =
{
VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_MEMORY_ALLOCATE_INFO_NV, // sType
NULL, // pNext
image, // image
VK_NULL_HANDLE, // buffer
};
VkMemoryAllocateInfo memoryAllocateInfo =
{
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, // sType
&dedicatedInfo, // pNext
memoryRequirements.size, // allocationSize
FindMemoryTypeIndex(memoryRequirements.memoryTypeBits), // memoryTypeIndex
};
VkDeviceMemory memory;
vkAllocateMemory(
device,
&memoryAllocateInfo,
NULL, // pAllocator
&memory);
// Bind the image to the memory
vkBindImageMemory(
device,
image,
memory,
0);</code></pre>
<h5>VK_NV_dedicated_allocation</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_NV_dedicated_allocation}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>27</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
</ul></dd>
<dt><b>Deprecation state</b></dt>
<dd><ul>
<li>
<em>Deprecated</em> by {@link KHRDedicatedAllocation VK_KHR_dedicated_allocation} extension
<ul>
<li>Which in turn was <em>promoted</em> to <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#versions-1.1-promotions">Vulkan 1.1</a></li>
</ul>
</li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Jeff Bolz <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_NV_dedicated_allocation]%20@jeffbolznv%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_NV_dedicated_allocation%20extension%3E%3E">jeffbolznv</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2016-05-31</dd>
<dt><b>IP Status</b></dt>
<dd>No known IP claims.</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Jeff Bolz, NVIDIA</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"NV_DEDICATED_ALLOCATION_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"NV_DEDICATED_ALLOCATION_EXTENSION_NAME".."VK_NV_dedicated_allocation"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_DEDICATED_ALLOCATION_IMAGE_CREATE_INFO_NV".."1000026000",
"STRUCTURE_TYPE_DEDICATED_ALLOCATION_BUFFER_CREATE_INFO_NV".."1000026001",
"STRUCTURE_TYPE_DEDICATED_ALLOCATION_MEMORY_ALLOCATE_INFO_NV".."1000026002"
)
} | bsd-3-clause |
awsdocs/aws-doc-sdk-examples | kotlin/services/redshift/src/main/kotlin/com/kotlin/redshift/ListEvents.kt | 1 | 2151 | // snippet-sourcedescription:[ListEvents.kt demonstrates how to list events for a given cluster.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Redshift]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.redshift
// snippet-start:[redshift.kotlin._events.import]
import aws.sdk.kotlin.services.redshift.RedshiftClient
import aws.sdk.kotlin.services.redshift.model.DescribeEventsRequest
import aws.sdk.kotlin.services.redshift.model.SourceType
import kotlin.system.exitProcess
// snippet-end:[redshift.kotlin._events.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<clusterId> <eventSourceType>
Where:
clusterId - The id of the cluster.
eventSourceType - The event type (ie, cluster).
"""
if (args.size != 2) {
println(usage)
exitProcess(0)
}
val clusterId = args[0]
val eventSourceType = args[1]
listRedShiftEvents(clusterId, eventSourceType)
}
// snippet-start:[redshift.kotlin._events.main]
suspend fun listRedShiftEvents(clusterId: String?, eventSourceType: String) {
val request = DescribeEventsRequest {
sourceIdentifier = clusterId
sourceType = SourceType.fromValue(eventSourceType)
startTime = aws.smithy.kotlin.runtime.time.Instant.fromEpochSeconds("1634058260")
maxRecords = 20
}
RedshiftClient { region = "us-west-2" }.use { redshiftClient ->
val eventsResponse = redshiftClient.describeEvents(request)
eventsResponse.events?.forEach { event ->
println("Source type is ${event.sourceType}")
println("Event message is ${event.message}")
}
}
}
// snippet-end:[redshift.kotlin._events.main]
| apache-2.0 |
subhalaxmin/Programming-Kotlin | Chapter07/src/main/kotlin/com/packt/chapter4/4.17.kt | 4 | 148 | import java.util.concurrent.atomic.AtomicInteger
val counter = AtomicInteger(1)
fun unpure(k: Int): Int {
return counter.incrementAndGet() + k
} | mit |
RomanBelkov/workshop-jb | test/v_builders/_38_The_Function_WIth.kt | 3 | 818 | package v_builders.examples
import junit.framework.Assert
import org.junit.Test
import java.util.HashMap
class _24_The_Function_With {
@Test fun testBuildString() {
val expected = buildString()
val actual = StringBuilder()
myWith (actual) {
append("Numbers: ")
for (i in 1..10) {
append(i)
}
}
Assert.assertEquals("String should be built:", expected, actual.toString())
}
@Test fun testBuildMap() {
val expected = buildMap()
val actual = HashMap<Int, String>()
myWith (actual) {
put(0, "0")
for (i in 1..10) {
put(i, "$i")
}
}
Assert.assertEquals("Map should be filled with the right values", expected, actual)
}
}
| mit |
TheMrMilchmann/lwjgl3 | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/KHR_8bit_storage.kt | 1 | 4216 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val KHR_8bit_storage = "KHR8bitStorage".nativeClassVK("KHR_8bit_storage", type = "device", postfix = "KHR") {
documentation =
"""
The {@code VK_KHR_8bit_storage} extension allows use of 8-bit types in uniform and storage buffers, and push constant blocks. This extension introduces several new optional features which map to SPIR-V capabilities and allow access to 8-bit data in {@code Block}-decorated objects in the {@code Uniform} and the {@code StorageBuffer} storage classes, and objects in the {@code PushConstant} storage class.
The {@code StorageBuffer8BitAccess} capability <b>must</b> be supported by all implementations of this extension. The other capabilities are optional.
<h5>Promotion to Vulkan 1.2</h5>
Functionality in this extension is included in core Vulkan 1.2, with the KHR suffix omitted. However, if Vulkan 1.2 is supported and this extension is not, the {@code StorageBuffer8BitAccess} capability is optional. The original type, enum and command names are still available as aliases of the core functionality.
<h5>VK_KHR_8bit_storage</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_KHR_8bit_storage}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>178</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
<li>Requires {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} to be enabled for any device-level functionality</li>
<li>Requires {@link KHRStorageBufferStorageClass VK_KHR_storage_buffer_storage_class} to be enabled for any device-level functionality</li>
</ul></dd>
<dt><b>Deprecation state</b></dt>
<dd><ul>
<li><em>Promoted</em> to <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#versions-1.2-promotions">Vulkan 1.2</a></li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Alexander Galazin <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_8bit_storage]%20@alegal-arm%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_8bit_storage%20extension%3E%3E">alegal-arm</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2018-02-05</dd>
<dt><b>Interactions and External Dependencies</b></dt>
<dd><ul>
<li>Promoted to Vulkan 1.2 Core</li>
<li>This extension requires <a target="_blank" href="https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/KHR/SPV_KHR_8bit_storage.html">{@code SPV_KHR_8bit_storage}</a></li>
<li>This extension provides API support for <a target="_blank" href="https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GL_EXT_shader_16bit_storage.txt">{@code GL_EXT_shader_16bit_storage}</a></li>
</ul></dd>
<dt><b>IP Status</b></dt>
<dd>No known IP claims.</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Alexander Galazin, Arm</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"KHR_8BIT_STORAGE_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"KHR_8BIT_STORAGE_EXTENSION_NAME".."VK_KHR_8bit_storage"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR".."1000177000"
)
} | bsd-3-clause |
zbeboy/ISY | src/main/java/top/zbeboy/isy/service/graduate/design/GraduationDesignSubjectTypeServiceImpl.kt | 1 | 869 | package top.zbeboy.isy.service.graduate.design
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import top.zbeboy.isy.domain.tables.daos.GraduationDesignSubjectTypeDao
import top.zbeboy.isy.domain.tables.pojos.GraduationDesignSubjectType
import javax.annotation.Resource
/**
* Created by zbeboy 2018-01-26 .
**/
@Service("graduationDesignSubjectTypeService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
open class GraduationDesignSubjectTypeServiceImpl :GraduationDesignSubjectTypeService{
@Resource
open lateinit var graduationDesignSubjectTypeDao: GraduationDesignSubjectTypeDao
override fun findAll(): List<GraduationDesignSubjectType> {
return graduationDesignSubjectTypeDao.findAll()
}
} | mit |
audit4j/audit4j-demo | audit4j-kotlin-demo-springboot/src/main/kotlin/org/springframework/samples/petclinic/model/Person.kt | 1 | 1109 | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.model
import javax.persistence.Column
import javax.persistence.MappedSuperclass
import org.hibernate.validator.constraints.NotEmpty
/**
* Simple JavaBean domain object representing an person.
*
* @author Ken Krebs
* @author Antoine Rey
*/
@MappedSuperclass
open class Person : BaseEntity() {
@Column(name = "first_name")
@NotEmpty
var firstName = ""
@Column(name = "last_name")
@NotEmpty
var lastName = ""
} | apache-2.0 |
encircled/Joiner | joiner-kotlin/src/main/java/cz/encircled/joiner/kotlin/JoinOps.kt | 1 | 3024 | package cz.encircled.joiner.kotlin
import com.querydsl.core.types.EntityPath
import com.querydsl.core.types.Predicate
import com.querydsl.core.types.dsl.CollectionPathBase
import cz.encircled.joiner.query.join.J
import cz.encircled.joiner.query.join.JoinDescription
interface JoinOps {
var lastJoin: JoinDescription?
infix fun JoinDescription.leftJoin(p: EntityPath<*>): JoinDescription {
return this.nested(J.left(p))
}
infix fun JoinDescription.innerJoin(p: EntityPath<*>): JoinDescription {
return this.nested(J.inner(p))
}
infix fun EntityPath<*>.leftJoin(p: EntityPath<*>): JoinDescription {
return JoinDescription(this).nested(J.left(p))
}
infix fun EntityPath<*>.leftJoin(p: JoinDescription): JoinDescription {
return JoinDescription(this).nested(p.left())
}
infix fun EntityPath<*>.innerJoin(p: JoinDescription): JoinDescription {
return JoinDescription(this).nested(p.inner())
}
infix fun EntityPath<*>.innerJoin(p: EntityPath<*>): JoinDescription {
return JoinDescription(this).nested(J.inner(p))
}
infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.leftJoin(j: JoinDescription): JoinerKtQuery<FROM_C, PROJ, FROM> {
val join = j.left()
lastJoin = j
delegate.joins(join)
return this
}
infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.leftJoin(p: EntityPath<*>): JoinerKtQuery<FROM_C, PROJ, FROM> {
val join = J.left(p)
lastJoin = join
delegate.joins(join)
return this
}
infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.leftJoin(p: CollectionPathBase<*, *, *>): JoinerKtQuery<FROM_C, PROJ, FROM> {
val join = J.left(p)
lastJoin = join
delegate.joins(join)
return this
}
infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.innerJoin(j: JoinDescription): JoinerKtQuery<FROM_C, PROJ, FROM> {
val join = j.inner()
lastJoin = j
delegate.joins(join)
return this
}
infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.innerJoin(p: EntityPath<*>): JoinerKtQuery<FROM_C, PROJ, FROM> {
val join = J.inner(p)
lastJoin = join
delegate.joins(join)
return this
}
infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.innerJoin(p: CollectionPathBase<*, *, *>): JoinerKtQuery<FROM_C, PROJ, FROM> {
val join = J.inner(p)
lastJoin = join
delegate.joins(join)
return this
}
infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.on(p: Predicate): JoinerKtQuery<FROM_C, PROJ, FROM> {
val join = lastJoin ?: throw IllegalStateException("Add a join statement before 'on' condition")
join.on(p)
return this
}
}
| apache-2.0 |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/AccessorProcessor.kt | 1 | 2112 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors
import com.intellij.lang.java.beans.PropertyKind
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.ElementClassHint
import com.intellij.util.SmartList
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.util.checkKind
import org.jetbrains.plugins.groovy.lang.psi.util.getAccessorName
import org.jetbrains.plugins.groovy.lang.resolve.AccessorResolveResult
import org.jetbrains.plugins.groovy.lang.resolve.GenericAccessorResolveResult
import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
import org.jetbrains.plugins.groovy.lang.resolve.imports.importedNameKey
class AccessorProcessor(
propertyName: String,
private val propertyKind: PropertyKind,
private val arguments: Arguments?,
private val place: PsiElement
) : ProcessorWithCommonHints(), GrResolverProcessor<GroovyResolveResult> {
private val accessorName = propertyKind.getAccessorName(propertyName)
init {
nameHint(accessorName)
elementClassHint(ElementClassHint.DeclarationKind.METHOD)
hint(GroovyResolveKind.HINT_KEY, GroovyResolveKind.EMPTY_HINT)
}
override fun execute(element: PsiElement, state: ResolveState): Boolean {
if (element !is PsiMethod) return true
val elementName = state[importedNameKey] ?: element.name
if (elementName != accessorName) return true
if (!element.checkKind(propertyKind)) return true
myResults += if (element.hasTypeParameters()) {
GenericAccessorResolveResult(element, place, state, arguments)
}
else {
AccessorResolveResult(element, place, state, arguments)
}
return true
}
private val myResults = SmartList<GroovyResolveResult>()
override val results: List<GroovyResolveResult> get() = myResults
}
| apache-2.0 |
google/intellij-community | platform/lang-impl/src/com/intellij/ide/navbar/ide/NavBarService.kt | 2 | 1107 | // 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.ide.navbar.ide
import com.intellij.ide.IdeEventQueue
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
class NavBarService(val myProject: Project) : Disposable {
private val cs = CoroutineScope(CoroutineName("NavigationBarStore"))
private val myEventFlow = MutableSharedFlow<Unit>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
private val navigationBar = NavigationBar(myProject, cs, myEventFlow.asSharedFlow())
init {
IdeEventQueue.getInstance().addActivityListener(Runnable {
myEventFlow.tryEmit(Unit)
}, this)
}
override fun dispose() {
cs.coroutineContext.cancel()
}
fun getPanel() = navigationBar.getComponent()
}
| apache-2.0 |
indianpoptart/RadioControl | RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/receivers/OnBootServiceStarter.kt | 1 | 940 | package com.nikhilparanjape.radiocontrol.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import com.nikhilparanjape.radiocontrol.services.OnBootIntentService
import com.nikhilparanjape.radiocontrol.utilities.Utilities
/**
* Created by Nikhil on 05/29/2021.
*
* @author Nikhil Paranjape
*
* Another on boot service starter
*/
class OnBootServiceStarter : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (Intent.ACTION_BOOT_COMPLETED == intent.action) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(Intent(context, OnBootIntentService::class.java))
} else {
context.startService(Intent(context, OnBootIntentService::class.java))
}
}
Utilities.scheduleJob(context)
}
} | gpl-3.0 |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveConstructorKeywordIntention.kt | 2 | 1168 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
class RemoveConstructorKeywordIntention : SelfTargetingIntention<KtPrimaryConstructor>(
KtPrimaryConstructor::class.java,
KotlinBundle.lazyMessage("remove.constructor.keyword")
) {
override fun applyTo(element: KtPrimaryConstructor, editor: Editor?) {
element.removeRedundantConstructorKeywordAndSpace()
}
override fun isApplicableTo(element: KtPrimaryConstructor, caretOffset: Int): Boolean {
if (element.containingClassOrObject !is KtClass) return false
if (element.getConstructorKeyword() == null) return false
return element.modifierList == null
}
} | apache-2.0 |
Bugfry/exercism | exercism/kotlin/sieve/src/main/kotlin/Sieve.kt | 2 | 312 | object Sieve {
fun primesUpTo(limit: Int): List<Int> {
val prime_candidate = Array(limit + 1, { true })
return (2 .. limit).filter {
if (prime_candidate[it]) {
for (k in it .. limit / it) {
prime_candidate[k * it] = false
}
}
prime_candidate[it]
}
}
}
| mit |
JetBrains/intellij-community | plugins/devkit/devkit-kotlin-tests/testData/inspections/useCoupleFix/UseCoupleTypeInConstant_after.kt | 1 | 156 | import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.Pair
object UseCoupleTypeInConstant {
private val ANY: Couple<String>? = null
}
| apache-2.0 |
NeatoRobotics/neato-sdk-android | Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/models/RobotState.kt | 1 | 4276 | /*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import java.util.ArrayList
import java.util.HashMap
@Parcelize
data class RobotState(var state: State = State.INVALID,
var action: Action = Action.INVALID,
var cleaningCategory: CleaningCategory = CleaningCategory.HOUSE,
var cleaningModifier: CleaningModifier = CleaningModifier.NORMAL,
var cleaningMode: CleaningMode = CleaningMode.TURBO,
var navigationMode: NavigationMode = NavigationMode.NORMAL,
var isCharging: Boolean = false,
var isDocked: Boolean = false,
var isDockHasBeenSeen: Boolean = false,
var isScheduleEnabled: Boolean = false,
var isStartAvailable: Boolean = false,
var isStopAvailable: Boolean = false,
var isPauseAvailable: Boolean = false,
var isResumeAvailable: Boolean = false,
var isGoToBaseAvailable: Boolean = false,
var cleaningSpotWidth: Int = 0,
var cleaningSpotHeight: Int = 0,
var mapId: String? = null,
var boundary: Boundary? = null,
var boundaries: MutableList<Boundary> = mutableListOf(),
var scheduleEvents: ArrayList<ScheduleEvent> = ArrayList(),
var availableServices: HashMap<String, String> = HashMap(),
var message: String? = null,
var error: String? = null,
var alert: String? = null,
var charge: Double = 0.toDouble(),
var serial: String? = null,
var result: String? = null,
var robotRemoteProtocolVersion: Int = 0,
var robotModelName: String? = null,
var firmware: String? = null) : Parcelable
enum class State(val value: Int) {
INVALID(0),
IDLE(1),
BUSY(2),
PAUSED(3),
ERROR(4);
companion object {
fun fromValue(value: Int): State {
val state = State.values().firstOrNull { it.value == value }
return state?:INVALID
}
}
}
enum class Action(val value: Int) {
INVALID(0),
HOUSE_CLEANING(1),
SPOT_CLEANING(2),
MANUAL_CLEANING(3),
DOCKING(4),
USER_MENU_ACTIVE(5),
SUSPENDED_CLEANING(6),
UPDATING(7),
COPYING_LOGS(8),
RECOVERING_LOCATION(9),
IEC_TEST(10),
MAP_CLEANING(11),
EXPLORING_MAP(12),
MAP_RETRIEVING(13),
MAP_CREATING(14),
EXPLORATION_SUSPENDED(15);
companion object {
fun fromValue(value: Int): Action {
val action = Action.values().firstOrNull { it.value == value }
return action?: Action.INVALID
}
}
}
enum class CleaningCategory(val value: Int) {
INVALID(0),
MANUAL(1),
HOUSE(2),
SPOT(3),
MAP(4);
companion object {
fun fromValue(value: Int): CleaningCategory {
val cc = CleaningCategory.values().firstOrNull { it.value == value }
return cc?:INVALID
}
}
}
enum class CleaningModifier(val value: Int) {
INVALID(0),
NORMAL(1),
DOUBLE(2);
companion object {
fun fromValue(value: Int): CleaningModifier {
val cm = CleaningModifier.values().firstOrNull { it.value == value }
return cm?:INVALID
}
}
}
enum class CleaningMode(val value: Int) {
INVALID(0),
ECO(1),
TURBO(2);
companion object {
fun fromValue(value: Int): CleaningMode {
val cm = CleaningMode.values().firstOrNull { it.value == value }
return cm?:INVALID
}
}
}
enum class NavigationMode(val value: Int) {
NORMAL(1),
EXTRA_CARE(2),
DEEP(3);
companion object {
fun fromValue(value: Int): NavigationMode {
val nm = NavigationMode.values().firstOrNull { it.value == value }
return nm?:NORMAL
}
}
}
| mit |
BartoszJarocki/Design-patterns-in-Kotlin | src/structural/Composite.kt | 1 | 1498 | package structural
import java.util.*
/** "Component" */
interface Graphic {
fun print()
}
/** "Composite" */
class CompositeGraphic(val graphics: ArrayList<Graphic> = ArrayList()) : Graphic {
//Prints the graphic.
override fun print() = graphics.forEach(Graphic::print)
//Adds the graphic to the composition.
fun add(graphic: Graphic) {
graphics.add(graphic)
}
//Removes the graphic from the composition.
fun remove(graphic: Graphic) {
graphics.remove(graphic)
}
}
class Ellipse : Graphic {
override fun print() = println("Ellipse")
}
class Square : Graphic {
override fun print() = println("Square")
}
fun main(args: Array<String>) {
//Initialize four ellipses
val ellipse1 = Ellipse()
val ellipse2 = Ellipse()
val ellipse3 = Ellipse()
val ellipse4 = Ellipse()
//Initialize four squares
val square1 = Square()
val square2 = Square()
val square3 = Square()
val square4 = Square()
//Initialize three composite graphics
val graphic = CompositeGraphic()
val graphic1 = CompositeGraphic()
val graphic2 = CompositeGraphic()
//Composes the graphics
graphic1.add(ellipse1)
graphic1.add(ellipse2)
graphic1.add(square1)
graphic1.add(ellipse3)
graphic2.add(ellipse4)
graphic2.add(square2)
graphic2.add(square3)
graphic2.add(square4)
graphic.add(graphic1)
graphic.add(graphic2)
//Prints the complete graphic
graphic.print()
} | apache-2.0 |
StepicOrg/stepik-android | app/src/main/java/org/stepic/droid/di/qualifiers/WishlistScheduler.kt | 2 | 117 | package org.stepic.droid.di.qualifiers
import javax.inject.Qualifier
@Qualifier
annotation class WishlistScheduler
| apache-2.0 |
vvv1559/intellij-community | platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationSchemeManager.kt | 1 | 3909 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.impl
import com.intellij.configurationStore.LazySchemeProcessor
import com.intellij.configurationStore.SchemeContentChangedHandler
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.InvalidDataException
import com.intellij.util.attribute
import org.jdom.Element
import java.util.function.Function
private val LOG = logger<RunConfigurationSchemeManager>()
internal class RunConfigurationSchemeManager(private val manager: RunManagerImpl, private val isShared: Boolean) :
LazySchemeProcessor<RunnerAndConfigurationSettingsImpl, RunnerAndConfigurationSettingsImpl>(), SchemeContentChangedHandler<RunnerAndConfigurationSettingsImpl> {
override fun createScheme(dataHolder: SchemeDataHolder<RunnerAndConfigurationSettingsImpl>, name: String, attributeProvider: Function<String, String?>, isBundled: Boolean): RunnerAndConfigurationSettingsImpl {
val settings = RunnerAndConfigurationSettingsImpl(manager)
val element = readData(settings, dataHolder)
manager.addConfiguration(element, settings)
return settings
}
private fun readData(settings: RunnerAndConfigurationSettingsImpl, dataHolder: SchemeDataHolder<RunnerAndConfigurationSettingsImpl>): Element {
var element = dataHolder.read()
if (isShared && element.name == "component") {
element = element.getChild("configuration")
}
try {
settings.readExternal(element, isShared)
}
catch (e: InvalidDataException) {
RunManagerImpl.LOG.error(e)
}
var elementAfterStateLoaded = element
try {
elementAfterStateLoaded = writeScheme(settings)
}
catch (e: Throwable) {
LOG.error("Cannot compute digest for RC using state after load", e)
}
// very important to not write file with only changed line separators
dataHolder.updateDigest(elementAfterStateLoaded)
return element
}
override fun getName(attributeProvider: Function<String, String?>, fileNameWithoutExtension: String): String {
var name = attributeProvider.apply("name")
if (name == "<template>" || name == null) {
attributeProvider.apply("type")?.let {
if (name == null) {
name = "<template>"
}
name += " of type ${it}"
}
}
return name ?: throw IllegalStateException("name is missed in the scheme data")
}
override fun isExternalizable(scheme: RunnerAndConfigurationSettingsImpl) = true
override fun schemeContentChanged(scheme: RunnerAndConfigurationSettingsImpl, name: String, dataHolder: SchemeDataHolder<RunnerAndConfigurationSettingsImpl>) {
readData(scheme, dataHolder)
manager.eventPublisher.runConfigurationChanged(scheme)
}
override fun onSchemeAdded(scheme: RunnerAndConfigurationSettingsImpl) {
// createScheme automatically call addConfiguration
}
override fun onSchemeDeleted(scheme: RunnerAndConfigurationSettingsImpl) {
manager.removeConfiguration(scheme)
}
override fun writeScheme(scheme: RunnerAndConfigurationSettingsImpl): Element {
val result = super.writeScheme(scheme)
if (isShared) {
return Element("component")
.attribute("name", "ProjectRunConfigurationManager")
.addContent(result)
}
return result
}
} | apache-2.0 |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/index/AemComponentClassicDialogIndex.kt | 1 | 1474 | package com.aemtools.index
import com.aemtools.index.dataexternalizer.AemComponentClassicDialogDefinitionExternalizer
import com.aemtools.index.indexer.AemComponentClassicDialogIndexer
import com.aemtools.index.model.dialog.AemComponentClassicDialogDefinition
import com.intellij.util.indexing.DataIndexer
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.FileContent
import com.intellij.util.indexing.ID
import com.intellij.util.io.DataExternalizer
import com.intellij.xml.index.XmlIndex
/**
* Indexes classic dialog files (dialog.xml).
*
* @author Dmytro Troynikov
*/
class AemComponentClassicDialogIndex : XmlIndex<AemComponentClassicDialogDefinition>() {
companion object {
val AEM_COMPONENT_CLASSIC_DIALOG_INDEX_ID: ID<String, AemComponentClassicDialogDefinition>
= ID.create<String, AemComponentClassicDialogDefinition>("AemComponentClassicDialogDefinitionIndex")
}
override fun getValueExternalizer(): DataExternalizer<AemComponentClassicDialogDefinition>
= AemComponentClassicDialogDefinitionExternalizer
override fun getName(): ID<String, AemComponentClassicDialogDefinition>
= AEM_COMPONENT_CLASSIC_DIALOG_INDEX_ID
override fun getIndexer(): DataIndexer<String, AemComponentClassicDialogDefinition, FileContent>
= AemComponentClassicDialogIndexer
override fun getInputFilter(): FileBasedIndex.InputFilter
= FileBasedIndex.InputFilter {
it.name == "dialog.xml"
}
}
| gpl-3.0 |
allotria/intellij-community | plugins/markdown/test/src/org/intellij/plugins/markdown/comment/MarkdownCommenterTest.kt | 3 | 1074 | // 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.intellij.plugins.markdown.comment
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.PluginPathManager
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import com.intellij.testFramework.PlatformTestUtil
class MarkdownCommenterTest: LightPlatformCodeInsightTestCase() {
override fun getTestDataPath(): String = PluginPathManager.getPluginHomePath("markdown") + "/test/data"
fun testSimpleLineComment() { doTest() }
fun testSimpleLineUncomment() { doTest() }
fun testCommentLineWithParenthesis() { doTest() }
fun testUncommentLineWithParenthesis() { doTest() }
fun testCommentWithoutEmptyLine() { doTest() }
private fun doTest() {
configureByFile("/comment/before" + getTestName(false) + ".md")
PlatformTestUtil.invokeNamedAction(IdeActions.ACTION_COMMENT_LINE)
checkResultByFile("/comment/after" + getTestName(false) + ".md")
}
} | apache-2.0 |
matrix-org/matrix-android-sdk | matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/cryptostore/db/model/DeviceInfoEntity.kt | 1 | 1778 | /*
* Copyright 2018 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.androidsdk.crypto.cryptostore.db.model
import io.realm.RealmObject
import io.realm.RealmResults
import io.realm.annotations.LinkingObjects
import io.realm.annotations.PrimaryKey
import org.matrix.androidsdk.crypto.cryptostore.db.deserializeFromRealm
import org.matrix.androidsdk.crypto.cryptostore.db.serializeForRealm
import org.matrix.androidsdk.crypto.data.MXDeviceInfo
fun DeviceInfoEntity.Companion.createPrimaryKey(userId: String, deviceId: String) = "$userId|$deviceId"
// deviceInfoData contains serialized data
open class DeviceInfoEntity(@PrimaryKey var primaryKey: String = "",
var deviceId: String? = null,
var identityKey: String? = null,
var deviceInfoData: String? = null)
: RealmObject() {
// Deserialize data
fun getDeviceInfo(): MXDeviceInfo? {
return deserializeFromRealm(deviceInfoData)
}
// Serialize data
fun putDeviceInfo(deviceInfo: MXDeviceInfo?) {
deviceInfoData = serializeForRealm(deviceInfo)
}
@LinkingObjects("devices")
val users: RealmResults<UserEntity>? = null
companion object
}
| apache-2.0 |
rightfromleft/weather-app | domain/src/main/java/com/rightfromleftsw/weather/domain/interactor/GetLocation.kt | 1 | 954 | package com.rightfromleftsw.weather.domain.interactor
import com.rightfromleftsw.weather.domain.executor.PostExecutionThread
import com.rightfromleftsw.weather.domain.executor.ThreadExecutor
import com.rightfromleftsw.weather.domain.interactor.base.SingleUseCase
import com.rightfromleftsw.weather.domain.model.Location
import com.rightfromleftsw.weather.domain.repository.IWeatherRepository
import io.reactivex.Single
import javax.inject.Inject
/**
* Created by clivelee on 9/21/17.
*/
open class GetLocation @Inject constructor(val weatherRepository: IWeatherRepository,
threadExecutor: ThreadExecutor,
postExecutionThread: PostExecutionThread):
SingleUseCase<Location, Void?>(threadExecutor, postExecutionThread) {
public override fun buildUseCaseObservable(params: Void?): Single<Location> {
return weatherRepository.getLocation()
}
}
| mit |
Tolriq/yatse-avreceiverplugin-api | sample/src/main/java/tv/yatse/plugin/avreceiver/sample/SettingsActivity.kt | 1 | 4598 | /*
* Copyright 2015 Tolriq / Genimee.
* 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 tv.yatse.plugin.avreceiver.sample
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import tv.yatse.plugin.avreceiver.api.AVReceiverPluginService
import tv.yatse.plugin.avreceiver.api.YatseLogger
import tv.yatse.plugin.avreceiver.sample.helpers.PreferencesHelper
/**
* Sample SettingsActivity that handle correctly the parameters passed by Yatse.
*
*
* You need to save the passed extra [AVReceiverPluginService.EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID]
* and return it in the result intent.
*
*
* **Production plugin should make input validation and tests before accepting the user input and returning RESULT_OK.**
*/
class SettingsActivity : AppCompatActivity() {
private var mMediaCenterUniqueId: String = ""
private var mMediaCenterName: String = ""
private var mMuted = false
private lateinit var mViewSettingsTitle: TextView
private lateinit var mViewReceiverIP: EditText
private lateinit var mViewMute: ImageButton
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
if (intent != null) {
mMediaCenterUniqueId = intent.getStringExtra(AVReceiverPluginService.EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID) ?: ""
mMediaCenterName = intent.getStringExtra(AVReceiverPluginService.EXTRA_STRING_MEDIA_CENTER_NAME) ?: ""
}
if (TextUtils.isEmpty(mMediaCenterUniqueId)) {
YatseLogger.logError(applicationContext, TAG, "Error : No media center unique id sent")
Snackbar.make(findViewById(R.id.receiver_settings_content), "Wrong data sent by Yatse !", Snackbar.LENGTH_LONG).show()
}
mViewSettingsTitle = findViewById(R.id.receiver_settings_title)
mViewReceiverIP = findViewById(R.id.receiver_ip)
mViewMute = findViewById(R.id.btn_toggle_mute)
mViewSettingsTitle.text = "${getString(R.string.sample_plugin_settings)} $mMediaCenterName"
mViewReceiverIP.setText(
PreferencesHelper.getInstance(applicationContext).hostIp(mMediaCenterUniqueId)
)
findViewById<View>(R.id.btn_toggle_mute).setOnClickListener {
mViewMute.setImageResource(if (!mMuted) R.drawable.ic_volume_low else R.drawable.ic_volume_off)
mMuted = !mMuted
Snackbar.make(findViewById(R.id.receiver_settings_content), "Toggling mute", Snackbar.LENGTH_LONG).show()
}
findViewById<View>(R.id.btn_vol_down).setOnClickListener {
Snackbar.make(findViewById(R.id.receiver_settings_content), "Volume down", Snackbar.LENGTH_LONG).show()
}
findViewById<View>(R.id.btn_vol_up).setOnClickListener {
Snackbar.make(findViewById(R.id.receiver_settings_content), "Volume up", Snackbar.LENGTH_LONG).show()
}
findViewById<View>(R.id.btn_ok).setOnClickListener {
PreferencesHelper.getInstance(applicationContext)
.hostIp(mMediaCenterUniqueId, mViewReceiverIP.text.toString())
setResult(
Activity.RESULT_OK, Intent()
.putExtra(AVReceiverPluginService.EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID, mMediaCenterUniqueId)
)
finish()
}
findViewById<View>(R.id.btn_cancel).setOnClickListener {
setResult(
Activity.RESULT_CANCELED, Intent()
.putExtra(AVReceiverPluginService.EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID, mMediaCenterUniqueId)
)
finish()
}
}
companion object {
private const val TAG = "SettingsActivity"
}
} | apache-2.0 |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/i18n/TranslatableText.kt | 1 | 1306 | /*
* (C) Copyright 2019 Lukas Morawietz (https://github.com/F43nd1r)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.faendir.acra.i18n
import com.vaadin.flow.component.UI
import com.vaadin.flow.i18n.I18NProvider
import com.vaadin.flow.server.VaadinService
import java.util.*
/**
* @author lukas
* @since 06.09.19
*/
open class TranslatableText(val id: String, vararg val params: Any) {
fun translate(): String {
return i18NProvider.getTranslation(
id,
UI.getCurrent()?.locale ?: VaadinService.getCurrent().instantiator.i18NProvider.providedLocales?.firstOrNull() ?: Locale.getDefault(),
*params
)
}
private val i18NProvider: I18NProvider
get() = VaadinService.getCurrent().instantiator.i18NProvider
} | apache-2.0 |
udevbe/westford | compositor/src/main/kotlin/org/westford/compositor/core/Rectangle.kt | 3 | 2193 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.core
import javax.annotation.Nonnegative
data class Rectangle(val x: Int,
val y: Int,
@param:Nonnegative val width: Int,
@param:Nonnegative val height: Int) {
constructor(position: Point,
width: Int,
height: Int) : this(position.x,
position.y,
width,
height)
val position: Point
get() = Point(x,
y)
companion object {
val ZERO = Rectangle(0,
0,
0,
0)
fun create(a: Point,
b: Point): Rectangle {
val width: Int
val x: Int
if (a.x > b.x) {
width = a.x - b.x
x = b.x
}
else {
width = b.x - a.x
x = a.x
}
val height: Int
val y: Int
if (a.x > b.y) {
height = a.y - b.y
y = b.y
}
else {
height = b.y - a.y
y = a.y
}
return Rectangle(x,
y,
width,
height)
}
}
}
| agpl-3.0 |
code-helix/slatekit | src/lib/kotlin/slatekit-tests/src/test/kotlin/test/common/VersionTests.kt | 1 | 1483 | package test.common
import org.junit.Assert
import org.junit.Test
import slatekit.common.types.Version
class VersionTests {
private fun ensure(version: Version, major:Int, minor:Int, patch:Int, build:Int ){
Assert.assertEquals(version.major, major)
Assert.assertEquals(version.minor, minor)
Assert.assertEquals(version.patch, patch)
Assert.assertEquals(version.build, build)
}
@Test fun can_initialize() {
val version1 = Version(1)
ensure(version1, 1, 0, 0, 0)
val version2 = Version(1, 2)
ensure(version2, 1, 2, 0, 0)
val version3 = Version(1, 2, 3)
ensure(version3, 1, 2, 3, 0)
val version4 = Version(1, 2, 3, 4)
ensure(version4, 1, 2, 3, 4)
}
@Test fun can_compare_less_than() {
val version1 = Version(1, 2, 3, 4)
val version2 = Version(1, 2, 3, 5)
Assert.assertEquals(version1.compareTo(version2), -1)
}
@Test fun can_compare_more_than() {
val version1 = Version(1, 2, 3, 4)
val version2 = Version(1, 2, 3, 3)
Assert.assertEquals(version1.compareTo(version2), 1)
}
@Test fun can_compare_equal() {
val version1 = Version(1, 2, 3, 4)
val version2 = Version(1, 2, 3, 4)
Assert.assertEquals(version1.compareTo(version2), 0)
}
@Test fun can_check_empty() {
val version = Version(0, 0, 0, 0)
Assert.assertTrue(version.isEmpty())
}
}
| apache-2.0 |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/datasource/StatusProviderPropertiesDao.kt | 1 | 928 | package org.mtransit.android.datasource
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Query
import org.mtransit.android.common.repository.BaseDao
import org.mtransit.android.data.StatusProviderProperties
@Dao
interface StatusProviderPropertiesDao : BaseDao<StatusProviderProperties> {
@Query("SELECT * FROM status_provider_properties")
fun getAllStatusProvider(): List<StatusProviderProperties>
@Query("SELECT * FROM status_provider_properties")
fun readingAllStatusProviders(): LiveData<List<StatusProviderProperties>>
@Query("SELECT * FROM status_provider_properties WHERE authority = :authority")
fun getStatusProvider(authority: String): StatusProviderProperties
@Query("SELECT * FROM status_provider_properties WHERE target_authority = :targetAuthority")
fun getTargetAuthorityStatusProvider(targetAuthority: String): List<StatusProviderProperties>
} | apache-2.0 |
io53/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/app/ui/MultiTouchViewPager.kt | 1 | 949 | package com.ruuvi.station.app.ui
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager
class MultiTouchViewPager(context: Context, attributeSet: AttributeSet): ViewPager(context, attributeSet) {
var isSwipeEnabled = true
override fun onTouchEvent(ev: MotionEvent?): Boolean {
if (isSwipeEnabled) {
try {
return super.onTouchEvent(ev)
} catch (exception: IllegalArgumentException) {
exception.printStackTrace()
}
}
return false
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
if (isSwipeEnabled) {
try {
return super.onInterceptTouchEvent(ev)
} catch (exception: IllegalArgumentException) {
exception.printStackTrace()
}
}
return false
}
} | mit |
zdary/intellij-community | platform/built-in-server/src/org/jetbrains/ide/ToolboxUpdateActions.kt | 1 | 2913 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.ide
import com.intellij.ide.actions.SettingsEntryPointAction
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.components.*
import com.intellij.openapi.util.Disposer
import com.intellij.util.Alarm
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import java.util.concurrent.ConcurrentHashMap
internal class ToolboxSettingsActionRegistryState: BaseState() {
val knownActions by list<String>()
}
@Service(Service.Level.APP)
@State(name = "toolbox-update-state", storages = [Storage(StoragePathMacros.CACHE_FILE)], allowLoadInTests = true)
internal class ToolboxSettingsActionRegistry : SimplePersistentStateComponent<ToolboxSettingsActionRegistryState>(ToolboxSettingsActionRegistryState()), Disposable {
private val pendingActions : MutableMap<String, AnAction> = ConcurrentHashMap()
private val alarm = MergingUpdateQueue("toolbox-updates", 500, true, null, this, null, Alarm.ThreadToUse.POOLED_THREAD).usePassThroughInUnitTestMode()
override fun dispose() = Unit
fun scheduleUpdate() {
alarm.queue(object: Update(this){
override fun run() {
//we would not like it to overflow
if (state.knownActions.size > 300) {
val tail = state.knownActions.toList().takeLast(30).toHashSet()
state.knownActions.clear()
state.knownActions.addAll(tail)
state.intIncrementModificationCount()
}
val ids = pendingActions.keys.toSortedSet()
val iconState = if (!state.knownActions.containsAll(ids)) {
state.knownActions.addAll(ids)
state.intIncrementModificationCount()
SettingsEntryPointAction.IconState.ApplicationUpdate
} else {
SettingsEntryPointAction.IconState.Current
}
invokeLater {
SettingsEntryPointAction.updateState(iconState)
}
}
})
}
fun registerUpdateAction(lifetime: Disposable, persistentActionId: String, action: AnAction) {
val dispose = Disposable {
pendingActions.remove(persistentActionId, action)
scheduleUpdate()
}
pendingActions[persistentActionId] = action
if (!Disposer.tryRegister(lifetime, dispose)) {
Disposer.dispose(dispose)
return
}
scheduleUpdate()
}
fun getActions() : List<AnAction> = pendingActions.entries.sortedBy { it.key }.map { it.value }
}
class ToolboxSettingsActionRegistryActionProvider : SettingsEntryPointAction.ActionProvider {
override fun getUpdateActions(context: DataContext) = service<ToolboxSettingsActionRegistry>().getActions()
}
| apache-2.0 |
blokadaorg/blokada | android5/app/src/main/java/service/PersistenceService.kt | 1 | 6113 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package service
import blocka.LegacyAccountImport
import model.*
import repository.PackMigration
import tunnel.LegacyAdsCounterImport
import tunnel.LegacyBlocklistImport
import ui.ActivationViewModel
import ui.utils.cause
import utils.Logger
import kotlin.reflect.KClass
object PersistenceService {
private val log = Logger("Persistence")
private val json = JsonSerializationService
private val newline = NewlineSerializationService
private val prefs = SharedPreferencesStorageService
private val file = FileStorageService
fun save(obj: Any) {
try {
when (obj) {
is Denied -> file.save(
key = BlocklistService.USER_DENIED,
data = newline.serialize(obj)
)
is Allowed -> file.save(
key = BlocklistService.USER_ALLOWED,
data = newline.serialize(obj)
)
else -> prefs.save(getPrefsKey(obj::class), json.serialize(obj))
}
} catch (ex: Exception) {
log.e("Could not save persistence, ignoring".cause(ex))
}
}
fun <T: Any> load(type: KClass<T>): T {
try {
val (string, deserializer) = when (type) {
Denied::class -> {
val legacy = LegacyBlocklistImport.importLegacyBlocklistUserDenied()
if (legacy != null) {
save(Denied(legacy)) // To save in the current format
legacy.joinToString("\n") to newline
} else file.load(key = BlocklistService.USER_DENIED) to newline
}
Allowed::class -> {
val legacy = LegacyBlocklistImport.importLegacyBlocklistUserAllowed()
if (legacy != null) {
save(Allowed(legacy)) // To save in the current format
legacy.joinToString("\n") to newline
} else file.load(key = BlocklistService.USER_ALLOWED) to newline
}
Account::class -> {
val legacy = LegacyAccountImport.importLegacyAccount()
if (legacy != null) {
save(legacy) // To save in the current format
legacy to PassthroughSerializationService
} else prefs.load(getPrefsKey(type)) to json
}
AdsCounter::class -> {
val legacy = LegacyAdsCounterImport.importLegacyCounter()
if (legacy != null) {
save(legacy) // To save in the current format
legacy to PassthroughSerializationService
}
else prefs.load(getPrefsKey(type)) to json
}
else -> prefs.load(getPrefsKey(type)) to json
}
if (string != null) {
val deserialized = deserializer.deserialize(string, type)
return when (type) {
Packs::class -> {
val (packs, migrated) = PackMigration.migrate(deserialized as Packs)
if (migrated) save(packs)
packs as T
}
else -> deserialized
}
}
throw BlokadaException("Nothing persisted yet")
} catch (ex: Exception) {
log.w("Could not load persistence for: $type, reason: ${ex.message}")
log.v("Returning defaults for $type")
return getDefault(type)
}
}
private fun getPrefsKey(type: KClass<*>) = when (type) {
StatsPersisted::class -> "stats"
Packs::class -> "packs"
BlockaConfig::class -> "blockaConfig"
LocalConfig::class -> "localConfig"
SyncableConfig::class -> "syncableConfig"
DnsWrapper::class -> "dns"
ActivationViewModel.ActivationState::class -> "activationState"
Account::class -> "account"
AdsCounter::class -> "adsCounter"
BypassedAppIds::class -> "bypassedApps"
BlockaRepoConfig::class -> "blockaRepoConfig"
BlockaRepoUpdate::class -> "blockaRepoUpdate"
BlockaRepoPayload::class -> "blockaRepoPayload"
BlockaAfterUpdate::class -> "blockaAfterUpdate"
NetworkSpecificConfigs::class -> "networkSpecificConfigs"
else -> throw BlokadaException("Unsupported type for persistence: $type")
}
private fun <T: Any> getDefault(type: KClass<T>) = when (type) {
StatsPersisted::class -> Defaults.stats() as T
Allowed::class -> Defaults.allowed() as T
Denied::class -> Defaults.denied() as T
Packs::class -> Defaults.packs() as T
BlockaConfig::class -> Defaults.blockaConfig() as T
LocalConfig::class -> Defaults.localConfig() as T
SyncableConfig::class -> Defaults.syncableConfig() as T
DnsWrapper::class -> Defaults.dnsWrapper() as T
ActivationViewModel.ActivationState::class -> ActivationViewModel.ActivationState.INACTIVE as T
Account::class -> throw NoPersistedAccount()
AdsCounter::class -> Defaults.adsCounter() as T
BypassedAppIds::class -> Defaults.bypassedAppIds() as T
BlockaRepoConfig::class -> Defaults.blockaRepoConfig() as T
BlockaRepoUpdate::class -> Defaults.noSeenUpdate() as T
BlockaRepoPayload::class -> Defaults.noPayload() as T
BlockaAfterUpdate::class -> Defaults.noAfterUpdate() as T
NetworkSpecificConfigs::class -> Defaults.noNetworkSpecificConfigs() as T
else -> throw BlokadaException("No default for persisted type: $type")
}
} | mpl-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/collections/GroupingTest/countEach.kt | 2 | 438 | import kotlin.test.*
fun box() {
val elements = listOf("foo", "bar", "flea", "zoo", "biscuit")
val counts = elements.groupingBy { it.first() }.eachCount()
assertEquals(mapOf('f' to 2, 'b' to 2, 'z' to 1), counts)
val elements2 = arrayOf("zebra", "baz", "cab")
val counts2 = elements2.groupingBy { it.last() }.eachCountTo(HashMap(counts))
assertEquals(mapOf('f' to 2, 'b' to 3, 'a' to 1, 'z' to 2), counts2)
}
| apache-2.0 |
Pozo/threejs-kotlin | threejs/src/main/kotlin/three/geometries/PlaneGeometry.kt | 1 | 173 | @file:JsQualifier("THREE")
package three.geometries
@JsName("PlaneGeometry")
external class PlaneGeometry(width: Int, height: Int, widthSegments: Int, heightSegments: Int) | mit |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/ide/ProjectViewSettingsTest.kt | 12 | 1952 | // 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.ide
import com.intellij.ide.projectView.ProjectViewSettings
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.util.treeView.NodeOptions
import org.junit.Assert
import org.junit.Test
class ProjectViewSettingsTest {
@Test
fun testDefaultNodeOptions() {
assertDefaultNodeOptions(NodeOptions.Immutable.DEFAULT)
assertDefaultNodeOptions(object : NodeOptions {})
}
private fun assertDefaultNodeOptions(options: NodeOptions) {
Assert.assertFalse(options.isFlattenPackages)
Assert.assertFalse(options.isAbbreviatePackageNames)
Assert.assertFalse(options.isHideEmptyMiddlePackages)
Assert.assertFalse(options.isCompactDirectories)
Assert.assertFalse(options.isShowLibraryContents)
}
@Test
fun testDefaultViewSettings() {
assertDefaultViewSettings(ViewSettings.Immutable.DEFAULT)
assertDefaultViewSettings(object : ViewSettings {})
}
private fun assertDefaultViewSettings(settings: ViewSettings) {
assertDefaultNodeOptions(settings)
Assert.assertTrue(settings.isFoldersAlwaysOnTop)
Assert.assertFalse(settings.isShowMembers)
Assert.assertFalse(settings.isStructureView)
Assert.assertTrue(settings.isShowModules)
Assert.assertFalse(settings.isFlattenModules)
Assert.assertTrue(settings.isShowURL)
}
@Test
fun testDefaultProjectViewSettings() {
assertDefaultProjectViewSettings(ProjectViewSettings.Immutable.DEFAULT)
assertDefaultProjectViewSettings(object : ProjectViewSettings {})
}
private fun assertDefaultProjectViewSettings(settings: ProjectViewSettings) {
assertDefaultViewSettings(settings)
Assert.assertTrue(settings.isShowExcludedFiles)
Assert.assertFalse(settings.isShowVisibilityIcons)
Assert.assertTrue(settings.isUseFileNestingRules)
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/uast/uast-kotlin-idea/tests/test/org/jetbrains/uast/test/kotlin/KotlinUastGenerationTest.kt | 1 | 46754 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.kotlin
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Ref
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import com.intellij.psi.SyntaxTraverser
import com.intellij.psi.util.parentOfType
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.UsefulTestCase
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.uast.*
import org.jetbrains.uast.expressions.UInjectionHost
import org.jetbrains.uast.generate.UParameterInfo
import org.jetbrains.uast.generate.UastCodeGenerationPlugin
import org.jetbrains.uast.generate.refreshed
import org.jetbrains.uast.generate.replace
import org.jetbrains.uast.kotlin.generate.KotlinUastElementFactory
import org.jetbrains.uast.test.env.kotlin.findElementByTextFromPsi
import org.jetbrains.uast.test.env.kotlin.findUElementByTextFromPsi
import org.jetbrains.uast.visitor.UastVisitor
import kotlin.test.fail as kfail
class KotlinUastGenerationTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor =
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
private val psiFactory
get() = KtPsiFactory(project)
private val generatePlugin: UastCodeGenerationPlugin
get() = UastCodeGenerationPlugin.byLanguage(KotlinLanguage.INSTANCE)!!
private val uastElementFactory
get() = generatePlugin.getElementFactory(myFixture.project) as KotlinUastElementFactory
fun `test logical and operation with simple operands`() {
val left = psiFactory.createExpression("true").toUElementOfType<UExpression>()
?: kfail("Cannot create left UExpression")
val right = psiFactory.createExpression("false").toUElementOfType<UExpression>()
?: kfail("Cannot create right UExpression")
val expression = uastElementFactory.createBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile())
?: kfail("Cannot create expression")
TestCase.assertEquals("true && false", expression.sourcePsi?.text)
}
fun `test logical and operation with simple operands with parenthesis`() {
val left = psiFactory.createExpression("(true)").toUElementOfType<UExpression>()
?: kfail("Cannot create left UExpression")
val right = psiFactory.createExpression("(false)").toUElementOfType<UExpression>()
?: kfail("Cannot create right UExpression")
val expression = uastElementFactory.createFlatBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile())
?: kfail("Cannot create expression")
TestCase.assertEquals("true && false", expression.sourcePsi?.text)
TestCase.assertEquals("""
UBinaryExpression (operator = &&)
ULiteralExpression (value = true)
ULiteralExpression (value = false)
""".trimIndent(), expression.putIntoFunctionBody().asRecursiveLogString().trim())
}
fun `test logical and operation with simple operands with parenthesis polyadic`() {
val left = psiFactory.createExpression("(true && false)").toUElementOfType<UExpression>()
?: kfail("Cannot create left UExpression")
val right = psiFactory.createExpression("(false)").toUElementOfType<UExpression>()
?: kfail("Cannot create right UExpression")
val expression = uastElementFactory.createFlatBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile())
?: kfail("Cannot create expression")
TestCase.assertEquals("true && false && false", expression.sourcePsi?.text)
TestCase.assertEquals("""
UBinaryExpression (operator = &&)
UBinaryExpression (operator = &&)
ULiteralExpression (value = null)
ULiteralExpression (value = null)
ULiteralExpression (value = null)
""".trimIndent(), expression.asRecursiveLogString().trim())
}
fun `test simple reference creating from variable`() {
val context = dummyContextFile()
val variable = uastElementFactory.createLocalVariable(
"a", PsiType.INT, uastElementFactory.createNullLiteral(context), false, context
)
val reference = uastElementFactory.createSimpleReference(variable, context) ?: kfail("cannot create reference")
TestCase.assertEquals("a", reference.identifier)
}
fun `test simple reference by name`() {
val reference = uastElementFactory.createSimpleReference("a", dummyContextFile())
TestCase.assertEquals("a", reference.identifier)
}
fun `test parenthesised expression`() {
val expression = psiFactory.createExpression("a + b").toUElementOfType<UExpression>()
?: kfail("cannot create expression")
val parenthesizedExpression = uastElementFactory.createParenthesizedExpression(expression, dummyContextFile())
?: kfail("cannot create parenthesized expression")
TestCase.assertEquals("(a + b)", parenthesizedExpression.sourcePsi?.text)
}
fun `test return expression`() {
val expression = psiFactory.createExpression("a + b").toUElementOfType<UExpression>()
?: kfail("Cannot find plugin")
val returnExpression = uastElementFactory.createReturnExpresion(expression, false, dummyContextFile())
TestCase.assertEquals("a + b", returnExpression.returnExpression?.asRenderString())
TestCase.assertEquals("return a + b", returnExpression.sourcePsi?.text)
}
fun `test variable declaration without type`() {
val expression = psiFactory.createExpression("1 + 2").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", null, expression, false, dummyContextFile())
TestCase.assertEquals("var a = 1 + 2", declaration.sourcePsi?.text)
}
fun `test variable declaration with type`() {
val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, false, dummyContextFile())
TestCase.assertEquals("var a: kotlin.Double = b", declaration.sourcePsi?.text)
}
fun `test final variable declaration`() {
val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, true, dummyContextFile())
TestCase.assertEquals("val a: kotlin.Double = b", declaration.sourcePsi?.text)
}
fun `test final variable declaration with unique name`() {
val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>()
?: kfail("cannot create variable declaration")
val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, true, dummyContextFile())
TestCase.assertEquals("val a: kotlin.Double = b", declaration.sourcePsi?.text)
TestCase.assertEquals("""
ULocalVariable (name = a)
USimpleNameReferenceExpression (identifier = b)
""".trimIndent(), declaration.asRecursiveLogString().trim())
}
fun `test block expression`() {
val statement1 = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val statement2 = psiFactory.createExpression("System.out.println(2)").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val block = uastElementFactory.createBlockExpression(listOf(statement1, statement2), dummyContextFile())
TestCase.assertEquals("""
{
System.out.println()
System.out.println(2)
}
""".trimIndent(), block.sourcePsi?.text
)
}
fun `test lambda expression`() {
val statement = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val lambda = uastElementFactory.createLambdaExpression(
listOf(
UParameterInfo(PsiType.INT, "a"),
UParameterInfo(null, "b")
),
statement,
dummyContextFile()
) ?: kfail("cannot create lambda")
TestCase.assertEquals("{ a: kotlin.Int, b -> System.out.println() }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UParameter (name = b)
UAnnotation (fqName = null)
UBlockExpression
UQualifiedReferenceExpression
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = System)
USimpleNameReferenceExpression (identifier = out)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
""".trimIndent(), lambda.putIntoFunctionBody().asRecursiveLogString().trim())
}
private fun UExpression.putIntoFunctionBody(): UExpression {
val file = myFixture.configureByText("dummyFile.kt", "fun foo() { TODO() }") as KtFile
val ktFunction = file.declarations.single { it.name == "foo" } as KtFunction
val uMethod = ktFunction.toUElementOfType<UMethod>()!!
return runWriteCommand {
uMethod.uastBody.cast<UBlockExpression>().expressions.single().replace(this)!!
}
}
private fun <T : UExpression> T.putIntoVarInitializer(): T {
val file = myFixture.configureByText("dummyFile.kt", "val foo = TODO()") as KtFile
val ktFunction = file.declarations.single { it.name == "foo" } as KtProperty
val uMethod = ktFunction.toUElementOfType<UVariable>()!!
return runWriteCommand {
@Suppress("UNCHECKED_CAST")
generatePlugin.replace(uMethod.uastInitializer!!, this, UExpression::class.java) as T
}
}
private fun <T : UExpression> runWriteCommand(uExpression: () -> T): T {
val result = Ref<T>()
WriteCommandAction.runWriteCommandAction(project) {
result.set(uExpression())
}
return result.get()
}
fun `test lambda expression with explicit types`() {
val statement = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>()
?: kfail("cannot create statement")
val lambda = uastElementFactory.createLambdaExpression(
listOf(
UParameterInfo(PsiType.INT, "a"),
UParameterInfo(PsiType.DOUBLE, "b")
),
statement,
dummyContextFile()
) ?: kfail("cannot create lambda")
TestCase.assertEquals("{ a: kotlin.Int, b: kotlin.Double -> System.out.println() }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UParameter (name = b)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UQualifiedReferenceExpression
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = System)
USimpleNameReferenceExpression (identifier = out)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
""".trimIndent(), lambda.putIntoFunctionBody().asRecursiveLogString().trim())
}
fun `test lambda expression with simplified block body with context`() {
val r = psiFactory.createExpression("return \"10\"").toUElementOfType<UExpression>()
?: kfail("cannot create return")
val block = uastElementFactory.createBlockExpression(listOf(r), dummyContextFile())
val lambda = uastElementFactory.createLambdaExpression(listOf(UParameterInfo(null, "a")), block, dummyContextFile())
?: kfail("cannot create lambda")
TestCase.assertEquals("""{ a -> "10" }""".trimMargin(), lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UReturnExpression
ULiteralExpression (value = "10")
""".trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim())
}
fun `test function argument replacement`() {
val file = myFixture.configureByText(
"test.kt", """
fun f(a: Any){}
fun main(){
f(a)
}
""".trimIndent()
)
val expression = file.findUElementByTextFromPsi<UCallExpression>("f(a)")
val newArgument = psiFactory.createExpression("b").toUElementOfType<USimpleNameReferenceExpression>()
?: kfail("cannot create reference")
WriteCommandAction.runWriteCommandAction(project) {
TestCase.assertNotNull(expression.valueArguments[0].replace(newArgument))
}
val updated = expression.refreshed() ?: kfail("cannot update expression")
TestCase.assertEquals("f", updated.methodName)
TestCase.assertTrue(updated.valueArguments[0] is USimpleNameReferenceExpression)
TestCase.assertEquals("b", (updated.valueArguments[0] as USimpleNameReferenceExpression).identifier)
TestCase.assertEquals("""
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (f))
USimpleNameReferenceExpression (identifier = f, resolvesTo = null)
USimpleNameReferenceExpression (identifier = b)
""".trimIndent(), updated.asRecursiveLogString().trim())
}
fun `test suggested name`() {
val expression = psiFactory.createExpression("f(a) + 1").toUElementOfType<UExpression>()
?: kfail("cannot create expression")
val variable = uastElementFactory.createLocalVariable(null, PsiType.INT, expression, true, dummyContextFile())
TestCase.assertEquals("val i: kotlin.Int = f(a) + 1", variable.sourcePsi?.text)
TestCase.assertEquals("""
ULocalVariable (name = i)
UBinaryExpression (operator = +)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (f))
USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null)
USimpleNameReferenceExpression (identifier = a)
ULiteralExpression (value = null)
""".trimIndent(), variable.asRecursiveLogString().trim())
}
fun `test method call generation with receiver`() {
val receiver = psiFactory.createExpression(""""10"""").toUElementOfType<UExpression>()
?: kfail("cannot create receiver")
val arg1 = psiFactory.createExpression("1").toUElementOfType<UExpression>()
?: kfail("cannot create arg1")
val arg2 = psiFactory.createExpression("2").toUElementOfType<UExpression>()
?: kfail("cannot create arg2")
val methodCall = uastElementFactory.createCallExpression(
receiver,
"substring",
listOf(arg1, arg2),
null,
UastCallKind.METHOD_CALL
) ?: kfail("cannot create call")
TestCase.assertEquals(""""10".substring(1,2)""", methodCall.uastParent?.sourcePsi?.text)
TestCase.assertEquals("""
UQualifiedReferenceExpression
ULiteralExpression (value = "10")
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 2))
UIdentifier (Identifier (substring))
USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null)
ULiteralExpression (value = null)
ULiteralExpression (value = null)
""".trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test method call generation without receiver`() {
val arg1 = psiFactory.createExpression("1").toUElementOfType<UExpression>()
?: kfail("cannot create arg1")
val arg2 = psiFactory.createExpression("2").toUElementOfType<UExpression>()
?: kfail("cannot create arg2")
val methodCall = uastElementFactory.createCallExpression(
null,
"substring",
listOf(arg1, arg2),
null,
UastCallKind.METHOD_CALL
) ?: kfail("cannot create call")
TestCase.assertEquals("""substring(1,2)""", methodCall.sourcePsi?.text)
}
fun `test method call generation with generics restoring`() {
val arrays = psiFactory.createExpression("java.util.Arrays").toUElementOfType<UExpression>()
?: kfail("cannot create receiver")
val methodCall = uastElementFactory.createCallExpression(
arrays,
"asList",
listOf(),
createTypeFromText("java.util.List<java.lang.String>", null),
UastCallKind.METHOD_CALL,
dummyContextFile()
) ?: kfail("cannot create call")
TestCase.assertEquals("java.util.Arrays.asList<kotlin.String>()", methodCall.uastParent?.sourcePsi?.text)
}
fun `test method call generation with generics restoring 2 parameters`() {
val collections = psiFactory.createExpression("java.util.Collections").toUElementOfType<UExpression>()
?: kfail("cannot create receiver")
TestCase.assertEquals("java.util.Collections", collections.asRenderString())
val methodCall = uastElementFactory.createCallExpression(
collections,
"emptyMap",
listOf(),
createTypeFromText(
"java.util.Map<java.lang.String, java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
dummyContextFile()
) ?: kfail("cannot create call")
TestCase.assertEquals("emptyMap<kotlin.String,kotlin.Int>()", methodCall.sourcePsi?.text)
TestCase.assertEquals("java.util.Collections.emptyMap<kotlin.String,kotlin.Int>()", methodCall.sourcePsi?.parent?.text)
TestCase.assertEquals(
"""
UQualifiedReferenceExpression
UQualifiedReferenceExpression
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = java)
USimpleNameReferenceExpression (identifier = util)
USimpleNameReferenceExpression (identifier = Collections)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (emptyMap))
USimpleNameReferenceExpression (identifier = emptyMap, resolvesTo = null)
""".trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim()
)
}
private fun dummyContextFile(): KtFile = myFixture.configureByText("file.kt", "fun foo() {}") as KtFile
fun `test method call generation with generics restoring 1 parameter with 1 existing`() {
val a = psiFactory.createExpression("A").toUElementOfType<UExpression>()
?: kfail("cannot create a receiver")
val param = psiFactory.createExpression("\"a\"").toUElementOfType<UExpression>()
?: kfail("cannot create a parameter")
val methodCall = uastElementFactory.createCallExpression(
a,
"kek",
listOf(param),
createTypeFromText(
"java.util.Map<java.lang.String, java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
dummyContextFile()
) ?: kfail("cannot create call")
TestCase.assertEquals("A.kek<kotlin.String,kotlin.Int>(\"a\")", methodCall.sourcePsi?.parent?.text)
TestCase.assertEquals(
"""
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = A)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (kek))
USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null)
ULiteralExpression (value = "a")
""".trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test callable reference generation with receiver`() {
val receiver = uastElementFactory.createQualifiedReference("java.util.Arrays", myFixture.file)
?: kfail("failed to create receiver")
val methodReference = uastElementFactory.createCallableReferenceExpression(receiver, "asList", myFixture.file)
?: kfail("failed to create method reference")
TestCase.assertEquals(methodReference.sourcePsi?.text, "java.util.Arrays::asList")
}
fun `test callable reference generation without receiver`() {
val methodReference = uastElementFactory.createCallableReferenceExpression(null, "asList", myFixture.file)
?: kfail("failed to create method reference")
TestCase.assertEquals(methodReference.sourcePsi?.text, "::asList")
}
//not implemented (currently we dont perform resolve in code generating)
fun `ignore method call generation with generics restoring 1 parameter with 1 unused `() {
val aClassFile = myFixture.configureByText(
"A.kt",
"""
object A {
fun <T1, T2, T3> kek(a: T1): Map<T1, T3> {
return TODO();
}
}
""".trimIndent()
)
val a = psiFactory.createExpression("A").toUElementOfType<UExpression>()
?: kfail("cannot create a receiver")
val param = psiFactory.createExpression("\"a\"").toUElementOfType<UExpression>()
?: kfail("cannot create a parameter")
val methodCall = uastElementFactory.createCallExpression(
a,
"kek",
listOf(param),
createTypeFromText(
"java.util.Map<java.lang.String, java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
aClassFile
) ?: kfail("cannot create call")
TestCase.assertEquals("A.<String, Object, Integer>kek(\"a\")", methodCall.sourcePsi?.text)
}
fun `test method call generation with generics with context`() {
val file = myFixture.configureByText("file.kt", """
class A {
fun <T> method(): List<T> { TODO() }
}
fun main(){
val a = A()
println(a)
}
""".trimIndent()
) as KtFile
val reference = file.findUElementByTextFromPsi<UElement>("println(a)")
.findElementByTextFromPsi<UReferenceExpression>("a")
val callExpression = uastElementFactory.createCallExpression(
reference,
"method",
emptyList(),
createTypeFromText(
"java.util.List<java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
context = reference.sourcePsi
) ?: kfail("cannot create method call")
TestCase.assertEquals("a.method<kotlin.Int>()", callExpression.uastParent?.sourcePsi?.text)
TestCase.assertEquals("""
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = a)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0))
UIdentifier (Identifier (method))
USimpleNameReferenceExpression (identifier = method, resolvesTo = null)
""".trimIndent(), callExpression.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test method call generation without generics with context`() {
val file = myFixture.configureByText("file.kt", """
class A {
fun <T> method(t: T): List<T> { TODO() }
}
fun main(){
val a = A()
println(a)
}
""".trimIndent()
) as KtFile
val reference = file.findUElementByTextFromPsi<UElement>("println(a)")
.findElementByTextFromPsi<UReferenceExpression>("a")
val callExpression = uastElementFactory.createCallExpression(
reference,
"method",
listOf(uastElementFactory.createIntLiteral(1, null)),
createTypeFromText(
"java.util.List<java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
context = reference.sourcePsi
) ?: kfail("cannot create method call")
TestCase.assertEquals("a.method(1)", callExpression.uastParent?.sourcePsi?.text)
TestCase.assertEquals("""
UQualifiedReferenceExpression
USimpleNameReferenceExpression (identifier = a)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (method))
USimpleNameReferenceExpression (identifier = method, resolvesTo = null)
ULiteralExpression (value = 1)
""".trimIndent(), callExpression.uastParent?.asRecursiveLogString()?.trim()
)
}
fun `test replace lambda implicit return value`() {
val file = myFixture.configureByText(
"file.kt", """
fun main(){
val a: (Int) -> String = {
println(it)
println(2)
"abc"
}
}
""".trimIndent()
) as KtFile
val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"")
.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
val expressions = uLambdaExpression.body.cast<UBlockExpression>().expressions
UsefulTestCase.assertSize(3, expressions)
val uReturnExpression = expressions.last() as UReturnExpression
val newStringLiteral = uastElementFactory.createStringLiteralExpression("def", file)
val defReturn = runWriteCommand { uReturnExpression.replace(newStringLiteral) ?: kfail("cant replace") }
val uLambdaExpression2 = defReturn.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
TestCase.assertEquals("{\n println(it)\n println(2)\n \"def\"\n }", uLambdaExpression2.sourcePsi?.text)
TestCase.assertEquals(
"""
ULambdaExpression
UParameter (name = it)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = it)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
ULiteralExpression (value = 2)
UReturnExpression
ULiteralExpression (value = "def")
""".trimIndent(), uLambdaExpression2.asRecursiveLogString().trim()
)
}
private class UserDataChecker {
private val storedData = Any()
private val KEY = Key.create<Any>("testKey")
private lateinit var uniqueStringLiteralText: String
fun store(uElement: UInjectionHost) {
val psiElement = uElement.sourcePsi as KtStringTemplateExpression
uniqueStringLiteralText = psiElement.text
psiElement.putCopyableUserData(KEY, storedData)
}
fun checkUserDataAlive(uElement: UElement) {
val psiElements = uElement.let { SyntaxTraverser.psiTraverser(it.sourcePsi) }
.filter(KtStringTemplateExpression::class.java)
.filter { it.text == uniqueStringLiteralText }.toList()
UsefulTestCase.assertNotEmpty(psiElements)
UsefulTestCase.assertTrue("uElement still should keep the userdata", psiElements.any { storedData === it!!.getCopyableUserData(KEY) })
}
}
fun `test add intermediate returns to lambda`() {
val file = myFixture.configureByText(
"file.kt", """
fun main(){
val a: (Int) -> String = lname@{
println(it)
println(2)
"abc"
}
}
""".trimIndent()
) as KtFile
val aliveChecker = UserDataChecker()
val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"")
.also(aliveChecker::store)
.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
val oldBlockExpression = uLambdaExpression.body.cast<UBlockExpression>()
UsefulTestCase.assertSize(3, oldBlockExpression.expressions)
val conditionalExit = with(uastElementFactory) {
createIfExpression(
createBinaryExpression(
createSimpleReference("it", uLambdaExpression.sourcePsi),
createIntLiteral(3, uLambdaExpression.sourcePsi),
UastBinaryOperator.GREATER,
uLambdaExpression.sourcePsi
)!!,
createReturnExpresion(
createStringLiteralExpression("exit", uLambdaExpression.sourcePsi), true,
uLambdaExpression.sourcePsi
),
null,
uLambdaExpression.sourcePsi
)!!
}
val newBlockExpression = uastElementFactory.createBlockExpression(
listOf(conditionalExit) + oldBlockExpression.expressions,
uLambdaExpression.sourcePsi
)
aliveChecker.checkUserDataAlive(newBlockExpression)
val uLambdaExpression2 = runWriteCommand {
oldBlockExpression.replace(newBlockExpression) ?: kfail("cant replace")
}.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
aliveChecker.checkUserDataAlive(uLambdaExpression2)
TestCase.assertEquals(
"""
lname@{
if (it > 3) return@lname "exit"
println(it)
println(2)
"abc"
}
""".trimIndent(), uLambdaExpression2.sourcePsi?.parent?.text
)
TestCase.assertEquals(
"""
ULambdaExpression
UParameter (name = it)
UBlockExpression
UIfExpression
UBinaryExpression (operator = >)
USimpleNameReferenceExpression (identifier = it)
ULiteralExpression (value = 3)
UReturnExpression
ULiteralExpression (value = "exit")
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = it)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
ULiteralExpression (value = 2)
UReturnExpression
ULiteralExpression (value = "abc")
""".trimIndent(), uLambdaExpression2.asRecursiveLogString().trim()
)
}
fun `test converting lambda to if`() {
val file = myFixture.configureByText(
"file.kt", """
fun foo(call: (Int) -> String): String = call.invoke(2)
fun main() {
foo {
println(it)
println(2)
"abc"
}
}
}
""".trimIndent()
) as KtFile
val aliveChecker = UserDataChecker()
val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"")
.also { aliveChecker.store(it) }
.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda")
val oldBlockExpression = uLambdaExpression.body.cast<UBlockExpression>()
aliveChecker.checkUserDataAlive(oldBlockExpression)
val newLambda = with(uastElementFactory) {
createLambdaExpression(
listOf(UParameterInfo(null, "it")),
createIfExpression(
createBinaryExpression(
createSimpleReference("it", uLambdaExpression.sourcePsi),
createIntLiteral(3, uLambdaExpression.sourcePsi),
UastBinaryOperator.GREATER,
uLambdaExpression.sourcePsi
)!!,
oldBlockExpression,
createReturnExpresion(
createStringLiteralExpression("exit", uLambdaExpression.sourcePsi), true,
uLambdaExpression.sourcePsi
),
uLambdaExpression.sourcePsi
)!!.also {
aliveChecker.checkUserDataAlive(it)
},
uLambdaExpression.sourcePsi
)!!
}
aliveChecker.checkUserDataAlive(newLambda)
val uLambdaExpression2 = runWriteCommand {
uLambdaExpression.replace(newLambda) ?: kfail("cant replace")
}
TestCase.assertEquals(
"""
{ it ->
if (it > 3) {
println(it)
println(2)
"abc"
} else return@foo "exit"
}
""".trimIndent(), uLambdaExpression2.sourcePsi?.parent?.text
)
TestCase.assertEquals(
"""
ULambdaExpression
UParameter (name = it)
UAnnotation (fqName = null)
UBlockExpression
UReturnExpression
UIfExpression
UBinaryExpression (operator = >)
USimpleNameReferenceExpression (identifier = it)
ULiteralExpression (value = 3)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = it)
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
ULiteralExpression (value = 2)
ULiteralExpression (value = "abc")
UReturnExpression
ULiteralExpression (value = "exit")
""".trimIndent(), uLambdaExpression2.asRecursiveLogString().trim()
)
aliveChecker.checkUserDataAlive(uLambdaExpression2)
}
fun `test removing unnecessary type parameters while replace`() {
val aClassFile = myFixture.configureByText(
"A.kt",
"""
class A {
fun <T> method():List<T> = TODO()
}
""".trimIndent()
)
val reference = psiFactory.createExpression("a")
.toUElementOfType<UReferenceExpression>() ?: kfail("cannot create reference expression")
val callExpression = uastElementFactory.createCallExpression(
reference,
"method",
emptyList(),
createTypeFromText(
"java.util.List<java.lang.Integer>",
null
),
UastCallKind.METHOD_CALL,
context = aClassFile
) ?: kfail("cannot create method call")
val listAssigment = myFixture.addFileToProject("temp.kt", """
fun foo(kek: List<Int>) {
val list: List<Int> = kek
}
""".trimIndent()).findUElementByTextFromPsi<UVariable>("val list: List<Int> = kek")
WriteCommandAction.runWriteCommandAction(project) {
val methodCall = listAssigment.uastInitializer?.replace(callExpression) ?: kfail("cannot replace!")
// originally result expected be `a.method()` but we expect to clean up type arguments in other plase
TestCase.assertEquals("a.method<Int>()", methodCall.sourcePsi?.parent?.text)
}
}
fun `test create if`() {
val condition = psiFactory.createExpression("true").toUElementOfType<UExpression>()
?: kfail("cannot create condition")
val thenBranch = psiFactory.createBlock("{a(b);}").toUElementOfType<UExpression>()
?: kfail("cannot create then branch")
val elseBranch = psiFactory.createExpression("c++").toUElementOfType<UExpression>()
?: kfail("cannot create else branch")
val ifExpression = uastElementFactory.createIfExpression(condition, thenBranch, elseBranch, dummyContextFile())
?: kfail("cannot create if expression")
TestCase.assertEquals("if (true) {\n { a(b); }\n } else c++", ifExpression.sourcePsi?.text)
}
fun `test qualified reference`() {
val reference = uastElementFactory.createQualifiedReference("java.util.List", myFixture.file)
TestCase.assertEquals("java.util.List", reference?.sourcePsi?.text)
}
fun `test build lambda from returning a variable`() {
val context = dummyContextFile()
val localVariable = uastElementFactory.createLocalVariable("a", null, uastElementFactory.createNullLiteral(context), true, context)
val declarationExpression =
uastElementFactory.createDeclarationExpression(listOf(localVariable), context)
val returnExpression = uastElementFactory.createReturnExpresion(
uastElementFactory.createSimpleReference(localVariable, context), false, context
)
val block = uastElementFactory.createBlockExpression(listOf(declarationExpression, returnExpression), context)
TestCase.assertEquals("""
UBlockExpression
UDeclarationsExpression
ULocalVariable (name = a)
ULiteralExpression (value = null)
UReturnExpression
USimpleNameReferenceExpression (identifier = a)
""".trimIndent(), block.asRecursiveLogString().trim())
val lambda = uastElementFactory.createLambdaExpression(listOf(), block, context) ?: kfail("cannot create lambda expression")
TestCase.assertEquals("{ val a = null\na }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UBlockExpression
UDeclarationsExpression
ULocalVariable (name = a)
ULiteralExpression (value = null)
UReturnExpression
USimpleNameReferenceExpression (identifier = a)
""".trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim())
}
fun `test expand oneline lambda`() {
val context = dummyContextFile()
val parameters = listOf(UParameterInfo(PsiType.INT, "a"))
val oneLineLambda = with(uastElementFactory) {
createLambdaExpression(
parameters,
createBinaryExpression(
createSimpleReference("a", context),
createSimpleReference("a", context),
UastBinaryOperator.PLUS, context
)!!, context
)!!
}.putIntoVarInitializer()
val lambdaReturn = (oneLineLambda.body as UBlockExpression).expressions.single()
val lambda = with(uastElementFactory) {
createLambdaExpression(
parameters,
createBlockExpression(
listOf(
createCallExpression(
null,
"println",
listOf(createSimpleReference("a", context)),
PsiType.VOID,
UastCallKind.METHOD_CALL,
context
)!!,
lambdaReturn
),
context
), context
)!!
}
TestCase.assertEquals("{ a: kotlin.Int -> println(a)\na + a }", lambda.sourcePsi?.text)
TestCase.assertEquals("""
ULambdaExpression
UParameter (name = a)
UAnnotation (fqName = org.jetbrains.annotations.NotNull)
UBlockExpression
UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1))
UIdentifier (Identifier (println))
USimpleNameReferenceExpression (identifier = println, resolvesTo = null)
USimpleNameReferenceExpression (identifier = a)
UReturnExpression
UBinaryExpression (operator = +)
USimpleNameReferenceExpression (identifier = a)
USimpleNameReferenceExpression (identifier = a)
""".trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim())
}
fun `test moving lambda from parenthesis`() {
myFixture.configureByText("myFile.kt", """
fun a(p: (Int) -> Unit) {}
""".trimIndent())
val lambdaExpression = uastElementFactory.createLambdaExpression(
emptyList(),
uastElementFactory.createNullLiteral(null),
null
) ?: kfail("Cannot create lambda")
val callExpression = uastElementFactory.createCallExpression(
null,
"a",
listOf(lambdaExpression),
null,
UastCallKind.METHOD_CALL,
myFixture.file
) ?: kfail("Cannot create method call")
TestCase.assertEquals("""a{ null }""", callExpression.sourcePsi?.text)
}
fun `test saving space after receiver`() {
myFixture.configureByText("myFile.kt", """
fun f() {
a
.b()
.c<caret>()
.d()
}
""".trimIndent())
val receiver =
myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtDotQualifiedExpression>().toUElementOfType<UExpression>()
?: kfail("Cannot find UExpression")
val callExpression = uastElementFactory.createCallExpression(
receiver,
"e",
listOf(),
null,
UastCallKind.METHOD_CALL,
null
) ?: kfail("Cannot create call expression")
TestCase.assertEquals(
"""
a
.b()
.c()
.e()
""".trimIndent(),
callExpression.sourcePsi?.parentOfType<KtDotQualifiedExpression>()?.text
)
}
private fun createTypeFromText(s: String, newClass: PsiElement?): PsiType {
return JavaPsiFacade.getElementFactory(myFixture.project).createTypeFromText(s, newClass)
}
}
// it is a copy of org.jetbrains.uast.UastUtils.asRecursiveLogString with `appendLine` instead of `appendln` to avoid windows related issues
private fun UElement.asRecursiveLogString(render: (UElement) -> String = { it.asLogString() }): String {
val stringBuilder = StringBuilder()
val indent = " "
accept(object : UastVisitor {
private var level = 0
override fun visitElement(node: UElement): Boolean {
stringBuilder.append(indent.repeat(level))
stringBuilder.appendLine(render(node))
level++
return false
}
override fun afterVisitElement(node: UElement) {
super.afterVisitElement(node)
level--
}
})
return stringBuilder.toString()
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/weighers/basic/contextualReturn/withReturnType/InWhenSingleExpression.kt | 5 | 151 | fun returnFun(): Int = 10
fun usage(a: Int): Int {
when (a) {
10 -> re<caret>
}
return 10
}
// ORDER: return
// ORDER: returnFun
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/hints/types/DestructingType.kt | 2 | 205 | // MODE: local_variable
fun foo() { val (i<# [: [jar://kotlin-stdlib-sources.jar!/kotlin/Primitives.kt:21054]Int] #>, s<# [: [jar://kotlin-stdlib-sources.jar!/kotlin/String.kt:618]String] #>) = 1 to "" } | apache-2.0 |
psenchanka/comant | comant-site/src/main/kotlin/com/psenchanka/comant/dto/DetailedClassDto.kt | 1 | 774 | package com.psenchanka.comant.dto
import com.psenchanka.comant.model.Class
import java.time.LocalDateTime
open class DetailedClassDto(
id: Int,
startsOn: LocalDateTime,
endsOn: LocalDateTime,
name: String?,
description: String?,
var course: BasicCourseDto,
var links: List<LinkDto>)
: BasicClassDto(id, startsOn, endsOn, name, description) {
companion object {
fun from(class_: Class) = DetailedClassDto(
class_.id!!,
class_.startsOn,
class_.endsOn,
class_.name,
class_.description,
BasicCourseDto.from(class_.course),
class_.links.sortedBy { it.order }.map { LinkDto.from(it) })
}
} | mit |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/KT31762.kt | 5 | 101 | enum class A { AAA }
enum class E(val one: A, val two: A) {
EE(A.<caret>, A.AAA)
}
// EXIST: AAA | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/unusedSymbol/propertyOfInlineClassType.kt | 9 | 106 | // WITH_STDLIB
// PROBLEM: none
inline class Inline(val x1: UInt)
class WrapInline(<caret>val x2: Inline) | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/gradle/newMultiplatformImport/kTIJ11622CommonDependenciesInMppCompositeBuild/includedBuild/p2/src/jvmTest/kotlin/P2JvmTest.kt | 11 | 99 | package org.jetbrains.kotlin
object P2JvmTest {
fun foo() {
P1CommonMain.foo()
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/convertNaNEquality/inequality.kt | 9 | 79 | // WITH_STDLIB
fun main() {
val result = 5.0 + 3.0 <caret>!= Double.NaN;
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/ide-features-trainer/src/training/statistic/FeatureUsageStatisticConsts.kt | 1 | 2228 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.statistic
object FeatureUsageStatisticConsts {
const val LESSON_ID = "lesson_id"
const val LANGUAGE = "language"
const val DURATION = "duration"
const val START = "start"
const val PASSED = "passed"
const val STOPPED = "stopped"
const val START_MODULE_ACTION = "start_module_action"
const val MODULE_NAME = "module_name"
const val PROGRESS = "progress"
const val COMPLETED_COUNT = "completed_count"
const val COURSE_SIZE = "course_size"
const val EXPAND_WELCOME_PANEL = "expand_welcome_screen"
const val SHORTCUT_CLICKED = "shortcut_clicked"
const val RESTORE = "restore"
const val LEARN_PROJECT_OPENED_FIRST_TIME = "learn_project_opened_first_time"
const val NON_LEARNING_PROJECT_OPENED = "non_learning_project_opened"
const val LEARN_PROJECT_OPENING_WAY = "learn_opening_way"
const val ACTION_ID = "action_id"
const val TASK_ID = "task_id"
const val KEYMAP_SCHEME = "keymap_scheme"
const val REASON = "reason"
const val NEW_LESSONS_NOTIFICATION_SHOWN = "new_lessons_notification_shown"
const val SHOW_NEW_LESSONS = "show_new_lessons"
const val NEED_SHOW_NEW_LESSONS_NOTIFICATIONS = "need_show_new_lessons_notifications"
const val NEW_LESSONS_COUNT = "new_lessons_count"
const val LAST_BUILD_LEARNING_OPENED = "last_build_learning_opened"
const val SHOULD_SHOW_NEW_LESSONS = "show_it"
const val TIP_FILENAME = "filename"
const val LESSON_LINK_CLICKED_FROM_TIP = "lesson_link_clicked_from_tip"
const val LESSON_STARTING_WAY = "starting_way"
const val HELP_LINK_CLICKED = "help_link_clicked"
const val ONBOARDING_FEEDBACK_NOTIFICATION_SHOWN = "onboarding_feedback_notification_shown"
const val ONBOARDING_FEEDBACK_DIALOG_RESULT = "onboarding_feedback_dialog_result"
const val FEEDBACK_ENTRY_PLACE = "feedback_entry_place"
const val FEEDBACK_HAS_BEEN_SENT = "feedback_has_been_sent"
const val FEEDBACK_OPENED_VIA_NOTIFICATION = "feedback_opened_via_notification"
const val FEEDBACK_LIKENESS_ANSWER = "feedback_likeness_answer"
const val FEEDBACK_EXPERIENCED_USER = "feedback_experienced_user"
}
| apache-2.0 |
Pattonville-App-Development-Team/Android-App | app/src/main/java/org/pattonvillecs/pattonvilleapp/view/ui/calendar/LiveDataUtils.kt | 1 | 3839 | /*
* Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.pattonvillecs.pattonvilleapp.view.ui.calendar
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MediatorLiveData
import android.arch.lifecycle.Transformations
/**
* This function creates a [LiveData] of a [Pair] of the two types provided. The resulting LiveData is updated whenever either input LiveData updates and both LiveData have updated at least once before.
*
* If the zip of A and B is C, and A and B are updated in this pattern: `AABA`, C would be updated twice (once with the second A value and first B value, and once with the third A value and first B value).
*
* @param a the first LiveData
* @param b the second LiveData
* @since 1.2.0
* @author Mitchell Skaggs
*/
fun <A, B> zipLiveData(a: LiveData<A>, b: LiveData<B>): LiveData<Pair<A, B>> {
return MediatorLiveData<Pair<A, B>>().apply {
var lastA: A? = null
var lastB: B? = null
fun update() {
val localLastA = lastA
val localLastB = lastB
if (localLastA != null && localLastB != null)
this.value = Pair(localLastA, localLastB)
}
addSource(a) {
lastA = it
update()
}
addSource(b) {
lastB = it
update()
}
}
}
/**
* This is merely an extension function for [zipLiveData].
*
* @see zipLiveData
* @since 1.2.0
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.zipTo(b: LiveData<B>): LiveData<Pair<A, B>> = zipLiveData(this, b)
/**
* This is an extension function that calls to [Transformations.map]. If null is received, null is returned instead of calling the provided function.
*
* @see Transformations.map
* @since 1.2.0
* @author Mitchell Skaggs
*/
inline fun <A, B> LiveData<A>.map(crossinline function: (A) -> B): LiveData<B> =
Transformations.map(this) { it: A? ->
if (it == null) null else function(it)
}
/**
* This is an extension function that calls to [Transformations.map]. It exposes the possibilities of receiving and returning null.
*
* @see Transformations.map
* @since 1.2.0
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.mapNullable(function: (A?) -> B?): LiveData<B> =
Transformations.map(this, function)
/**
* This is an extension function that calls to [Transformations.switchMap]. If null is received, null is returned instead of calling the provided function.
*
* @see Transformations.switchMap
* @since 1.2.0
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.switchMap(function: (A) -> LiveData<B>): LiveData<B> =
Transformations.switchMap(this) {
if (it == null) null else function(it)
}
/**
* This is an extension function that calls to [Transformations.switchMap]. It exposes the possibilities of receiving and returning null.
*
* @see Transformations.switchMap
* @since 1.2.0
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.switchMapNullable(function: (A?) -> LiveData<B>?): LiveData<B> =
Transformations.switchMap(this, function)
| gpl-3.0 |
fabmax/kool | kool-physics/src/jsMain/kotlin/physx/Common.kt | 1 | 18496 | /*
* Generated from WebIDL by webidl-util
*/
@file:Suppress("UnsafeCastFromDynamic", "ClassName", "FunctionName", "UNUSED_VARIABLE", "UNUSED_PARAMETER", "unused")
package physx
external interface PxBase {
/**
* Native object address.
*/
val ptr: Int
fun release()
/**
* @return WebIDL type: DOMString (Const)
*/
fun getConcreteTypeName(): String
/**
* @return WebIDL type: long
*/
fun getConcreteType(): Int
/**
* @param flag WebIDL type: [PxBaseFlagEnum] (enum)
* @param value WebIDL type: boolean
*/
fun setBaseFlag(flag: Int, value: Boolean)
/**
* @param inFlags WebIDL type: [PxBaseFlags] (Ref)
*/
fun setBaseFlags(inFlags: PxBaseFlags)
/**
* @return WebIDL type: [PxBaseFlags] (Value)
*/
fun getBaseFlags(): PxBaseFlags
/**
* @return WebIDL type: boolean
*/
fun isReleasable(): Boolean
}
val PxBase.concreteTypeName
get() = getConcreteTypeName()
val PxBase.concreteType
get() = getConcreteType()
var PxBase.baseFlags
get() = getBaseFlags()
set(value) { setBaseFlags(value) }
external interface PxBaseFlags {
/**
* Native object address.
*/
val ptr: Int
/**
* @param flag WebIDL type: [PxBaseFlagEnum] (enum)
* @return WebIDL type: boolean
*/
fun isSet(flag: Int): Boolean
/**
* @param flag WebIDL type: [PxBaseFlagEnum] (enum)
*/
fun set(flag: Int)
/**
* @param flag WebIDL type: [PxBaseFlagEnum] (enum)
*/
fun clear(flag: Int)
}
/**
* @param flags WebIDL type: unsigned short
*/
fun PxBaseFlags(flags: Short): PxBaseFlags {
fun _PxBaseFlags(_module: dynamic, flags: Short) = js("new _module.PxBaseFlags(flags)")
return _PxBaseFlags(PhysXJsLoader.physXJs, flags)
}
fun PxBaseFlags.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxBaseTask
fun PxBaseTask.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxBoundedData {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: unsigned long
*/
var count: Int
/**
* WebIDL type: unsigned long
*/
var stride: Int
/**
* WebIDL type: VoidPtr (Const)
*/
var data: Any
}
fun PxBoundedData(): PxBoundedData {
fun _PxBoundedData(_module: dynamic) = js("new _module.PxBoundedData()")
return _PxBoundedData(PhysXJsLoader.physXJs)
}
fun PxBoundedData.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxBounds3 {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: [PxVec3] (Value)
*/
var minimum: PxVec3
/**
* WebIDL type: [PxVec3] (Value)
*/
var maximum: PxVec3
fun setEmpty()
fun setMaximal()
/**
* @param v WebIDL type: [PxVec3] (Const, Ref)
*/
fun include(v: PxVec3)
/**
* @return WebIDL type: boolean
*/
fun isEmpty(): Boolean
/**
* @param b WebIDL type: [PxBounds3] (Const, Ref)
* @return WebIDL type: boolean
*/
fun intersects(b: PxBounds3): Boolean
/**
* @param b WebIDL type: [PxBounds3] (Const, Ref)
* @param axis WebIDL type: unsigned long
* @return WebIDL type: boolean
*/
fun intersects1D(b: PxBounds3, axis: Int): Boolean
/**
* @param v WebIDL type: [PxVec3] (Const, Ref)
* @return WebIDL type: boolean
*/
fun contains(v: PxVec3): Boolean
/**
* @param box WebIDL type: [PxBounds3] (Const, Ref)
* @return WebIDL type: boolean
*/
fun isInside(box: PxBounds3): Boolean
/**
* @return WebIDL type: [PxVec3] (Value)
*/
fun getCenter(): PxVec3
/**
* @return WebIDL type: [PxVec3] (Value)
*/
fun getDimensions(): PxVec3
/**
* @return WebIDL type: [PxVec3] (Value)
*/
fun getExtents(): PxVec3
/**
* @param scale WebIDL type: float
*/
fun scaleSafe(scale: Float)
/**
* @param scale WebIDL type: float
*/
fun scaleFast(scale: Float)
/**
* @param distance WebIDL type: float
*/
fun fattenSafe(distance: Float)
/**
* @param distance WebIDL type: float
*/
fun fattenFast(distance: Float)
/**
* @return WebIDL type: boolean
*/
fun isFinite(): Boolean
/**
* @return WebIDL type: boolean
*/
fun isValid(): Boolean
}
fun PxBounds3(): PxBounds3 {
fun _PxBounds3(_module: dynamic) = js("new _module.PxBounds3()")
return _PxBounds3(PhysXJsLoader.physXJs)
}
/**
* @param minimum WebIDL type: [PxVec3] (Const, Ref)
* @param maximum WebIDL type: [PxVec3] (Const, Ref)
*/
fun PxBounds3(minimum: PxVec3, maximum: PxVec3): PxBounds3 {
fun _PxBounds3(_module: dynamic, minimum: PxVec3, maximum: PxVec3) = js("new _module.PxBounds3(minimum, maximum)")
return _PxBounds3(PhysXJsLoader.physXJs, minimum, maximum)
}
fun PxBounds3.destroy() {
PhysXJsLoader.destroy(this)
}
val PxBounds3.center
get() = getCenter()
val PxBounds3.dimensions
get() = getDimensions()
val PxBounds3.extents
get() = getExtents()
external interface PxCollection {
/**
* Native object address.
*/
val ptr: Int
/**
* @param obj WebIDL type: [PxBase] (Ref)
*/
fun add(obj: PxBase)
/**
* @param obj WebIDL type: [PxBase] (Ref)
* @param id WebIDL type: unsigned long long
*/
fun add(obj: PxBase, id: Long)
/**
* @param obj WebIDL type: [PxBase] (Ref)
*/
fun remove(obj: PxBase)
/**
* @param obj WebIDL type: [PxBase] (Ref)
* @return WebIDL type: boolean
*/
fun contains(obj: PxBase): Boolean
/**
* @param obj WebIDL type: [PxBase] (Ref)
* @param id WebIDL type: unsigned long long
*/
fun addId(obj: PxBase, id: Long)
/**
* @param id WebIDL type: unsigned long long
*/
fun removeId(id: Long)
/**
* @return WebIDL type: unsigned long
*/
fun getNbObjects(): Int
/**
* @param index WebIDL type: unsigned long
* @return WebIDL type: [PxBase] (Ref)
*/
fun getObject(index: Int): PxBase
/**
* @param id WebIDL type: unsigned long long
* @return WebIDL type: [PxBase]
*/
fun find(id: Long): PxBase
/**
* @return WebIDL type: unsigned long
*/
fun getNbIds(): Int
/**
* @param obj WebIDL type: [PxBase] (Const, Ref)
* @return WebIDL type: unsigned long long
*/
fun getId(obj: PxBase): Long
fun release()
}
val PxCollection.nbObjects
get() = getNbObjects()
val PxCollection.nbIds
get() = getNbIds()
external interface PxCpuDispatcher
fun PxCpuDispatcher.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxCudaContextManager {
/**
* Native object address.
*/
val ptr: Int
/**
* @return WebIDL type: boolean
*/
fun contextIsValid(): Boolean
/**
* @return WebIDL type: boolean
*/
fun supportsArchSM10(): Boolean
/**
* @return WebIDL type: boolean
*/
fun supportsArchSM11(): Boolean
/**
* @return WebIDL type: boolean
*/
fun supportsArchSM12(): Boolean
/**
* @return WebIDL type: boolean
*/
fun supportsArchSM13(): Boolean
/**
* @return WebIDL type: boolean
*/
fun supportsArchSM20(): Boolean
/**
* @return WebIDL type: boolean
*/
fun supportsArchSM30(): Boolean
/**
* @return WebIDL type: boolean
*/
fun supportsArchSM35(): Boolean
/**
* @return WebIDL type: boolean
*/
fun supportsArchSM50(): Boolean
/**
* @return WebIDL type: boolean
*/
fun supportsArchSM52(): Boolean
/**
* @return WebIDL type: boolean
*/
fun isIntegrated(): Boolean
/**
* @return WebIDL type: boolean
*/
fun canMapHostMemory(): Boolean
/**
* @return WebIDL type: long
*/
fun getDriverVersion(): Int
/**
* @return WebIDL type: unsigned long long
*/
fun getDeviceTotalMemBytes(): Long
/**
* @return WebIDL type: long
*/
fun getMultiprocessorCount(): Int
/**
* @return WebIDL type: unsigned long
*/
fun getClockRate(): Int
/**
* @return WebIDL type: long
*/
fun getSharedMemPerBlock(): Int
/**
* @return WebIDL type: long
*/
fun getMaxThreadsPerBlock(): Int
/**
* @return WebIDL type: DOMString (Const)
*/
fun getDeviceName(): String
/**
* @return WebIDL type: [PxCudaInteropModeEnum] (enum)
*/
fun getInteropMode(): Int
/**
* @param flag WebIDL type: boolean
*/
fun setUsingConcurrentStreams(flag: Boolean)
/**
* @return WebIDL type: boolean
*/
fun getUsingConcurrentStreams(): Boolean
/**
* @return WebIDL type: long
*/
fun usingDedicatedGPU(): Int
fun release()
}
val PxCudaContextManager.driverVersion
get() = getDriverVersion()
val PxCudaContextManager.deviceTotalMemBytes
get() = getDeviceTotalMemBytes()
val PxCudaContextManager.multiprocessorCount
get() = getMultiprocessorCount()
val PxCudaContextManager.clockRate
get() = getClockRate()
val PxCudaContextManager.sharedMemPerBlock
get() = getSharedMemPerBlock()
val PxCudaContextManager.maxThreadsPerBlock
get() = getMaxThreadsPerBlock()
val PxCudaContextManager.deviceName
get() = getDeviceName()
val PxCudaContextManager.interopMode
get() = getInteropMode()
var PxCudaContextManager.usingConcurrentStreams
get() = getUsingConcurrentStreams()
set(value) { setUsingConcurrentStreams(value) }
external interface PxCudaContextManagerDesc {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: VoidPtr
*/
var graphicsDevice: Any
/**
* WebIDL type: [PxCudaInteropModeEnum] (enum)
*/
var interopMode: Int
/**
* WebIDL type: unsigned long
*/
var maxMemorySize: Array<Int>
/**
* WebIDL type: unsigned long
*/
var memoryBaseSize: Array<Int>
/**
* WebIDL type: unsigned long
*/
var memoryPageSize: Array<Int>
}
fun PxCudaContextManagerDesc(): PxCudaContextManagerDesc {
fun _PxCudaContextManagerDesc(_module: dynamic) = js("new _module.PxCudaContextManagerDesc()")
return _PxCudaContextManagerDesc(PhysXJsLoader.physXJs)
}
fun PxCudaContextManagerDesc.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxDefaultErrorCallback : PxErrorCallback
fun PxDefaultErrorCallback(): PxDefaultErrorCallback {
fun _PxDefaultErrorCallback(_module: dynamic) = js("new _module.PxDefaultErrorCallback()")
return _PxDefaultErrorCallback(PhysXJsLoader.physXJs)
}
fun PxDefaultErrorCallback.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxErrorCallback {
/**
* Native object address.
*/
val ptr: Int
/**
* @param code WebIDL type: [PxErrorCodeEnum] (enum)
* @param message WebIDL type: DOMString (Const)
* @param file WebIDL type: DOMString (Const)
* @param line WebIDL type: long
*/
fun reportError(code: Int, message: String, file: String, line: Int)
}
fun PxErrorCallback.destroy() {
PhysXJsLoader.destroy(this)
}
external interface JavaErrorCallback : PxErrorCallback {
/**
* param code WebIDL type: [PxErrorCodeEnum] (enum)
* param message WebIDL type: DOMString (Const)
* param file WebIDL type: DOMString (Const)
* param line WebIDL type: long
*/
var reportError: (code: Int, message: String, file: String, line: Int) -> Unit
}
fun JavaErrorCallback(): JavaErrorCallback {
fun _JavaErrorCallback(_module: dynamic) = js("new _module.JavaErrorCallback()")
return _JavaErrorCallback(PhysXJsLoader.physXJs)
}
external interface PxFoundation {
/**
* Native object address.
*/
val ptr: Int
fun release()
}
external interface PxInputData
fun PxInputData.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxOutputStream
fun PxOutputStream.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxPhysicsInsertionCallback
external interface PxQuat {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: float
*/
var x: Float
/**
* WebIDL type: float
*/
var y: Float
/**
* WebIDL type: float
*/
var z: Float
/**
* WebIDL type: float
*/
var w: Float
}
fun PxQuat(): PxQuat {
fun _PxQuat(_module: dynamic) = js("new _module.PxQuat()")
return _PxQuat(PhysXJsLoader.physXJs)
}
/**
* @param r WebIDL type: [PxIDENTITYEnum] (enum)
*/
fun PxQuat(r: Int): PxQuat {
fun _PxQuat(_module: dynamic, r: Int) = js("new _module.PxQuat(r)")
return _PxQuat(PhysXJsLoader.physXJs, r)
}
/**
* @param x WebIDL type: float
* @param y WebIDL type: float
* @param z WebIDL type: float
* @param w WebIDL type: float
*/
fun PxQuat(x: Float, y: Float, z: Float, w: Float): PxQuat {
fun _PxQuat(_module: dynamic, x: Float, y: Float, z: Float, w: Float) = js("new _module.PxQuat(x, y, z, w)")
return _PxQuat(PhysXJsLoader.physXJs, x, y, z, w)
}
fun PxQuat.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxTolerancesScale
fun PxTolerancesScale(): PxTolerancesScale {
fun _PxTolerancesScale(_module: dynamic) = js("new _module.PxTolerancesScale()")
return _PxTolerancesScale(PhysXJsLoader.physXJs)
}
fun PxTolerancesScale.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxTransform {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: [PxQuat] (Value)
*/
var q: PxQuat
/**
* WebIDL type: [PxVec3] (Value)
*/
var p: PxVec3
}
fun PxTransform(): PxTransform {
fun _PxTransform(_module: dynamic) = js("new _module.PxTransform()")
return _PxTransform(PhysXJsLoader.physXJs)
}
/**
* @param r WebIDL type: [PxIDENTITYEnum] (enum)
*/
fun PxTransform(r: Int): PxTransform {
fun _PxTransform(_module: dynamic, r: Int) = js("new _module.PxTransform(r)")
return _PxTransform(PhysXJsLoader.physXJs, r)
}
/**
* @param p0 WebIDL type: [PxVec3] (Const, Ref)
* @param q0 WebIDL type: [PxQuat] (Const, Ref)
*/
fun PxTransform(p0: PxVec3, q0: PxQuat): PxTransform {
fun _PxTransform(_module: dynamic, p0: PxVec3, q0: PxQuat) = js("new _module.PxTransform(p0, q0)")
return _PxTransform(PhysXJsLoader.physXJs, p0, q0)
}
fun PxTransform.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxStridedData {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: unsigned long
*/
var stride: Int
/**
* WebIDL type: VoidPtr (Const)
*/
var data: Any
}
fun PxStridedData.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxU16StridedData {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: unsigned long
*/
var stride: Int
/**
* WebIDL type: [PxU16ConstPtr] (Const, Value)
*/
var data: PxU16ConstPtr
}
fun PxU16StridedData.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxVec3 {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: float
*/
var x: Float
/**
* WebIDL type: float
*/
var y: Float
/**
* WebIDL type: float
*/
var z: Float
}
fun PxVec3(): PxVec3 {
fun _PxVec3(_module: dynamic) = js("new _module.PxVec3()")
return _PxVec3(PhysXJsLoader.physXJs)
}
/**
* @param x WebIDL type: float
* @param y WebIDL type: float
* @param z WebIDL type: float
*/
fun PxVec3(x: Float, y: Float, z: Float): PxVec3 {
fun _PxVec3(_module: dynamic, x: Float, y: Float, z: Float) = js("new _module.PxVec3(x, y, z)")
return _PxVec3(PhysXJsLoader.physXJs, x, y, z)
}
fun PxVec3.destroy() {
PhysXJsLoader.destroy(this)
}
object PxBaseFlagEnum {
val eOWNS_MEMORY: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxBaseFlagEnum_eOWNS_MEMORY()
val eIS_RELEASABLE: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxBaseFlagEnum_eIS_RELEASABLE()
}
object PxCudaBufferMemorySpaceEnum {
val T_GPU: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxCudaBufferMemorySpaceEnum_T_GPU()
val T_PINNED_HOST: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxCudaBufferMemorySpaceEnum_T_PINNED_HOST()
val T_WRITE_COMBINED: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxCudaBufferMemorySpaceEnum_T_WRITE_COMBINED()
val T_HOST: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxCudaBufferMemorySpaceEnum_T_HOST()
}
object PxCudaInteropModeEnum {
val NO_INTEROP: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxCudaInteropModeEnum_NO_INTEROP()
val D3D10_INTEROP: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxCudaInteropModeEnum_D3D10_INTEROP()
val D3D11_INTEROP: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxCudaInteropModeEnum_D3D11_INTEROP()
val OGL_INTEROP: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxCudaInteropModeEnum_OGL_INTEROP()
}
object PxErrorCodeEnum {
val eNO_ERROR: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxErrorCodeEnum_eNO_ERROR()
val eDEBUG_INFO: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxErrorCodeEnum_eDEBUG_INFO()
val eDEBUG_WARNING: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxErrorCodeEnum_eDEBUG_WARNING()
val eINVALID_PARAMETER: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxErrorCodeEnum_eINVALID_PARAMETER()
val eINVALID_OPERATION: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxErrorCodeEnum_eINVALID_OPERATION()
val eOUT_OF_MEMORY: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxErrorCodeEnum_eOUT_OF_MEMORY()
val eINTERNAL_ERROR: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxErrorCodeEnum_eINTERNAL_ERROR()
val eABORT: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxErrorCodeEnum_eABORT()
val ePERF_WARNING: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxErrorCodeEnum_ePERF_WARNING()
val eMASK_ALL: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxErrorCodeEnum_eMASK_ALL()
}
object PxIDENTITYEnum {
val PxIdentity: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxIDENTITYEnum_PxIdentity()
}
| apache-2.0 |
jotomo/AndroidAPS | app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExistsTest.kt | 1 | 702 | package info.nightscout.androidaps.plugins.general.automation.elements
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerTestBase
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class ComparatorExistsTest : TriggerTestBase() {
@Test fun labelsTest() {
Assert.assertEquals(2, ComparatorExists.Compare.labels(resourceHelper).size)
}
@Test fun setValueTest() {
val c = ComparatorExists(injector)
c.value = ComparatorExists.Compare.NOT_EXISTS
Assert.assertEquals(ComparatorExists.Compare.NOT_EXISTS, c.value)
}
} | agpl-3.0 |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/Colors.kt | 1 | 5685 | package de.fabmax.kool.modules.ui2
import de.fabmax.kool.math.clamp
import de.fabmax.kool.util.Color
import kotlin.math.roundToInt
/**
* UI colors. Somewhat based on the Material Design color system:
* https://material.io/design/color/the-color-system.html#color-theme-creation
* However, primary and secondary color are replaced by a single accent color.
*
* - [primary]: Accent color used by UI elements.
* - [primaryVariant]: A little less prominent than the primary accent color.
* - [secondary]: Secondary accent color used by UI elements.
* - [secondaryVariant]: A little less prominent than the secondary accent color.
* - [background]: Used on surfaces of components, such as menus.
* - [backgroundVariant]: Appears behind scrollable content.
* - [onPrimary]: Used for icons and text displayed on top of the primary accent color.
* - [onSecondary]: Used for icons and text displayed on top of the secondary accent color.
* - [onBackground]: Used for icons and text displayed on top of the background color.
* - [isLight]: Whether this color is considered as a 'light' or 'dark' set of colors.
*/
data class Colors(
val primary: Color,
val primaryVariant: Color,
val secondary: Color,
val secondaryVariant: Color,
val background: Color,
val backgroundVariant: Color,
val onPrimary: Color,
val onSecondary: Color,
val onBackground: Color,
val isLight: Boolean
) {
private val primaryAlpha = AlphaColorCache(primary)
private val primaryVariantAlpha = AlphaColorCache(primaryVariant)
private val secondaryAlpha = AlphaColorCache(secondary)
private val secondaryVariantAlpha = AlphaColorCache(secondaryVariant)
private val backgroundAlpha = AlphaColorCache(background)
private val backgroundVariantAlpha = AlphaColorCache(backgroundVariant)
private val onPrimaryAlpha = AlphaColorCache(onPrimary)
private val onSecondaryAlpha = AlphaColorCache(onSecondary)
private val onBackgroundAlpha = AlphaColorCache(onBackground)
fun primaryAlpha(alpha: Float) = primaryAlpha.getAlphaColor(alpha)
fun primaryVariantAlpha(alpha: Float) = primaryVariantAlpha.getAlphaColor(alpha)
fun secondaryAlpha(alpha: Float) = secondaryAlpha.getAlphaColor(alpha)
fun secondaryVariantAlpha(alpha: Float) = secondaryVariantAlpha.getAlphaColor(alpha)
fun backgroundAlpha(alpha: Float) = backgroundAlpha.getAlphaColor(alpha)
fun backgroundVariantAlpha(alpha: Float) = backgroundVariantAlpha.getAlphaColor(alpha)
fun onPrimaryAlpha(alpha: Float) = onPrimaryAlpha.getAlphaColor(alpha)
fun onSecondaryAlpha(alpha: Float) = onSecondaryAlpha.getAlphaColor(alpha)
fun onBackgroundAlpha(alpha: Float) = onBackgroundAlpha.getAlphaColor(alpha)
companion object {
fun singleColorLight(
accent: Color,
background: Color = Color("f3f3f3ff"),
onAccent: Color = Color.WHITE,
onBackground: Color = Color("343434ff"),
): Colors = Colors(
primary = accent,
primaryVariant = accent.mix(Color.BLACK, 0.3f),
secondary = accent.mix(Color.BLACK, 0.3f),
secondaryVariant = accent.mix(Color.BLACK, 0.5f),
background = background,
backgroundVariant = background.mix(Color.BLACK, 0.05f).mix(accent, 0.1f),
onPrimary = onAccent,
onSecondary = onAccent,
onBackground = onBackground,
isLight = true
)
fun singleColorDark(
accent: Color,
background: Color = Color("1a1a1aff"),
onAccent: Color = Color.WHITE,
onBackground: Color = Color("f2f2f2ff"),
): Colors = Colors(
primary = accent,
primaryVariant = accent.mix(Color.BLACK, 0.3f),
secondary = accent.mix(Color.BLACK, 0.3f),
secondaryVariant = accent.mix(Color.BLACK, 0.5f),
background = background,
backgroundVariant = background.mix(accent, 0.05f),
onPrimary = onAccent,
onSecondary = onAccent,
onBackground = onBackground,
isLight = false
)
fun darkColors(
primary: Color = Color("ffb703ff"),
primaryVariant: Color = Color("fb8500f0"),
secondary: Color = Color("8ecae6ff"),
secondaryVariant: Color = Color("219ebcff"),
background: Color = Color("023047ff"),
backgroundVariant: Color = Color("143d52ff"),
onPrimary: Color = Color.WHITE,
onSecondary: Color = Color.BLACK,
onBackground: Color = Color("dcf7ffff"),
isLight: Boolean = false
): Colors = Colors(
primary,
primaryVariant,
secondary,
secondaryVariant,
background,
backgroundVariant,
onPrimary,
onSecondary,
onBackground,
isLight
)
val neon = darkColors(
primary = Color("b2ff00"),
primaryVariant = Color("7cb200"),
secondary = Color("b2ff00").withAlpha(0.6f),
secondaryVariant = Color("7cb200").withAlpha(0.6f),
background = Color("101010d0"),
backgroundVariant = Color("202020d0"),
onPrimary = Color.BLACK
)
}
private class AlphaColorCache(baseColor: Color) {
val alphaColors = Array<Color>(20) { baseColor.withAlpha(it / 20f) }
fun getAlphaColor(alpha: Float): Color {
val alphaI = (alpha * 20f).roundToInt().clamp(0, alphaColors.lastIndex)
return alphaColors[alphaI]
}
}
}
| apache-2.0 |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/viewholders/EmptyCommentsViewHolder.kt | 1 | 1815 | package com.kickstarter.ui.viewholders
import android.util.Pair
import android.view.View
import androidx.annotation.StringRes
import com.kickstarter.R
import com.kickstarter.databinding.EmptyCommentsLayoutBinding
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.models.Project
import com.kickstarter.models.User
class EmptyCommentsViewHolder(private val binding: EmptyCommentsLayoutBinding, private val delegate: Delegate) : KSViewHolder(binding.root) {
private var project: Project? = null
private var user: User? = null
interface Delegate {
fun emptyCommentsLoginClicked(viewHolder: EmptyCommentsViewHolder?)
}
@Throws(Exception::class)
override fun bindData(data: Any?) {
val projectAndUser = ObjectUtils.requireNonNull(data as? Pair<Project, User>?)
project = ObjectUtils.requireNonNull(projectAndUser.first, Project::class.java)
user = projectAndUser.second
}
override fun onBind() {
when {
user == null -> {
bindView(View.VISIBLE, R.string.project_comments_empty_state_logged_out_message_log_in)
}
project?.isBacking() == true -> {
bindView(View.GONE, R.string.project_comments_empty_state_backer_message)
}
else -> {
bindView(View.GONE, R.string.update_comments_empty_state_non_backer_message)
}
}
binding.commentsLoginButton.setOnClickListener {
emptyCommentsLogin()
}
}
private fun bindView(hasVisibility: Int, @StringRes string: Int) {
binding.commentsLoginButton.visibility = hasVisibility
binding.noCommentsMessage.setText(string)
}
fun emptyCommentsLogin() {
delegate.emptyCommentsLoginClicked(this)
}
}
| apache-2.0 |
NikAshanin/Design-Patterns-In-Swift-Compare-Kotlin | Structural/Composite/Composite.kt | 1 | 642 | // Implementation
interface Shape {
fun draw(fillColor: String)
}
class Square: Shape {
override fun draw(fillColor: String) {
println("Drawing a Square with color" + fillColor)
}
}
class Circle: Shape {
override fun draw(fillColor: String) {
println("Drawing a Circle with color" + fillColor)
}
}
class WhiteBoard(var shapes: ArrayList<Shape>): Shape {
override fun draw(fillColor: String) {
for (shape in shapes) {
shape.draw(fillColor)
}
}
}
// Usage
val shapes = arrayListOf<Shape>(Circle(), Square())
var whiteboard = WhiteBoard(shapes)
whiteboard.draw("Red") | mit |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ide/impl/TrustedHosts.kt | 2 | 3922 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.impl
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.io.URLUtil
import com.intellij.util.io.URLUtil.SCHEME_SEPARATOR
import com.intellij.util.io.isAncestor
import com.intellij.util.xmlb.annotations.OptionTag
import org.jetbrains.annotations.VisibleForTesting
import java.net.URI
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
@NlsSafe
fun getProjectOriginUrl(projectDir: Path?): String? {
if (projectDir == null) return null
val epName = ExtensionPointName.create<ProjectOriginInfoProvider>("com.intellij.projectOriginInfoProvider")
for (extension in epName.extensions) {
val url = extension.getOriginUrl(projectDir)
if (url != null) {
return url
}
}
return null
}
private val KNOWN_HOSTINGS = listOf(
"git.jetbrains.space",
"github.com",
"bitbucket.org",
"gitlab.com")
@VisibleForTesting
data class Origin(val protocol: String?, val host: String)
@VisibleForTesting
fun getOriginFromUrl(url: String): Origin? {
try {
val urlWithScheme = if (URLUtil.containsScheme(url)) url else "ssh://$url"
val uri = URI(urlWithScheme)
var host = uri.host
if (host == null) {
if (uri.scheme == "ssh") {
if (uri.authority != null) {
// [email protected]:JetBrains
val at = uri.authority.split("@")
val hostAndOrg = if (at.size > 1) at[1] else at[0]
val comma = hostAndOrg.split(":")
host = comma[0]
if (comma.size > 1) {
val org = comma[1]
return Origin(uri.scheme, "$host/$org")
}
}
}
}
if (host == null) return null
if (KNOWN_HOSTINGS.contains(host)) {
val path = uri.path
val secondSlash = path.indexOf("/", 1) // path always starts with '/'
val organization = if (secondSlash >= 0) path.substring(0, secondSlash) else path
return Origin(uri.scheme, uri.host + organization)
}
return Origin(uri.scheme, uri.host)
}
catch (e: Exception) {
LOG.warn("Couldn't parse URL $url", e)
}
return null
}
@State(name = "Trusted.Hosts.Settings", storages = [Storage("trusted-hosts.xml")])
@Service(Service.Level.APP)
class TrustedHostsSettings : SimplePersistentStateComponent<TrustedHostsSettings.State>(State()) {
class State : BaseState() {
@get:OptionTag("TRUSTED_HOSTS")
var trustedHosts by list<String>()
}
fun isUrlTrusted(url: String): Boolean {
return false
}
fun setHostTrusted(host: String, value: Boolean) {
if (value) {
state.trustedHosts.add(host)
}
else {
state.trustedHosts.remove(host)
}
}
fun getTrustedHosts(): List<String> = Collections.unmodifiableList(state.trustedHosts)
fun setTrustedHosts(hosts: List<String>) {
state.trustedHosts = ArrayList<String>(hosts)
}
}
@State(name = "Trusted.Paths.Settings", storages = [Storage("trusted-paths.xml")])
@Service(Service.Level.APP)
internal class TrustedPathsSettings : SimplePersistentStateComponent<TrustedPathsSettings.State>(State()) {
class State : BaseState() {
@get:OptionTag("TRUSTED_PATHS")
var trustedPaths by list<String>()
}
fun isPathTrusted(path: Path): Boolean {
return state.trustedPaths.map { Paths.get(it) }.any { it.isAncestor(path) }
}
fun getTrustedPaths(): List<String> = Collections.unmodifiableList(state.trustedPaths)
fun setTrustedPaths(paths: List<String>) {
state.trustedPaths = ArrayList<String>(paths)
}
fun addTrustedPath(path: String) {
state.trustedPaths.add(path)
}
}
private val LOG = Logger.getInstance("com.intellij.ide.impl.TrustedHosts")
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/ScriptDefinitionsManager.kt | 1 | 22846 | // 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.core.script
import com.intellij.diagnostic.PluginException
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.scratch.ScratchFileService
import com.intellij.ide.scratch.ScratchRootType
import com.intellij.ide.script.IdeConsoleRootType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.extensions.ProjectExtensionPointName
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.ex.PathUtilEx
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.util.containers.SLRUMap
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.caches.project.SdkInfo
import org.jetbrains.kotlin.idea.caches.project.getScriptRelatedModuleInfo
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings
import org.jetbrains.kotlin.idea.core.util.CheckCanceledLock
import org.jetbrains.kotlin.idea.core.util.writeWithCheckCanceled
import org.jetbrains.kotlin.idea.util.application.getServiceSafe
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.getProjectJdkTableSafe
import org.jetbrains.kotlin.script.ScriptTemplatesProvider
import org.jetbrains.kotlin.scripting.definitions.*
import org.jetbrains.kotlin.scripting.resolve.VirtualFileScriptSource
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import java.io.File
import java.net.URLClassLoader
import java.nio.file.Path
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.script.dependencies.Environment
import kotlin.script.dependencies.ScriptContents
import kotlin.script.experimental.api.SourceCode
import kotlin.script.experimental.dependencies.DependenciesResolver
import kotlin.script.experimental.dependencies.ScriptDependencies
import kotlin.script.experimental.dependencies.asSuccess
import kotlin.script.experimental.host.ScriptingHostConfiguration
import kotlin.script.experimental.host.configurationDependencies
import kotlin.script.experimental.host.toScriptSource
import kotlin.script.experimental.jvm.JvmDependency
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
import kotlin.script.experimental.jvm.util.ClasspathExtractionException
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContextOrStdlib
import kotlin.script.templates.standard.ScriptTemplateWithArgs
class LoadScriptDefinitionsStartupActivity : StartupActivity.Background {
override fun runActivity(project: Project) {
if (isUnitTestMode()) {
// In tests definitions are loaded synchronously because they are needed to analyze script
// In IDE script won't be highlighted before all definitions are loaded, then the highlighting will be restarted
ScriptDefinitionsManager.getInstance(project).reloadScriptDefinitionsIfNeeded()
} else {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(KotlinPluginDisposable.getInstance(project)) {
ScriptDefinitionsManager.getInstance(project).reloadScriptDefinitionsIfNeeded()
ScriptConfigurationManager.getInstance(project).loadPlugins()
}
}
}
}
class ScriptDefinitionsManager(private val project: Project) : LazyScriptDefinitionProvider(), Disposable {
private val definitionsLock = ReentrantReadWriteLock()
private val definitionsBySource = mutableMapOf<ScriptDefinitionsSource, List<ScriptDefinition>>()
@Volatile
private var definitions: List<ScriptDefinition>? = null
private val sourcesToReload = mutableSetOf<ScriptDefinitionsSource>()
private val failedContributorsHashes = HashSet<Int>()
private val scriptDefinitionsCacheLock = CheckCanceledLock()
private val scriptDefinitionsCache = SLRUMap<String, ScriptDefinition>(10, 10)
// cache service as it's getter is on the hot path
// it is safe, since both services are in same plugin
@Volatile
private var configurations: CompositeScriptConfigurationManager? =
ScriptConfigurationManager.compositeScriptConfigurationManager(project)
override fun findDefinition(script: SourceCode): ScriptDefinition? {
val locationId = script.locationId ?: return null
if (nonScriptId(locationId)) return null
configurations?.tryGetScriptDefinitionFast(locationId)?.let { fastPath -> return fastPath }
if (!isReady()) return null
scriptDefinitionsCacheLock.withLock { scriptDefinitionsCache.get(locationId) }?.let { cached -> return cached }
val definition =
if (isScratchFile(script)) {
// Scratch should always have default script definition
getDefaultDefinition()
} else {
super.findDefinition(script) ?: return null
}
scriptDefinitionsCacheLock.withLock {
scriptDefinitionsCache.put(locationId, definition)
}
return definition
}
private fun isScratchFile(script: SourceCode): Boolean {
val virtualFile =
if (script is VirtualFileScriptSource) script.virtualFile
else script.locationId?.let { VirtualFileManager.getInstance().findFileByUrl(it) }
return virtualFile != null && ScratchFileService.getInstance().getRootType(virtualFile) is ScratchRootType
}
override fun findScriptDefinition(fileName: String): KotlinScriptDefinition? =
findDefinition(File(fileName).toScriptSource())?.legacyDefinition
fun reloadDefinitionsBy(source: ScriptDefinitionsSource) {
definitionsLock.writeWithCheckCanceled {
if (definitions == null) {
sourcesToReload.add(source)
return // not loaded yet
}
if (source !in definitionsBySource) error("Unknown script definition source: $source")
}
val safeGetDefinitions = source.safeGetDefinitions()
val updateDefinitionsResult = definitionsLock.writeWithCheckCanceled {
definitionsBySource[source] = safeGetDefinitions
definitions = definitionsBySource.values.flattenTo(mutableListOf())
updateDefinitions()
}
updateDefinitionsResult?.apply()
}
override val currentDefinitions: Sequence<ScriptDefinition>
get() {
val scriptingSettings = kotlinScriptingSettingsSafe() ?: return emptySequence()
return (definitions ?: run {
reloadScriptDefinitions()
definitions!!
}).asSequence().filter { scriptingSettings.isScriptDefinitionEnabled(it) }
}
private fun getSources(): List<ScriptDefinitionsSource> {
@Suppress("DEPRECATION")
val fromDeprecatedEP = Extensions.getArea(project).getExtensionPoint(ScriptTemplatesProvider.EP_NAME).extensions.toList()
.map { ScriptTemplatesProviderAdapter(it).asSource() }
val fromNewEp = ScriptDefinitionContributor.EP_NAME.getPoint(project).extensions.toList()
.map { it.asSource() }
return fromNewEp.dropLast(1) + fromDeprecatedEP + fromNewEp.last()
}
fun reloadScriptDefinitionsIfNeeded() {
definitions ?: loadScriptDefinitions()
}
fun reloadScriptDefinitions() = loadScriptDefinitions()
private fun loadScriptDefinitions() {
if (project.isDisposed) return
val newDefinitionsBySource = getSources().associateWith { it.safeGetDefinitions() }
val updateDefinitionsResult = definitionsLock.writeWithCheckCanceled {
definitionsBySource.putAll(newDefinitionsBySource)
definitions = definitionsBySource.values.flattenTo(mutableListOf())
updateDefinitions()
}
updateDefinitionsResult?.apply()
definitionsLock.writeWithCheckCanceled {
sourcesToReload.takeIf { it.isNotEmpty() }?.let {
val copy = ArrayList<ScriptDefinitionsSource>(it)
it.clear()
copy
}
}?.forEach(::reloadDefinitionsBy)
}
fun reorderScriptDefinitions() {
val scriptingSettings = kotlinScriptingSettingsSafe() ?: return
val updateDefinitionsResult = definitionsLock.writeWithCheckCanceled {
definitions?.let { list ->
list.forEach {
it.order = scriptingSettings.getScriptDefinitionOrder(it)
}
definitions = list.sortedBy(ScriptDefinition::order)
updateDefinitions()
}
}
updateDefinitionsResult?.apply()
}
private fun kotlinScriptingSettingsSafe() = runReadAction {
if (!project.isDisposed) KotlinScriptingSettings.getInstance(project) else null
}
fun getAllDefinitions(): List<ScriptDefinition> = definitions ?: run {
reloadScriptDefinitions()
definitions!!
}
fun isReady(): Boolean {
if (definitions == null) return false
val keys = definitionsLock.writeWithCheckCanceled { definitionsBySource.keys }
return keys.all { source ->
// TODO: implement another API for readiness checking
(source as? ScriptDefinitionContributor)?.isReady() != false
}
}
override fun getDefaultDefinition(): ScriptDefinition {
val standardScriptDefinitionContributor = ScriptDefinitionContributor.find<StandardScriptDefinitionContributor>(project)
?: error("StandardScriptDefinitionContributor should be registered in plugin.xml")
return ScriptDefinition.FromLegacy(getScriptingHostConfiguration(), standardScriptDefinitionContributor.getDefinitions().last())
}
private fun updateDefinitions(): UpdateDefinitionsResult? {
assert(definitionsLock.isWriteLocked) { "updateDefinitions should only be called under the write lock" }
if (project.isDisposed) return null
val fileTypeManager = FileTypeManager.getInstance()
val newExtensions = getKnownFilenameExtensions().toSet().filter {
val fileTypeByExtension = fileTypeManager.getFileTypeByFileName("xxx.$it")
val notKnown = fileTypeByExtension != KotlinFileType.INSTANCE
if (notKnown) {
scriptingWarnLog("extension $it file type [${fileTypeByExtension.name}] is not registered as ${KotlinFileType.INSTANCE.name}")
}
notKnown
}.toSet()
clearCache()
scriptDefinitionsCacheLock.withLock { scriptDefinitionsCache.clear() }
return UpdateDefinitionsResult(project, newExtensions)
}
private data class UpdateDefinitionsResult(val project: Project, val newExtensions: Set<String>) {
fun apply() {
if (newExtensions.isNotEmpty()) {
scriptingWarnLog("extensions ${newExtensions} is about to be registered as ${KotlinFileType.INSTANCE.name}")
// Register new file extensions
ApplicationManager.getApplication().invokeLater {
val fileTypeManager = FileTypeManager.getInstance()
runWriteAction {
newExtensions.forEach {
fileTypeManager.associateExtension(KotlinFileType.INSTANCE, it)
}
}
}
}
// TODO: clear by script type/definition
ScriptConfigurationManager.getInstance(project).updateScriptDefinitionReferences()
}
}
private fun ScriptDefinitionsSource.safeGetDefinitions(): List<ScriptDefinition> {
if (!failedContributorsHashes.contains([email protected]())) try {
return definitions.toList()
} catch (t: Throwable) {
if (t is ControlFlowException) throw t
// reporting failed loading only once
failedContributorsHashes.add([email protected]())
// Assuming that direct ClasspathExtractionException is the result of versions mismatch and missing subsystems, e.g. kotlin plugin
// so, it only results in warning, while other errors are severe misconfigurations, resulting it user-visible error
if (t.cause is ClasspathExtractionException || t is ClasspathExtractionException) {
scriptingWarnLog("Cannot load script definitions from $this: ${t.cause?.message ?: t.message}")
} else {
scriptingErrorLog("[kts] cannot load script definitions using $this", t)
}
}
return emptyList()
}
override fun dispose() {
super.dispose()
clearCache()
definitionsBySource.clear()
definitions = null
failedContributorsHashes.clear()
scriptDefinitionsCache.clear()
configurations = null
}
companion object {
fun getInstance(project: Project): ScriptDefinitionsManager =
project.getServiceSafe<ScriptDefinitionProvider>() as ScriptDefinitionsManager
}
}
fun loadDefinitionsFromTemplates(
templateClassNames: List<String>,
templateClasspath: List<File>,
baseHostConfiguration: ScriptingHostConfiguration,
// TODO: need to provide a way to specify this in compiler/repl .. etc
/*
* Allows to specify additional jars needed for DependenciesResolver (and not script template).
* Script template dependencies naturally become (part of) dependencies of the script which is not always desired for resolver dependencies.
* i.e. gradle resolver may depend on some jars that 'built.gradle.kts' files should not depend on.
*/
additionalResolverClasspath: List<File> = emptyList(),
defaultCompilerOptions: Iterable<String> = emptyList()
): List<ScriptDefinition> = loadDefinitionsFromTemplatesByPaths(
templateClassNames,
templateClasspath.map(File::toPath),
baseHostConfiguration,
additionalResolverClasspath.map(File::toPath),
defaultCompilerOptions
)
// TODO: consider rewriting to return sequence
fun loadDefinitionsFromTemplatesByPaths(
templateClassNames: List<String>,
templateClasspath: List<Path>,
baseHostConfiguration: ScriptingHostConfiguration,
// TODO: need to provide a way to specify this in compiler/repl .. etc
/*
* Allows to specify additional jars needed for DependenciesResolver (and not script template).
* Script template dependencies naturally become (part of) dependencies of the script which is not always desired for resolver dependencies.
* i.e. gradle resolver may depend on some jars that 'built.gradle.kts' files should not depend on.
*/
additionalResolverClasspath: List<Path> = emptyList(),
defaultCompilerOptions: Iterable<String> = emptyList()
): List<ScriptDefinition> {
val classpath = templateClasspath + additionalResolverClasspath
scriptingInfoLog("Loading script definitions $templateClassNames using classpath: ${classpath.joinToString(File.pathSeparator)}")
val baseLoader = ScriptDefinitionContributor::class.java.classLoader
val loader = if (classpath.isEmpty())
baseLoader
else
URLClassLoader(classpath.map { it.toUri().toURL() }.toTypedArray(), baseLoader)
return templateClassNames.mapNotNull { templateClassName ->
try {
// TODO: drop class loading here - it should be handled downstream
// as a compatibility measure, the asm based reading of annotations should be implemented to filter classes before classloading
val template = loader.loadClass(templateClassName).kotlin
val templateClasspathAsFiles = templateClasspath.map(Path::toFile)
val hostConfiguration = ScriptingHostConfiguration(baseHostConfiguration) {
configurationDependencies(JvmDependency(templateClasspathAsFiles))
}
when {
template.annotations.firstIsInstanceOrNull<kotlin.script.templates.ScriptTemplateDefinition>() != null -> {
ScriptDefinition.FromLegacyTemplate(hostConfiguration, template, templateClasspathAsFiles, defaultCompilerOptions)
}
template.annotations.firstIsInstanceOrNull<kotlin.script.experimental.annotations.KotlinScript>() != null -> {
ScriptDefinition.FromTemplate(hostConfiguration, template, ScriptDefinition::class, defaultCompilerOptions)
}
else -> {
scriptingWarnLog("Cannot find a valid script definition annotation on the class $template")
null
}
}
} catch (e: ClassNotFoundException) {
// Assuming that direct ClassNotFoundException is the result of versions mismatch and missing subsystems, e.g. gradle
// so, it only results in warning, while other errors are severe misconfigurations, resulting it user-visible error
scriptingWarnLog("Cannot load script definition class $templateClassName")
null
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
val message = "Cannot load script definition class $templateClassName"
PluginManagerCore.getPluginByClassName(templateClassName)?.let {
scriptingErrorLog(message, PluginException(message, e, it))
} ?: scriptingErrorLog(message, e)
null
}
}
}
@Deprecated("migrating to new configuration refinement: use ScriptDefinitionsSource internally and kotlin.script.experimental.intellij.ScriptDefinitionsProvider as a providing extension point")
interface ScriptDefinitionContributor {
@Deprecated("migrating to new configuration refinement: drop usages")
val id: String
@Deprecated("migrating to new configuration refinement: use ScriptDefinitionsSource instead")
fun getDefinitions(): List<KotlinScriptDefinition>
@JvmDefault
@Deprecated("migrating to new configuration refinement: drop usages")
fun isReady() = true
companion object {
val EP_NAME: ProjectExtensionPointName<ScriptDefinitionContributor> =
ProjectExtensionPointName("org.jetbrains.kotlin.scriptDefinitionContributor")
inline fun <reified T> find(project: Project) =
EP_NAME.getPoint(project).extensionList.filterIsInstance<T>().firstOrNull()
}
}
@Deprecated("migrating to new configuration refinement: use ScriptDefinitionsSource directly instead")
interface ScriptDefinitionSourceAsContributor : ScriptDefinitionContributor, ScriptDefinitionsSource {
override fun getDefinitions(): List<KotlinScriptDefinition> = definitions.map { it.legacyDefinition }.toList()
}
@Deprecated("migrating to new configuration refinement: convert all contributors to ScriptDefinitionsSource/ScriptDefinitionsProvider")
class ScriptDefinitionSourceFromContributor(
val contributor: ScriptDefinitionContributor,
val hostConfiguration: ScriptingHostConfiguration = defaultJvmScriptingHostConfiguration
) : ScriptDefinitionsSource {
override val definitions: Sequence<ScriptDefinition>
get() =
if (contributor is ScriptDefinitionsSource) contributor.definitions
else contributor.getDefinitions().asSequence().map { ScriptDefinition.FromLegacy(hostConfiguration, it) }
override fun equals(other: Any?): Boolean {
return contributor.id == (other as? ScriptDefinitionSourceFromContributor)?.contributor?.id
}
override fun hashCode(): Int {
return contributor.id.hashCode()
}
}
fun ScriptDefinitionContributor.asSource(): ScriptDefinitionsSource =
if (this is ScriptDefinitionsSource) this
else ScriptDefinitionSourceFromContributor(this)
class StandardScriptDefinitionContributor(val project: Project) : ScriptDefinitionContributor {
private val standardIdeScriptDefinition = StandardIdeScriptDefinition(project)
override fun getDefinitions() = listOf(standardIdeScriptDefinition)
override val id: String = "StandardKotlinScript"
}
class StandardIdeScriptDefinition internal constructor(project: Project) : KotlinScriptDefinition(ScriptTemplateWithArgs::class) {
override val dependencyResolver = BundledKotlinScriptDependenciesResolver(project)
}
class BundledKotlinScriptDependenciesResolver(private val project: Project) : DependenciesResolver {
override fun resolve(
scriptContents: ScriptContents,
environment: Environment
): DependenciesResolver.ResolveResult {
val virtualFile = scriptContents.file?.let { VfsUtil.findFileByIoFile(it, true) }
val javaHome = getScriptSDK(project, virtualFile)
var classpath = with(KotlinArtifacts.instance) {
listOf(kotlinReflect, kotlinStdlib, kotlinScriptRuntime)
}
if (ScratchFileService.getInstance().getRootType(virtualFile) is IdeConsoleRootType) {
classpath = scriptCompilationClasspathFromContextOrStdlib(wholeClasspath = true) + classpath
}
return ScriptDependencies(javaHome = javaHome?.let(::File), classpath = classpath).asSuccess()
}
private fun getScriptSDK(project: Project, virtualFile: VirtualFile?): String? {
if (virtualFile != null) {
val dependentModuleSourceInfo = getScriptRelatedModuleInfo(project, virtualFile)
val sdk = dependentModuleSourceInfo?.dependencies()?.filterIsInstance<SdkInfo>()?.singleOrNull()?.sdk
if (sdk != null) {
return sdk.homePath
}
}
val jdk = ProjectRootManager.getInstance(project).projectSdk
?: getProjectJdkTableSafe().allJdks.firstOrNull { sdk -> sdk.sdkType is JavaSdk }
?: PathUtilEx.getAnyJdk(project)
return jdk?.homePath
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/LoggingErrorReporter.kt | 2 | 858 | // 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.decompiler.textBuilder
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.serialization.deserialization.ErrorReporter
class LoggingErrorReporter(private val log: Logger) : ErrorReporter {
override fun reportIncompleteHierarchy(descriptor: ClassDescriptor, unresolvedSuperClasses: List<String>) {
// This is absolutely fine for the decompiler
}
override fun reportCannotInferVisibility(descriptor: CallableMemberDescriptor) {
log.error("Could not infer visibility for $descriptor")
}
}
| apache-2.0 |
Passw/Kotlin | forLoop.kt | 1 | 133 |
fun main(args: Array<String>) {
for (arg in args)
println(arg)
for (i in args.indices)
println(args[i])
}
| gpl-3.0 |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/gradle/testing/js/KotlinMultiplatformJsTestMethodGradleConfigurationProducer.kt | 1 | 989 | // 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.gradle.testing.js
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.openapi.module.Module
import org.jetbrains.kotlin.idea.js.KotlinJSRunConfigurationDataProvider
import org.jetbrains.kotlin.idea.run.AbstractKotlinMultiplatformTestMethodGradleConfigurationProducer
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.js.isJs
class KotlinMultiplatformJsTestMethodGradleConfigurationProducer
: AbstractKotlinMultiplatformTestMethodGradleConfigurationProducer(), KotlinJSRunConfigurationDataProvider<Unit>
{
override val isForTests: Boolean get() = true
override fun isApplicable(module: Module, platform: TargetPlatform) = platform.isJs()
override fun getConfigurationData(context: ConfigurationContext) = Unit
} | apache-2.0 |
jwren/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/toolbar/MainMenuButton.kt | 1 | 2927 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.customFrameDecorations.header.toolbar
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.ui.IconManager
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus
import java.awt.Dimension
import javax.swing.JComponent
@ApiStatus.Internal
internal class MainMenuButton {
private val menuAction = ShowMenuAction()
val button: ActionButton = createMenuButton(menuAction)
val menuShortcutHandler = MainMenuMnemonicHandler(menuAction)
private inner class ShowMenuAction : DumbAwareAction() {
private val icon = IconManager.getInstance().getIcon("expui/general/[email protected]", AllIcons::class.java)
override fun update(e: AnActionEvent) {
e.presentation.icon = icon
e.presentation.text = IdeBundle.message("main.toolbar.menu.button")
}
override fun actionPerformed(e: AnActionEvent) = createPopup(e.dataContext).showUnderneathOf(button)
private fun createPopup(context: DataContext): JBPopup {
val mainMenu = ActionManager.getInstance().getAction(IdeActions.GROUP_MAIN_MENU) as ActionGroup
return JBPopupFactory.getInstance()
.createActionGroupPopup(null, mainMenu, context, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true,
ActionPlaces.MAIN_MENU_IN_POPUP)
.apply { setShowSubmenuOnHover(true) }
.apply { setMinimumSize(Dimension(JBUI.CurrentTheme.CustomFrameDecorations.menuPopupMinWidth(), 0)) }
}
}
companion object {
private fun createMenuButton(action: AnAction): ActionButton {
return ActionButton(action, PresentationFactory().getPresentation(action),
ActionPlaces.MAIN_MENU_IN_POPUP, Dimension(40, 40))
.apply { setLook(HeaderToolbarButtonLook()) }
}
}
}
class MainMenuMnemonicHandler(val action: AnAction) : Disposable {
private var disposable: Disposable? = null
fun registerShortcuts(component: JComponent) {
if (disposable == null) disposable = Disposer.newDisposable()
val shortcutSet = ActionUtil.getShortcutSet("MainMenuButton.ShowMenu")
action.registerCustomShortcutSet(shortcutSet, component, disposable)
}
fun unregisterShortcuts() {
disposable?.let { Disposer.dispose(it) }
}
override fun dispose() = unregisterShortcuts()
}
| apache-2.0 |
vovagrechka/fucking-everything | attic/photlin/src/photlinc/photlin.kt | 1 | 110 | package photlinc
object PhotlinGlobal {
val serverPort = 11211
val tempDir = "c:/tmp/photlin-tmp"
}
| apache-2.0 |
jwren/intellij-community | platform/feedback/src/com/intellij/feedback/common/IdleFeedbackTypes.kt | 1 | 4414 | // 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.feedback.common
import com.intellij.feedback.common.IdleFeedbackTypeResolver.isFeedbackNotificationDisabled
import com.intellij.feedback.common.bundle.CommonFeedbackBundle
import com.intellij.feedback.common.notification.RequestFeedbackNotification
import com.intellij.feedback.npw.bundle.NPWFeedbackBundle
import com.intellij.feedback.npw.dialog.ProjectCreationFeedbackDialog
import com.intellij.feedback.npw.state.ProjectCreationInfoService
import com.intellij.feedback.npw.state.ProjectCreationInfoState
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
enum class IdleFeedbackTypes {
PROJECT_CREATION_FEEDBACK {
private val unknownProjectTypeName = "UNKNOWN"
private val testProjectTypeName = "TEST"
private val maxNumberNotificationShowed = 3
override val suitableIdeVersion: String = "2022.1"
override fun isSuitable(): Boolean {
val projectCreationInfoState = ProjectCreationInfoService.getInstance().state
return isIntellijIdeaEAP() &&
checkIdeVersionIsSuitable() &&
checkProjectCreationFeedbackNotSent(projectCreationInfoState) &&
checkProjectCreated(projectCreationInfoState) &&
checkNotificationNumberNotExceeded(projectCreationInfoState)
}
private fun checkProjectCreationFeedbackNotSent(state: ProjectCreationInfoState): Boolean {
return !state.feedbackSent
}
private fun checkProjectCreated(state: ProjectCreationInfoState): Boolean {
return state.lastCreatedProjectBuilderId != null
}
private fun checkNotificationNumberNotExceeded(state: ProjectCreationInfoState): Boolean {
return state.numberNotificationShowed < maxNumberNotificationShowed
}
override fun createNotification(forTest: Boolean): Notification {
return RequestFeedbackNotification(NPWFeedbackBundle.message("notification.created.project.request.feedback.title"),
NPWFeedbackBundle.message("notification.created.project.request.feedback.content"))
}
override fun createFeedbackDialog(project: Project?, forTest: Boolean): DialogWrapper {
return ProjectCreationFeedbackDialog(project, getLastCreatedProjectTypeName(forTest), forTest)
}
private fun getLastCreatedProjectTypeName(forTest: Boolean): String {
if (forTest) {
return testProjectTypeName
}
val projectCreationInfoState = ProjectCreationInfoService.getInstance().state
return projectCreationInfoState.lastCreatedProjectBuilderId ?: unknownProjectTypeName
}
override fun updateStateAfterNotificationShowed() {
val projectCreationInfoState = ProjectCreationInfoService.getInstance().state
projectCreationInfoState.numberNotificationShowed += 1
}
};
protected abstract val suitableIdeVersion: String
abstract fun isSuitable(): Boolean
protected fun isIntellijIdeaEAP(): Boolean {
return ApplicationInfoEx.getInstanceEx().isEAP
}
protected fun checkIdeVersionIsSuitable(): Boolean {
return suitableIdeVersion == ApplicationInfoEx.getInstanceEx().shortVersion
}
protected abstract fun createNotification(forTest: Boolean): Notification
protected abstract fun createFeedbackDialog(project: Project?, forTest: Boolean): DialogWrapper
protected abstract fun updateStateAfterNotificationShowed()
fun showNotification(project: Project?, forTest: Boolean = false) {
val notification = createNotification(forTest)
notification.addAction(
NotificationAction.createSimpleExpiring(CommonFeedbackBundle.message("notification.request.feedback.action.respond.text")) {
val dialog = createFeedbackDialog(project, forTest)
dialog.show()
}
)
notification.addAction(
NotificationAction.createSimpleExpiring(CommonFeedbackBundle.message("notification.request.feedback.action.dont.show.text")) {
if (!forTest) {
isFeedbackNotificationDisabled = true
}
}
)
notification.notify(project)
if (!forTest) {
updateStateAfterNotificationShowed()
}
}
} | apache-2.0 |
jwren/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/RefsTable.kt | 1 | 24969 | // 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.impl
import com.google.common.collect.BiMap
import com.google.common.collect.HashBiMap
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.util.containers.HashSetInterner
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId.ConnectionType
import com.intellij.workspaceModel.storage.impl.containers.*
import it.unimi.dsi.fastutil.ints.IntArrayList
import java.util.function.IntFunction
class ConnectionId private constructor(
val parentClass: Int,
val childClass: Int,
val connectionType: ConnectionType,
val isParentNullable: Boolean
) {
enum class ConnectionType {
ONE_TO_ONE,
ONE_TO_MANY,
ONE_TO_ABSTRACT_MANY,
ABSTRACT_ONE_TO_ONE
}
/**
* This function returns true if this connection allows removing parent of child.
*
* E.g. parent is optional (nullable) for child entity, so the parent can be safely removed.
*/
fun canRemoveParent(): Boolean = isParentNullable
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ConnectionId
if (parentClass != other.parentClass) return false
if (childClass != other.childClass) return false
if (connectionType != other.connectionType) return false
if (isParentNullable != other.isParentNullable) return false
return true
}
override fun hashCode(): Int {
var result = parentClass.hashCode()
result = 31 * result + childClass.hashCode()
result = 31 * result + connectionType.hashCode()
result = 31 * result + isParentNullable.hashCode()
return result
}
override fun toString(): String {
return "Connection(parent=${ClassToIntConverter.INSTANCE.getClassOrDie(parentClass).simpleName} " +
"child=${ClassToIntConverter.INSTANCE.getClassOrDie(childClass).simpleName} $connectionType)"
}
fun debugStr(): String = """
ConnectionId info:
- Parent class: ${this.parentClass.findEntityClass<WorkspaceEntity>()}
- Child class: ${this.childClass.findEntityClass<WorkspaceEntity>()}
- Connection type: $connectionType
- Parent of child is nullable: $isParentNullable
""".trimIndent()
companion object {
/** This function should be [@Synchronized] because interner is not thread-save */
@Synchronized
fun <Parent : WorkspaceEntity, Child : WorkspaceEntity> create(
parentClass: Class<Parent>,
childClass: Class<Child>,
connectionType: ConnectionType,
isParentNullable: Boolean
): ConnectionId {
val connectionId = ConnectionId(parentClass.toClassId(), childClass.toClassId(), connectionType, isParentNullable)
return interner.intern(connectionId)
}
private val interner = HashSetInterner<ConnectionId>()
}
}
/**
* [oneToManyContainer]: [ImmutableNonNegativeIntIntBiMap] - key - child, value - parent
*/
internal class RefsTable internal constructor(
override val oneToManyContainer: Map<ConnectionId, ImmutableNonNegativeIntIntBiMap>,
override val oneToOneContainer: Map<ConnectionId, ImmutableIntIntUniqueBiMap>,
override val oneToAbstractManyContainer: Map<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>,
override val abstractOneToOneContainer: Map<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
) : AbstractRefsTable() {
constructor() : this(HashMap(), HashMap(), HashMap(), HashMap())
}
internal class MutableRefsTable(
override val oneToManyContainer: MutableMap<ConnectionId, NonNegativeIntIntBiMap>,
override val oneToOneContainer: MutableMap<ConnectionId, IntIntUniqueBiMap>,
override val oneToAbstractManyContainer: MutableMap<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>,
override val abstractOneToOneContainer: MutableMap<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
) : AbstractRefsTable() {
private val oneToAbstractManyCopiedToModify: MutableSet<ConnectionId> = HashSet()
private val abstractOneToOneCopiedToModify: MutableSet<ConnectionId> = HashSet()
private fun getOneToManyMutableMap(connectionId: ConnectionId): MutableNonNegativeIntIntBiMap {
val bimap = oneToManyContainer[connectionId] ?: run {
val empty = MutableNonNegativeIntIntBiMap()
oneToManyContainer[connectionId] = empty
return empty
}
return when (bimap) {
is MutableNonNegativeIntIntBiMap -> bimap
is ImmutableNonNegativeIntIntBiMap -> {
val copy = bimap.toMutable()
oneToManyContainer[connectionId] = copy
copy
}
}
}
private fun getOneToAbstractManyMutableMap(connectionId: ConnectionId): LinkedBidirectionalMap<ChildEntityId, ParentEntityId> {
if (connectionId !in oneToAbstractManyContainer) {
oneToAbstractManyContainer[connectionId] = LinkedBidirectionalMap()
}
return if (connectionId in oneToAbstractManyCopiedToModify) {
oneToAbstractManyContainer[connectionId]!!
}
else {
val copy = LinkedBidirectionalMap<ChildEntityId, ParentEntityId>()
val original = oneToAbstractManyContainer[connectionId]!!
original.forEach { (k, v) -> copy[k] = v }
oneToAbstractManyContainer[connectionId] = copy
oneToAbstractManyCopiedToModify.add(connectionId)
copy
}
}
private fun getAbstractOneToOneMutableMap(connectionId: ConnectionId): BiMap<ChildEntityId, ParentEntityId> {
if (connectionId !in abstractOneToOneContainer) {
abstractOneToOneContainer[connectionId] = HashBiMap.create()
}
return if (connectionId in abstractOneToOneCopiedToModify) {
abstractOneToOneContainer[connectionId]!!
}
else {
val copy = HashBiMap.create<ChildEntityId, ParentEntityId>()
val original = abstractOneToOneContainer[connectionId]!!
original.forEach { (k, v) -> copy[k] = v }
abstractOneToOneContainer[connectionId] = copy
abstractOneToOneCopiedToModify.add(connectionId)
copy
}
}
private fun getOneToOneMutableMap(connectionId: ConnectionId): MutableIntIntUniqueBiMap {
val bimap = oneToOneContainer[connectionId] ?: run {
val empty = MutableIntIntUniqueBiMap()
oneToOneContainer[connectionId] = empty
return empty
}
return when (bimap) {
is MutableIntIntUniqueBiMap -> bimap
is ImmutableIntIntUniqueBiMap -> {
val copy = bimap.toMutable()
oneToOneContainer[connectionId] = copy
copy
}
}
}
fun removeRefsByParent(connectionId: ConnectionId, parentId: ParentEntityId) {
@Suppress("IMPLICIT_CAST_TO_ANY")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> getOneToManyMutableMap(connectionId).removeValue(parentId.id.arrayId)
ConnectionType.ONE_TO_ONE -> getOneToOneMutableMap(connectionId).removeValue(parentId.id.arrayId)
ConnectionType.ONE_TO_ABSTRACT_MANY -> getOneToAbstractManyMutableMap(connectionId).removeValue(parentId)
ConnectionType.ABSTRACT_ONE_TO_ONE -> getAbstractOneToOneMutableMap(connectionId).inverse().remove(parentId)
}.let { }
}
fun removeOneToOneRefByParent(connectionId: ConnectionId, parentId: Int) {
getOneToOneMutableMap(connectionId).removeValue(parentId)
}
fun removeOneToAbstractOneRefByParent(connectionId: ConnectionId, parentId: ParentEntityId) {
getAbstractOneToOneMutableMap(connectionId).inverse().remove(parentId)
}
fun removeOneToOneRefByChild(connectionId: ConnectionId, childId: Int) {
getOneToOneMutableMap(connectionId).removeKey(childId)
}
fun removeOneToManyRefsByChild(connectionId: ConnectionId, childId: Int) {
getOneToManyMutableMap(connectionId).removeKey(childId)
}
fun removeParentToChildRef(connectionId: ConnectionId, parentId: ParentEntityId, childId: ChildEntityId) {
@Suppress("IMPLICIT_CAST_TO_ANY")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> getOneToManyMutableMap(connectionId).remove(childId.id.arrayId, parentId.id.arrayId)
ConnectionType.ONE_TO_ONE -> getOneToOneMutableMap(connectionId).remove(childId.id.arrayId, parentId.id.arrayId)
ConnectionType.ONE_TO_ABSTRACT_MANY -> getOneToAbstractManyMutableMap(connectionId).remove(childId, parentId)
ConnectionType.ABSTRACT_ONE_TO_ONE -> getAbstractOneToOneMutableMap(connectionId).remove(childId, parentId)
}.let { }
}
internal fun updateChildrenOfParent(connectionId: ConnectionId, parentId: ParentEntityId, childrenIds: List<ChildEntityId>) {
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeValue(parentId.id.arrayId)
val children = childrenIds.map { it.id.arrayId }.toIntArray()
copiedMap.putAll(children, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ONE -> {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.putForce(childrenIds.single().id.arrayId, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ABSTRACT_MANY -> {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
// In theory this removing can be avoided because keys will be replaced anyway, but without this cleanup we may get an
// incorrect ordering of the children
childrenIds.forEach { copiedMap.remove(it) }
childrenIds.forEach { copiedMap[it] = parentId }
}
ConnectionType.ABSTRACT_ONE_TO_ONE -> {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.inverse().remove(parentId)
childrenIds.forEach { copiedMap[it] = parentId }
}
}.let { }
}
fun updateOneToManyChildrenOfParent(connectionId: ConnectionId, parentId: Int, childrenEntityIds: Sequence<ChildEntityId>) {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
val children = childrenEntityIds.mapToIntArray { it.id.arrayId }
copiedMap.putAll(children, parentId)
}
fun updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId,
parentId: ParentEntityId,
childrenEntityIds: Sequence<ChildEntityId>) {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
childrenEntityIds.forEach { copiedMap[it] = parentId }
}
fun <Parent : WorkspaceEntityBase, OriginParent : Parent> updateOneToAbstractOneParentOfChild(connectionId: ConnectionId,
childId: ChildEntityId,
parentEntity: OriginParent) {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap[childId] = parentEntity.id.asParent()
}
fun updateOneToAbstractOneChildOfParent(connectionId: ConnectionId,
parentId: ParentEntityId,
childEntityId: ChildEntityId) {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.inverse().remove(parentId)
copiedMap[childEntityId.id.asChild()] = parentId
}
fun updateOneToOneChildOfParent(connectionId: ConnectionId, parentId: Int, childEntityId: ChildEntityId) {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeValue(parentId)
copiedMap.put(childEntityId.id.arrayId, parentId)
}
fun <Parent : WorkspaceEntityBase> updateOneToOneParentOfChild(connectionId: ConnectionId, childId: Int, parentEntity: Parent) {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeKey(childId)
copiedMap.putForce(childId, parentEntity.id.arrayId)
}
internal fun updateParentOfChild(connectionId: ConnectionId, childId: ChildEntityId, parentId: ParentEntityId) {
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeKey(childId.id.arrayId)
copiedMap.putAll(intArrayOf(childId.id.arrayId), parentId.id.arrayId)
}
ConnectionType.ONE_TO_ONE -> {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeKey(childId.id.arrayId)
copiedMap.putForce(childId.id.arrayId, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ABSTRACT_MANY -> {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap[childId] = parentId
}
ConnectionType.ABSTRACT_ONE_TO_ONE -> {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap.forcePut(childId, parentId)
Unit
}
}.let { }
}
fun <Parent : WorkspaceEntityBase> updateOneToManyParentOfChild(connectionId: ConnectionId, childId: Int, parent: Parent) {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeKey(childId)
copiedMap.putAll(intArrayOf(childId), parent.id.arrayId)
}
fun toImmutable(): RefsTable = RefsTable(
oneToManyContainer.mapValues { it.value.toImmutable() },
oneToOneContainer.mapValues { it.value.toImmutable() },
oneToAbstractManyContainer.mapValues {
it.value.let { value ->
val map = LinkedBidirectionalMap<ChildEntityId, ParentEntityId>()
value.forEach { (k, v) -> map[k] = v }
map
}
},
abstractOneToOneContainer.mapValues {
it.value.let { value ->
val map = HashBiMap.create<ChildEntityId, ParentEntityId>()
value.forEach { (k, v) -> map[k] = v }
map
}
}
)
companion object {
fun from(other: RefsTable): MutableRefsTable = MutableRefsTable(
HashMap(other.oneToManyContainer), HashMap(other.oneToOneContainer),
HashMap(other.oneToAbstractManyContainer),
HashMap(other.abstractOneToOneContainer))
}
private fun <T> Sequence<T>.mapToIntArray(action: (T) -> Int): IntArray {
val intArrayList = IntArrayList()
this.forEach { item ->
intArrayList.add(action(item))
}
return intArrayList.toIntArray()
}
}
internal sealed class AbstractRefsTable {
internal abstract val oneToManyContainer: Map<ConnectionId, NonNegativeIntIntBiMap>
internal abstract val oneToOneContainer: Map<ConnectionId, IntIntUniqueBiMap>
internal abstract val oneToAbstractManyContainer: Map<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>
internal abstract val abstractOneToOneContainer: Map<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
fun <Parent : WorkspaceEntity, Child : WorkspaceEntity> findConnectionId(parentClass: Class<Parent>, childClass: Class<Child>): ConnectionId? {
val parentClassId = parentClass.toClassId()
val childClassId = childClass.toClassId()
return (oneToManyContainer.keys.find { it.parentClass == parentClassId && it.childClass == childClassId }
?: oneToOneContainer.keys.find { it.parentClass == parentClassId && it.childClass == childClassId }
?: oneToAbstractManyContainer.keys.find {
it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) &&
it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass)
}
?: abstractOneToOneContainer.keys.find {
it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) &&
it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass)
})
}
fun getParentRefsOfChild(childId: ChildEntityId): Map<ConnectionId, ParentEntityId> {
val childArrayId = childId.id.arrayId
val childClassId = childId.id.clazz
val childClass = childId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ParentEntityId>()
val filteredOneToMany = oneToManyContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToMany) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredOneToOne = oneToOneContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredOneToAbstractMany = oneToAbstractManyContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredOneToAbstractMany) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
return res
}
fun getParentOneToOneRefsOfChild(childId: ChildEntityId): Map<ConnectionId, ParentEntityId> {
val childArrayId = childId.id.arrayId
val childClassId = childId.id.clazz
val childClass = childId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ParentEntityId>()
val filteredOneToOne = oneToOneContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
return res
}
fun getChildrenRefsOfParentBy(parentId: ParentEntityId): Map<ConnectionId, List<ChildEntityId>> {
val parentArrayId = parentId.id.arrayId
val parentClassId = parentId.id.clazz
val parentClass = parentId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, List<ChildEntityId>>()
val filteredOneToMany = oneToManyContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToMany) {
val keys = bimap.getKeys(parentArrayId)
if (!keys.isEmpty()) {
val children = keys.map { createEntityId(it, connectionId.childClass) }.mapTo(ArrayList()) { it.asChild() }
val existingValue = res.putIfAbsent(connectionId, children)
if (existingValue != null) thisLogger().error("These children already exist")
}
}
val filteredOneToOne = oneToOneContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsValue(parentArrayId)) continue
val key = bimap.getKey(parentArrayId)
val existingValue = res.putIfAbsent(connectionId, listOf(createEntityId(key, connectionId.childClass).asChild()))
if (existingValue != null) thisLogger().error("These children already exist")
}
val filteredOneToAbstractMany = oneToAbstractManyContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredOneToAbstractMany) {
val keys = bimap.getKeysByValue(parentId) ?: continue
if (keys.isNotEmpty()) {
val existingValue = res.putIfAbsent(connectionId, keys.map { it })
if (existingValue != null) thisLogger().error("These children already exist")
}
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
val key = bimap.inverse()[parentId]
if (key == null) continue
val existingValue = res.putIfAbsent(connectionId, listOf(key))
if (existingValue != null) thisLogger().error("These children already exist")
}
return res
}
fun getChildrenOneToOneRefsOfParentBy(parentId: ParentEntityId): Map<ConnectionId, ChildEntityId> {
val parentArrayId = parentId.id.arrayId
val parentClassId = parentId.id.clazz
val parentClass = parentId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ChildEntityId>()
val filteredOneToOne = oneToOneContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsValue(parentArrayId)) continue
val key = bimap.getKey(parentArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(key, connectionId.childClass).asChild())
if (existingValue != null) thisLogger().error("These children already exist")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
val key = bimap.inverse()[parentId]
if (key == null) continue
val existingValue = res.putIfAbsent(connectionId, key)
if (existingValue != null) thisLogger().error("These children already exist")
}
return res
}
fun getOneToManyChildren(connectionId: ConnectionId, parentId: Int): NonNegativeIntIntMultiMap.IntSequence? {
return oneToManyContainer[connectionId]?.getKeys(parentId)
}
fun getOneToAbstractManyChildren(connectionId: ConnectionId, parentId: ParentEntityId): List<ChildEntityId>? {
val map = oneToAbstractManyContainer[connectionId]
return map?.getKeysByValue(parentId)
}
fun getAbstractOneToOneChildren(connectionId: ConnectionId, parentId: ParentEntityId): ChildEntityId? {
val map = abstractOneToOneContainer[connectionId]
return map?.inverse()?.get(parentId)
}
fun getOneToAbstractOneParent(connectionId: ConnectionId, childId: ChildEntityId): ParentEntityId? {
return abstractOneToOneContainer[connectionId]?.get(childId)
}
fun <Child : WorkspaceEntity> getOneToOneChild(connectionId: ConnectionId, parentId: Int, transformer: IntFunction<Child?>): Child? {
val bimap = oneToOneContainer[connectionId] ?: return null
if (!bimap.containsValue(parentId)) return null
return transformer.apply(bimap.getKey(parentId))
}
fun <Parent : WorkspaceEntity> getOneToOneParent(connectionId: ConnectionId, childId: Int, transformer: IntFunction<Parent?>): Parent? {
val bimap = oneToOneContainer[connectionId] ?: return null
if (!bimap.containsKey(childId)) return null
return transformer.apply(bimap.get(childId))
}
fun <Parent : WorkspaceEntity> getOneToManyParent(connectionId: ConnectionId, childId: Int, transformer: IntFunction<Parent?>): Parent? {
val bimap = oneToManyContainer[connectionId] ?: return null
if (!bimap.containsKey(childId)) return null
return transformer.apply(bimap.get(childId))
}
}
// TODO: 25.05.2021 Make it value class
internal data class ChildEntityId(val id: EntityId) {
override fun toString(): String {
return "ChildEntityId(id=${id.asString()})"
}
}
internal data class ParentEntityId(val id: EntityId) {
override fun toString(): String {
return "ParentEntityId(id=${id.asString()})"
}
}
internal fun EntityId.asChild(): ChildEntityId = ChildEntityId(this)
internal fun EntityId.asParent(): ParentEntityId = ParentEntityId(this)
| apache-2.0 |
alisle/Penella | src/main/java/org/penella/codecs/ShardGetCodec.kt | 1 | 800 | package org.penella.codecs
import io.vertx.core.buffer.Buffer
import org.penella.messages.ShardGet
/**
* 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.
*
* Created by alisle on 1/26/17.
*/
class ShardGetCodec : JSONCodec<ShardGet>(ShardGet::class.java) {
override fun name() = "ShardGet"
} | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.