content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* 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.LogRecordAssertion.Companion.assertThat
import info.novatec.testit.logrecorder.assertion.containsExactly
import info.novatec.testit.logrecorder.assertion.logEntry
import info.novatec.testit.logrecorder.assertion.logRecord
import org.junit.jupiter.api.*
import org.junit.jupiter.api.DynamicTest.dynamicTest
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
internal class MessagesAssertionBlockDslElementsTests {
val exampleLogRecord = logRecord(
logEntry(INFO, "start"),
logEntry(TRACE, "trace message"),
logEntry(DEBUG, "debug message"),
logEntry(INFO, "info message"),
logEntry(WARN, "warn message"),
logEntry(ERROR, "error message"),
logEntry(INFO, "end")
)
@Test
fun `smoke test example`() {
assertThat(exampleLogRecord) {
containsExactly {
info("start")
trace("trace message")
debug("debug message")
info("info message")
warn("warn message")
error("error message")
info("end")
}
containsExactly {
info(startsWith("start"))
trace(contains("trace"))
debug(equalTo("debug message"))
info(matches(".+"))
warn(containsInOrder("w", "ar", "n"))
error(contains("error", "message"))
info(endsWith("end"))
}
}
}
@Test
fun `anything matcher matches all log levels and messages`() {
assertThat(exampleLogRecord) {
containsExactly {
info("start")
anything()
anything()
anything()
anything()
anything()
info("end")
}
}
}
@Nested
inner class LogLevelMatcherDslElements {
val logLevelsAndCorrespondingMatchers: List<Pair<LogLevel, MessagesAssertionBlock.() -> Unit>> =
listOf(
TRACE to { trace() },
DEBUG to { debug() },
INFO to { info() },
WARN to { warn() },
ERROR to { error() },
)
@TestFactory
fun `specific level matchers match entries with expected log level`() =
logLevelsAndCorrespondingMatchers.map { (level, matcher) ->
dynamicTest("$level") {
val log = logRecord(logEntry(level = level))
assertThat(log) { containsExactly(matcher) }
}
}
@TestFactory
fun `specific level matchers do not match entries with different log levels`() =
logLevelsAndCorrespondingMatchers.flatMap { (level, matcher) ->
LogLevel.values()
.filter { it != level }
.map { wrongLevel ->
dynamicTest("$level != $wrongLevel") {
assertThrows<AssertionError> {
val log = logRecord(logEntry(level = wrongLevel))
assertThat(log) { containsExactly(matcher) }
}
}
}
}
@ParameterizedTest
@EnumSource(LogLevel::class)
fun `any matcher matches all log levels`(logLevel: LogLevel) {
assertThat(logRecord(logEntry(logLevel))) { containsExactly { any() } }
assertThat(logRecord(logEntry(logLevel, "foo"))) { containsExactly { any("foo") } }
assertThat(logRecord(logEntry(logLevel, "bar"))) { containsExactly { any(equalTo("bar")) } }
}
}
@Nested
inner class MessageMatcherDslElements {
val log = logRecord(logEntry(message = "Foo bar XUR"))
@Nested
@DisplayName("equalTo(..)")
inner class EqualTo {
@Test
fun `exactly matching message is OK`() {
assertThat(log) { containsExactly { any(equalTo("Foo bar XUR")) } }
}
@Test
fun `not matching message throws assertion error`() {
assertThrows<AssertionError> {
assertThat(log) { containsExactly { any(equalTo("something else")) } }
}
}
}
@Nested
@DisplayName("matches(..)")
inner class Matches {
@Test
fun `message matching the RegEx is OK`() {
assertThat(log) { containsExactly { any(matches("Foo.+")) } }
}
@Test
fun `message not matching the RegEx throws assertion error`() {
assertThrows<AssertionError> {
assertThat(log) { containsExactly { any(matches("Bar.+")) } }
}
}
}
@Nested
@DisplayName("contains(..)")
inner class Contains {
@Test
fun `message containing all supplied parts in any order is OK`() {
assertThat(log) { containsExactly { any(contains("XUR", "Foo")) } }
}
@Test
fun `message containing non of the parts throws assertion error`() {
assertThrows<AssertionError> {
assertThat(log) { containsExactly { any(contains("message")) } }
}
}
}
@Nested
@DisplayName("containsInOrder(..)")
inner class ContainsInOrderTests {
@Test
fun `message containing all supplied parts in order is OK`() {
assertThat(log) { containsExactly { any(containsInOrder("Foo", "XUR")) } }
}
@Test
fun `message containing all supplied parts but not in order throws assertion error`() {
assertThrows<AssertionError> {
assertThat(log) { containsExactly { any(containsInOrder("XUR", "Foo")) } }
}
}
}
@Nested
@DisplayName("startsWith(..)")
inner class StartsWith {
@Test
fun `message starting with prefix is OK`() {
assertThat(log) { containsExactly { any(startsWith("Foo ")) } }
}
@Test
fun `message not starting with prefix throws assertion error`() {
assertThrows<AssertionError> {
assertThat(log) { containsExactly { any(startsWith("message")) } }
}
}
}
@Nested
@DisplayName("endsWith(..)")
inner class EndsWith {
@Test
fun `message starting with prefix is OK`() {
assertThat(log) { containsExactly { any(endsWith(" XUR")) } }
}
@Test
fun `message not starting with prefix throws assertion error`() {
assertThrows<AssertionError> {
assertThat(log) { containsExactly { any(endsWith("message")) } }
}
}
}
}
}
| logrecorder/logrecorder-assertions/src/test/kotlin/info/novatec/testit/logrecorder/assertion/blocks/MessagesAssertionBlockDslElementsTests.kt | 3038463082 |
package com.bigscreen.binarygame.setting
import com.bigscreen.binarygame.arch.UserAction
class SettingPresenter : SettingContract.Presenter() {
override fun onAttach() {
}
override fun onUserAction(action: UserAction) {
}
override fun onDetach() {
}
} | app/src/main/java/com/bigscreen/binarygame/setting/SettingPresenter.kt | 580974463 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.datacapture.validation
sealed class ValidationResult
object NotValidated : ValidationResult()
object Valid : ValidationResult()
data class Invalid(private val validationMessages: List<String>) : ValidationResult() {
fun getSingleStringValidationMessage() = this.validationMessages.joinToString(separator = "\n")
}
| datacapture/src/main/java/com/google/android/fhir/datacapture/validation/ValidationResult.kt | 3131444731 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package openxr.templates
import org.lwjgl.generator.*
import openxr.*
val MSFT_controller_model = "MSFTControllerModel".nativeClassXR("MSFT_controller_model", type = "instance", postfix = "MSFT") {
documentation =
"""
The <a href="https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html\#XR_MSFT_controller_model">XR_MSFT_controller_model</a> extension.
This extension provides a mechanism to load a GLTF model for controllers. An application <b>can</b> render the controller model using the real time pose input from controller’s grip action pose and animate controller parts representing the user’s interactions, such as pressing a button, or pulling a trigger.
This extension supports any controller interaction profile that supports subpathname:/grip/pose. The returned controller model represents the physical controller held in the user’s hands, and it <b>may</b> be different from the current interaction profile.
"""
IntConstant(
"The extension specification version.",
"MSFT_controller_model_SPEC_VERSION".."2"
)
StringConstant(
"The extension name.",
"MSFT_CONTROLLER_MODEL_EXTENSION_NAME".."XR_MSFT_controller_model"
)
EnumConstant(
"XR_MAX_CONTROLLER_MODEL_NODE_NAME_SIZE_MSFT",
"MAX_CONTROLLER_MODEL_NODE_NAME_SIZE_MSFT".."64"
)
EnumConstant(
"Extends {@code XrStructureType}.",
"TYPE_CONTROLLER_MODEL_KEY_STATE_MSFT".."1000055000",
"TYPE_CONTROLLER_MODEL_NODE_PROPERTIES_MSFT".."1000055001",
"TYPE_CONTROLLER_MODEL_PROPERTIES_MSFT".."1000055002",
"TYPE_CONTROLLER_MODEL_NODE_STATE_MSFT".."1000055003",
"TYPE_CONTROLLER_MODEL_STATE_MSFT".."1000055004"
)
EnumConstant(
"Extends {@code XrResult}.",
"ERROR_CONTROLLER_MODEL_KEY_INVALID_MSFT".."-1000055000"
)
XrResult(
"GetControllerModelKeyMSFT",
"""
Retrieve the model key for the controller.
<h5>C Specification</h5>
#GetControllerModelKeyMSFT() retrieves the {@code XrControllerModelKeyMSFT} for a controller. This model key <b>may</b> later be used to retrieve the model data.
The #GetControllerModelKeyMSFT() function is defined as:
<pre><code>
XrResult xrGetControllerModelKeyMSFT(
XrSession session,
XrPath topLevelUserPath,
XrControllerModelKeyStateMSFT* controllerModelKeyState);</code></pre>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>The {@link MSFTControllerModel XR_MSFT_controller_model} extension <b>must</b> be enabled prior to calling #GetControllerModelKeyMSFT()</li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
<li>{@code controllerModelKeyState} <b>must</b> be a pointer to an ##XrControllerModelKeyStateMSFT structure</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
<li>#SESSION_LOSS_PENDING</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_FUNCTION_UNSUPPORTED</li>
<li>#ERROR_VALIDATION_FAILURE</li>
<li>#ERROR_HANDLE_INVALID</li>
<li>#ERROR_INSTANCE_LOST</li>
<li>#ERROR_SESSION_LOST</li>
<li>#ERROR_OUT_OF_MEMORY</li>
<li>#ERROR_PATH_UNSUPPORTED</li>
<li>#ERROR_PATH_INVALID</li>
<li>#ERROR_CONTROLLER_MODEL_KEY_INVALID_MSFT</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##XrControllerModelKeyStateMSFT
""",
XrSession("session", "the specified {@code XrSession}."),
XrPath("topLevelUserPath", "the top level user path corresponding to the controller render model being queried (e.g. pathname:/user/hand/left or pathname:/user/hand/right)."),
XrControllerModelKeyStateMSFT.p("controllerModelKeyState", "a pointer to the ##XrControllerModelKeyStateMSFT to write the model key state to.")
)
XrResult(
"LoadControllerModelMSFT",
"""
Load controller render model.
<h5>C Specification</h5>
The #LoadControllerModelMSFT() function loads the controller model as a byte buffer containing a binary form of glTF (a.k.a GLB file format) for the controller. The binary glTF data <b>must</b> conform to glTF 2.0 format defined at <a target="_blank" href="https://github.com/KhronosGroup/glTF/tree/master/specification/2.0">https://github.com/KhronosGroup/glTF/tree/master/specification/2.0</a>.
<pre><code>
XrResult xrLoadControllerModelMSFT(
XrSession session,
XrControllerModelKeyMSFT modelKey,
uint32_t bufferCapacityInput,
uint32_t* bufferCountOutput,
uint8_t* buffer);</code></pre>
<h5>Description</h5>
The #LoadControllerModelMSFT() function <b>may</b> be a slow operation and therefore <b>should</b> be invoked from a non-timing critical thread.
If the input {@code modelKey} is invalid, i.e. it is #NULL_CONTROLLER_MODEL_KEY_MSFT or not a key returned from ##XrControllerModelKeyStateMSFT, the runtime <b>must</b> return #ERROR_CONTROLLER_MODEL_KEY_INVALID_MSFT.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>The {@link MSFTControllerModel XR_MSFT_controller_model} extension <b>must</b> be enabled prior to calling #LoadControllerModelMSFT()</li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
<li>{@code bufferCountOutput} <b>must</b> be a pointer to a {@code uint32_t} value</li>
<li>If {@code bufferCapacityInput} is not 0, {@code buffer} <b>must</b> be a pointer to an array of {@code bufferCapacityInput} {@code uint8_t} values</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
<li>#SESSION_LOSS_PENDING</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_FUNCTION_UNSUPPORTED</li>
<li>#ERROR_VALIDATION_FAILURE</li>
<li>#ERROR_HANDLE_INVALID</li>
<li>#ERROR_INSTANCE_LOST</li>
<li>#ERROR_SESSION_LOST</li>
<li>#ERROR_OUT_OF_MEMORY</li>
<li>#ERROR_SIZE_INSUFFICIENT</li>
<li>#ERROR_CONTROLLER_MODEL_KEY_INVALID_MSFT</li>
</ul></dd>
</dl>
""",
XrSession("session", "the specified {@code XrSession}."),
XrControllerModelKeyMSFT("modelKey", "the model key corresponding to the controller render model being queried."),
AutoSize("buffer")..uint32_t("bufferCapacityInput", "the capacity of the {@code buffer} array, or 0 to indicate a request to retrieve the required capacity."),
Check(1)..uint32_t.p("bufferCountOutput", "filled in by the runtime with the count of elements in {@code buffer} array, or returns the required capacity in the case that {@code bufferCapacityInput} is insufficient."),
nullable..uint8_t.p("buffer", "a pointer to an application-allocated array of the model for the device that will be filled with the {@code uint8_t} values by the runtime. It <b>can</b> be {@code NULL} if {@code bufferCapacityInput} is 0.")
)
XrResult(
"GetControllerModelPropertiesMSFT",
"""
Get controller model properties.
<h5>C Specification</h5>
The #GetControllerModelPropertiesMSFT() function returns the controller model properties for a given {@code modelKey}.
<pre><code>
XrResult xrGetControllerModelPropertiesMSFT(
XrSession session,
XrControllerModelKeyMSFT modelKey,
XrControllerModelPropertiesMSFT* properties);</code></pre>
<h5>Description</h5>
The runtime <b>must</b> return the same data in ##XrControllerModelPropertiesMSFT for a valid {@code modelKey}. Therefore, the application <b>can</b> cache the returned ##XrControllerModelPropertiesMSFT using {@code modelKey} and reuse the data for each frame.
If the input {@code modelKey} is invalid, i.e. it is #NULL_CONTROLLER_MODEL_KEY_MSFT or not a key returned from ##XrControllerModelKeyStateMSFT, the runtime <b>must</b> return #ERROR_CONTROLLER_MODEL_KEY_INVALID_MSFT.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>The {@link MSFTControllerModel XR_MSFT_controller_model} extension <b>must</b> be enabled prior to calling #GetControllerModelPropertiesMSFT()</li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
<li>{@code properties} <b>must</b> be a pointer to an ##XrControllerModelPropertiesMSFT structure</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
<li>#SESSION_LOSS_PENDING</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_FUNCTION_UNSUPPORTED</li>
<li>#ERROR_VALIDATION_FAILURE</li>
<li>#ERROR_HANDLE_INVALID</li>
<li>#ERROR_INSTANCE_LOST</li>
<li>#ERROR_SESSION_LOST</li>
<li>#ERROR_OUT_OF_MEMORY</li>
<li>#ERROR_CONTROLLER_MODEL_KEY_INVALID_MSFT</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##XrControllerModelPropertiesMSFT
""",
XrSession("session", "the specified {@code XrSession}."),
XrControllerModelKeyMSFT("modelKey", "a valid model key obtained from ##XrControllerModelKeyStateMSFT"),
XrControllerModelPropertiesMSFT.p("properties", "an ##XrControllerModelPropertiesMSFT returning the properties of the controller model")
)
XrResult(
"GetControllerModelStateMSFT",
"""
Get controller model state.
<h5>C Specification</h5>
The #GetControllerModelStateMSFT() function returns the current state of the controller model representing user’s interaction to the controller, such as pressing a button or pulling a trigger.
<pre><code>
XrResult xrGetControllerModelStateMSFT(
XrSession session,
XrControllerModelKeyMSFT modelKey,
XrControllerModelStateMSFT* state);</code></pre>
<h5>Description</h5>
The runtime <b>may</b> return different state for a model key after each call to #SyncActions(), which represents the latest state of the user interactions.
If the input {@code modelKey} is invalid, i.e. it is #NULL_CONTROLLER_MODEL_KEY_MSFT or not a key returned from ##XrControllerModelKeyStateMSFT, the runtime <b>must</b> return #ERROR_CONTROLLER_MODEL_KEY_INVALID_MSFT.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>The {@link MSFTControllerModel XR_MSFT_controller_model} extension <b>must</b> be enabled prior to calling #GetControllerModelStateMSFT()</li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
<li>{@code state} <b>must</b> be a pointer to an ##XrControllerModelStateMSFT structure</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
<li>#SESSION_LOSS_PENDING</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_FUNCTION_UNSUPPORTED</li>
<li>#ERROR_VALIDATION_FAILURE</li>
<li>#ERROR_HANDLE_INVALID</li>
<li>#ERROR_INSTANCE_LOST</li>
<li>#ERROR_SESSION_LOST</li>
<li>#ERROR_OUT_OF_MEMORY</li>
<li>#ERROR_CONTROLLER_MODEL_KEY_INVALID_MSFT</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##XrControllerModelStateMSFT
""",
XrSession("session", "the specified {@code XrSession}."),
XrControllerModelKeyMSFT("modelKey", "the model key corresponding to the controller model being queried."),
XrControllerModelStateMSFT.p("state", "a pointer to ##XrControllerModelNodeStateMSFT returns the current controller model state.")
)
} | modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/MSFT_controller_model.kt | 37836050 |
package com.scavi.brainsqueeze.adventofcode
class Day5BinaryBoarding {
private fun next(value: Int) = if (value % 2 == 1) (value / 2) + 1 else (value / 2)
fun solve(boardingPasses: List<String>, mySeat: Boolean = false): Int {
val seatIds = mutableListOf<Int>()
for (boardingPass in boardingPasses) {
val row = calculate(boardingPass, 127, 0, boardingPass.length - 3)
val column = calculate(boardingPass, 7, boardingPass.length - 3, boardingPass.length)
seatIds.add((row * 8) + column)
}
seatIds.sort()
if (mySeat) {
for (i in seatIds[0] until seatIds[seatIds.size - 1]) {
if (!seatIds.contains(i) && seatIds.contains(i - 1) && seatIds.contains(i + 1)) {
return i
}
}
}
return seatIds[seatIds.size - 1]
}
private fun calculate(boardingPass: String, hi: Int, from: Int, till: Int): Int {
var low = 0
var high = hi
var reminder = high
for (i in from until till) {
reminder = next(reminder)
when (boardingPass[i]) {
'F', 'L' -> high -= reminder
'B', 'R' -> low += reminder
}
}
return high
}
}
| src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day5BinaryBoarding.kt | 2560329261 |
/*
* Copyright (c) 2015 PocketHub
*
* 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.github.pockethub.android.ui.issue
import android.content.res.Resources
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Color.WHITE
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface.DEFAULT_BOLD
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.LayerDrawable
import android.graphics.drawable.PaintDrawable
import android.text.style.DynamicDrawableSpan
import android.widget.TextView
import androidx.text.buildSpannedString
import androidx.text.inSpans
import com.github.pockethub.android.R
import com.github.pockethub.android.util.ServiceUtils
import com.meisolsson.githubsdk.model.Label
import java.lang.Integer.MIN_VALUE
import java.lang.String.CASE_INSENSITIVE_ORDER
import java.util.*
import java.util.Locale.US
/**
* Span that draws a [Label]
*
* @constructor Create background span for label
*/
class LabelDrawableSpan(private val resources: Resources, private val textSize: Float, color: String, private val paddingLeft: Float, private val textHeight: Float, private val bounds: Rect, private val name: String) : DynamicDrawableSpan() {
private val color = Color.parseColor("#$color")
/**
* @constructor Create drawable for labels
*/
private class LabelDrawable(private val paddingLeft: Float, private val textHeight: Float, bounds: Rect, resources: Resources, textSize: Float, private val name: String, bg: Int) : PaintDrawable() {
private val height = bounds.height().toFloat()
private val textColor: Int
private val layers: LayerDrawable
init {
val hsv = FloatArray(3)
Color.colorToHSV(bg, hsv)
if (hsv[2] > 0.6 && hsv[1] < 0.4 || hsv[2] > 0.7 && hsv[0] > 40 && hsv[0] < 200) {
hsv[2] = 0.4f
textColor = Color.HSVToColor(hsv)
} else {
textColor = WHITE
}
layers = resources.getDrawable(R.drawable.label_background) as LayerDrawable
((layers
.findDrawableByLayerId(R.id.item_outer_layer) as LayerDrawable)
.findDrawableByLayerId(R.id.item_outer) as GradientDrawable).setColor(bg)
((layers
.findDrawableByLayerId(R.id.item_inner_layer) as LayerDrawable)
.findDrawableByLayerId(R.id.item_inner) as GradientDrawable).setColor(bg)
(layers.findDrawableByLayerId(R.id.item_bg) as GradientDrawable)
.setColor(bg)
paint.apply {
isAntiAlias = true
color = resources.getColor(android.R.color.transparent)
typeface = DEFAULT_BOLD
this.textSize = textSize
}
layers.bounds = bounds
setBounds(bounds)
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
layers.draw(canvas)
val paint = paint
val original = paint.color
paint.color = textColor
canvas.drawText(name, paddingLeft, height - (height - textHeight) / 2, paint)
paint.color = original
}
}
override fun getDrawable(): Drawable =
LabelDrawable(paddingLeft, textHeight, bounds, resources, textSize, name, color)
companion object {
/**
* Set text on view to be given labels
*
* @param view
* @param labels
*/
@JvmStatic
fun setText(view: TextView, labels: Collection<Label>) {
val sortedLabels = labels.toTypedArray()
Arrays.sort(sortedLabels) { lhs, rhs -> CASE_INSENSITIVE_ORDER.compare(lhs.name(), rhs.name()) }
setText(view, sortedLabels)
}
/**
* Set text on view to be given label
*
* @param view
* @param label
*/
@JvmStatic
fun setText(view: TextView, label: Label) {
setText(view, arrayOf(label))
}
private fun setText(view: TextView, labels: Array<Label>) {
val resources = view.resources
val paddingTop = resources.getDimension(R.dimen.label_padding_top)
val paddingLeft = resources.getDimension(R.dimen.label_padding_left)
val paddingRight = resources.getDimension(R.dimen.label_padding_right)
val paddingBottom = resources.getDimension(R.dimen.label_padding_bottom)
val p = Paint()
p.typeface = DEFAULT_BOLD
p.textSize = view.textSize
val textBounds = Rect()
val names = arrayOfNulls<String>(labels.size)
val nameWidths = IntArray(labels.size)
var textHeight = MIN_VALUE
for (i in labels.indices) {
val name = labels[i].name()!!.toUpperCase(US)
textBounds.setEmpty()
p.getTextBounds(name, 0, name.length, textBounds)
names[i] = name
textHeight = Math.max(textBounds.height(), textHeight)
nameWidths[i] = textBounds.width()
}
val textSize = view.textSize
view.text = buildSpannedString {
for (i in labels.indices) {
val bounds = Rect()
bounds.right = Math.round(nameWidths[i].toFloat() + paddingLeft + paddingRight + 0.5f)
bounds.bottom = Math.round(textHeight.toFloat() + paddingTop + paddingBottom + 0.5f)
inSpans(LabelDrawableSpan(resources, textSize, labels[i].color()!!, paddingLeft, textHeight.toFloat(), bounds, names[i]!!)) {
append('\uFFFC')
}
if (i + 1 < labels.size) {
append(' ')
}
}
}
}
}
}
| app/src/main/java/com/github/pockethub/android/ui/issue/LabelDrawableSpan.kt | 646244243 |
package org.livingdoc.engine.execution.examples.scenarios.matching
import org.assertj.core.api.AbstractAssert
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.slf4j.LoggerFactory
class AlignmentTest {
@Nested inner class `given a StepTemplate without variables` {
@Test fun `aligns perfectly matching step`() {
val alignment = align("Elvis has left the building.", "Elvis has left the building.")
assertThat(alignment)
.hasNoVariables()
.alignsAs(
"Elvis has left the building.",
"Elvis has left the building."
)
}
@Test fun `aligns similar step`() {
val alignment = align("Elvis has entered the building.", "Peter has left the building.")
assertThat(alignment)
.hasNoVariables()
.alignsAs(
"Elvis has -entered the building.",
"Peter has left---- the building."
)
}
@Test fun `aligns empty string`() {
val alignment = align("Elvis likes pizza.", "")
assertThat(alignment)
.hasNoVariables()
.alignsAs(
"Elvis likes pizza.",
"------------------"
)
}
}
@Nested inner class `given a StepTemplate with variables` {
@Test fun `extracts value from perfectly matching step`() {
val alignment = align("User {username} has entered the building.", "User Peter has entered the building.")
assertThat(alignment).hasVariables("username" to "Peter")
}
@Test fun `extracts value from step with slightly different text fragments`() {
val alignment = align("User {user} has entered the building.", "A user Peter has left the building.")
assertThat(alignment).hasVariables("user" to "Peter")
}
@Test fun `extracts value from step when the variable is the first part of the template`() {
val alignment = align("{username} has entered the building.", "Peter has left the building.")
assertThat(alignment).hasVariables("username" to "Peter")
}
@Test fun `extracts all of the values`() {
val alignment = align("{username} has {action} the {object}.", "Peter has left the building.")
assertThat(alignment).hasVariables(
"username" to "Peter",
"action" to "left",
"object" to "building"
)
}
@Test fun `extracts empty string as value from perfectly matching step`() {
val alignment = align("My name is {username}.", "My name is .")
assertThat(alignment)
.hasVariables("username" to "")
.alignsAs(
"My name is X.",
"My name is -."
)
}
}
@Test fun `given no matching StepTemplate, it is misaligned`() {
val alignment = align(
"Elvis left the building and this is a really long sentence that doesn't align with the next one at all.",
"Peter likes pizza."
)
assertThat(alignment)
.isMisaligned()
.alignsAs(
"Elvis left the building and this is a really long sentence that doesn't align with the next one at all.",
"Peter likes pizza."
)
.hasNoVariables()
Assertions.assertThat(alignment.maxCost <= alignment.totalCost).isTrue()
}
@Nested inner class `given a StepTemplate with quotation characters` {
@Test fun `extracts variable from perfectly matching step`() {
val alignment = alignWithQuotationCharacters("Peter likes '{stuff}'.", "Peter likes 'Pizza'.")
assertThat(alignment).hasVariables("stuff" to "Pizza")
}
@Test fun `extracts variable with adjacent insertion`() {
val alignment =
alignWithQuotationCharacters("'{user}' likes '{stuff}'.", "'Peter' likes delicious 'Pizza'.")
assertThat(alignment).hasVariables("user" to "Peter", "stuff" to "Pizza")
}
@Test fun `extracts from quoted and unquoted variables in the same template`() {
val alignment = alignWithQuotationCharacters("{user} likes '{stuff}'.", "Peter likes delicious 'Pizza'.")
assertThat(alignment).hasVariables("user" to "Peter", "stuff" to "Pizza")
}
@Test fun `is misaligned, if a quotation character is missing in the step`() {
val alignment = alignWithQuotationCharacters(
"Peter does not like '{stuff}'.",
"Peter does not like missing punctuation marks'."
)
assertThat(alignment).isMisaligned()
}
@Test fun `extracted variables do not contain quotation characters`() {
val alignment = alignWithQuotationCharacters(
"Peter does not like '{stuff}'.",
"Peter does not like ''unnecessary quotation marks'."
)
Assertions.assertThat(alignment.variables["stuff"]).doesNotContain("'")
assertThat(alignment).hasVariables("stuff" to "unnecessary quotation marks")
}
private fun alignWithQuotationCharacters(templateString: String, step: String): Alignment {
return Alignment(
StepTemplate.parse(templateString, quotationCharacters = setOf('\'')),
step,
maxCost = maxDistance
)
}
}
private fun align(templateString: String, step: String): Alignment {
return Alignment(StepTemplate.parse(templateString), step, maxCost = maxDistance)
}
private val maxDistance = 40 // allow for 20 insertions (a bit much, but useful for the examples in this test)
}
private fun assertThat(actual: Alignment): AlignmentAssert {
val logger = LoggerFactory.getLogger(AlignmentAssert::class.java)
if (logger.isDebugEnabled) {
printDistanceMatrix(actual)
printAlignment(actual)
}
return AlignmentAssert(actual)
}
private class AlignmentAssert(actual: Alignment) :
AbstractAssert<AlignmentAssert, Alignment>(actual, AlignmentAssert::class.java) {
fun hasTotalCost(cost: Int): AlignmentAssert {
if (actual.totalCost != cost)
failWithMessage("Expected a total cost of $cost, but was ${actual.totalCost}")
return this
}
fun isMisaligned(): AlignmentAssert {
if (!actual.isMisaligned())
failWithMessage("Expected alignment to be misaligned, but it was not.")
return this
}
fun alignsAs(template: String, step: String): AlignmentAssert {
if (actual.alignedStrings != Pair(template, step)) {
val reason = when {
actual.alignedStrings.first != template -> "the template is aligned differently"
actual.alignedStrings.second != step -> "the step is aligned differently"
else -> "both template and step are aligned differently"
}
failWithMessage(
"Expected alignment\n\t(template) %s\n\t (step) %s\n" +
"to be equal to\n\t(template) %s\n\t (step) %s\nbut %s.",
actual.alignedStrings.first, actual.alignedStrings.second, template, step, reason
)
}
return this
}
fun hasNoVariables(): AlignmentAssert {
if (!actual.variables.isEmpty())
failWithMessage(
"Expected alignment with no variables, but there are:\n%s",
formatVariables(actual.variables)
)
return this
}
fun hasVariables(vararg variables: Pair<String, String>): AlignmentAssert {
val variablesToValues = variables.toMap()
val missingVariables = variablesToValues.keys.subtract(actual.variables.keys)
val unexpectedVariables = actual.variables.keys.subtract(variablesToValues.keys)
val wrongValues = variablesToValues.keys
.intersect(actual.variables.keys)
.filter { variablesToValues[it] != actual.variables[it] }
if (missingVariables.isNotEmpty() || unexpectedVariables.isNotEmpty() || wrongValues.isNotEmpty()) {
val reasons = mutableListOf<String>()
if (missingVariables.isNotEmpty())
reasons.add("it is missing " + missingVariables.joinToString { "'$it'" })
if (unexpectedVariables.isNotEmpty())
reasons.add("it unexpectedly also yields " + unexpectedVariables.joinToString { "'$it'" })
if (wrongValues.isNotEmpty())
wrongValues.forEach {
reasons.add("the value of '$it' was '${actual.variables[it]}', not '${variablesToValues[it]}'")
}
val description = if (actual.variables.isEmpty())
"with no variables "
else
String.format("yielding the variables\n%s\n", formatVariables(actual.variables))
failWithMessage(
"Expected alignment %sto yield\n%s\nbut %s.",
description,
formatVariables(variablesToValues),
reasons.joinToString(separator = "\n\tand ")
)
}
return this
}
private fun formatVariables(variables: Map<String, String>) =
variables.asIterable().joinToString(separator = "\n\t", prefix = "\t") { "${it.key} = ${it.value}" }
}
/**
* Prints the distance matrix of the given alignment.
*/
private fun printDistanceMatrix(alignment: Alignment) {
print(" ")
alignment.step.forEach { print(String.format("%3c", it)) }
println()
for (line in alignment.distanceMatrix) {
line.forEach { print(String.format("%3d", it)) }
println()
}
}
/**
* Prints the aligned strings of template and step for the given alignment.
*/
private fun printAlignment(alignment: Alignment) {
println(
"\t(template) ${alignment.alignedStrings.first}" +
"\n\t (step) ${alignment.alignedStrings.second}"
)
}
| livingdoc-engine/src/test/kotlin/org/livingdoc/engine/execution/examples/scenarios/matching/AlignmentTest.kt | 4280810660 |
/*
* 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.processor
import com.google.common.truth.Truth
import com.google.testing.compile.JavaFileObjects
import com.google.testing.compile.JavaSourceSubjectFactory
import com.google.testing.compile.JavaSourcesSubject
import com.tickaroo.tikxml.annotation.GenericAdapter
import com.tickaroo.tikxml.annotation.Xml
import org.junit.Test
import javax.tools.JavaFileObject
import kotlin.test.assertEquals
/**
*
* @author Hannes Dorfmann
*/
class XmlProcessorTest {
@Test
fun annotatingInterface() {
val componentFile = JavaFileObjects.forSourceLines("test.NotAClass",
"package test;",
"@${Xml::class.qualifiedName}",
"interface NotAClass {}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Only classes can be annotated with")
}
@Test
fun annotatingEnum() {
val componentFile = JavaFileObjects.forSourceLines("test.NotAClass",
"package test;",
"@${Xml::class.qualifiedName}",
"enum NotAClass {}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Only classes can be annotated with")
}
@Test
fun abstractClass() {
val componentFile = JavaFileObjects.forSourceLines("test.AbstractClass",
"package test;",
"@${Xml::class.qualifiedName}",
"abstract class AbstractClass {}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun typeConverterForPrimitiveTypesNoOptions() {
val processor = XmlProcessor()
assertEquals(emptySet<String>(), processor.readPrimitiveTypeConverterOptions(null))
assertEquals(emptySet<String>(), processor.readPrimitiveTypeConverterOptions(""))
}
@Test
fun typeConverterForPrimitiveTypesSingle() {
val expectedOptions = setOf("java.lang.String")
val processor = XmlProcessor()
assertEquals(expectedOptions, processor.readPrimitiveTypeConverterOptions("java.lang.String"))
}
@Test
fun typeConverterForPrimitiveTypesMultiple() {
val expectedOptions = setOf("java.lang.String", "java.lang.int", "java.lang.Integer")
val processor = XmlProcessor()
assertEquals(expectedOptions,
processor.readPrimitiveTypeConverterOptions("java.lang.String, java.lang.int, java.lang.Integer"))
}
@Test
fun typeConverterForPrimitiveTypesMultipleTrim() {
val expectedOptions = setOf("java.lang.String", "java.lang.int", "java.lang.Integer")
val processor = XmlProcessor()
assertEquals(expectedOptions,
processor.readPrimitiveTypeConverterOptions(" java.lang.String, java.lang.int , java.lang.Integer "))
}
@Test
fun interfaceGenericAdapter() {
val componentFile = JavaFileObjects.forSourceLines("test.NotAClass",
"package test;",
"@${GenericAdapter::class.qualifiedName}",
"interface NotAClass {}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun abstractClassGenericAdapter() {
val componentFile = JavaFileObjects.forSourceLines("test.AbstractClass",
"package test;",
"@${GenericAdapter::class.qualifiedName}",
"abstract class AbstractClass {}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun classGenericAdapter() {
val componentFile = JavaFileObjects.forSourceLines("test.ConcreteClass",
"package test;",
"@${GenericAdapter::class.qualifiedName}",
"class ConcreteClass {}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Only interfaces and abstract classes can be annotated with @${GenericAdapter::class.java.simpleName}! Please remove @${GenericAdapter::class.java.simpleName} from test.ConcreteClass!")
}
} | processor/src/test/java/com/tickaroo/tikxml/processor/XmlProcessorTest.kt | 2862686825 |
package com.github.programmerr47.ganalytics.core
import java.lang.reflect.Method
import kotlin.reflect.KClass
interface ArgsManager {
fun manage(method: Method, args: Array<Any>?): Pair<String?, Number?>
}
class LabelArgsManager(
private val convention: NamingConvention) : ArgsManager {
override fun manage(method: Method, args: Array<Any>?) = when (args?.size) {
in arrayOf(0, null) -> buildPair(method, null)
1 -> buildPair(method, manageArgAsValue(method, args))
else -> throw IllegalArgumentException("Method ${method.name} are label, so it can have up to 1 parameter, which is value")
}
private fun buildPair(method: Method, value: Number?) = Pair(buildLabel(method), value)
private fun buildLabel(method: Method): String {
return method.getAnnotation(LabelFun::class.java)?.label?.takeNotEmpty() ?:
applyConvention(convention, method.name)
}
private fun manageArgAsValue(method: Method, args: Array<Any>): Number? {
return manageValueArg(method, args[0], method.parameterAnnotations[0].label())
}
private fun manageValueArg(method: Method, vArg: Any, vArgA: Label?) = if (vArgA != null) {
throw IllegalArgumentException("Method ${method.name} can not have @Label annotation on parameters, since it is already a label")
} else {
vArg as? Number ?:
throw IllegalArgumentException("Method ${method.name} can have only 1 parameter which must be a Number")
}
}
class ActionArgsManager(
private val globalSettings: GanalyticsSettings) : ArgsManager {
override fun manage(method: Method, args: Array<Any>?) = when (args?.size) {
in arrayOf(0, null) -> Pair(null, null)
1 -> Pair(convertLabelArg(args[0], method.parameterAnnotations[0]), null)
2 -> manageTwoArgs(args, method.parameterAnnotations)
else -> throw IllegalArgumentException("Method ${method.name} have ${method.parameterCount} parameter(s). You can have up to 2 parameters in ordinary methods.")
}
private fun manageTwoArgs(args: Array<Any>, annotations: Array<Array<Annotation>>): Pair<String, Number> {
return manageTwoArgs(args[0], annotations[0].label(), args[1], annotations[1].label())
}
private fun manageTwoArgs(arg1: Any, argA1: Label?, arg2: Any, argA2: Label?): Pair<String, Number> {
return manageArgAsValue(arg2, argA2, arg1, argA1) {
manageArgAsValue(arg1, argA1, arg2, argA2) {
throw IllegalArgumentException("For methods with 2 parameters one of them have to be Number without Label annotation")
}
}
}
private inline fun manageArgAsValue(vArg: Any, vArgA: Label?, lArg: Any, lArgA: Label?, defaultAction: () -> Pair<String, Number>): Pair<String, Number> {
return if (vArg is Number && vArgA == null) {
Pair(convertLabelArg(lArg, lArgA), vArg)
} else {
defaultAction()
}
}
private fun convertLabelArg(label: Any, annotations: Array<Annotation>): String {
return convertLabelArg(label, annotations.firstOrNull(Label::class))
}
private fun convertLabelArg(label: Any, annotation: Label?): String {
return chooseConverter(label, annotation).convert(label)
}
private fun chooseConverter(label: Any, annotation: Label?): LabelConverter {
return annotation?.converter?.init() ?: lookupGlobalConverter(label) ?: SimpleLabelConverter
}
private fun lookupGlobalConverter(label: Any): LabelConverter? {
label.converterClasses().forEach {
val converter = globalSettings.labelTypeConverters.lookup(it)
if (converter != null) return converter
}
return null
}
private fun Any.converterClasses() = if (globalSettings.useTypeConvertersForSubType)
javaClass.classHierarchy()
else
arrayListOf(javaClass)
private fun Class<in Any>.classHierarchy() = ArrayList<Class<Any>>().also {
var clazz: Class<in Any>? = this
do {
it.add(clazz!!)
clazz = clazz.superclass
} while (clazz != null)
}
private fun KClass<out LabelConverter>.init() = objectInstance ?: java.newInstance()
}
private fun Array<Annotation>.label() = firstOrNull(Label::class)
private fun <R : Any> Array<*>.firstOrNull(klass: KClass<R>): R? {
return filterIsInstance(klass.java).firstOrNull()
}
| ganalytics-core/src/main/java/com/github/programmerr47/ganalytics/core/argsmanagers.kt | 1765889261 |
package rynkbit.tk.coffeelist.ui.admin.invoice
import androidx.lifecycle.ViewModel
class ManageInvoicesViewModel : ViewModel() {
// TODO: Implement the ViewModel
}
| app/src/main/java/rynkbit/tk/coffeelist/ui/admin/invoice/ManageInvoicesViewModel.kt | 1349217354 |
/*
* ProtocolLib - Bukkit server library that allows access to the Minecraft protocol.
* Copyright (C) 2012 Kristian S. Stangeland
*
* 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
/*
* 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.util
abstract class ConvertedList<VI, VO>(
private val inner: MutableList<VI>
) : ConvertedCollection<VI, VO>(inner),
MutableList<VO> {
override fun add(index: Int, element: VO)
= inner.add(index, toIn(element))
override fun addAll(index: Int, elements: Collection<VO>): Boolean
= inner.addAll(index, getInnerCollection(elements.toMutableList()))
override fun get(index: Int): VO
= toOut(inner[index])
override fun indexOf(element: VO): Int
= inner.indexOf(toIn(element))
override fun lastIndexOf(element: VO): Int
= inner.lastIndexOf(toIn(element))
override fun listIterator(): MutableListIterator<VO>
= listIterator(0)
override fun listIterator(index: Int): MutableListIterator<VO> {
val innerIterator = inner.listIterator(index)
return object: MutableListIterator<VO> {
override fun hasPrevious(): Boolean
= innerIterator.hasPrevious()
override fun nextIndex(): Int
= innerIterator.nextIndex()
override fun previous(): VO
= toOut(innerIterator.previous())
override fun previousIndex(): Int
= innerIterator.previousIndex()
override fun add(element: VO)
= innerIterator.add(toIn(element))
override fun hasNext(): Boolean
= innerIterator.hasNext()
override fun next(): VO
= toOut(innerIterator.next())
override fun remove()
= innerIterator.remove()
override fun set(element: VO)
= innerIterator.set(toIn(element))
}
}
override fun removeAt(index: Int): VO
= toOut(inner.removeAt(index))
override fun set(index: Int, element: VO): VO
= toOut(inner.set(index, toIn(element)))
override fun subList(fromIndex: Int, toIndex: Int): MutableList<VO> {
return object: ConvertedList<VI, VO>(inner.subList(fromIndex, toIndex)) {
override fun toIn(outer: VO): VI
= [email protected](outer)
override fun toOut(inner: VI): VO
= [email protected](inner)
}
}
private fun getInnerCollection(elements: MutableCollection<VO>): ConvertedCollection<VO, VI> {
return object: ConvertedCollection<VO, VI>(elements) {
override fun toIn(outer: VI): VO
= [email protected](outer)
override fun toOut(inner: VO): VI
= [email protected](inner)
}
}
}
| API/src/main/kotlin/com/mcmoonlake/api/util/ConvertedList.kt | 1649436878 |
package me.serce.solidity.ide.quickFix
import me.serce.solidity.ide.inspections.ResolveNameInspection
class SolImportFileTest : SolQuickFixTestBase() {
fun testImportFileFix() {
myFixture.enableInspections(ResolveNameInspection().javaClass)
InlineFile(
code = "contract a {}",
name = "a.sol"
)
testQuickFix(
"contract b is a {}",
"\nimport \"./a.sol\";contract b is a {}"
)
}
// https://github.com/intellij-solidity/intellij-solidity/issues/64
fun testNoImportFixPopup() {
myFixture.enableInspections(ResolveNameInspection().javaClass)
InlineFile(
code = """
contract A {
struct MyStruct {}
}
""",
name = "A.sol"
)
InlineFile(
code = """
import "A.sol";
contract B is A {
}
""",
name = "B.sol"
)
assertNoQuickFix("""
import "B.sol";
contract C is B {
MyStruct A; //My struct is correctly imported as its part of B
}
"""
)
}
}
| src/test/kotlin/me/serce/solidity/ide/quickFix/SolImportFileTest.kt | 2529204597 |
// AFTER-WARNING: Parameter 's' is never used
fun foo(vararg s: String){}
fun bar(array: Array<String>) {
foo(<caret>s = *array)
} | plugins/kotlin/idea/tests/testData/intentions/removeArgumentName/star.kt | 2913953504 |
// WITH_STDLIB
fun assertCall(x: Int, b: Boolean, c: Boolean) {
if (x < 0) return
if (Math.random() > 0.5) {
assert(x >= 0)
}
if (Math.random() > 0.5) {
assert(b && x >= 0)
}
if (Math.random() > 0.5) {
assert(b || x >= 0)
}
if (Math.random() > 0.5) {
assert(<warning descr="Condition 'c && !(b || x >= 0)' is always false">c && <warning descr="Condition '!(b || x >= 0)' is always false when reached">!(b || <warning descr="Condition 'x >= 0' is always true when reached">x >= 0</warning>)</warning></warning>)
}
if (Math.random() > 0.5) {
assert(c && !(b || x < 0))
}
if (Math.random() > 0.5) {
assert(<warning descr="Condition 'x < 0' is always false">x < 0</warning>)
}
}
fun requireCall(x: Int) {
if (x < 0) return
require(x >= 0)
require(<warning descr="Condition 'x < 0' is always false">x < 0</warning>)
}
fun compilerWarningSuppression() {
val x: Int = 1
@Suppress("SENSELESS_COMPARISON")
if (x == null) {}
}
fun compilerWarningDuplicate(x : Int) {
// Reported as a compiler warning: suppress
if (<warning descr="[SENSELESS_COMPARISON] Condition 'x != null' is always 'true'">x != null</warning>) {
}
}
fun compilerWarningDuplicateWhen(x : X) {
// Reported as a compiler warning: suppress
when (x) {
<warning descr="[USELESS_IS_CHECK] Check for instance is always 'true'">is X</warning> -> {}
}
}
fun nothingOrNull(s: String?): String? {
return s?.let {
if (it.isEmpty()) return null
return s
}
}
fun nothingOrNullToElvis(s: String?): Boolean {
return s?.let {
if (it.isEmpty()) return false
return s.hashCode() < 0
} ?: false
}
// f.get() always returns null but it's inevitable: we cannot return anything else, hence suppress the warning
fun alwaysNull(f : MyFuture<Void>) = f.get()
fun unusedResult(x: Int) {
// Whole condition is always true but reporting it is not very useful
x > 0 || return
}
interface MyFuture<T> {
fun get():T?
}
class X
fun updateChain(b: Boolean, c: Boolean): Int {
var x = 0
if (b) x = x or 1
if (c) x = x or 2
return x
}
fun updateChainBoolean(b: Boolean, c: Boolean): Boolean {
var x = false
x = x || b
x = x || c
return x
}
fun updateChainInterrupted(b: Boolean, c: Boolean): Int {
var x = 0
x++
<warning descr="Value of 'x--' is always zero">x--</warning>
if (b) x = <weak_warning descr="Value of 'x' is always zero">x</weak_warning> or 1
if (c) x = x or 2
return x
}
| plugins/kotlin/idea/tests/testData/inspections/dfa/Suppressions.kt | 3851831355 |
/*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores.type
import java.lang.reflect.Type
/**
* Builder of a [GenericType].
*
* Examples:
*
* List of String:
* `GenericTypeBuilder().withType(List::class.codeType).addOfBound(String::class.codeType).build()`
*
* T extends List of wildcard extends CharSequence: `<T: List<out CharSequence>>` or `<T extends List<? extends CharSequence>>`
* ```
* GenericTypeBuilder().withName("T").withExtendsBound(
* GenericTypeBuilder().withType(List::class.codeType).withExtendsBound(
* GenericTypeBuilder().wildcard().withExtendsBound(CharSequence::class.codeType).build()
* ).build()
* )
* ```
*
* You may also prefer the [Generic] style:
* ```
* Generic.type("T").extends_(
* Generic.type(List::class.codeType).extends_(
* Generic.wildcard().extends_(CharSequence::class.codeType)
* )
* )
* ```
*
* **Attention: All calls of the methods of [Generic] class creates a copy of the `bound` array (except the first call), if you mind performance use the [GenericTypeBuilder]**
*
*/
class GenericTypeBuilder() : GenericType.Builder<GenericType, GenericTypeBuilder> {
var name: String? = null
var type: KoresType? = null
var bounds: MutableList<GenericType.Bound> = mutableListOf()
constructor(defaults: GenericType) : this() {
if (!defaults.isType)
this.name = defaults.name
else
this.type = defaults.resolvedType
this.bounds = defaults.bounds.toMutableList()
}
override fun name(value: String): GenericType.Builder<GenericType, GenericTypeBuilder> {
this.name = value
this.type = null
return this
}
override fun wildcard(): GenericType.Builder<GenericType, GenericTypeBuilder> {
this.name = "*"
this.type = null
return this
}
override fun type(value: Type): GenericType.Builder<GenericType, GenericTypeBuilder> {
this.name = null
this.type = value.koresType
return this
}
override fun bounds(value: Array<GenericType.Bound>): GenericType.Builder<GenericType, GenericTypeBuilder> {
this.bounds = value.toMutableList()
return this
}
override fun addBounds(bounds: Array<GenericType.Bound>): GenericType.Builder<GenericType, GenericTypeBuilder> {
bounds.forEach {
this.bounds.add(it)
}
return this
}
override fun addBounds(bounds: Collection<GenericType.Bound>): GenericType.Builder<GenericType, GenericTypeBuilder> {
this.bounds.addAll(bounds)
return this
}
override fun addBound(bound: GenericType.Bound): GenericType.Builder<GenericType, GenericTypeBuilder> {
this.bounds.add(bound)
return this
}
override fun addExtendsBound(value: Type): GenericType.Builder<GenericType, GenericTypeBuilder> {
this.bounds.add(GenericType.Extends(value.koresType))
return this
}
override fun addSuperBound(value: Type): GenericType.Builder<GenericType, GenericTypeBuilder> {
this.bounds.add(GenericType.Super(value.koresType))
return this
}
override fun addOfBound(value: Type): GenericType.Builder<GenericType, GenericTypeBuilder> {
this.bounds.add(GenericType.GenericBound(value.koresType))
return this
}
override fun build(): GenericType = GenericTypeImpl(
name = this.name,
codeType = this.type,
bounds = this.bounds.toTypedArray()
)
companion object {
@JvmStatic
fun builder() = GenericTypeBuilder()
}
} | src/main/kotlin/com/github/jonathanxd/kores/type/GenericTypeBuilder.kt | 2368444122 |
@file:Suppress("unused")
package katas.kotlin.leetcode.license_key_formatting
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/problems/license-key-formatting/
*/
class LicenseKeyFormattingTests {
@Test fun `format license key`() {
licenseKeyFormatting("ABCD", width = 4) shouldEqual "ABCD"
licenseKeyFormatting("ABCD", width = 5) shouldEqual "ABCD"
licenseKeyFormatting("ABCD", width = 1) shouldEqual "A-B-C-D"
licenseKeyFormatting("AB-CD", width = 1) shouldEqual "A-B-C-D"
licenseKeyFormatting("A-BCD", width = 2) shouldEqual "AB-CD"
licenseKeyFormatting("AB-CD", width = 2) shouldEqual "AB-CD"
licenseKeyFormatting("ABC-D", width = 2) shouldEqual "AB-CD"
licenseKeyFormatting("ABCDE", width = 2) shouldEqual "A-BC-DE"
licenseKeyFormatting("5F3Z-2e-9-w", width = 4) shouldEqual "5F3Z-2E9W"
licenseKeyFormatting("2-5g-3-J", width = 2) shouldEqual "2-5G-3J"
}
private fun licenseKeyFormatting(s: String, width: Int): String {
var result = ""
var count = 0
(s.length - 1 downTo 0).forEach { i ->
if (s[i] != '-') {
result += s[i].toUpperCase()
if (++count % width == 0 && i != 0) result += "-"
}
}
return result.reversed()
}
private fun licenseKeyFormatting_(s: String, width: Int): String {
return s.reversed().split("-")
.joinToString("").windowed(size = width, step = width, partialWindows = true)
.joinToString("-").reversed()
.toUpperCase()
}
}
| kotlin/src/katas/kotlin/leetcode/license_key_formatting/LicenseKeyFormatting.kt | 4040525756 |
val xx = (fu<caret>n Int.(x: Int, y: Int) = this + y).invoke(1, 2, 3) | plugins/kotlin/idea/tests/testData/refactoring/inline/anonymousFunction/withReceiverAsInvoke.kt | 2422042870 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.wizard
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.util.UserDataHolderBase
class RootNewProjectWizardStep(override val context: WizardContext) : NewProjectWizardStep {
override val data = UserDataHolderBase()
override val propertyGraph = PropertyGraph("New project wizard")
override var keywords = NewProjectWizardStep.Keywords()
} | platform/platform-impl/src/com/intellij/ide/wizard/RootNewProjectWizardStep.kt | 3930246312 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.busschedule.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.busschedule.BusScheduleApplication
import com.example.busschedule.data.BusSchedule
import com.example.busschedule.data.BusScheduleDao
import kotlinx.coroutines.flow.Flow
/*
* View model for Bus Schedule
* contains methods to access Room DB through [busScheduleDao]
*/
class BusScheduleViewModel(private val busScheduleDao: BusScheduleDao): ViewModel() {
// Get full bus schedule from Room DB
fun getFullSchedule(): Flow<List<BusSchedule>> = busScheduleDao.getAll()
// Get bus schedule based on the stop name from Room DB
fun getScheduleFor(stopName: String): Flow<List<BusSchedule>> =
busScheduleDao.getByStopName(stopName)
companion object {
val factory : ViewModelProvider.Factory = viewModelFactory {
initializer {
val application = (this[APPLICATION_KEY] as BusScheduleApplication)
BusScheduleViewModel(application.database.busScheduleDao())
}
}
}
}
| app/src/main/java/com/example/busschedule/ui/BusScheduleViewModel.kt | 1579328340 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.intellij.ideabuck.actions.select
import com.facebook.buck.intellij.ideabuck.actions.select.BuckKotlinTestClassDetectorTest.MockPotentialTestClass
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/** Tests [BuckKotlinTestDetector] */
class BuckKotlinTestFunctionDetectorTest {
@Test
fun testSimpleClassNotATest() {
val notATestClass = MockPotentialTestClass()
val notATestFunction = MockPotentialTestFunction(containingClass = notATestClass)
assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction))
}
@Test
fun testAbstractClassNotATest() {
val notATestClass = MockPotentialTestClass(isAbstract = true)
val notATestFunction =
MockPotentialTestFunction(containingClass = notATestClass, isAbstract = true)
assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction))
}
@Test
fun testJUnit3TestCase() {
val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase")
val notATestFunction = MockPotentialTestFunction(containingClass = testClass)
assertTrue(BuckKotlinTestDetector.isTestFunction(notATestFunction))
}
@Test
fun testJUnit3TestCaseNotTestWrongFunctionName() {
val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase")
val notATestFunction =
MockPotentialTestFunction(
containingClass = testClass, functionName = "doesn'tStartWithTest")
assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction))
}
@Test
fun testJUnit3TestCaseNotTestPrivateFunction() {
val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase")
val notATestFunction = MockPotentialTestFunction(containingClass = testClass, isPublic = false)
assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction))
}
@Test
fun testJUnit3TestCaseNotTestAbstractFunction() {
val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase")
val notATestFunction = MockPotentialTestFunction(containingClass = testClass, isAbstract = true)
assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction))
}
@Test
fun testJUnit3TestCaseNotTestFunctionHasParameters() {
val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase")
val notATestFunction =
MockPotentialTestFunction(containingClass = testClass, hasParameters = true)
assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction))
}
@Test
fun testPrivateJUnit3TestCaseNotATest() {
val notATestClass =
MockPotentialTestClass(superClass = "junit.framework.TestCase", isPrivate = true)
val notATestFunction = MockPotentialTestFunction(containingClass = notATestClass)
assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction))
}
@Test
fun testNotAccessibleJUnit3TestCaseNotATest() {
val notATestClass =
MockPotentialTestClass(superClass = "junit.framework.TestCase", isData = true)
val notATestFunction = MockPotentialTestFunction(containingClass = notATestClass)
assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction))
}
@Test
fun testJUnit4TestFunctionWithTestAnnotation() {
val plainClass = MockPotentialTestClass()
val testFunction =
MockPotentialTestFunction(
containingClass = plainClass, functionAnnotations = listOf("org.junit.Test"))
assertTrue(BuckKotlinTestDetector.isTestFunction(testFunction))
}
@Test
fun testJUnit4TestFunctionWithParameters() {
val plainClass = MockPotentialTestClass()
val testFunction =
MockPotentialTestFunction(
containingClass = plainClass,
hasParameters = true, // it's ok to have that in JUnit4
functionAnnotations = listOf("org.junit.Test"))
assertTrue(BuckKotlinTestDetector.isTestFunction(testFunction))
}
@Test
fun testJUnit4FunctionWithRunWithAnnotations() {
val testClass = MockPotentialTestClass(classAnnotations = listOf("org.junit.runner.RunWith"))
val testFunction =
MockPotentialTestFunction(
containingClass = testClass, functionAnnotations = listOf("org.junit.Test"))
assertTrue(BuckKotlinTestDetector.isTestFunction(testFunction))
}
@Test
fun testJUnit4FunctionWithPartialAnnotations() {
val testClass = MockPotentialTestClass(classAnnotations = listOf("org.junit.runner.RunWith"))
val testFunction = MockPotentialTestFunction(containingClass = testClass) // missing @Test
assertFalse(BuckKotlinTestDetector.isTestFunction(testFunction))
}
@Test
fun testJUnit4TestFunctionWithNGAnnotation() {
val testFunction =
MockPotentialTestFunction(
containingClass = MockPotentialTestClass(),
functionAnnotations = listOf("org.testng.annotations.Test"))
assertTrue(BuckKotlinTestDetector.isTestFunction(testFunction))
}
@Test
fun testJUnit4TestAbstractFunctionWithNGAnnotation() {
val testFunction =
MockPotentialTestFunction(
containingClass = MockPotentialTestClass(),
isAbstract = true,
functionAnnotations = listOf("org.testng.annotations.Test"))
assertFalse(BuckKotlinTestDetector.isTestFunction(testFunction))
}
}
class MockPotentialTestFunction(
private val functionAnnotations: List<String> = emptyList(),
private val functionName: String = "testJunit3Function",
private val isAbstract: Boolean = false,
private val isPublic: Boolean = true,
private val hasReturnType: Boolean = false,
private val hasParameters: Boolean = false,
private val containingClass: PotentialTestClass
) : PotentialTestFunction {
override fun getContainingClass(): PotentialTestClass? {
return containingClass
}
override fun isPotentialTestFunction(): Boolean = !isAbstract
override fun hasAnnotation(annotationName: String): Boolean =
functionAnnotations.contains(annotationName)
override fun isJUnit3TestMethod(): Boolean {
return isPublic &&
!isAbstract &&
!hasReturnType &&
!hasParameters &&
functionName.startsWith("test")
}
}
| tools/ideabuck/tests/unit/com/facebook/buck/intellij/ideabuck/actions/select/BuckKotlinTestFunctionDetectorTest.kt | 2856323463 |
package top.zbeboy.isy.glue.system
import com.alibaba.fastjson.JSONObject
import org.elasticsearch.index.query.QueryBuilder
import org.elasticsearch.index.query.QueryBuilders
import org.elasticsearch.search.sort.SortBuilders
import org.elasticsearch.search.sort.SortOrder
import org.springframework.data.domain.Page
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Repository
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import top.zbeboy.isy.elastic.pojo.SystemLogElastic
import top.zbeboy.isy.elastic.repository.SystemLogElasticRepository
import top.zbeboy.isy.glue.plugin.ElasticPlugin
import top.zbeboy.isy.glue.util.ResultUtils
import top.zbeboy.isy.service.util.DateTimeUtils
import top.zbeboy.isy.service.util.SQLQueryUtils
import top.zbeboy.isy.web.bean.system.log.SystemLogBean
import top.zbeboy.isy.web.util.DataTablesUtils
import java.util.*
import javax.annotation.Resource
/**
* Created by zbeboy 2017-10-31 .
**/
@Repository("systemLogGlue")
open class SystemLogGlueImpl : ElasticPlugin<SystemLogBean>(), SystemLogGlue {
@Resource
open lateinit var systemLogElasticRepository: SystemLogElasticRepository
override fun findAllByPage(dataTablesUtils: DataTablesUtils<SystemLogBean>): ResultUtils<List<SystemLogBean>> {
val search = dataTablesUtils.search
val resultUtils = ResultUtils<List<SystemLogBean>>()
val systemLogElasticPage = systemLogElasticRepository.search(buildSearchQuery(search, dataTablesUtils, false))
return resultUtils.data(dataBuilder(systemLogElasticPage)).totalElements(systemLogElasticPage.totalElements)
}
override fun countAll(): Long {
return systemLogElasticRepository.count()
}
@Async
override fun save(systemLogElastic: SystemLogElastic) {
systemLogElasticRepository.save(systemLogElastic)
}
/**
* 构建新数据
*
* @param systemLogElasticPage 分页数据
* @return 新数据
*/
private fun dataBuilder(systemLogElasticPage: Page<SystemLogElastic>): List<SystemLogBean> {
val systemLogs = ArrayList<SystemLogBean>()
systemLogElasticPage.content.forEach { s ->
val systemLogBean = SystemLogBean()
systemLogBean.systemLogId = s.systemLogId
systemLogBean.behavior = s.behavior
systemLogBean.operatingTime = s.operatingTime
systemLogBean.username = s.username
systemLogBean.ipAddress = s.ipAddress
val date = DateTimeUtils.timestampToDate(s.operatingTime!!)
systemLogBean.operatingTimeNew = DateTimeUtils.formatDate(date)
systemLogs.add(systemLogBean)
}
return systemLogs
}
/**
* 系统日志全局搜索条件
*
* @param search 搜索参数
* @return 搜索条件
*/
override fun searchCondition(search: JSONObject?): QueryBuilder? {
val bluerBuilder = QueryBuilders.boolQuery()
if (!ObjectUtils.isEmpty(search)) {
val username = StringUtils.trimWhitespace(search!!.getString("username"))
val behavior = StringUtils.trimWhitespace(search.getString("behavior"))
val ipAddress = StringUtils.trimWhitespace(search.getString("ipAddress"))
if (StringUtils.hasLength(username)) {
val wildcardQueryBuilder = QueryBuilders.wildcardQuery("username", SQLQueryUtils.elasticLikeAllParam(username))
bluerBuilder.must(wildcardQueryBuilder)
}
if (StringUtils.hasLength(behavior)) {
val matchQueryBuilder = QueryBuilders.matchPhraseQuery("behavior", behavior)
bluerBuilder.must(matchQueryBuilder)
}
if (StringUtils.hasLength(ipAddress)) {
val wildcardQueryBuilder = QueryBuilders.wildcardQuery("ipAddress", SQLQueryUtils.elasticLikeAllParam(ipAddress))
bluerBuilder.must(wildcardQueryBuilder)
}
}
return bluerBuilder
}
/**
* 系统日志排序
*
* @param dataTablesUtils datatables工具类
* @param nativeSearchQueryBuilder 查询器
*/
override fun sortCondition(dataTablesUtils: DataTablesUtils<SystemLogBean>, nativeSearchQueryBuilder: NativeSearchQueryBuilder): NativeSearchQueryBuilder? {
val orderColumnName = dataTablesUtils.orderColumnName
val orderDir = dataTablesUtils.orderDir
val isAsc = "asc".equals(orderDir, ignoreCase = true)
if (StringUtils.hasLength(orderColumnName)) {
if ("system_log_id".equals(orderColumnName, ignoreCase = true)) {
if (isAsc) {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.ASC).unmappedType("string"))
} else {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.DESC).unmappedType("string"))
}
}
if ("username".equals(orderColumnName, ignoreCase = true)) {
if (isAsc) {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("username.keyword").order(SortOrder.ASC).unmappedType("string"))
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.ASC).unmappedType("string"))
} else {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("username.keyword").order(SortOrder.DESC).unmappedType("string"))
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.DESC).unmappedType("string"))
}
}
if ("behavior".equals(orderColumnName, ignoreCase = true)) {
if (isAsc) {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("behavior.keyword").order(SortOrder.ASC).unmappedType("string"))
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.ASC).unmappedType("string"))
} else {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("behavior.keyword").order(SortOrder.DESC).unmappedType("string"))
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.DESC).unmappedType("string"))
}
}
if ("operating_time".equals(orderColumnName, ignoreCase = true)) {
if (isAsc) {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("operatingTime").order(SortOrder.ASC).unmappedType("long"))
} else {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("operatingTime").order(SortOrder.DESC).unmappedType("long"))
}
}
if ("ip_address".equals(orderColumnName, ignoreCase = true)) {
if (isAsc) {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ipAddress.keyword").order(SortOrder.ASC).unmappedType("string"))
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.ASC).unmappedType("string"))
} else {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ipAddress.keyword").order(SortOrder.DESC).unmappedType("string"))
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.DESC).unmappedType("string"))
}
}
}
return nativeSearchQueryBuilder
}
} | src/main/java/top/zbeboy/isy/glue/system/SystemLogGlueImpl.kt | 509462320 |
package org.firezenk.kartographer.library.core
import org.firezenk.kartographer.library.Logger
import org.firezenk.kartographer.library.core.util.TargetRoute
import org.firezenk.kartographer.library.dsl.route
import org.firezenk.kartographer.library.types.Path
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* Created by Jorge Garrido Oval, aka firezenk on 14/01/18.
* Project: Kartographer
*/
class CoreTest {
lateinit var core: Core
lateinit var move: Move
@Before fun setup() {
core = Core(Any(), Logger())
move = Move(core)
}
@Test fun `given a history with one route on default path, the current route is correct`() {
val route = route {
target = TargetRoute()
anchor = Any()
}
move.routeTo(route)
val currentRoute = core.current()
assertEquals(route, currentRoute)
}
@Test fun `given a history with one route on default path, the current route payload is correct`() {
val route = route {
target = TargetRoute()
params = mapOf("param1" to 1, "param2" to "hi!")
anchor = Any()
}
move.routeTo(route)
val currentParam1 = core.payload<Int>("param1")
val currentParam2 = core.payload<String>("param2")
assertEquals(currentParam1, 1)
assertEquals(currentParam2, "hi!")
}
@Test fun `given a history with some route in a custom path, check if exist will return valid`() {
val validRoute = route {
target = TargetRoute()
path = Path("NOTE")
anchor = Any()
}
val invalidRoute = route {
target = TargetRoute()
path = Path("NONE")
anchor = Any()
}
move.routeTo(validRoute)
assertTrue(core.pathExists(validRoute))
assertFalse(core.pathExists(invalidRoute))
}
@Test fun `given two routes, the second is valid if don't have the same path than the previous one`() {
val validRoute = route {
target = TargetRoute()
path = Path("ONE")
anchor = Any()
}
val invalidRoute = route {
target = TargetRoute()
path = Path("TWO")
anchor = Any()
}
assertTrue(core.pathIsValid(validRoute, invalidRoute))
assertFalse(core.pathIsValid(validRoute, validRoute))
}
} | library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt | 2137756124 |
package org.syncloud.android.discovery
interface Discovery {
fun start()
fun stop()
} | syncloud/src/main/java/org/syncloud/android/discovery/Discovery.kt | 1844543959 |
/*
* 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.stats.completion
import com.intellij.stats.validation.EventLine
import com.intellij.stats.validation.InputSessionValidator
import com.intellij.stats.validation.SessionValidationResult
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.io.File
class ValidatorTest {
private companion object {
const val SESSION_ID = "d09b94c2c1aa"
}
lateinit var validator: InputSessionValidator
val sessionStatuses = hashMapOf<String, Boolean>()
@Before
fun setup() {
sessionStatuses.clear()
val result = object : SessionValidationResult {
override fun addErrorSession(errorSession: List<EventLine>) {
val sessionUid = errorSession.first().sessionUid ?: return
sessionStatuses[sessionUid] = false
}
override fun addValidSession(validSession: List<EventLine>) {
val sessionUid = validSession.first().sessionUid ?: return
sessionStatuses[sessionUid] = true
}
}
validator = InputSessionValidator(result)
}
private fun file(path: String): File {
return File(javaClass.classLoader.getResource(path).file)
}
private fun doTest(fileName: String, isValid: Boolean) {
val file = file("data/$fileName")
validator.validate(file.readLines())
Assert.assertEquals(isValid, sessionStatuses[SESSION_ID])
}
@Test
fun testValidData() = doTest("valid_data.txt", true)
@Test
fun testDataWithAbsentFieldInvalid() = doTest("absent_field.txt", false)
@Test
fun testInvalidWithoutBacket() = doTest("no_bucket.txt", false)
@Test
fun testInvalidWithoutVersion() = doTest("no_version.txt", false)
@Test
fun testDataWithExtraFieldInvalid() = doTest("extra_field.txt", false)
@Test
fun testWrongFactorsDiff() = doTest("wrong_factors_diff.txt", false)
} | plugins/stats-collector/log-events/test/com/intellij/stats/completion/ValidatorTest.kt | 1771368592 |
/*
* 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.diff.comparison
import com.intellij.diff.DiffTestCase
import com.intellij.diff.comparison.ComparisonUtilTestBase.Companion.convertLineFragments
import com.intellij.diff.comparison.ComparisonUtilTestBase.Companion.del
import com.intellij.diff.comparison.ComparisonUtilTestBase.Companion.ins
import com.intellij.diff.comparison.ComparisonUtilTestBase.Companion.mod
import com.intellij.diff.fragments.LineFragment
import com.intellij.diff.tools.util.text.LineOffsetsUtil
import com.intellij.diff.util.IntPair
import com.intellij.diff.util.Range
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.TextRange
import com.intellij.util.containers.ContainerUtil
import java.util.*
class IgnoreComparisonUtilTest : DiffTestCase() {
fun testSimple() {
Test("", "",
"", "",
"", "")
.run()
Test("X", "Y",
" ", " ",
"-", "-")
.run()
Test("X", "Y",
"+", " ",
" ", "-")
.run()
Test("X", "Y",
" ", "+",
"-", " ")
.run()
Test("X", "Y",
"+", "+",
" ", " ")
.run()
Test("X", "",
" ", "",
"-", "")
.run()
Test("X", "",
"+", "",
" ", "")
.run()
Test("", "Y",
"", "+",
"", " ")
.run()
}
fun testSpaces() {
Test("X Y Z", "A B Z",
"++ ", "++ ",
" - ", " - ")
.run()
Test("X Y Z", "A B Z",
" ++", " ++",
"--- ", "--- ")
.run()
Test("X Y Z", "A Y C",
"++ ", "++ ",
" -", " -")
.run()
Test("X Y Z", "A Y C",
"+++++", "+++++",
" ", " ")
.run()
Test("X Y Z", "A B C",
"+ +", "+ +",
"-----", "-----")
.run()
Test("A Y C", "A B C",
"+ +", "+ +",
" - ", " - ")
.run()
Test("A B", "A B",
" ++ ", " + ",
" ", " ")
.run()
Test("A B", "A X",
" ++ ", " + ",
" -", " -")
.run()
Test(" A B", "X B ",
"+ ++ ", " + +",
" - ", "- ")
.run()
Test("A B", "A B",
" + ", " ",
" - ", " ")
.run()
Test("A B", "A B",
" + ", " ",
" -- ", " ")
.run()
}
fun testTrim() {
Test("A B_", "",
" ", "",
"----", "")
.run()
Test("A B_", "",
"++++", "",
" ", "")
.run()
Test("A B_", "",
" +", "",
"----", "")
.run()
Test("A B_", "",
"+++ ", "",
"----", "")
.run()
Test("A B_", "",
"+ +", "",
"----", "")
.run()
Test("A B_", "",
"+ ++", "",
"----", "")
.run()
Test("A B_", "",
" +++", "",
"----", "")
.run()
Test("A_B_C_", "",
" +++++", "",
"-- ", "")
.run()
Test("A_B_C_", "",
"++++ +", "",
" --", "")
.run()
}
fun testLines() {
Test("X_", "X_Y_",
" ", " ",
" ", " --")
.changedLinesNumber(0, 1)
.run()
Test("X_", "X_Y_",
" ", " ++",
" ", " ")
.run()
Test("X_", "X_Y_",
" ", "++ ",
"- ", " - ")
.changedLines(mod(0, 1, 1, 1))
.run()
Test("X_Y_", "X_",
" ", " ",
" --", " ")
.run()
Test("X_Y_", "X_",
" ++", " ",
" ", " ")
.run()
Test("X_Y_Z", "X_B_Z",
" ", " ",
" - ", " - ")
.changedLinesNumber(1, 1)
.run()
Test("X_Y_Z", "X_Y_Z",
" ", " ",
" ", " ")
.run()
Test("X_Y_Z", "X_Y_Z",
" + + ", " + + ",
" ", " ")
.run()
Test("X_Y_Z", "A_Y_Z",
" ", " ",
"- ", "- ")
.run()
Test("X_Y_Z", "A_Y_Z",
"++ ", " ",
" ", "-- ")
.changedLines(ins(1, 0, 1))
.run()
Test("X_Y_Z", "A_Y_Z",
"++ ", "++ ",
" ", " ")
.run()
Test("X_Y_Z", "A_Y_Z",
" ", " ++ ",
"- ", "- ")
.run()
Test("X_Y_Z", "X_Y_C",
" ", " ",
" -", " -")
.run()
Test("X_Y_Z", "X_Y_C",
" ", " +",
" -", " ")
.run()
Test("X_Y_Z", "X_Y_C",
" +", " ",
" ", " -")
.run()
Test("X_Y_Z", "X_B_Z",
" ", " ",
" - ", " - ")
.run()
Test("X_Y_Z", "X_B_Z",
" + ", " + ",
" ", " ")
.run()
Test("X_Y_Z", "X_B_Z",
" + ", " ",
" ", " - ")
.run()
Test("X_Y_Z", "X_B_Z",
" + ", " ",
" ", " - ")
.run()
}
fun testTrimLines() {
Test("X_W_Y_W_Z", "X_B_Z",
" +++ +++ ", " + + ",
" - ", " - ")
.changedLinesNumber(1, 1)
.run()
Test("X_W_W_Z", "X_Z",
" +++++ ", " + ",
" ", " ")
.changedLinesNumber(0, 0)
.run()
Test("X_W 1 W_Y_W 2 W_Z", "X_W 3 W_B_W 4 W_Z",
" + + ", " + + ",
" - ", " - ")
.changedLinesNumber(1, 1)
.run()
Test("X_W W W_Z", "X_W W_ W_Z",
" + + + + ", " + + ++ + ",
" ", " ")
.changedLinesNumber(0, 0)
.run()
Test("X_W M W_Z", "X_W W_ W_Z",
" + + + + ", " + + ++ + ",
" - ", " - ")
.changedLinesNumber(1, 2)
.run()
}
fun testNoInnerChanges() {
Test("X_W_Y_W_Z", "X_B_Z",
" +++ +++ ", " + + ",
" -- ", " -- ")
.changedLinesNumber(1, 1)
.noInnerChanges()
.run()
Test("X_W_W_Z", "X_Z",
" +++++ ", " + ",
" ", " ")
.changedLinesNumber(0, 0)
.noInnerChanges()
.run()
Test("X_W 1 W_Y_W 2 W_Z", "X_W 3 W_B_W 4 W_Z",
" + + ", " + + ",
" -- ", " -- ")
.changedLinesNumber(1, 1)
.noInnerChanges()
.run()
Test("X_W W W_Z", "X_W W_ W_Z",
" + + + + ", " + + ++ + ",
" ------ ", " ------- ")
.changedLinesNumber(1, 2)
.noInnerChanges()
.run()
Test("X_W M W_Z", "X_W W_ W_Z",
" + + + + ", " + + ++ + ",
" ------ ", " ------- ")
.changedLinesNumber(1, 2)
.noInnerChanges()
.run()
}
fun `test trim vs trimExpand for inner ranges`() {
Test("X M Y Z", "A B Y C",
"+ +", "+ +",
" -- ", " -- ")
.run()
Test("X M Y Z", "A B Y C",
" + ", " + ",
"-- -", "-- -")
.run()
Test("X MZ Y Z", "A BZ Y C",
" + ", " + ",
"---- -", "---- -")
.run()
Test("ZX M Y Z", "A B Y C",
" + +", "+ +",
"---- ", " -- ")
.run()
Test("X Y", "XY",
" + ", " ",
"---", "--")
.changedLinesNumber(1, 1)
.run()
}
fun `test Java samples`() {
Test("System . out.println(\"Hello world\");", "System.out.println(\"Hello world\");",
" + + . . ", " . . ",
" . . ", " . . ")
.changedLinesNumber(0, 0)
.run()
Test(" System . out . println(\"Hello world\") ; ", "System.out.println(\"Hello world\");",
"+ + + + + . . + +", " . . ",
" . - . ", " . . ")
.run()
Test("import java.util.Random;_import java.util.List;__class Test {_}", "import java.util.List;_import java.util.Timer;__class Foo {_}",
"+++++++++++++++++++++++++++++++++++++++++++++++++ ", "++++++++++++++++++++++++++++++++++++++++++++++++ ",
" ---- ", " --- ")
.changedLinesNumber(1, 1)
.run()
Test("final_int x = 0;", "final int Y = 0;",
" + + + + ", " + + + + ",
" - ", " - ")
.changedLinesNumber(2, 1)
.changedLines(mod(0, 0, 2, 1))
.run()
Test("int X = 0;", "intX = 0;",
" + + + ", " + + ",
"----- ", "---- ")
.changedLinesNumber(1, 1)
.run()
Test("import xx.x;_import xx.y;_import xx.z;", "import xx.x;_// import xx.y;_import xx.z;",
"++++++++++++++++++++++++++++++++++++++", "+++++++++++++ +++++++++++++",
" ", " ---------------- ")
.changedLinesNumber(0, 1)
.run()
Test("import xx.x;_import xx.y;_import xx.z;_import xx.a;", "//import xx.x;_import xx.y;_import xx.z;_//import xx.a;",
"+++++++++++++++++++++++++++++++++++++++++++++++++++", " +++++++++++++++++++++++++++ ",
" ", "--------------- --------------")
.changedLinesNumber(0, 2)
.run()
Test("foo();_bar 'text';", "foo();_// TODO: bar 'text'",
" + ", " ++++++++++++++++++++",
" -----------", " ")
.changedLines(del(1, 2, 1))
.changedLinesNumber(1, 0)
.run()
Test("import x.A;_import x.B;_import x.C;__@C_class Test { }_", "import x.B;[email protected]_class Test {}_",
"+++++++++++++++++++++++++++++++++++++ + + + + +", "+++++++++++++ + + + +",
" ", " -- ")
.changedLinesNumber(1, 1)
.changedLines(mod(4, 2, 1, 1))
.run()
}
fun `test Java bad samples`() {
//TODO
Test("System.out.println (\"Hello world\");", "System.out.println(\"Hello world\");",
" . + . ", " . . ",
" - . - . ", " . . ")
.run()
Test("private static final Cleaner NOP = () -> { };_", "private static final Cleaner NOP = () -> { _ };_",
" + + + + + + + + + +", " + + + + + + + + +++ +",
" -- ", " -- ")
.run()
Test("private static final Cleaner NOP = () -> { };", "private static final Cleaner NOP = () -> { _ };",
" + + + + + + + + + ", " + + + + + + + + +++ ",
" ", " ")
.run()
}
fun `test explicit blocks`() {
Test("X_a_Y_b_Z", "X_a 1 c_Y_b 1 c_Z",
" ", " +++ +++ ",
" ", " - ")
.ranged(Range(1, 2, 1, 2))
.changedLinesNumber(1, 1)
.run()
Test("X_a_Y_b_Z", "X_a 1 c_Y_b 1 c_Z",
" ", " ++++ +++ ",
" ", " ")
.ranged(Range(1, 2, 1, 2))
.changedLinesNumber(0, 0)
.run()
Test("X_a_Y_b_Z", "X_a 1 c_Y_b 1 c_Z",
" ", " + ",
" ", " --- ")
.ranged(Range(3, 4, 3, 4))
.changedLinesNumber(1, 1)
.run()
Test("X_a_Y_b_Z", "X_a 1 c_Y_b 1 c_Z",
" ", " + ",
" - ", " ---- ")
.ranged(Range(1, 2, 3, 4))
.changedLinesNumber(1, 1)
.run()
Test("X_a_Y_b_Z", "Y_b 1 c_Z",
" ", " + ",
" ", " --- ")
.ranged(Range(3, 4, 1, 2))
.changedLinesNumber(1, 1)
.run()
Test("X_a_Y_b_Z", "Y_c_d_b_Z",
" ", " ++++ ",
" ", " ")
.ranged(Range(3, 4, 1, 4))
.changedLinesNumber(0, 0)
.run()
Test("X_a_Y_Z", "Y_c_d_Z",
" ", " ++++ ",
" ", " ")
.ranged(Range(3, 3, 1, 3))
.changedLinesNumber(0, 0)
.run()
Test("X_a_Y_Z", "Y_c_d_Z",
" ", " ",
" ", " ---- ")
.ranged(Range(3, 3, 1, 3))
.changedLinesNumber(0, 2)
.run()
Test("X_W 1 W_Y_W 2 W_Z", "X_W 3 W_B_W 4 W_Z",
" + + ", " + + ",
" -- ", " -- ")
.ranged(Range(2, 4, 2, 4))
.changedLinesNumber(1, 1)
.noInnerChanges()
.run()
Test("X_W 1 W_Y_W 2 W_Z", "X_W 3 W_B_W 4 W_Z",
" + + ", " + + ",
" -- ", " -- ")
.ranged(Range(1, 5, 1, 5))
.changedLinesNumber(1, 1)
.noInnerChanges()
.run()
Test("X_W 1 W_Y_W 2 W_Z", "X_W 3 W_B_W 4 W_Z",
" + + ", " + + ",
" ", " ")
.ranged(Range(1, 2, 3, 4))
.changedLinesNumber(0, 0)
.noInnerChanges()
.run()
Test("X_a Y_Z", "Y_aY_Z",
" + + ", " + ",
" --- ", " -- ")
.ranged(Range(1, 2, 1, 2))
.changedLinesNumber(1, 1)
.run()
Test("X_a Y_Z", "X_aY_Z",
" + + ", " + ",
" --- ", " -- ")
.ranged(Range(1, 2, 1, 2))
.changedLinesNumber(1, 1)
.run()
}
private inner class Test(val input1: String, val input2: String,
ignored1: String, ignored2: String,
result1: String, result2: String) {
val ignored1: String = ignored1.filterNot { it == '.' }
val ignored2: String = ignored2.filterNot { it == '.' }
val result1: String = result1.filterNot { it == '.' }
val result2: String = result2.filterNot { it == '.' }
private var innerPolicy = InnerFragmentsPolicy.WORDS
private var changedLinesNumber: IntPair? = null
private var range: Range? = null
private var changedLines: List<Couple<IntPair>>? = null
fun noInnerChanges(): Test {
innerPolicy = InnerFragmentsPolicy.NONE
return this
}
fun changedLinesNumber(lines1: Int, lines2: Int): Test {
changedLinesNumber = IntPair(lines1, lines2)
return this
}
fun ranged(range: Range): Test {
this.range = range
return this
}
fun changedLines(vararg expected: Couple<IntPair>): Test {
changedLines = ContainerUtil.list(*expected)
return this
}
fun run() {
assertEquals(input1.length, ignored1.length)
assertEquals(input1.length, result1.length)
assertEquals(input2.length, ignored2.length)
assertEquals(input2.length, result2.length)
val text1 = parseText(input1)
val text2 = parseText(input2)
val ignoredRanges1 = parseIgnored(ignored1)
val ignoredRanges2 = parseIgnored(ignored2)
val ignored1 = ComparisonManagerImpl.collectIgnoredRanges(ignoredRanges1)
val ignored2 = ComparisonManagerImpl.collectIgnoredRanges(ignoredRanges2)
val lineOffsets1 = LineOffsetsUtil.create(text1)
val lineOffsets2 = LineOffsetsUtil.create(text2)
val result = if (range != null) {
MANAGER.compareLinesWithIgnoredRanges(range!!, text1, text2, lineOffsets1, lineOffsets2, ignored1, ignored2, innerPolicy, INDICATOR)
}
else {
MANAGER.compareLinesWithIgnoredRanges(text1, text2, lineOffsets1, lineOffsets2, ignored1, ignored2, innerPolicy, INDICATOR)
}
val expected = Couple(parseExpected(result1), parseExpected(result2))
val actual = parseActual(result)
assertEquals(expected, actual)
if (changedLinesNumber != null) {
val actualLines = countChangedLines(result)
assertEquals(changedLinesNumber, actualLines)
}
if (changedLines != null) {
val actualChangedLines = convertLineFragments(result)
assertOrderedEquals(changedLines!!, actualChangedLines)
}
}
}
private fun parseText(input: String): String {
return input.replace('_', '\n')
}
private fun parseIgnored(ignored: String): List<TextRange> {
assertTrue(ignored.find { it != ' ' && it != '+' } == null)
val result = ArrayList<TextRange>()
ignored.forEachIndexed { index, c ->
if (c == '+') result += TextRange(index, index + 1)
}
return result
}
private fun parseExpected(result: String): BitSet {
assertTrue(result.find { it != ' ' && it != '-' } == null)
val set = BitSet()
result.forEachIndexed { index, c ->
if (c == '-') set.set(index)
}
return set
}
private fun parseActual(result: List<LineFragment>): Couple<BitSet> {
val set1 = BitSet()
val set2 = BitSet()
result.forEach { fragment ->
val inner = fragment.innerFragments
if (inner == null) {
set1.set(fragment.startOffset1, fragment.endOffset1)
set2.set(fragment.startOffset2, fragment.endOffset2)
}
else {
inner.forEach { inner ->
set1.set(fragment.startOffset1 + inner.startOffset1, fragment.startOffset1 + inner.endOffset1)
set2.set(fragment.startOffset2 + inner.startOffset2, fragment.startOffset2 + inner.endOffset2)
}
}
}
return Couple(set1, set2)
}
private fun countChangedLines(result: List<LineFragment>): IntPair {
var count1 = 0
var count2 = 0
result.forEach {
count1 += it.endLine1 - it.startLine1
count2 += it.endLine2 - it.startLine2
}
return IntPair(count1, count2)
}
} | platform/diff-impl/tests/com/intellij/diff/comparison/IgnoreComparisonUtilTest.kt | 676565864 |
package com.planbase.pdf.lm2.attributes
import com.planbase.pdf.lm2.attributes.Padding.Companion.DEFAULT_TEXT_PADDING
import com.planbase.pdf.lm2.attributes.Padding.Companion.NO_PADDING
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.organicdesign.testUtils.EqualsContract.equalsDistinctHashCode
import kotlin.test.Test
class PaddingTest {
@Test
fun staticFactoryTest() {
assertTrue(NO_PADDING == Padding(0.0))
assertTrue(NO_PADDING == Padding(0.0, 0.0, 0.0, 0.0))
assertTrue(DEFAULT_TEXT_PADDING == Padding(1.5, 1.5, 2.0, 1.5))
val (top, right, bottom, left) = Padding(2.0)
assertEquals(2.0, top, 0.0)
assertEquals(2.0, right, 0.0)
assertEquals(2.0, bottom, 0.0)
assertEquals(2.0, left, 0.0)
val (top1, right1, bottom1, left1) = Padding(3.0, 5.0, 7.0, 11.0)
assertEquals(3.0, top1, 0.0)
assertEquals(5.0, right1, 0.0)
assertEquals(7.0, bottom1, 0.0)
assertEquals(11.0, left1, 0.0)
}
@Test
fun equalHashTest() {
// Test first item different
equalsDistinctHashCode(Padding(1.0), Padding(1.0, 1.0), Padding(1.0),
Padding(2.0, 1.0, 1.0, 1.0))
// Test transposed middle items are different (but have same hashcode)
equalsDistinctHashCode(Padding(3.0, 5.0, 7.0, 1.1), Padding(3.0, 5.0, 7.0, 1.1),
Padding(3.0, 5.0, 7.0, 1.1),
Padding(3.0, 7.0, 5.0, 1.1))
// Padding values that differ by less than 0.1 have the same hashcode
// but are not equal. Prove it (also tests last item is different):
equalsDistinctHashCode(Padding(1.0), Padding(1.0, 1.0, 1.0, 1.0), Padding(1.0),
Padding(1.0, 1.0, 1.0, 1.0001))
}
@Test fun withModifiersTest() {
val pad = NO_PADDING
assertEquals(Padding(0.0, 0.0, 0.0, 0.0), pad)
assertEquals(Padding(1.0, 0.0, 0.0, 0.0), pad.withTop(1.0))
assertEquals(Padding(0.0, 3.0, 0.0, 0.0), pad.withRight(3.0))
assertEquals(Padding(0.0, 0.0, 5.0, 0.0), pad.withBottom(5.0))
assertEquals(Padding(0.0, 0.0, 0.0, 7.0), pad.withLeft(7.0))
assertEquals(Padding(7.0, 5.0, 3.0, 1.0),
pad.withTop(7.0)
.withRight(5.0)
.withBottom(3.0)
.withLeft(1.0))
}
} | src/test/java/com/planbase/pdf/lm2/attributes/PaddingTest.kt | 3353956105 |
package io.georocket.output.geojson
import io.georocket.output.Merger
import io.georocket.storage.GeoJsonChunkMeta
import io.vertx.core.buffer.Buffer
import io.vertx.core.json.Json
import io.vertx.core.json.JsonObject
import io.vertx.core.streams.WriteStream
import io.vertx.kotlin.core.json.jsonObjectOf
/**
* Merges chunks to valid GeoJSON documents
* @param optimistic `true` if chunks should be merged optimistically
* without prior initialization. In this mode, the merger will always return
* `FeatureCollection`s.
* @author Michel Kraemer
*/
class GeoJsonMerger(optimistic: Boolean, private val extensionProperties: JsonObject = jsonObjectOf()) :
Merger<GeoJsonChunkMeta> {
companion object {
private const val NOT_SPECIFIED = 0
private const val GEOMETRY_COLLECTION = 1
private const val FEATURE_COLLECTION = 2
private val TRANSITIONS = listOf(
listOf(FEATURE_COLLECTION, GEOMETRY_COLLECTION),
listOf(FEATURE_COLLECTION, GEOMETRY_COLLECTION),
listOf(FEATURE_COLLECTION, FEATURE_COLLECTION)
)
private val RESERVED_PROPERTY_NAMES = listOf("type", "features", "geometries")
}
/**
* `true` if [merge] has been called at least once
*/
private var mergeStarted = false
/**
* True if the header has already been written in [merge]
*/
private var headerWritten = false
/**
* The GeoJSON object type the merged result should have
*/
private var mergedType = if (optimistic) FEATURE_COLLECTION else NOT_SPECIFIED
init {
// check, that all passed extension properties are valid.
val usesReservedProperty = RESERVED_PROPERTY_NAMES.any {
extensionProperties.containsKey(it)
}
if (usesReservedProperty) {
throw IllegalArgumentException("One of the extension properties is invalid, because the property " +
"names \"${RESERVED_PROPERTY_NAMES.joinToString("\", \"")}\" are reserved.")
}
}
private fun writeExtensionProperties(outputStream: WriteStream<Buffer>) {
for ((key, value) in extensionProperties) {
outputStream.write(Json.encodeToBuffer(key))
outputStream.write(Buffer.buffer(":"))
outputStream.write(Json.encodeToBuffer(value))
outputStream.write(Buffer.buffer(","))
}
}
/**
* Write the header to the given [outputStream]
*/
private fun writeHeader(outputStream: WriteStream<Buffer>) {
outputStream.write(Buffer.buffer("{"))
writeExtensionProperties(outputStream)
if (mergedType == FEATURE_COLLECTION) {
outputStream.write(Buffer.buffer("\"type\":\"FeatureCollection\",\"features\":["))
} else if (mergedType == GEOMETRY_COLLECTION) {
outputStream.write(Buffer.buffer("\"type\":\"GeometryCollection\",\"geometries\":["))
}
}
override fun init(chunkMetadata: GeoJsonChunkMeta) {
if (mergeStarted) {
throw IllegalStateException(
"You cannot initialize the merger anymore " +
"after merging has begun"
)
}
if (mergedType == FEATURE_COLLECTION) {
// shortcut: we don't need to analyse the other chunks anymore,
// we already reached the most generic type
return
}
// calculate the type of the merged document
mergedType = if ("Feature" == chunkMetadata.type) {
TRANSITIONS[mergedType][0]
} else {
TRANSITIONS[mergedType][1]
}
}
override suspend fun merge(
chunk: Buffer, chunkMetadata: GeoJsonChunkMeta,
outputStream: WriteStream<Buffer>
) {
mergeStarted = true
if (!headerWritten) {
writeHeader(outputStream)
headerWritten = true
} else {
if (mergedType == FEATURE_COLLECTION || mergedType == GEOMETRY_COLLECTION) {
outputStream.write(Buffer.buffer(","))
} else {
throw IllegalStateException(
"Trying to merge two or more chunks but " +
"the merger has only been initialized with one chunk."
)
}
}
// check if we have to wrap a geometry into a feature
val wrap = mergedType == FEATURE_COLLECTION && "Feature" != chunkMetadata.type
if (wrap) {
outputStream.write(Buffer.buffer("{\"type\":\"Feature\",\"geometry\":"))
}
outputStream.write(chunk)
if (wrap) {
outputStream.write(Buffer.buffer("}"))
}
}
override fun finish(outputStream: WriteStream<Buffer>) {
if (!headerWritten) {
writeHeader(outputStream)
}
if (mergedType == FEATURE_COLLECTION || mergedType == GEOMETRY_COLLECTION) {
outputStream.write(Buffer.buffer("]}"))
}
}
}
| src/main/kotlin/io/georocket/output/geojson/GeoJsonMerger.kt | 159924021 |
package com.lisuperhong.openeye.ui.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.google.gson.Gson
import com.lisuperhong.openeye.R
import com.lisuperhong.openeye.mvp.model.bean.BaseBean
import com.lisuperhong.openeye.mvp.model.bean.SquareCard
import com.lisuperhong.openeye.utils.DensityUtil
import com.lisuperhong.openeye.utils.ImageLoad
import com.lisuperhong.openeye.utils.JumpActivityUtil
import com.lisuperhong.openeye.utils.TypefaceUtil
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.item_squarecard.view.*
import org.json.JSONException
import org.json.JSONObject
/**
* Author: lisuperhong
* Time: Create on 2018/9/17 10:21
* Github: https://github.com/lisuperhong
* Desc:
*/
class CategoryAdapter(context: Context, dataList: ArrayList<BaseBean.Item>) :
RecyclerView.Adapter<CategoryAdapter.ItemHolder>() {
private var context: Context? = null
private var dataList: ArrayList<BaseBean.Item>
init {
this.context = context
this.dataList = dataList
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryAdapter.ItemHolder {
val view = LayoutInflater.from(context)
.inflate(R.layout.item_squarecard, parent, false)
return ItemHolder(view)
}
override fun getItemCount(): Int {
return dataList.size
}
override fun onBindViewHolder(holder: CategoryAdapter.ItemHolder, position: Int) {
val item = dataList[position]
val gson = Gson()
val dataMap = item.data as Map<*, *>
var dataJson: JSONObject? = null
try {
dataJson = JSONObject(dataMap)
} catch (e: JSONException) {
Logger.d(e.printStackTrace())
}
val squareCard = gson.fromJson(dataJson.toString(), SquareCard::class.java)
holder.squareCardTv.typeface =
TypefaceUtil.getTypefaceFromAsset(TypefaceUtil.FZLanTingCuHei)
holder.squareCardTv.text = squareCard.title
if (item.type == "squareCard") {
val width =
(DensityUtil.getScreenWidth(context!!) - DensityUtil.dip2px(context!!, 8f)) / 2
ImageLoad.loadImage(holder.squareCardIv, squareCard.image, width, width)
} else if (item.type == "rectangleCard") {
val width = DensityUtil.getScreenWidth(context!!) - DensityUtil.dip2px(context!!, 4f)
ImageLoad.loadImage(holder.squareCardIv, squareCard.image, width, width / 2)
}
holder.squareCardRl.setOnClickListener {
JumpActivityUtil.parseActionUrl(context!!, squareCard.actionUrl)
}
}
private fun clearAll() = dataList.clear()
/**
* 初始化或刷新数据
*/
fun setRefreshData(datas: ArrayList<BaseBean.Item>) {
notifyItemRangeRemoved(0, itemCount)
clearAll()
dataList.addAll(datas)
notifyItemRangeInserted(0, datas.size)
}
class ItemHolder(view: View) : RecyclerView.ViewHolder(view) {
var squareCardRl: RelativeLayout = view.squareCardRl
var squareCardIv: ImageView = view.squareCardIv
var squareCardTv: TextView = view.squareCardTv
}
} | KaiyanModule/src/main/java/com/lisuperhong/openeye/ui/adapter/CategoryAdapter.kt | 411722565 |
package hamburg.remme.tinygit.domain
class Rebase(val next: Int, val last: Int) {
operator fun component1() = next
operator fun component2() = last
}
| src/main/kotlin/hamburg/remme/tinygit/domain/Rebase.kt | 1752950357 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.inspections.sideonly
import com.demonwav.mcdev.util.findContainingClass
import com.intellij.psi.PsiReferenceExpression
import com.intellij.psi.impl.source.PsiFieldImpl
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import org.jetbrains.annotations.Nls
class VariableUseSideOnlyInspection : BaseInspection() {
@Nls
override fun getDisplayName() = "Invalid usage of variable annotated with @SideOnly"
override fun buildErrorString(vararg infos: Any): String {
val error = infos[0] as Error
return error.getErrorString(*SideOnlyUtil.getSubArray(infos))
}
override fun getStaticDescription() =
"Variables which are declared with a @SideOnly annotation can only be used " +
"in matching @SideOnly classes and methods."
override fun buildVisitor(): BaseInspectionVisitor {
return object : BaseInspectionVisitor() {
override fun visitReferenceExpression(expression: PsiReferenceExpression?) {
if (!SideOnlyUtil.beginningCheck(expression!!)) {
return
}
val declaration = expression.resolve() as? PsiFieldImpl ?: return
var elementSide = SideOnlyUtil.checkField(declaration)
// Check the class(es) the element is declared in
val declarationContainingClass = declaration.containingClass ?: return
val declarationClassHierarchySides = SideOnlyUtil.checkClassHierarchy(declarationContainingClass)
val declarationClassSide = SideOnlyUtil.getFirstSide(declarationClassHierarchySides)
// The element inherits the @SideOnly from it's parent class if it doesn't explicitly set it itself
var inherited = false
if (declarationClassSide !== Side.NONE && (elementSide === Side.INVALID || elementSide === Side.NONE)) {
inherited = true
elementSide = declarationClassSide
}
if (elementSide === Side.INVALID || elementSide === Side.NONE) {
return
}
// Check the class(es) the element is in
val containingClass = expression.findContainingClass() ?: return
val classSide = SideOnlyUtil.getSideForClass(containingClass)
var classAnnotated = false
if (classSide !== Side.NONE && classSide !== Side.INVALID) {
if (classSide !== elementSide) {
if (inherited) {
registerError(
expression.element,
Error.ANNOTATED_CLASS_VAR_IN_CROSS_ANNOTATED_CLASS_METHOD,
elementSide.annotation,
classSide.annotation,
declaration
)
} else {
registerError(
expression.element,
Error.ANNOTATED_VAR_IN_CROSS_ANNOTATED_CLASS_METHOD,
elementSide.annotation,
classSide.annotation,
declaration
)
}
}
classAnnotated = true
}
// Check the method the element is in
val methodSide = SideOnlyUtil.checkElementInMethod(expression)
// Put error on for method
if (elementSide !== methodSide && methodSide !== Side.INVALID) {
if (methodSide === Side.NONE) {
// If the class is properly annotated the method doesn't need to also be annotated
if (!classAnnotated) {
if (inherited) {
registerError(
expression.element,
Error.ANNOTATED_CLASS_VAR_IN_UNANNOTATED_METHOD,
elementSide.annotation,
null,
declaration
)
} else {
registerError(
expression.element,
Error.ANNOTATED_VAR_IN_UNANNOTATED_METHOD,
elementSide.annotation,
null,
declaration
)
}
}
} else {
if (inherited) {
registerError(
expression.element,
Error.ANNOTATED_CLASS_VAR_IN_CROSS_ANNOTATED_METHOD,
elementSide.annotation,
methodSide.annotation,
declaration
)
} else {
registerError(
expression.element,
Error.ANNOTATED_VAR_IN_CROSS_ANNOTATED_METHOD,
elementSide.annotation,
methodSide.annotation,
declaration
)
}
}
}
}
}
}
enum class Error {
ANNOTATED_VAR_IN_UNANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Variable annotated with ${infos[0]} cannot be referenced in an un-annotated method."
}
},
ANNOTATED_CLASS_VAR_IN_UNANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Variable declared in a class annotated with ${infos[0]} " +
"cannot be referenced in an un-annotated method."
}
},
ANNOTATED_VAR_IN_CROSS_ANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Variable annotated with ${infos[0]} " +
"cannot be referenced in a method annotated with ${infos[1]}."
}
},
ANNOTATED_CLASS_VAR_IN_CROSS_ANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Variable declared in a class annotated with ${infos[0]} " +
"cannot be referenced in a method annotated with ${infos[1]}."
}
},
ANNOTATED_VAR_IN_CROSS_ANNOTATED_CLASS_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Variable annotated with ${infos[0]} " +
"cannot be referenced in a class annotated with ${infos[1]}."
}
},
ANNOTATED_CLASS_VAR_IN_CROSS_ANNOTATED_CLASS_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Variable declared in a class annotated with ${infos[0]}" +
" cannot be referenced in a class annotated with ${infos[1]}."
}
};
abstract fun getErrorString(vararg infos: Any): String
}
}
| src/main/kotlin/com/demonwav/mcdev/platform/forge/inspections/sideonly/VariableUseSideOnlyInspection.kt | 3430560930 |
package com.github.bumblebee.bot
import com.github.bumblebee.util.logger
import org.springframework.context.annotation.Configuration
import java.util.*
import javax.annotation.PostConstruct
@Configuration
class TimeZoneConfig(private val config: BumblebeeConfig) {
@PostConstruct
fun setupTimezone() {
val timeZone = TimeZone.getTimeZone(config.timezone ?: "UTC")
logger<TimeZoneConfig>().info("Using timezone: $timeZone")
TimeZone.setDefault(timeZone)
}
} | telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/bot/TimeZoneConfig.kt | 2426361011 |
package com.gmail.cristiandeives.motofretado
import android.content.Context
import android.support.annotation.MainThread
import android.support.v4.content.Loader
import android.util.Log
@MainThread
internal class TrackBusPresenterLoader(context: Context) : Loader<TrackBusMvp.Presenter>(context) {
companion object {
private val TAG = TrackBusPresenterLoader::class.java.simpleName
}
private var mPresenter: TrackBusMvp.Presenter? = null
override fun onStartLoading() {
Log.v(TAG, "> onStartLoading()")
if (mPresenter == null) {
forceLoad()
} else {
deliverResult(mPresenter)
}
Log.v(TAG, "< onStartLoading()")
}
override fun onForceLoad() {
Log.v(TAG, "> onForceLoad()")
mPresenter = TrackBusPresenter(context.applicationContext)
deliverResult(mPresenter)
Log.v(TAG, "< onForceLoad()")
}
override fun onReset() {
Log.v(TAG, "> onReset()")
mPresenter = null
Log.v(TAG, "< onReset()")
}
} | app/src/main/java/com/gmail/cristiandeives/motofretado/TrackBusPresenterLoader.kt | 547667500 |
/*
* Copyright (C) 2020 Square, 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 okhttp.regression.compare;
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.apache.hc.client5.http.classic.methods.HttpGet
import org.apache.hc.client5.http.impl.classic.HttpClients
import org.apache.hc.core5.http.HttpVersion
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Apache HttpClient 5.x.
*
* https://hc.apache.org/httpcomponents-client-5.0.x/index.html
*/
@RunWith(AndroidJUnit4::class)
class ApacheHttpClientTest {
private var httpClient = HttpClients.createDefault()
@After fun tearDown() {
httpClient.close()
}
@Test fun get() {
val request = HttpGet("https://google.com/robots.txt")
httpClient.execute(request).use { response ->
assertEquals(200, response.code)
// TODO enable ALPN later
assertEquals(HttpVersion.HTTP_1_1, response.version)
}
}
}
| regression-test/src/androidTest/java/okhttp/regression/compare/ApacheHttpClientTest.kt | 2397048005 |
package com.github.vhromada.catalog.mapper.impl
import com.github.vhromada.catalog.domain.CheatData
import com.github.vhromada.catalog.entity.ChangeCheatData
import com.github.vhromada.catalog.mapper.CheatDataMapper
import org.springframework.stereotype.Component
/**
* A class represents implementation of mapper for cheat's data.
*
* @author Vladimir Hromada
*/
@Component("cheatDataMapper")
class CheatDataMapperImpl : CheatDataMapper {
override fun mapCheatDataList(source: List<CheatData>): List<com.github.vhromada.catalog.entity.CheatData> {
return source.map { mapCheatData(source = it) }
}
override fun mapRequest(source: ChangeCheatData): CheatData {
return CheatData(
id = null,
action = source.action!!,
description = source.description!!
)
}
override fun mapRequests(source: List<ChangeCheatData>): List<CheatData> {
return source.map { mapRequest(source = it) }
}
/**
* Maps cheat's data.
*
* @param source cheat's data
* @return mapped cheat's data
*/
private fun mapCheatData(source: CheatData): com.github.vhromada.catalog.entity.CheatData {
return com.github.vhromada.catalog.entity.CheatData(
action = source.action,
description = source.description
)
}
}
| core/src/main/kotlin/com/github/vhromada/catalog/mapper/impl/CheatDataMapperImpl.kt | 2822564556 |
// 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.quickfix.expectactual
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker
import org.jetbrains.kotlin.idea.refactoring.getExpressionShortText
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AddActualFix(
actualClassOrObject: KtClassOrObject,
missedDeclarations: List<KtDeclaration>
) : KotlinQuickFixAction<KtClassOrObject>(actualClassOrObject) {
private val missedDeclarationPointers = missedDeclarations.map { it.createSmartPointer() }
override fun getFamilyName() = text
override fun getText() = KotlinBundle.message("fix.create.missing.actual.members")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val psiFactory = KtPsiFactory(project)
val codeStyleManager = CodeStyleManager.getInstance(project)
fun PsiElement.clean() {
ShortenReferences.DEFAULT.process(codeStyleManager.reformat(this) as KtElement)
}
val module = element.module ?: return
val checker = TypeAccessibilityChecker.create(project, module)
val errors = linkedMapOf<KtDeclaration, KotlinTypeInaccessibleException>()
for (missedDeclaration in missedDeclarationPointers.mapNotNull { it.element }) {
val actualDeclaration = try {
when (missedDeclaration) {
is KtClassOrObject -> psiFactory.generateClassOrObject(project, false, missedDeclaration, checker)
is KtFunction, is KtProperty -> missedDeclaration.toDescriptor()?.safeAs<CallableMemberDescriptor>()?.let {
generateCallable(project, false, missedDeclaration, it, element, checker = checker)
}
else -> null
} ?: continue
} catch (e: KotlinTypeInaccessibleException) {
errors += missedDeclaration to e
continue
}
if (actualDeclaration is KtPrimaryConstructor) {
if (element.primaryConstructor == null)
element.addAfter(actualDeclaration, element.nameIdentifier).clean()
} else {
element.addDeclaration(actualDeclaration).clean()
}
}
if (errors.isNotEmpty()) {
val message = errors.entries.joinToString(
separator = "\n",
prefix = KotlinBundle.message("fix.create.declaration.error.some.types.inaccessible") + "\n"
) { (declaration, error) ->
getExpressionShortText(declaration) + " -> " + error.message
}
showInaccessibleDeclarationError(element, message, editor)
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val missedDeclarations = DiagnosticFactory.cast(diagnostic, Errors.NO_ACTUAL_CLASS_MEMBER_FOR_EXPECTED_CLASS).b.mapNotNull {
DescriptorToSourceUtils.descriptorToDeclaration(it.first) as? KtDeclaration
}.ifEmpty { return null }
return (diagnostic.psiElement as? KtClassOrObject)?.let {
AddActualFix(it, missedDeclarations)
}
}
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/expectactual/AddActualFix.kt | 2809043236 |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.data.userevent
import androidx.annotation.WorkerThread
import com.google.samples.apps.iosched.model.ConferenceDay
import com.google.samples.apps.iosched.model.Session
import com.google.samples.apps.iosched.model.SessionId
import com.google.samples.apps.iosched.model.userdata.UserEvent
import com.google.samples.apps.iosched.model.userdata.UserSession
import com.google.samples.apps.iosched.shared.data.session.SessionRepository
import com.google.samples.apps.iosched.shared.domain.sessions.LoadUserSessionUseCaseResult
import com.google.samples.apps.iosched.shared.domain.users.ReservationRequestAction
import com.google.samples.apps.iosched.shared.domain.users.ReservationRequestAction.RequestAction
import com.google.samples.apps.iosched.shared.domain.users.ReservationRequestAction.SwapAction
import com.google.samples.apps.iosched.shared.domain.users.StarUpdatedStatus
import com.google.samples.apps.iosched.shared.domain.users.SwapRequestAction
import com.google.samples.apps.iosched.shared.domain.users.SwapRequestParameters
import com.google.samples.apps.iosched.shared.result.Result
import kotlinx.coroutines.ExperimentalCoroutinesApi
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import timber.log.Timber
/**
* Single point of access to user events data associated with a user for the presentation layer.
*/
@ExperimentalCoroutinesApi
@Singleton
open class DefaultSessionAndUserEventRepository @Inject constructor(
private val userEventDataSource: UserEventDataSource,
private val sessionRepository: SessionRepository
) : SessionAndUserEventRepository {
@WorkerThread
override fun getObservableUserEvents(
userId: String?
): Flow<Result<ObservableUserEvents>> {
return flow {
emit(Result.Loading)
// If there is no logged-in user, return the map with null UserEvents
if (userId == null) {
Timber.d(
"""EventRepository: No user logged in,
|returning sessions without user events.""".trimMargin()
)
val allSessions = sessionRepository.getSessions()
val userSessions = mergeUserDataAndSessions(null, allSessions)
emit(
Result.Success(
ObservableUserEvents(
userSessions = userSessions
)
)
)
} else {
emitAll(
userEventDataSource.getObservableUserEvents(userId).map { userEvents ->
Timber.d(
"""EventRepository: Received ${userEvents.userEvents.size}
|user events changes""".trimMargin()
)
// Get the sessions, synchronously
val allSessions = sessionRepository.getSessions()
val userSessions = mergeUserDataAndSessions(userEvents, allSessions)
// TODO(b/122306429) expose user events messages separately
val userEventsMessageSession = allSessions.firstOrNull {
it.id == userEvents.userEventsMessage?.sessionId
}
Result.Success(
ObservableUserEvents(
userSessions = userSessions,
userMessage = userEvents.userEventsMessage,
userMessageSession = userEventsMessageSession
)
)
}
)
}
}
}
override fun getObservableUserEvent(
userId: String?,
eventId: SessionId
): Flow<Result<LoadUserSessionUseCaseResult>> {
// If there is no logged-in user, return the session with a null UserEvent
if (userId == null) {
Timber.d("EventRepository: No user logged in, returning session without user event")
return flow {
val session = sessionRepository.getSession(eventId)
emit(
Result.Success(
LoadUserSessionUseCaseResult(
userSession = UserSession(session, createDefaultUserEvent(session))
)
)
)
}
}
// Observes the user events and merges them with session data.
return userEventDataSource.getObservableUserEvent(userId, eventId).map { userEventResult ->
Timber.d("EventRepository: Received user event changes")
// Get the session, synchronously
val event = sessionRepository.getSession(eventId)
// Merges session with user data and emits the result
val userSession = UserSession(
event,
userEventResult.userEvent ?: createDefaultUserEvent(event)
)
Result.Success(LoadUserSessionUseCaseResult(userSession = userSession))
}
}
override fun getUserEvents(userId: String?): List<UserEvent> {
return userEventDataSource.getUserEvents(userId ?: "")
}
override fun getUserSession(userId: String, sessionId: SessionId): UserSession {
val session = sessionRepository.getSession(sessionId)
val userEvent = userEventDataSource.getUserEvent(userId, sessionId)
?: throw Exception("UserEvent not found")
return UserSession(
session = session,
userEvent = userEvent
)
}
override suspend fun starEvent(
userId: String,
userEvent: UserEvent
): Result<StarUpdatedStatus> = userEventDataSource.starEvent(userId, userEvent)
override suspend fun recordFeedbackSent(userId: String, userEvent: UserEvent): Result<Unit> {
return userEventDataSource.recordFeedbackSent(userId, userEvent)
}
override suspend fun changeReservation(
userId: String,
sessionId: SessionId,
action: ReservationRequestAction
): Result<ReservationRequestAction> {
val sessions = sessionRepository.getSessions().associateBy { it.id }
val userEvents = getUserEvents(userId)
val session = sessionRepository.getSession(sessionId)
val overlappingId = findOverlappingReservationId(session, action, sessions, userEvents)
if (overlappingId != null) {
// If there is already an overlapping reservation, return the result as
// SwapAction is needed.
val overlappingSession = sessionRepository.getSession(overlappingId)
Timber.d(
"""User is trying to reserve a session that overlaps with the
|session id: $overlappingId, title: ${overlappingSession.title}""".trimMargin()
)
return Result.Success(
SwapAction(
SwapRequestParameters(
userId,
fromId = overlappingId,
fromTitle = overlappingSession.title,
toId = sessionId,
toTitle = session.title
)
)
)
}
return userEventDataSource.requestReservation(userId, session, action)
}
override suspend fun swapReservation(
userId: String,
fromId: SessionId,
toId: SessionId
): Result<SwapRequestAction> {
val toSession = sessionRepository.getSession(toId)
val fromSession = sessionRepository.getSession(fromId)
return userEventDataSource.swapReservation(userId, fromSession, toSession)
}
private fun findOverlappingReservationId(
session: Session,
action: ReservationRequestAction,
sessions: Map<String, Session>,
userEvents: List<UserEvent>
): String? {
if (action !is RequestAction) return null
val overlappingUserEvent = userEvents.find {
sessions[it.id]?.isOverlapping(session) == true &&
(it.isReserved() || it.isWaitlisted())
}
return overlappingUserEvent?.id
}
private fun createDefaultUserEvent(session: Session): UserEvent {
return UserEvent(id = session.id)
}
/**
* Merges user data with sessions.
*/
@WorkerThread
private fun mergeUserDataAndSessions(
userData: UserEventsResult?,
allSessions: List<Session>
): List<UserSession> {
// If there is no logged-in user, return the map with null UserEvents
if (userData == null) {
return allSessions.map { UserSession(it, createDefaultUserEvent(it)) }
}
val (userEvents, _) = userData
val eventIdToUserEvent = userEvents.associateBy { it.id }
return allSessions.map {
UserSession(it, eventIdToUserEvent[it.id] ?: createDefaultUserEvent(it))
}
}
override fun getConferenceDays(): List<ConferenceDay> = sessionRepository.getConferenceDays()
}
interface SessionAndUserEventRepository {
// TODO(b/122112739): Repository should not have source dependency on UseCase result
fun getObservableUserEvents(
userId: String?
): Flow<Result<ObservableUserEvents>>
// TODO(b/122112739): Repository should not have source dependency on UseCase result
fun getObservableUserEvent(
userId: String?,
eventId: SessionId
): Flow<Result<LoadUserSessionUseCaseResult>>
fun getUserEvents(userId: String?): List<UserEvent>
suspend fun changeReservation(
userId: String,
sessionId: SessionId,
action: ReservationRequestAction
): Result<ReservationRequestAction>
suspend fun swapReservation(
userId: String,
fromId: SessionId,
toId: SessionId
): Result<SwapRequestAction>
suspend fun starEvent(userId: String, userEvent: UserEvent): Result<StarUpdatedStatus>
suspend fun recordFeedbackSent(
userId: String,
userEvent: UserEvent
): Result<Unit>
fun getConferenceDays(): List<ConferenceDay>
fun getUserSession(userId: String, sessionId: SessionId): UserSession
}
data class ObservableUserEvents(
val userSessions: List<UserSession>,
/** A message to show to the user with important changes like reservation confirmations */
val userMessage: UserEventMessage? = null,
/** The session the user message is about, if any. */
val userMessageSession: Session? = null
)
| shared/src/main/java/com/google/samples/apps/iosched/shared/data/userevent/DefaultSessionAndUserEventRepository.kt | 2309010731 |
package com.github.vhromada.catalog.validator
import com.github.vhromada.catalog.common.exception.InputException
import com.github.vhromada.catalog.entity.ChangeMusicRequest
/**
* An interface represents validator for music.
*
* @author Vladimir Hromada
*/
interface MusicValidator {
/**
* Validates request for changing music.
* <br></br>
* Validation errors:
*
* * Name is null
* * Name is empty string
* * Count of media is null
* * Count of media isn't positive number
*
* @param request request for changing music
* @throws InputException if request for changing music isn't valid
*/
fun validateRequest(request: ChangeMusicRequest)
}
| core/src/main/kotlin/com/github/vhromada/catalog/validator/MusicValidator.kt | 2566781275 |
package no.skatteetaten.aurora.boober.feature
import mu.KotlinLogging
import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec
import no.skatteetaten.aurora.boober.service.CantusService
import no.skatteetaten.aurora.boober.service.ImageMetadata
private const val IMAGE_METADATA_CONTEXT_KEY = "imageMetadata"
private val logger = KotlinLogging.logger {}
abstract class AbstractResolveTagFeature(open val cantusService: CantusService) : Feature {
internal val FeatureContext.imageMetadata: ImageMetadata
get() = this.getContextKey(
IMAGE_METADATA_CONTEXT_KEY
)
abstract fun isActive(spec: AuroraDeploymentSpec): Boolean
fun dockerDigestExistsWarning(context: FeatureContext): String? {
val imageMetadata = context.imageMetadata
return if (imageMetadata.dockerDigest == null) {
"Was unable to resolve dockerDigest for image=${imageMetadata.getFullImagePath()}. Using tag instead."
} else {
null
}
}
fun createImageMetadataContext(repo: String, name: String, tag: String): FeatureContext {
logger.debug("Asking cantus about /$repo/$name/$tag")
val imageInformationResult = cantusService.getImageMetadata(repo, name, tag)
logger.debug("Cantus says: ${imageInformationResult.imagePath} / ${imageInformationResult.imageTag} / ${imageInformationResult.getFullImagePath()}")
return mapOf(
IMAGE_METADATA_CONTEXT_KEY to imageInformationResult
)
}
}
| src/main/kotlin/no/skatteetaten/aurora/boober/feature/AbstractResolveTagFeature.kt | 1973638703 |
// 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.internal.statistic.eventLog
import com.intellij.internal.statistic.StatisticsStringUtil
import java.io.File
import java.nio.file.Path
interface EventLogRecorderConfig {
fun getRecorderId(): String
fun isSendEnabled(): Boolean
fun getLogFilesProvider(): EventLogFilesProvider
}
interface EventLogFilesProvider {
fun getLogFilesDir(): Path?
fun getLogFiles(): List<EventLogFile>
}
class DefaultEventLogFilesProvider(private val dir: Path, private val activeFileProvider: () -> String?): EventLogFilesProvider {
override fun getLogFilesDir(): Path = dir
override fun getLogFiles(): List<EventLogFile> {
val activeFile = activeFileProvider()
val files = File(dir.toUri()).listFiles { f: File -> activeFile == null || !StatisticsStringUtil.equals(f.name, activeFile) }
return files?.map { EventLogFile(it) }?.toList() ?: emptyList()
}
} | platform/statistics/uploader/src/com/intellij/internal/statistic/eventLog/EventLogFilesProvider.kt | 3987894313 |
package com.gportas.paymentkeyboards.view
import rx.Observable
import rx.Observer
/**
* Created by guillermo on 13/10/17.
*/
class RxExpirationDateKeyboardFragment(private val yearsNumber: Int, private val primaryColorResId: Int, private val secondaryColorResId: Int, private val primaryTextColorResId: Int, private val secondaryTextColorResId: Int) : BaseExpirationDateKeyboardFragment(yearsNumber, primaryColorResId, secondaryColorResId, primaryTextColorResId, secondaryTextColorResId) {
private var observers = arrayListOf<Observer<String>>()
private val keyboardObservable = Observable.create(
Observable.OnSubscribe<String> { sub ->
sub.onNext(selectedMonth + "/" + selectedYear)
sub.onCompleted()
}
)
fun addObserver(observer: Observer<String>) {
observers.add(observer)
}
override fun onDateChanged() {
if(selectedMonth != null && selectedYear != null) {
for (observer in observers) {
keyboardObservable.subscribe(observer)
}
}
}
}
| payment-keyboards/src/main/java/com/gportas/paymentkeyboards/view/RxExpirationDateKeyboardFragment.kt | 2556112051 |
package com.aemtools.completion.widget
import com.aemtools.common.constant.const
import com.aemtools.completion.model.WidgetMember
import com.aemtools.completion.model.psi.PsiWidgetDefinition
import com.aemtools.common.util.PsiXmlUtil
import com.aemtools.service.ServiceFacade
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.XmlAttributeInsertHandler
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.psi.xml.XmlToken
/**
* @author Dmytro_Troynikov.
*/
object WidgetVariantsProvider {
val DEFAULT_ATTRIBUTES = listOf("jcr:primaryType", const.XTYPE)
val JCR_PRIMARY_TYPE_VALUES = listOf("nt:unstructured",
"cq:Widget",
"cq:WidgetCollection",
"cq:Dialog",
"cq:TabPanel",
"cq:Panel")
/**
* Generate variants for given completion parameters and widget definition.
*
* @param parameters the completion parameters
* @param widgetDefinition the widget definition
* @return collection of lookup elements
*/
fun generateVariants(parameters: CompletionParameters,
widgetDefinition: PsiWidgetDefinition?)
: Collection<LookupElement> {
val currentElement = parameters.position as XmlToken
val currentPositionType = currentElement.tokenType.toString()
if (widgetXtypeUnknown(widgetDefinition)) {
when (currentPositionType) {
const.xml.XML_ATTRIBUTE_NAME -> {
val collection = genericForName()
if (widgetDefinition != null) {
return collection.filter { it ->
widgetDefinition
.getFieldValue(it.lookupString) == null
}
} else {
return collection
}
}
const.xml.XML_ATTRIBUTE_VALUE -> {
return when (PsiXmlUtil.nameOfAttribute(currentElement)) {
const.XTYPE -> variantsForXTypeValue(currentElement)
const.JCR_PRIMARY_TYPE -> variantsForJcrPrimaryType()
else -> variantsForValue(parameters, widgetDefinition as PsiWidgetDefinition)
}
}
else -> return listOf()
}
}
when (currentPositionType) {
const.xml.XML_ATTRIBUTE_NAME -> return variantsForName(widgetDefinition as PsiWidgetDefinition)
.filter { it ->
widgetDefinition.getFieldValue(it.lookupString) == null
}
const.xml.XML_ATTRIBUTE_VALUE -> {
return when (PsiXmlUtil.nameOfAttribute(currentElement)) {
const.XTYPE -> variantsForXTypeValue(currentElement)
const.JCR_PRIMARY_TYPE -> variantsForJcrPrimaryType()
else -> variantsForValue(parameters, widgetDefinition as PsiWidgetDefinition)
}
}
}
return listOf()
}
private fun widgetXtypeUnknown(widgetDefinition: PsiWidgetDefinition?): Boolean
= widgetDefinition?.getFieldValue(const.XTYPE) == null
private fun genericForName(): Collection<LookupElement> {
return DEFAULT_ATTRIBUTES.map { it ->
LookupElementBuilder.create(it)
.withInsertHandler(XmlAttributeInsertHandler())
}
}
private fun variantsForXTypeValue(currentToken: XmlToken): Collection<LookupElement> {
val widgetDocRepository = ServiceFacade.getWidgetRepository()
val query: String? = PsiXmlUtil.removeCaretPlaceholder(currentToken.text)
val xtypes: List<String> = widgetDocRepository.findXTypes(query)
return xtypes.map { it -> LookupElementBuilder.create(it) }
}
private fun variantsForJcrPrimaryType(): Collection<LookupElement> =
JCR_PRIMARY_TYPE_VALUES.map { it -> LookupElementBuilder.create(it) }
/**
* Give variants for attribute name
*/
private fun variantsForName(widgetDefinition: PsiWidgetDefinition): Collection<LookupElement> {
val widgetDocRepository = ServiceFacade.getWidgetRepository()
val xtype = widgetDefinition.getFieldValue("xtype") ?: return listOf()
val doc = widgetDocRepository.findByXType(xtype) ?: return listOf()
val result = doc.members
.filter { it.memberType != WidgetMember.MemberType.PUBLIC_METHOD }
.map {
LookupElementBuilder.create(it.name)
.withTypeText(it.type)
.withInsertHandler(XmlAttributeInsertHandler())
}
return result
}
/**
* Give variants for attribute value
*/
private fun variantsForValue(parameters: CompletionParameters,
widgetDefinition: PsiWidgetDefinition): Collection<LookupElement> = listOf()
}
| aem-intellij-core/src/main/kotlin/com/aemtools/completion/widget/WidgetVariantsProvider.kt | 3026550700 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight.typing
import com.intellij.psi.PsiReference
import com.jetbrains.python.PyNames
import com.jetbrains.python.inspections.PyInspectionExtension
import com.jetbrains.python.psi.PyElement
import com.jetbrains.python.psi.PyReferenceExpression
import com.jetbrains.python.psi.PySubscriptionExpression
import com.jetbrains.python.psi.PyTargetExpression
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.impl.references.PyOperatorReference
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.types.PyClassLikeType
import com.jetbrains.python.psi.types.PyClassType
import com.jetbrains.python.psi.types.TypeEvalContext
class PyTypingInspectionExtension : PyInspectionExtension() {
override fun ignoreUnresolvedReference(node: PyElement, reference: PsiReference, context: TypeEvalContext): Boolean {
if (node is PySubscriptionExpression && reference is PyOperatorReference && node.referencedName == PyNames.GETITEM) {
val operand = node.operand
val type = context.getType(operand)
if (type is PyClassLikeType && type.isDefinition && isGenericItselfOrDescendant(type, context)) {
// `true` is not returned for the cases like `typing.List[int]`
// because these types contain builtins as a class
if (!isBuiltin(type)) return true
// here is the check that current element is like `typing.List[int]`
// but be careful: builtin collections inherit `typing.Generic` in typeshed
if (operand is PyReferenceExpression) {
val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context)
val resolveResults = operand.getReference(resolveContext).multiResolve(false)
if (resolveResults
.asSequence()
.map { it.element }
.any { it is PyTargetExpression && PyTypingTypeProvider.BUILTIN_COLLECTION_CLASSES.containsKey(it.qualifiedName) }) {
return true
}
}
}
}
return false
}
private fun isGenericItselfOrDescendant(type: PyClassLikeType, context: TypeEvalContext): Boolean {
return PyTypingTypeProvider.GENERIC_CLASSES.contains(type.classQName) || PyTypingTypeProvider.isGeneric(type, context)
}
private fun isBuiltin(type: PyClassLikeType): Boolean {
return if (type is PyClassType) PyBuiltinCache.getInstance(type.pyClass).isBuiltin(type.pyClass) else false
}
}
| python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypingInspectionExtension.kt | 2281471522 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.server
import com.intellij.execution.wsl.WSLDistribution
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent
import org.jetbrains.idea.maven.utils.MavenUtil
import java.io.File
interface MavenDistribution {
val name: String
val mavenHome: File
val version: String?
fun isValid(): Boolean
fun compatibleWith(mavenDistribution: MavenDistribution): Boolean
companion object {
@JvmStatic
fun fromSettings(project: Project?): MavenDistribution? {
val mavenHome = MavenWorkspaceSettingsComponent.getInstance(project).settings.generalSettings.mavenHome
return MavenDistributionConverter().fromString(mavenHome)
}
}
}
class LocalMavenDistribution(override val mavenHome: File, override val name: String) : MavenDistribution {
override val version: String? by lazy {
MavenUtil.getMavenVersion(mavenHome)
}
override fun compatibleWith(mavenDistribution: MavenDistribution): Boolean {
return mavenDistribution == this || FileUtil.filesEqual(mavenDistribution.mavenHome, mavenHome)
}
override fun isValid() = version != null
override fun toString(): String {
return name + "(" + mavenHome + ") v " + version
}
}
class WslMavenDistribution(private val wslDistribution: WSLDistribution,
val pathToMaven: String,
override val name: String) : MavenDistribution {
override val version: String? by lazy {
MavenUtil.getMavenVersion(wslDistribution.getWindowsPath(pathToMaven))
}
override val mavenHome = File(wslDistribution.getWindowsPath(pathToMaven)!!)
override fun compatibleWith(mavenDistribution: MavenDistribution): Boolean {
if (mavenDistribution == this) return true
val another = mavenDistribution as? WslMavenDistribution ?: return false;
return another.wslDistribution == wslDistribution && another.pathToMaven == pathToMaven
}
override fun isValid() = version != null
override fun toString(): String {
return name + "(" + mavenHome + ") v " + version
}
} | plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenDistribution.kt | 1322827335 |
package com.lapismc.minecraft.versioning
/**
* Basic library inclusion rule.
* @param allowed Flag indicating whether the library should be included.
*/
open class Rule(val allowed: Boolean) {
/**
* Checks whether this rule applies to the current system.
* @return True if the rule should be considered, false otherwise.
*/
open fun isApplicable() = true
/**
* Creates a string representation of the rule.
* @return Rule as a string.
*/
override fun toString(): String {
val allowedStr = if(allowed) "Allowed" else "Denied"
return "Rule($allowedStr)"
}
} | src/main/kotlin/com/lapismc/minecraft/versioning/Rule.kt | 557738619 |
package ch.difty.scipamato.publ.persistence.code
import ch.difty.scipamato.common.persistence.code.CodeLikeRepository
import ch.difty.scipamato.publ.entity.Code
/**
* Provides access to the localized [Code]s.
*/
interface CodeRepository : CodeLikeRepository<Code>
| public/public-persistence-jooq/src/main/kotlin/ch/difty/scipamato/publ/persistence/code/CodeRepository.kt | 2928622893 |
/*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.navigation.availability
import android.view.Menu
import android.view.MenuItem
import com.nhaarman.mockitokotlin2.*
import com.vrem.wifianalyzer.MainActivity
import com.vrem.wifianalyzer.R
import com.vrem.wifianalyzer.navigation.options.OptionMenu
import org.junit.After
import org.junit.Test
class FilterOffTest {
private val mainActivity: MainActivity = mock()
private val optionMenu: OptionMenu = mock()
private val menu: Menu = mock()
private val menuItem: MenuItem = mock()
@After
fun tearDown() {
verifyNoMoreInteractions(mainActivity)
verifyNoMoreInteractions(optionMenu)
verifyNoMoreInteractions(menu)
verifyNoMoreInteractions(menuItem)
}
@Test
fun testNavigationOptionFilterOff() {
// setup
whenever(mainActivity.optionMenu).thenReturn(optionMenu)
whenever(optionMenu.menu).thenReturn(menu)
whenever(menu.findItem(R.id.action_filter)).thenReturn(menuItem)
// execute
navigationOptionFilterOff(mainActivity)
// validate
verify(mainActivity).optionMenu
verify(optionMenu).menu
verify(menu).findItem(R.id.action_filter)
verify(menuItem).isVisible = false
}
@Test
fun testNavigationOptionFilterOffWithNoMenuDoesNotSetVisibleFalse() {
// setup
whenever(mainActivity.optionMenu).thenReturn(optionMenu)
whenever(optionMenu.menu).thenReturn(null)
// execute
navigationOptionFilterOff(mainActivity)
// validate
verify(mainActivity).optionMenu
verify(optionMenu).menu
verify(menu, never()).findItem(R.id.action_filter)
verify(menuItem, never()).isVisible = any()
}
} | app/src/test/kotlin/com/vrem/wifianalyzer/navigation/availability/FilterOffTest.kt | 3603613906 |
package org.mtransit.android.ui
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.slidingpanelayout.widget.SlidingPaneLayout
import org.mtransit.android.commons.MTLog
class TwoPaneOnBackPressedCallback(
private val slidingPaneLayout: SlidingPaneLayout,
private val onPanelHandledBackPressedCallback: () -> Unit,
private val onPanelOpenedCallback: () -> Unit,
private val onPanelClosedCallback: () -> Unit,
) : OnBackPressedCallback(
slidingPaneLayout.isSlideable && slidingPaneLayout.isOpen
), SlidingPaneLayout.PanelSlideListener, MTLog.Loggable {
companion object {
private val LOG_TAG = OnBackPressedCallback::class.java.simpleName
}
init {
slidingPaneLayout.addPanelSlideListener(this)
}
override fun getLogTag(): String = LOG_TAG
override fun handleOnBackPressed() {
slidingPaneLayout.closePane()
onPanelHandledBackPressedCallback()
}
override fun onPanelSlide(panel: View, slideOffset: Float) {
}
override fun onPanelOpened(panel: View) {
isEnabled = true
onPanelOpenedCallback()
}
override fun onPanelClosed(panel: View) {
isEnabled = false
onPanelClosedCallback()
}
} | src/main/java/org/mtransit/android/ui/TwoPaneOnBackPressedCallback.kt | 3251821507 |
// 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 git4idea.index
import com.google.common.util.concurrent.MoreExecutors
import com.google.common.util.concurrent.SettableFuture
import com.intellij.idea.Bombed
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.Executor
import com.intellij.testFramework.UsefulTestCase
import com.intellij.vcsUtil.VcsUtil
import git4idea.index.vfs.GitIndexVirtualFile
import git4idea.test.GitSingleRepoTest
import junit.framework.TestCase
import org.apache.commons.lang.RandomStringUtils
import java.util.*
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
@Bombed(year = 2021, month = Calendar.APRIL, day = 30, user = "Julia Beliaeva")
class GitStageTrackerTest : GitSingleRepoTest() {
private var _tracker: GitStageTracker? = null
private val tracker get() = _tracker!!
override fun setUp() {
super.setUp()
_tracker = GitStageTracker(project)
}
override fun tearDown() {
val t = _tracker
_tracker = null
t?.let { Disposer.dispose(it) }
super.tearDown()
}
fun `test unstaged`() {
val fileName = "file.txt"
Executor.touch(fileName, RandomStringUtils.randomAlphanumeric(200))
git("add .")
git("commit -m file")
runWithTrackerUpdate("refresh") {
refresh()
}
assertTrue(trackerState().isEmpty())
val file = projectRoot.findChild(fileName)!!
val document = runReadAction { FileDocumentManager.getInstance().getDocument(file)!! }
runWithTrackerUpdate("setText") {
invokeAndWaitIfNeeded { runWriteAction { document.setText(RandomStringUtils.randomAlphanumeric(100)) } }
}
trackerState().let { state ->
TestCase.assertEquals(GitFileStatus(' ', 'M', VcsUtil.getFilePath(file)),
state.statuses.getValue(VcsUtil.getFilePath(file)))
}
runWithTrackerUpdate("saveDocument") {
invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) }
}
trackerState().let { state ->
TestCase.assertEquals(GitFileStatus(' ', 'M', VcsUtil.getFilePath(file)),
state.statuses.getValue(VcsUtil.getFilePath(file)))
}
}
fun `test staged`() {
val fileName = "file.txt"
Executor.touch(fileName, RandomStringUtils.randomAlphanumeric(200))
git("add .")
git("commit -m file")
runWithTrackerUpdate("refresh") {
refresh()
}
assertTrue(trackerState().isEmpty())
val file = projectRoot.findChild(fileName)!!
val indexFile = GitIndexVirtualFile(project, projectRoot, VcsUtil.getFilePath(file))
val document = runReadAction { FileDocumentManager.getInstance().getDocument(indexFile)!!}
runWithTrackerUpdate("setText") {
invokeAndWaitIfNeeded { runWriteAction { document.setText(RandomStringUtils.randomAlphanumeric(100)) } }
}
trackerState().let { state ->
TestCase.assertEquals(GitFileStatus('M', ' ', VcsUtil.getFilePath(file)),
state.statuses.getValue(VcsUtil.getFilePath(file)))
}
runWithTrackerUpdate("saveDocument") {
invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) }
}
trackerState().let { state ->
TestCase.assertEquals(GitFileStatus('M', 'M', VcsUtil.getFilePath(file)),
state.statuses.getValue(VcsUtil.getFilePath(file)))
}
}
fun `test untracked`() {
val fileName = "file.txt"
val file = runWithTrackerUpdate("createChildData") {
invokeAndWaitIfNeeded { runWriteAction { projectRoot.createChildData(this, fileName) }}
}
TestCase.assertEquals(GitFileStatus('?', '?', VcsUtil.getFilePath(file)),
trackerState().statuses.getValue(VcsUtil.getFilePath(projectRoot, fileName)))
val document = runReadAction { FileDocumentManager.getInstance().getDocument(file)!!}
runWithTrackerUpdate("setText") {
invokeAndWaitIfNeeded { runWriteAction { document.setText(RandomStringUtils.randomAlphanumeric(100)) } }
}
trackerState().let { state ->
TestCase.assertEquals(GitFileStatus('?', '?', VcsUtil.getFilePath(file)),
state.statuses.getValue(VcsUtil.getFilePath(file)))
}
runWithTrackerUpdate("saveDocument") {
invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) }
}
trackerState().let { state ->
TestCase.assertEquals(GitFileStatus('?', '?', VcsUtil.getFilePath(file)),
state.statuses.getValue(VcsUtil.getFilePath(file)))
}
}
private fun trackerState() = tracker.state.rootStates.getValue(projectRoot)
private fun <T> runWithTrackerUpdate(name: String, function: () -> T): T {
return tracker.futureUpdate(name).let { futureUpdate ->
val result = function()
futureUpdate.waitOrCancel()
return@let result
}
}
private fun Future<Unit>.waitOrCancel() {
try {
get(2, TimeUnit.SECONDS)
}
finally {
cancel(false)
}
}
private fun GitStageTracker.futureUpdate(name: String): Future<Unit> {
val removeListener = Disposer.newDisposable("Listener disposable")
val future = SettableFuture.create<Unit>()
addListener(object : GitStageTrackerListener {
override fun update() {
UsefulTestCase.LOG.debug("Refreshed tracker after \"$name\"")
future.set(Unit)
}
}, removeListener)
future.addListener(Runnable { Disposer.dispose(removeListener) }, MoreExecutors.directExecutor())
return future
}
} | plugins/git4idea/tests/git4idea/index/GitStageTrackerTest.kt | 1820726782 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.ui.cloneDialog
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.Project
import com.intellij.openapi.rd.attachChild
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.vcs.CheckoutProvider
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogComponentStateListener
import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtension
import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent
import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame
import com.intellij.ui.*
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.cloneDialog.RepositoryUrlCloneDialogExtension.RepositoryUrlMainExtensionComponent
import java.awt.CardLayout
import java.util.*
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.event.ListSelectionListener
/**
* Top-level UI-component for new clone/checkout dialog
*/
class VcsCloneDialog private constructor(private val project: Project,
initialExtensionClass: Class<out VcsCloneDialogExtension>,
private var initialVcs: Class<out CheckoutProvider>? = null) : DialogWrapper(project) {
private lateinit var extensionList: VcsCloneDialogExtensionList
private val cardLayout = CardLayout()
private val mainPanel = JPanel(cardLayout)
private val extensionComponents: MutableMap<String, VcsCloneDialogExtensionComponent> = HashMap()
private val listModel = CollectionListModel<VcsCloneDialogExtension>(VcsCloneDialogExtension.EP_NAME.extensionList)
private val listener = object : VcsCloneDialogComponentStateListener {
override fun onOkActionNameChanged(name: String) = setOKButtonText(name)
override fun onOkActionEnabled(enabled: Boolean) {
isOKActionEnabled = enabled
}
override fun onListItemChanged() = listModel.allContentsChanged()
}
init {
init()
title = VcsBundle.message("get.from.version.control")
JBUI.size(FlatWelcomeFrame.MAX_DEFAULT_WIDTH, FlatWelcomeFrame.DEFAULT_HEIGHT).let {
rootPane.minimumSize = it
rootPane.preferredSize = it
}
VcsCloneDialogExtension.EP_NAME.findExtension(initialExtensionClass)?.let {
ScrollingUtil.selectItem(extensionList, it)
}
}
override fun getStyle() = DialogStyle.COMPACT
override fun createCenterPanel(): JComponent {
extensionList = VcsCloneDialogExtensionList(listModel).apply {
addListSelectionListener(ListSelectionListener { e ->
val source = e.source as VcsCloneDialogExtensionList
switchComponent(source.selectedValue)
})
preferredSize = JBDimension(200, 0) // width fixed by design
}
val scrollableList = ScrollPaneFactory.createScrollPane(extensionList, true).apply {
border = IdeBorderFactory.createBorder(SideBorder.RIGHT)
}
return JBUI.Panels.simplePanel()
.addToCenter(mainPanel)
.addToLeft(scrollableList)
}
override fun doValidateAll(): List<ValidationInfo> {
return getSelectedComponent()?.doValidateAll() ?: emptyList()
}
override fun getPreferredFocusedComponent(): JComponent? = getSelectedComponent()?.getPreferredFocusedComponent()
fun doClone(checkoutListener: CheckoutProvider.Listener) {
getSelectedComponent()?.doClone(checkoutListener)
}
private fun switchComponent(extension: VcsCloneDialogExtension) {
val extensionId = extension.javaClass.name
val mainComponent = extensionComponents.getOrPut(extensionId, {
val component = extension.createMainComponent(project, ModalityState.stateForComponent(window))
mainPanel.add(component.getView(), extensionId)
disposable.attachChild(component)
component.addComponentStateListener(listener)
component
})
if (mainComponent is RepositoryUrlMainExtensionComponent) {
initialVcs?.let { mainComponent.openForVcs(it) }
}
mainComponent.onComponentSelected()
cardLayout.show(mainPanel, extensionId)
}
private fun getSelectedComponent(): VcsCloneDialogExtensionComponent? {
return extensionComponents[extensionList.selectedValue.javaClass.name]
}
class Builder(private val project: Project) {
fun forExtension(clazz: Class<out VcsCloneDialogExtension> = RepositoryUrlCloneDialogExtension::class.java): VcsCloneDialog {
return VcsCloneDialog(project, clazz, null)
}
fun forVcs(clazz: Class<out CheckoutProvider>): VcsCloneDialog {
return VcsCloneDialog(project, RepositoryUrlCloneDialogExtension::class.java, clazz)
}
}
} | platform/vcs-impl/src/com/intellij/util/ui/cloneDialog/VcsCloneDialog.kt | 3327384017 |
// 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 git4idea.config
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import git4idea.i18n.GitBundle
import java.io.File
class MacExecutableProblemHandler(val project: Project) : GitExecutableProblemHandler {
companion object {
val LOG = logger<MacExecutableProblemHandler>()
}
private val tempPath = FileUtil.createTempDirectory("git-install", null)
private val mountPoint = File(tempPath, "mount")
override fun showError(exception: Throwable, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) {
when {
isXcodeLicenseError(exception) -> showXCodeLicenseError(errorNotifier)
isInvalidActiveDeveloperPath(exception) -> showInvalidActiveDeveloperPathError(errorNotifier)
else -> showGenericError(exception, errorNotifier, onErrorResolved)
}
}
private fun showGenericError(exception: Throwable, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) {
errorNotifier.showError(GitBundle.message("executable.error.git.not.installed"),
ErrorNotifier.FixOption.Standard(GitBundle.message("install.download.and.install.action")) {
errorNotifier.executeTask(GitBundle.message("install.downloading.progress"), false) {
try {
val installer = fetchInstaller(errorNotifier) { it.os == "macOS" && it.pkgFileName != null}
if (installer != null) {
val fileName = installer.fileName
val dmgFile = File(tempPath, fileName)
val pkgFileName = installer.pkgFileName!!
if (downloadGit(installer, dmgFile, project, errorNotifier)) {
errorNotifier.changeProgressTitle(GitBundle.message("install.installing.progress"))
installGit(dmgFile, pkgFileName, errorNotifier, onErrorResolved)
}
}
}
finally {
FileUtil.delete(tempPath)
}
}
})
}
private fun installGit(dmgFile: File, pkgFileName: String, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) {
if (attachVolume(dmgFile, errorNotifier)) {
try {
if (installPackageOrShowError(pkgFileName, errorNotifier)) {
errorNotifier.showMessage(GitBundle.message("install.success.message"))
onErrorResolved()
errorNotifier.resetGitExecutable()
}
}
finally {
detachVolume()
}
}
}
private fun attachVolume(file: File, errorNotifier: ErrorNotifier): Boolean {
val cmd = GeneralCommandLine("hdiutil", "attach", "-readonly", "-noautoopen", "-noautofsck", "-nobrowse",
"-mountpoint", mountPoint.path, file.path)
return runOrShowError(cmd, errorNotifier, sudo = false)
}
private fun installPackageOrShowError(pkgFileName: String, errorNotifier: ErrorNotifier) =
runOrShowError(GeneralCommandLine("installer", "-package", "${mountPoint}/$pkgFileName", "-target", "/"),
errorNotifier, sudo = true)
private fun detachVolume() {
runCommand(GeneralCommandLine("hdiutil", "detach", mountPoint.path), sudo = false, onError = {})
}
private fun runOrShowError(commandLine: GeneralCommandLine, errorNotifier: ErrorNotifier, sudo: Boolean): Boolean {
return runCommand(commandLine, sudo) {
showCouldntInstallError(errorNotifier)
}
}
private fun runCommand(commandLine: GeneralCommandLine, sudo: Boolean, onError: () -> Unit): Boolean {
try {
val cmd = if (sudo) ExecUtil.sudoCommand(commandLine, "Install Git") else commandLine
val output = ExecUtil.execAndGetOutput(cmd)
if (output.checkSuccess(LOG)) {
return true
}
LOG.warn(output.stderr)
onError()
return false
}
catch (e: Exception) {
LOG.warn(e)
onError()
return false
}
}
private fun showCouldntInstallError(errorNotifier: ErrorNotifier) {
errorNotifier.showError(GitBundle.message("install.general.error"), getLinkToConfigure(project))
}
private fun showCouldntStartInstallerError(errorNotifier: ErrorNotifier) {
errorNotifier.showError(GitBundle.message("install.mac.error.couldnt.start.command.line.tools"), getLinkToConfigure(project))
}
private fun showXCodeLicenseError(errorNotifier: ErrorNotifier) {
errorNotifier.showError(GitBundle.getString("git.executable.validation.error.xcode.title"),
GitBundle.getString("git.executable.validation.error.xcode.message"),
getLinkToConfigure(project))
}
private fun showInvalidActiveDeveloperPathError(errorNotifier: ErrorNotifier) {
val fixPathOption = ErrorNotifier.FixOption.Standard(GitBundle.message("executable.mac.fix.path.action")) {
errorNotifier.executeTask(GitBundle.message("install.mac.requesting.command.line.tools") + StringUtil.ELLIPSIS, false) {
execXCodeSelectInstall(errorNotifier)
}
}
errorNotifier.showError(GitBundle.message("executable.mac.error.invalid.path.to.command.line.tools"), fixPathOption)
}
/**
* Check if validation failed because the XCode license was not accepted yet
*/
private fun isXcodeLicenseError(exception: Throwable): Boolean =
isXcodeError(exception) { it.contains("Agreeing to the Xcode/iOS license") }
/**
* Check if validation failed because the XCode command line tools were not found
*/
private fun isInvalidActiveDeveloperPath(exception: Throwable): Boolean =
isXcodeError(exception) { it.contains("invalid active developer path") && it.contains("xcrun") }
private fun isXcodeError(exception: Throwable, messageIndicator: (String) -> Boolean): Boolean {
val message = if (exception is GitVersionIdentificationException) {
exception.cause?.message
}
else {
exception.message
}
return (message != null && messageIndicator(message))
}
private fun execXCodeSelectInstall(errorNotifier: ErrorNotifier) {
try {
val cmd = GeneralCommandLine("xcode-select", "--install")
val output = ExecUtil.execAndGetOutput(cmd)
errorNotifier.hideProgress()
if (!output.checkSuccess(LOG)) {
LOG.warn(output.stderr)
showCouldntStartInstallerError(errorNotifier)
}
else {
errorNotifier.resetGitExecutable()
}
}
catch (e: Exception) {
LOG.warn(e)
showCouldntStartInstallerError(errorNotifier)
}
}
} | plugins/git4idea/src/git4idea/config/MacExecutableProblemHandler.kt | 2985144551 |
package com.github.triplet.gradle.play.tasks.internal
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
class CliOptionsTest {
@Test
fun `Bootstrap holder defaults to true values`() {
val holder = BootstrapOptions.Holder()
assertThat(holder.downloadAppDetails).isTrue()
assertThat(holder.downloadListings).isTrue()
assertThat(holder.downloadReleaseNotes).isTrue()
assertThat(holder.downloadProducts).isTrue()
}
@Test
fun `Bootstrap holder sets other flags to false once one is manually updated`() {
val holder = BootstrapOptions.Holder()
holder.downloadAppDetails = true
assertThat(holder.downloadAppDetails).isTrue()
assertThat(holder.downloadListings).isFalse()
assertThat(holder.downloadReleaseNotes).isFalse()
assertThat(holder.downloadProducts).isFalse()
}
}
| play/plugin/src/test/kotlin/com/github/triplet/gradle/play/tasks/internal/CliOptionsTest.kt | 237308683 |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.coroutines.experimental
import kotlin.coroutines.experimental.intrinsics.COROUTINE_SUSPENDED
import kotlin.coroutines.experimental.intrinsics.suspendCoroutineOrReturn
import kotlin.coroutines.experimental.intrinsics.createCoroutineUnchecked
import konan.internal.SafeContinuation
/**
* Starts coroutine with receiver type [R] and result type [T].
* This function creates and start a new, fresh instance of suspendable computation every time it is invoked.
* The [completion] continuation is invoked when coroutine completes with result or exception.
*/
@Suppress("UNCHECKED_CAST")
public fun <R, T> (suspend R.() -> T).startCoroutine(
receiver: R,
completion: Continuation<T>
) {
createCoroutineUnchecked(receiver, completion).resume(Unit)
}
/**
* Starts coroutine without receiver and with result type [T].
* This function creates and start a new, fresh instance of suspendable computation every time it is invoked.
* The [completion] continuation is invoked when coroutine completes with result or exception.
*/
@Suppress("UNCHECKED_CAST")
public fun <T> (suspend () -> T).startCoroutine(
completion: Continuation<T>
) {
createCoroutineUnchecked(completion).resume(Unit)
}
/**
* Creates a coroutine with receiver type [R] and result type [T].
* This function creates a new, fresh instance of suspendable computation every time it is invoked.
*
* To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
* The [completion] continuation is invoked when coroutine completes with result or exception.
* Repeated invocation of any resume function on the resulting continuation produces [IllegalStateException].
*/
@Suppress("UNCHECKED_CAST")
public fun <R, T> (suspend R.() -> T).createCoroutine(
receiver: R,
completion: Continuation<T>
): Continuation<Unit> = SafeContinuation(createCoroutineUnchecked(receiver, completion), COROUTINE_SUSPENDED)
/**
* Creates a coroutine without receiver and with result type [T].
* This function creates a new, fresh instance of suspendable computation every time it is invoked.
*
* To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
* The [completion] continuation is invoked when coroutine completes with result or exception.
* Repeated invocation of any resume function on the resulting continuation produces [IllegalStateException].
*/
@Suppress("UNCHECKED_CAST")
public fun <T> (suspend () -> T).createCoroutine(
completion: Continuation<T>
): Continuation<Unit> = SafeContinuation(createCoroutineUnchecked(completion), COROUTINE_SUSPENDED)
/**
* Obtains the current continuation instance inside suspend functions and suspends
* currently running coroutine.
*
* In this function both [Continuation.resume] and [Continuation.resumeWithException] can be used either synchronously in
* the same stack-frame where suspension function is run or asynchronously later in the same thread or
* from a different thread of execution. Repeated invocation of any resume function produces [IllegalStateException].
*/
public inline suspend fun <T> suspendCoroutine(crossinline block: (Continuation<T>) -> Unit): T =
suspendCoroutineOrReturn { c: Continuation<T> ->
val safe = SafeContinuation(c)
block(safe)
safe.getResult()
}
// INTERNAL DECLARATIONS
@kotlin.internal.InlineOnly
internal inline fun processBareContinuationResume(completion: Continuation<*>, block: () -> Any?) {
try {
val result = block()
if (result !== COROUTINE_SUSPENDED) {
@Suppress("UNCHECKED_CAST") (completion as Continuation<Any?>).resume(result)
}
} catch (t: Throwable) {
completion.resumeWithException(t)
}
}
| runtime/src/main/kotlin/kotlin/coroutines/experimental/CoroutinesLibrary.kt | 2883108925 |
// FILE: 1.kt
package test
class A {
val param = "start"
var result = "fail"
var addParam = "_additional_"
inline fun inlineFun(arg: String, crossinline f: (String) -> Unit) {
{
f(arg + addParam)
}()
}
fun box(): String {
inlineFun("2") { a ->
{
result = param + a
}()
}
return if (result == "start2_additional_") "OK" else "fail: $result"
}
}
// FILE: 2.kt
//NO_CHECK_LAMBDA_INLINING
import test.*
fun box(): String {
return A().box()
}
| backend.native/tests/external/codegen/boxInline/anonymousObject/properRecapturingInClass/lambdaChainSimple.kt | 3586780013 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("TestKt")
package test
private val prop = "O"
private fun test() = "K"
fun box(): String {
return {
prop + test()
}()
}
| backend.native/tests/external/codegen/box/topLevelPrivate/syntheticAccessorInMultiFile.kt | 587892178 |
package org.nextras.orm.intellij.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.util.ProcessingContext
import com.jetbrains.php.PhpIcons
import com.jetbrains.php.PhpIndex
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocProperty
import com.jetbrains.php.lang.psi.elements.MethodReference
import com.jetbrains.php.lang.psi.elements.ParameterList
import org.nextras.orm.intellij.utils.OrmUtils
import org.nextras.orm.intellij.utils.PhpIndexUtils
class PropertyNameCompletionProvider : CompletionProvider<CompletionParameters>() {
companion object {
private val METHODS = arrayOf("setValue", "setReadOnlyValue", "getValue", "hasValue", "getProperty", "getRawProperty")
}
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val el = parameters.position
if (el.parent?.parent !is ParameterList || (el.parent.parent as ParameterList).parameters[0] !== el.parent) {
return
}
val methodReference = el.parent?.parent?.parent as? MethodReference ?: return
if (methodReference.name !in METHODS) {
return
}
val phpIndex = PhpIndex.getInstance(el.project)
val classes = PhpIndexUtils.getByType(methodReference.classReference!!.type, phpIndex)
classes
.filter { OrmUtils.OrmClass.ENTITY.`is`(it, phpIndex) }
.flatMap { it.fields }
.filterIsInstance<PhpDocProperty>()
.forEach {
result.addElement(
LookupElementBuilder.create(it.name)
.withIcon(PhpIcons.FIELD)
.withTypeText(it.type.toString())
)
}
}
}
| src/main/kotlin/org/nextras/orm/intellij/completion/PropertyNameCompletionProvider.kt | 1879434083 |
package com.intellij.settingsSync.config
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.settingsSync.SettingsSyncBundle.message
import com.intellij.settingsSync.SettingsSyncSettings
import com.intellij.settingsSync.auth.SettingsSyncAuthService
import com.intellij.settingsSync.isSettingsSyncEnabled
class SettingsSyncStatusAction : AnAction(message("title.settings.sync")) {
override fun actionPerformed(e: AnActionEvent) {
ShowSettingsUtil.getInstance().showSettingsDialog(null, SettingsSyncConfigurable::class.java)
}
override fun update(e: AnActionEvent) {
val p = e.presentation
if (!isSettingsSyncEnabled()) {
p.isEnabledAndVisible = false
return
}
when(getStatus()) {
SyncStatus.ON -> {
p.icon = AllIcons.General.InspectionsOK // TODO<rv>: Change icon
@Suppress("DialogTitleCapitalization") // we use "is", not "Is
p.text = message("status.action.settings.sync.is.on")
}
SyncStatus.OFF -> {
p.icon = AllIcons.Actions.Cancel // TODO<rv>: Change icon
@Suppress("DialogTitleCapitalization") // we use "is", not "Is
p.text = message("status.action.settings.sync.is.off")
}
SyncStatus.FAILED -> {
p.icon = AllIcons.General.Error
p.text = message("status.action.settings.sync.failed")
}
}
}
private enum class SyncStatus {ON, OFF, FAILED}
private fun getStatus() : SyncStatus {
// TODO<rv>: Support FAILED status
return if (SettingsSyncSettings.getInstance().syncEnabled &&
SettingsSyncAuthService.getInstance().isLoggedIn()) SyncStatus.ON
else SyncStatus.OFF
}
} | plugins/settings-sync/src/com/intellij/settingsSync/config/SettingsSyncStatusAction.kt | 1340988616 |
// 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.formatter
class KotlinPackageEntry(
packageName: String,
val withSubpackages: Boolean
) {
val packageName = packageName.removeSuffix(".*")
companion object {
@JvmField
val ALL_OTHER_IMPORTS_ENTRY = KotlinPackageEntry("<all other imports>", withSubpackages = true)
@JvmField
val ALL_OTHER_ALIAS_IMPORTS_ENTRY = KotlinPackageEntry("<all other alias imports>", withSubpackages = true)
}
fun matchesPackageName(otherPackageName: String): Boolean {
if (otherPackageName.startsWith(packageName)) {
if (otherPackageName.length == packageName.length) return true
if (withSubpackages) {
if (otherPackageName[packageName.length] == '.') return true
}
}
return false
}
val isSpecial: Boolean get() = this == ALL_OTHER_IMPORTS_ENTRY || this == ALL_OTHER_ALIAS_IMPORTS_ENTRY
override fun toString(): String {
return packageName
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is KotlinPackageEntry) return false
return withSubpackages == other.withSubpackages && packageName == other.packageName
}
override fun hashCode(): Int = packageName.hashCode()
}
| plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/core/formatter/KotlinPackageEntry.kt | 1742338403 |
// PROBLEM: none
// WITH_STDLIB
fun test(list: List<Int>): List<Int> {
return list
.reversed()
.<caret>map { it + 1 }
.dropLast(1)
.takeLast(2)
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/noTargetCallChain3.kt | 2696109477 |
val staticField = 42 //KT-40835
fun a() {
JavaClass().a()
val d = JavaClass()
d.a()
d.let {
it.a()
}
d.also {
it.a()
}
with(d) {
a()
}
with(d) out@{
with(4) {
[email protected]()
}
}
}
fun a2() {
val d: JavaClass? = null
d?.a()
d?.let {
it.a()
}
d?.also {
it.a()
}
with(d) {
this?.a()
}
with(d) out@{
with(4) {
this@out?.a()
}
}
}
fun a3() {
val d: JavaClass? = null
val a1 = d?.a()
val a2 = d?.let {
it.a()
}
val a3 = d?.also {
it.a()
}
val a4 = with(d) {
this?.a()
}
val a5 = with(d) out@{
with(4) {
this@out?.a()
}
}
}
fun a4() {
val d: JavaClass? = null
d?.a()?.dec()
val a2 = d?.let {
it.a()
}
a2?.toLong()
d?.also {
it.a()
}?.a()?.and(4)
val a4 = with(d) {
this?.a()
}
val a5 = with(d) out@{
with(4) {
this@out?.a()
}
}
val a6 = a4?.let { out -> a5?.let { out + it } }
}
fun JavaClass.b(): Int? = a()
fun JavaClass.c(): Int = this.a()
fun d(d: JavaClass) = d.a()
| plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/fromJavaToKotlin/delegateToStaticFieldWithNameConflict.kt | 2540278475 |
package com.okta.oidc.clients.web
import org.ccci.gto.android.common.util.getDeclaredFieldOrNull
import org.ccci.gto.android.common.util.getOrNull
private val implSyncAuthClientField by lazy { getDeclaredFieldOrNull<WebAuthClientImpl>("mSyncAuthClient") }
internal val WebAuthClient.syncAuthClient
get() = when (this) {
is WebAuthClientImpl -> implSyncAuthClientField?.getOrNull<SyncWebAuthClient>(this)
else -> null
}
| gto-support-okta/src/main/kotlin/com/okta/oidc/clients/web/WebAuthClientInternals.kt | 2400520357 |
/*
* 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 org.jetbrains.debugger
import com.intellij.openapi.util.NotNullLazyValue
const val RECEIVER_NAME: String = "this"
@Deprecated("")
/**
* Use kotlin - base class is not required in this case (no boilerplate code)
*/
/**
* You must initialize [.scopes] or override [.getVariableScopes]
*/
abstract class CallFrameBase(override val functionName: String?, override val line: Int, override val column: Int, override val evaluateContext: EvaluateContext) : CallFrame {
protected var scopes: NotNullLazyValue<List<Scope>>? = null
override var hasOnlyGlobalScope: Boolean = false
protected set(value: Boolean) {
field = value
}
override val variableScopes: List<Scope>
get() = scopes!!.value
override val asyncFunctionName: String? = null
override val isFromAsyncStack: Boolean = false
override val returnValue: Variable? = null
} | platform/script-debugger/backend/src/debugger/CallFrameBase.kt | 3086378652 |
/*
* Copyright 2021 Appmattus Limited
*
* 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.appmattus.layercache
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual
import org.hamcrest.core.StringStartsWith
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.Mockito.verifyNoInteractions
import org.mockito.kotlin.any
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoMoreInteractions
import org.mockito.kotlin.whenever
class FetcherMapKeysShould {
private val cache = mock<AbstractFetcher<String, Any>> {
on { keyTransform(any<(Int) -> String>()) }.thenCallRealMethod()
}
private val function = mock<(Int) -> String>()
private lateinit var mappedKeysCache: Fetcher<Int, Any>
@Before
fun before() {
mappedKeysCache = cache.keyTransform(function)
verify(cache, atLeastOnce()).keyTransform(any<(Int) -> String>())
}
@Test
fun `contain cache in composed parents`() {
val localCache = mappedKeysCache
if (localCache !is ComposedCache<*, *>) {
fail()
return
}
assertThat(localCache.parents, IsEqual.equalTo(listOf<Cache<*, *>>(cache)))
}
// get
@Test
fun `map string value in get to int`() {
runBlocking {
// given we have a string
transformConvertsIntToString()
whenever(cache.get("1")).then { "value" }
// when we get the value
val result = mappedKeysCache.get(1)
assertEquals("value", result)
}
}
@Test
fun `throw exception when transform returns null during get`() {
runBlocking {
// given transform returns null
whenever(function.invoke(anyInt())).then { TestUtils.uninitialized() }
// when the mapping function returns null
val throwable = assertThrows(IllegalArgumentException::class.java) {
runBlocking {
mappedKeysCache.get(1)
}
}
// expect exception
assertThat(throwable.message, StringStartsWith("Required value was null"))
}
}
@Test(expected = TestException::class)
fun `throw exception when transform throws during get`() {
runBlocking {
// given we have a string
whenever(function.invoke(anyInt())).then { throw TestException() }
// whenever(cache.get("1")).then { async(CommonPool) { "value" } }
// when we get the value from a map with exception throwing functions
mappedKeysCache.get(1)
// then an exception is thrown
}
}
@Test(expected = TestException::class)
fun `throw exception when get throws`() {
runBlocking {
// given we have a string
transformConvertsIntToString()
whenever(cache.get("1")).then { throw TestException() }
// when we get the value from a map
mappedKeysCache.get(1)
// then an exception is thrown
}
}
@Test(expected = CancellationException::class)
fun `throw exception when cancelled during get`() {
runBlocking {
// given we have a long running job
transformConvertsIntToString()
whenever(cache.get("1")).then { runBlocking { delay(250) } }
// when we cancel the job
val job = async { mappedKeysCache.get(1) }
delay(50)
job.cancel()
// then an exception is thrown
job.await()
}
}
// set
@Test
fun `not interact with parent set`() {
runBlocking {
// when we set the value
@Suppress("DEPRECATION_ERROR")
mappedKeysCache.set(1, "1")
// then the parent cache is not called
verifyNoMoreInteractions(cache)
}
}
@Test
fun `not interact with transform during set`() {
runBlocking {
// when we set the value
@Suppress("DEPRECATION_ERROR")
mappedKeysCache.set(1, "1")
// then the parent cache is not called
verifyNoInteractions(function)
}
}
// evict
@Test
fun `not interact with parent evict`() {
runBlocking {
// when we set the value
@Suppress("DEPRECATION_ERROR")
mappedKeysCache.evict(1)
// then the parent cache is not called
verifyNoMoreInteractions(cache)
}
}
@Test
fun `not interact with transform during evict`() {
runBlocking {
// when we set the value
@Suppress("DEPRECATION_ERROR")
mappedKeysCache.evict(1)
// then the parent cache is not called
verifyNoInteractions(function)
}
}
// evictAll
@Test
fun `not interact with parent evictAll`() {
runBlocking {
// when we evictAll values
@Suppress("DEPRECATION_ERROR")
mappedKeysCache.evictAll()
// then the parent cache is not called
verifyNoMoreInteractions(cache)
}
}
@Test
fun `not interact with transform during evictAll`() {
runBlocking {
// when we evictAll values
@Suppress("DEPRECATION_ERROR")
mappedKeysCache.evictAll()
// then the parent cache is not called
verifyNoInteractions(function)
}
}
private fun transformConvertsIntToString() {
whenever(function.invoke(anyInt())).then { it.getArgument<Int>(0).toString() }
}
}
| layercache/src/test/kotlin/com/appmattus/layercache/FetcherMapKeysShould.kt | 1359891450 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.tagTreeHighlighting
import com.intellij.application.options.editor.WebEditorOptions
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.options.UiDslUnnamedConfigurable
import com.intellij.openapi.project.ProjectManager
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.layout.*
import com.intellij.xml.XmlBundle
import com.intellij.xml.breadcrumbs.BreadcrumbsPanel
class XmlTagTreeHighlightingConfigurable : UiDslUnnamedConfigurable.Simple() {
override fun Panel.createContent() {
val options = WebEditorOptions.getInstance()
lateinit var enable: Cell<JBCheckBox>
panel {
row {
enable = checkBox(XmlBundle.message("settings.enable.html.xml.tag.tree.highlighting"))
.bindSelected(options::isTagTreeHighlightingEnabled, options::setTagTreeHighlightingEnabled)
.onApply { clearTagTreeHighlighting() }
}
indent {
row(XmlBundle.message("settings.levels.to.highlight")) {
spinner(1..50)
.bindIntValue({ options.tagTreeHighlightingLevelCount }, { options.tagTreeHighlightingLevelCount = it })
.onApply { clearTagTreeHighlighting() }
.horizontalAlign(HorizontalAlign.FILL)
cell()
}.layout(RowLayout.PARENT_GRID)
row(XmlBundle.message("settings.opacity")) {
spinner(0.0..1.0, step = 0.05)
.bind({ ((it.value as Double) * 100).toInt() }, { it, value -> it.value = value * 0.01 },
PropertyBinding(options::getTagTreeHighlightingOpacity, options::setTagTreeHighlightingOpacity))
.onApply { clearTagTreeHighlighting() }
.horizontalAlign(HorizontalAlign.FILL)
cell()
}.layout(RowLayout.PARENT_GRID)
.bottomGap(BottomGap.SMALL)
}.enabledIf(enable.selected)
}
}
companion object {
private fun clearTagTreeHighlighting() {
for (project in ProjectManager.getInstance().openProjects) {
for (fileEditor in FileEditorManager.getInstance(project).allEditors) {
if (fileEditor is TextEditor) {
val editor = fileEditor.editor
XmlTagTreeHighlightingPass.clearHighlightingAndLineMarkers(editor, project)
val breadcrumbs = BreadcrumbsPanel.getBreadcrumbsComponent(editor)
breadcrumbs?.queueUpdate()
}
}
}
}
}
}
| xml/impl/src/com/intellij/codeInsight/daemon/impl/tagTreeHighlighting/XmlTagTreeHighlightingConfigurable.kt | 1898714175 |
package test
fun fff(): Array<Int> = throw Exception()
| plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/type/ArrayOfInt.kt | 585064803 |
object X{ }
<selection>class Y {
fun f(op: X.()->Unit) {
X.op()
}
}</selection> | plugins/kotlin/idea/tests/testData/shortenRefs/extensionFunctionVarInvokedWithQualifier.kt | 3766537496 |
/**
* @param <info descr="null" textAttributesKey="KDOC_LINK">x</info> foo and <info descr="null" textAttributesKey="KDOC_LINK">[baz]</info>
* @param <info descr="null" textAttributesKey="KDOC_LINK">y</info> bar
* @return notALink here
*/
fun <info descr="null">f</info>(<info descr="null">x</info>: <info descr="null">Int</info>, <info descr="null">y</info>: <info descr="null">Int</info>): <info descr="null">Int</info> {
return <info descr="null">x</info> + <info descr="null">y</info>
}
fun <info descr="null">baz</info>() {} | plugins/kotlin/idea/tests/testData/highlighter/KDoc.kt | 1943176549 |
package com.example.testModule14
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.common.anotherSampleTestMethod
import com.example.common.ignoredTest
import com.example.common.testSampleMethod
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ModuleTests {
@Test
fun sampleTest() {
testSampleMethod()
}
@Test
fun sampleTest2() {
anotherSampleTestMethod()
}
@Test
@Ignore("For testing #818")
fun sampleTest3() {
ignoredTest()
}
}
| test_projects/android/multi-modules/testModule14/src/androidTest/java/com/example/testModule14/ModuleTests.kt | 1868967242 |
package info.nightscout.androidaps.logging
/**
* Created by adrian on 2019-12-27.
*/
class AAPSLoggerTest : AAPSLogger {
override fun debug(message: String) {
println("DEBUG: $message")
}
override fun debug(enable: Boolean, tag: LTag, message: String) {
println("DEBUG: " + message)
}
override fun debug(tag: LTag, message: String) {
println("DEBUG: : " + tag.tag + " " + message)
}
override fun debug(tag: LTag, format: String, vararg arguments: Any?) {
println("DEBUG: : " + tag.tag + " " + String.format(format, arguments))
}
override fun warn(tag: LTag, message: String) {
println("WARN: " + tag.tag + " " + message)
}
override fun warn(tag: LTag, format: String, vararg arguments: Any?) {
println("INFO: : " + tag.tag + " " + String.format(format, arguments))
}
override fun info(tag: LTag, message: String) {
println("INFO: " + tag.tag + " " + message)
}
override fun info(tag: LTag, format: String, vararg arguments: Any?) {
println("INFO: : " + tag.tag + " " + String.format(format, arguments))
}
override fun error(tag: LTag, message: String) {
println("ERROR: " + tag.tag + " " + message)
}
override fun error(message: String) {
println("ERROR: " + message)
}
override fun error(message: String, throwable: Throwable) {
println("ERROR: " + message + " " + throwable)
}
override fun error(format: String, vararg arguments: Any?) {
println("ERROR: : " + String.format(format, arguments))
}
override fun error(tag: LTag, message: String, throwable: Throwable) {
println("ERROR: " + tag.tag + " " + message + " " + throwable)
}
override fun error(tag: LTag, format: String, vararg arguments: Any?) {
println("ERROR: : " + tag.tag + " " + String.format(format, arguments))
}
} | core/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerTest.kt | 1688205275 |
package uy.kohesive.iac.model.aws.contexts
import com.amazonaws.services.gamelift.AmazonGameLift
import com.amazonaws.services.gamelift.model.*
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.KohesiveIdentifiable
import uy.kohesive.iac.model.aws.utils.DslScope
interface GameLiftIdentifiable : KohesiveIdentifiable {
}
interface GameLiftEnabled : GameLiftIdentifiable {
val gameLiftClient: AmazonGameLift
val gameLiftContext: GameLiftContext
fun <T> withGameLiftContext(init: GameLiftContext.(AmazonGameLift) -> T): T = gameLiftContext.init(gameLiftClient)
}
open class BaseGameLiftContext(protected val context: IacContext) : GameLiftEnabled by context {
open fun createAlias(name: String, init: CreateAliasRequest.() -> Unit): Alias {
return gameLiftClient.createAlias(CreateAliasRequest().apply {
withName(name)
init()
}).getAlias()
}
open fun createBuild(name: String, init: CreateBuildRequest.() -> Unit): Build {
return gameLiftClient.createBuild(CreateBuildRequest().apply {
withName(name)
init()
}).getBuild()
}
open fun createFleet(name: String, init: CreateFleetRequest.() -> Unit): CreateFleetResult {
return gameLiftClient.createFleet(CreateFleetRequest().apply {
withName(name)
init()
})
}
open fun createGameSession(name: String, init: CreateGameSessionRequest.() -> Unit): GameSession {
return gameLiftClient.createGameSession(CreateGameSessionRequest().apply {
withName(name)
init()
}).getGameSession()
}
open fun createGameSessionQueue(name: String, init: CreateGameSessionQueueRequest.() -> Unit): GameSessionQueue {
return gameLiftClient.createGameSessionQueue(CreateGameSessionQueueRequest().apply {
withName(name)
init()
}).getGameSessionQueue()
}
}
@DslScope
class GameLiftContext(context: IacContext) : BaseGameLiftContext(context) {
}
| model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/contexts/GameLift.kt | 2727073800 |
package ftl.util
import ftl.run.platform.android.SdkSuppressLevels
data class FlankTestMethod(
val testName: String,
val ignored: Boolean = false,
val isParameterizedClass: Boolean = false,
val sdkSuppressLevels: SdkSuppressLevels? = null
)
| test_runner/src/main/kotlin/ftl/util/FlankTestMethod.kt | 89147121 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.project
import com.intellij.ide.plugins.DependencyCollector
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginAdvertiserService
import kotlinx.coroutines.launch
internal class MavenDependencyCollector : DependencyCollector {
override fun collectDependencies(project: Project): List<String> {
val result = mutableSetOf<String>()
for (mavenProject in MavenProjectsManager.getInstance(project).projects) {
for (dependency in mavenProject.dependencies) {
result.add(dependency.groupId + ":" + dependency.artifactId)
}
}
return result.toList()
}
}
internal class MavenDependencyUpdater(private val project: Project) : MavenImportListener {
override fun importFinished(importedProjects: Collection<MavenProject>, newModules: List<Module>) {
project.coroutineScope.launch {
PluginAdvertiserService.getInstance().rescanDependencies(project)
}
}
} | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenDependencyCollector.kt | 465495184 |
val test = when {<caret>foo()
fun foo() = 42 | plugins/kotlin/idea/tests/testData/indentationOnNewline/afterUnmatchedBrace/WhenBeforeTopLevelPropertyInitializer.kt | 3799693751 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.actions
import com.intellij.configurationStore.StateStorageManagerImpl
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import org.jetbrains.settingsRepository.*
internal val NOTIFICATION_GROUP = NotificationGroup.balloonGroup(PLUGIN_NAME)
internal abstract class SyncAction(private val syncType: SyncType) : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val repositoryManager = icsManager.repositoryManager
e.presentation.isEnabledAndVisible = repositoryManager.isRepositoryExists() && repositoryManager.hasUpstream()
}
override fun actionPerformed(event: AnActionEvent) {
syncAndNotify(syncType, event.project)
}
}
fun syncAndNotify(syncType: SyncType, project: Project?, notifyIfUpToDate: Boolean = true) {
try {
if (icsManager.sync(syncType, project) == null && !notifyIfUpToDate) {
return
}
NOTIFICATION_GROUP.createNotification(icsMessage("sync.done.message"), NotificationType.INFORMATION).notify(project)
}
catch (e: Exception) {
LOG.warn(e)
NOTIFICATION_GROUP.createNotification(icsMessage("sync.rejected.title"), e.message ?: "Internal error", NotificationType.ERROR, null).notify(project)
}
}
internal class MergeAction : SyncAction(SyncType.MERGE)
internal class ResetToTheirsAction : SyncAction(SyncType.OVERWRITE_LOCAL)
internal class ResetToMyAction : SyncAction(SyncType.OVERWRITE_REMOTE)
internal class ConfigureIcsAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
icsManager.runInAutoCommitDisabledMode {
IcsSettingsPanel(e.project).show()
}
}
override fun update(e: AnActionEvent) {
if (icsManager.repositoryActive) {
e.presentation.isEnabledAndVisible = true
}
else {
val application = ApplicationManager.getApplication()
val provider = (application.stateStore.stateStorageManager as StateStorageManagerImpl).streamProvider
e.presentation.isEnabledAndVisible = provider == null || !provider.enabled
}
e.presentation.icon = null
}
} | plugins/settings-repository/src/actions/SyncAction.kt | 3685103960 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter
// OPTIONS: usages
data class A(val <caret>x: Int, val y: Int, val z: String)
data class B(val a: A, val n: Int)
class C {
operator fun component1(): A = TODO()
operator fun component2() = 0
}
fun f(b: B, c: C) {
val (a, n) = b
val (x, y, z) = a
val (a1, n1) = c
val (x1, y1, z1) = a1
}
// FIR_IGNORE | plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/dataClassInsideDataClass.0.kt | 3695949999 |
package foo.bar
/*p:foo.bar*/fun testOperators(a: /*p:foo.bar*/A, b: /*p:foo.bar p:kotlin*/Int) {
var d = /*p:foo.bar(A)*/a
/*p:foo.bar(A)*/d/*c:foo.bar.A(inc)*/++
/*c:foo.bar.A(inc) p:foo.bar(A)*/++/*p:foo.bar(A)*/d
/*p:foo.bar(A)*/d/*c:foo.bar.A(dec) c:foo.bar.A(getDEC) c:foo.bar.A(getDec) p:foo.bar(dec)*/--
/*c:foo.bar.A(dec) c:foo.bar.A(getDEC) c:foo.bar.A(getDec) p:foo.bar(A) p:foo.bar(dec)*/--/*p:foo.bar(A)*/d
/*p:foo.bar(A)*/a /*c:foo.bar.A(plus)*/+ /*p:kotlin(Int)*/b
/*p:foo.bar(A)*/a /*c:foo.bar.A(getMINUS) c:foo.bar.A(getMinus) c:foo.bar.A(minus) p:foo.bar(minus)*/- /*p:kotlin(Int)*/b
/*c:foo.bar.A(getNOT) c:foo.bar.A(getNot) c:foo.bar.A(not) p:foo.bar(not)*/!/*p:foo.bar(A)*/a
// for val
/*p:foo.bar(A)*/a /*c:foo.bar.A(timesAssign)*/*= /*p:kotlin(Int)*/b
/*p:foo.bar(A)*/a /*c:foo.bar.A(divAssign) c:foo.bar.A(getDIVAssign) c:foo.bar.A(getDivAssign) p:foo.bar(divAssign)*//= /*p:kotlin(Int)*/b
// for var
/*p:foo.bar(A)*/d /*c:foo.bar.A(getPLUSAssign) c:foo.bar.A(getPlusAssign) c:foo.bar.A(plus) c:foo.bar.A(plusAssign) p:foo.bar(plusAssign) p:java.lang(plusAssign) p:kotlin(plusAssign) p:kotlin.annotation(plusAssign) p:kotlin.collections(plusAssign) p:kotlin.comparisons(plusAssign) p:kotlin.io(plusAssign) p:kotlin.jvm(plusAssign) p:kotlin.ranges(plusAssign) p:kotlin.sequences(plusAssign) p:kotlin.text(plusAssign)*/+= /*p:kotlin(Int)*/b
/*p:foo.bar(A)*/d /*c:foo.bar.A(getMINUS) c:foo.bar.A(getMINUSAssign) c:foo.bar.A(getMinus) c:foo.bar.A(getMinusAssign) c:foo.bar.A(minus) c:foo.bar.A(minusAssign) p:foo.bar(minus) p:foo.bar(minusAssign) p:java.lang(minusAssign) p:kotlin(minusAssign) p:kotlin.annotation(minusAssign) p:kotlin.collections(minusAssign) p:kotlin.comparisons(minusAssign) p:kotlin.io(minusAssign) p:kotlin.jvm(minusAssign) p:kotlin.ranges(minusAssign) p:kotlin.sequences(minusAssign) p:kotlin.text(minusAssign)*/-= /*p:kotlin(Int)*/b
/*p:foo.bar(A)*/d /*c:foo.bar.A(getTIMES) c:foo.bar.A(getTimes) c:foo.bar.A(times) c:foo.bar.A(timesAssign) p:foo.bar(times) p:java.lang(times) p:kotlin(times) p:kotlin.annotation(times) p:kotlin.collections(times) p:kotlin.comparisons(times) p:kotlin.io(times) p:kotlin.jvm(times) p:kotlin.ranges(times) p:kotlin.sequences(times) p:kotlin.text(times)*/*= /*p:kotlin(Int)*/b
/*p:foo.bar(A)*/d /*c:foo.bar.A(div) c:foo.bar.A(divAssign) c:foo.bar.A(getDIV) c:foo.bar.A(getDIVAssign) c:foo.bar.A(getDiv) c:foo.bar.A(getDivAssign) p:foo.bar(div) p:foo.bar(divAssign) p:java.lang(div) p:kotlin(div) p:kotlin.annotation(div) p:kotlin.collections(div) p:kotlin.comparisons(div) p:kotlin.io(div) p:kotlin.jvm(div) p:kotlin.ranges(div) p:kotlin.sequences(div) p:kotlin.text(div)*//= /*p:kotlin(Int)*/b
}
| plugins/kotlin/jps/jps-plugin/tests/testData/incremental/lookupTracker/jvm/conventions/mathematicalLike.kt | 955786911 |
// WITH_RUNTIME
val list = listOf(1, 2, 3).map(<caret>Utils::foo) | plugins/kotlin/idea/tests/testData/intentions/convertReferenceToLambda/static.kt | 937988820 |
package com.github.kerubistan.kerub.sshtestutils
import com.github.kerubistan.kerub.toInputStream
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.argThat
import com.nhaarman.mockito_kotlin.doAnswer
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.apache.commons.io.input.NullInputStream
import org.apache.sshd.client.channel.ChannelExec
import org.apache.sshd.client.future.OpenFuture
import org.apache.sshd.client.session.ClientSession
import java.io.OutputStream
fun ClientSession.mockCommandExecution(
commandMatcher: String = ".*",
output: String = "",
error: String = "") : ChannelExec =
this.mockCommandExecution(commandMatcher.toRegex(), output, error)
fun ClientSession.mockCommandExecution(
commandMatcher: Regex,
output: String = "",
error: String = "") : ChannelExec =
mock<ChannelExec>().let {exec ->
whenever(this.createExecChannel(argThat { matches(commandMatcher) })).thenReturn(exec)
whenever(exec.open()).thenReturn(mock())
whenever(exec.invertedErr).then { error.toInputStream() }
whenever(exec.invertedOut).then { output.toInputStream() }
exec
}
fun ClientSession.mockCommandExecutionSequence(
commandMatcher: Regex,
outputs : List<String> = listOf()
) : ChannelExec =
mock<ChannelExec>().let {exec ->
val iterator = outputs.iterator()
whenever(this.createExecChannel(argThat { matches(commandMatcher) })).thenReturn(exec)
whenever(exec.open()).thenReturn(mock())
whenever(exec.invertedOut).then {
iterator.next().toInputStream()
}
whenever(exec.invertedErr).then { NullInputStream(0) }
exec
}
fun ClientSession.verifyCommandExecution(commandMatcher: Regex) {
verify(this).createExecChannel(argThat { commandMatcher.matches(this) })
}
fun ClientSession.verifyCommandExecution(commandMatcher: Regex, mode: org.mockito.verification.VerificationMode) {
verify(this, mode).createExecChannel(argThat { commandMatcher.matches(this) })
}
fun ClientSession.mockProcess(commandMatcher: Regex, output: String, stderr : String = "") {
val execChannel: ChannelExec = mock()
val openFuture : OpenFuture = mock()
whenever(this.createExecChannel(argThat { commandMatcher.matches(this) })).thenReturn(execChannel)
whenever(execChannel.open()).thenReturn(openFuture)
doAnswer {
val out = it.arguments[0] as OutputStream
output.forEach { chr ->
out.write( chr.toInt() )
}
null
} .whenever(execChannel)!!.out = any()
doAnswer {
val err = it.arguments[0] as OutputStream
stderr.forEach { chr ->
err.write( chr.toInt() )
}
null
} .whenever(execChannel)!!.err = any()
whenever(execChannel.invertedErr).thenReturn(NullInputStream(0))
} | src/test/kotlin/com/github/kerubistan/kerub/sshtestutils/SshTestUtils.kt | 2316784906 |
// "Create class 'Unknown'" "true"
// ACTION: Create class 'Unknown'
// ACTION: Create interface 'Unknown'
// ACTION: Create type parameter 'Unknown' in class 'A'
// ACTION: Do not show return expression hints
// DISABLE-ERRORS
class A() : Unknown<caret> {
constructor(i: Int) : this()
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/delegationSpecifier/createSuperClassFromSuperTypeEntry3.kt | 306042994 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.dsl.builder.impl
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.putUserData
import com.intellij.ui.dsl.builder.CellBase
import com.intellij.ui.dsl.builder.DSL_PANEL_HIERARCHY
import com.intellij.ui.dsl.builder.SpacingConfiguration
import com.intellij.ui.dsl.gridLayout.Constraints
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
@ApiStatus.Internal
internal abstract class PlaceholderBaseImpl<T : CellBase<T>>(private val parent: RowImpl) : CellBaseImpl<T>() {
protected var placeholderCellData: PlaceholderCellData? = null
private set
private var visible = true
private var enabled = true
var component: JComponent? = null
set(value) {
reinstallComponent(field, value)
field = value
}
override fun enabledFromParent(parentEnabled: Boolean) {
doEnabled(parentEnabled && enabled)
}
override fun enabled(isEnabled: Boolean): CellBase<T> {
enabled = isEnabled
if (parent.isEnabled()) {
doEnabled(enabled)
}
return this
}
override fun visibleFromParent(parentVisible: Boolean) {
doVisible(parentVisible && visible)
}
override fun visible(isVisible: Boolean): CellBase<T> {
visible = isVisible
if (parent.isVisible()) {
doVisible(visible)
}
component?.isVisible = isVisible
return this
}
open fun init(panel: DialogPanel, constraints: Constraints, spacing: SpacingConfiguration) {
placeholderCellData = PlaceholderCellData(panel, constraints, spacing)
if (component != null) {
reinstallComponent(null, component)
}
}
private fun reinstallComponent(oldComponent: JComponent?, newComponent: JComponent?) {
oldComponent?.putUserData(DSL_PANEL_HIERARCHY, null)
newComponent?.putUserData(DSL_PANEL_HIERARCHY, buildPanelHierarchy(parent))
var invalidate = false
if (oldComponent != null) {
placeholderCellData?.let {
if (oldComponent is DialogPanel) {
it.panel.unregisterIntegratedPanel(oldComponent)
}
it.panel.remove(oldComponent)
invalidate = true
}
}
if (newComponent != null) {
newComponent.isVisible = visible && parent.isVisible()
newComponent.isEnabled = enabled && parent.isEnabled()
placeholderCellData?.let {
val gaps = customGaps ?: getComponentGaps(it.constraints.gaps.left, it.constraints.gaps.right, newComponent, it.spacing)
it.constraints = it.constraints.copy(
gaps = gaps,
visualPaddings = prepareVisualPaddings(newComponent.origin)
)
it.panel.add(newComponent, it.constraints)
if (newComponent is DialogPanel) {
it.panel.registerIntegratedPanel(newComponent)
}
invalidate = true
}
}
if (invalidate) {
invalidate()
}
}
private fun doVisible(isVisible: Boolean) {
component?.let {
if (it.isVisible != isVisible) {
it.isVisible = isVisible
invalidate()
}
}
}
private fun doEnabled(isEnabled: Boolean) {
component?.let {
it.isEnabled = isEnabled
}
}
private fun invalidate() {
placeholderCellData?.let {
// Force parent to re-layout
it.panel.revalidate()
it.panel.repaint()
}
}
}
@ApiStatus.Internal
internal data class PlaceholderCellData(val panel: DialogPanel, var constraints: Constraints, val spacing: SpacingConfiguration)
| platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/PlaceholderBaseImpl.kt | 1851591602 |
package com.maubis.scarlet.base.support.database
import android.content.Context
import com.maubis.scarlet.base.config.CoreConfig.Companion.foldersDb
import com.maubis.scarlet.base.config.CoreConfig.Companion.notesDb
import com.maubis.scarlet.base.core.note.NoteImage.Companion.deleteIfExist
import com.maubis.scarlet.base.core.note.ReminderInterval
import com.maubis.scarlet.base.core.note.getReminderV2
import com.maubis.scarlet.base.core.note.setReminderV2
import com.maubis.scarlet.base.note.delete
import com.maubis.scarlet.base.note.reminders.ReminderJob.Companion.nextJobTimestamp
import com.maubis.scarlet.base.note.reminders.ReminderJob.Companion.scheduleJob
import com.maubis.scarlet.base.note.save
import com.maubis.scarlet.base.note.saveWithoutSync
import java.io.File
import java.util.*
import java.util.concurrent.TimeUnit
class HouseKeeper(val context: Context) {
private val houseKeeperTasks: Array<() -> Unit> = arrayOf(
{ removeOlderClips() },
{ removeDecoupledFolders() },
{ removeOldReminders() },
{ deleteRedundantImageFiles() },
{ migrateZeroUidNotes() }
)
fun execute() {
for (task in houseKeeperTasks) {
task()
}
}
fun removeOlderClips(deltaTimeMs: Long = 604800000L) {
val notes = notesDb.database()
.getOldTrashedNotes(Calendar.getInstance().timeInMillis - deltaTimeMs)
for (note in notes) {
note.delete(context)
}
}
private fun removeDecoupledFolders() {
val folders = foldersDb.getAll().map { it.uuid }
notesDb.getAll()
.filter { it.folder.isNotBlank() }
.forEach {
if (!folders.contains(it.folder)) {
it.folder = ""
it.save(context)
}
}
}
private fun removeOldReminders() {
notesDb.getAll().forEach {
val reminder = it.getReminderV2()
if (reminder === null) {
return@forEach
}
// Some gap to allow delays in alarm
if (reminder.timestamp >= System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(30)) {
return@forEach
}
if (reminder.interval == ReminderInterval.ONCE) {
it.meta = ""
it.saveWithoutSync(context)
return@forEach
}
reminder.timestamp = nextJobTimestamp(reminder.timestamp, System.currentTimeMillis())
reminder.uid = scheduleJob(it.uuid, reminder)
it.setReminderV2(reminder)
it.saveWithoutSync(context)
}
}
private fun deleteRedundantImageFiles() {
val uuids = notesDb.getAllUUIDs()
val imagesFolder = File(context.filesDir, "images" + File.separator)
val uuidFiles = imagesFolder.listFiles()
if (uuidFiles === null || uuidFiles.isEmpty()) {
return
}
val availableDirectories = HashSet<String>()
for (file in uuidFiles) {
if (file.isDirectory) {
availableDirectories.add(file.name)
}
}
for (id in uuids) {
availableDirectories.remove(id)
}
for (uuid in availableDirectories) {
val noteFolder = File(imagesFolder, uuid)
for (file in noteFolder.listFiles()) {
deleteIfExist(file)
}
}
}
private fun migrateZeroUidNotes() {
val note = notesDb.getByID(0)
if (note != null) {
notesDb.database().delete(note)
notesDb.notifyDelete(note)
note.uid = null
note.save(context)
}
}
} | base/src/main/java/com/maubis/scarlet/base/support/database/HouseKeeper.kt | 2543466199 |
class C {
val something: String = ""
val s: String = ""
fun calcSomething(c: C?): String {
if (c != null) {
return c.<caret>
}
}
}
// ORDER: calcSomething
// ORDER: something
// ORDER: s
| plugins/kotlin/completion/tests/testData/weighers/smart/ReturnValue2.kt | 3251677596 |
// 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.ide.impl.jps.serialization
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.workspaceModel.ide.JpsProjectLoadedListener
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.WorkspaceModelImpl
import kotlin.system.measureTimeMillis
/**
* Loading the real state of the project after loading from cache.
*
* Initially IJ loads the state of workspace model from the cache. In this startup activity it synchronizes the state
* of workspace model with project model files (iml/xml).
*/
class DelayedProjectSynchronizer : StartupActivity.DumbAware {
override fun runActivity(project: Project) {
if (WorkspaceModel.isEnabled) {
val projectModelSynchronizer = JpsProjectModelSynchronizer.getInstance(project)
if (projectModelSynchronizer != null && (WorkspaceModel.getInstance(project) as WorkspaceModelImpl).loadedFromCache) {
val loadingTime = measureTimeMillis {
projectModelSynchronizer.loadRealProject(project)
project.messageBus.syncPublisher(JpsProjectLoadedListener.LOADED).loaded()
}
log.info("Workspace model loaded from cache. Syncing real project state into workspace model in $loadingTime ms. ${Thread.currentThread()}")
}
}
}
companion object {
private val log = logger<DelayedProjectSynchronizer>()
}
} | platform/platform-impl/src/com/intellij/workspaceModel/ide/impl/jps/serialization/DelayedProjectSynchronizer.kt | 1513672403 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.maven
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.SourceFolder
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.XmlElementFactory
import com.intellij.psi.xml.XmlFile
import com.intellij.psi.xml.XmlTag
import com.intellij.psi.xml.XmlText
import com.intellij.util.xml.GenericDomValue
import org.jetbrains.idea.maven.dom.MavenDomElement
import org.jetbrains.idea.maven.dom.MavenDomUtil
import org.jetbrains.idea.maven.dom.model.*
import org.jetbrains.idea.maven.model.MavenId
import org.jetbrains.idea.maven.model.MavenPlugin
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenArtifactScope
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.kotlin.idea.base.codeInsight.CliArgumentStringBuilder.buildArgumentString
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.SourceKotlinRootType
import org.jetbrains.kotlin.config.TestSourceKotlinRootType
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.maven.configuration.KotlinMavenConfigurator
import org.jetbrains.kotlin.idea.projectConfiguration.RepositoryDescription
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
import org.jetbrains.kotlin.util.capitalizeDecapitalize.toLowerCaseAsciiOnly
import org.jetbrains.kotlin.utils.SmartList
fun kotlinPluginId(version: String?) = MavenId(KotlinMavenConfigurator.GROUP_ID, KotlinMavenConfigurator.MAVEN_PLUGIN_ID, version)
class PomFile private constructor(private val xmlFile: XmlFile, val domModel: MavenDomProjectModel) {
constructor(xmlFile: XmlFile) : this(
xmlFile,
MavenDomUtil.getMavenDomProjectModel(xmlFile.project, xmlFile.virtualFile)
?: throw IllegalStateException("No DOM model found for pom ${xmlFile.name}")
)
private val nodesByName = HashMap<String, XmlTag>()
private val projectElement: XmlTag
init {
var projectElement: XmlTag? = null
xmlFile.document?.accept(object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
super.visitElement(element)
if (element is XmlTag && element.localName in recommendedElementsOrder && element.parent === projectElement) {
nodesByName[element.localName] = element
} else if (element is XmlTag && element.localName == "project") {
projectElement = element
element.acceptChildren(this)
} else {
element.acceptChildren(this)
}
}
})
require(projectElement != null) { "pom file should have project element" }
this.projectElement = projectElement!!
}
fun addProperty(name: String, value: String) {
val properties = ensureElement(projectElement, "properties")
val existing = properties.children.filterIsInstance<XmlTag>().filter { it.localName == name }
if (existing.isNotEmpty()) {
for (tag in existing) {
val textNode = tag.children.filterIsInstance<XmlText>().firstOrNull()
if (textNode != null) {
textNode.value = value
} else {
tag.replace(projectElement.createChildTag(name, value))
}
}
} else {
properties.add(projectElement.createChildTag(name, value))
}
}
fun findProperty(name: String): XmlTag? {
val propertiesNode = nodesByName["properties"] ?: return null
return propertiesNode.findFirstSubTag(name)
}
fun addDependency(
artifact: MavenId,
scope: MavenArtifactScope? = null,
classifier: String? = null,
optional: Boolean = false,
systemPath: String? = null
): MavenDomDependency {
require(systemPath == null || scope == MavenArtifactScope.SYSTEM) { "systemPath is only applicable for system scope dependency" }
require(artifact.groupId != null) { "groupId shouldn't be null" }
require(artifact.artifactId != null) { "artifactId shouldn't be null" }
ensureDependencies()
val versionless = artifact.withNoVersion().withoutJDKSpecificSuffix()
val dependency = domModel.dependencies.dependencies.firstOrNull { it.matches(versionless) } ?: domModel.dependencies.addDependency()
dependency.groupId.stringValue = artifact.groupId
dependency.artifactId.stringValue = artifact.artifactId
dependency.version.stringValue = artifact.version
dependency.classifier.stringValue = classifier
if (scope != null && scope != MavenArtifactScope.COMPILE) {
dependency.scope.stringValue = scope.name.toLowerCaseAsciiOnly()
}
if (optional) {
dependency.optional.value = true
}
dependency.systemPath.stringValue = systemPath
dependency.ensureTagExists()
return dependency
}
fun addKotlinPlugin(version: String?) = addPlugin(kotlinPluginId(version))
fun addPlugin(artifact: MavenId): MavenDomPlugin {
ensureBuild()
val groupArtifact = artifact.withNoVersion()
val plugin = findPlugin(groupArtifact) ?: domModel.build.plugins.addPlugin()
plugin.groupId.stringValue = artifact.groupId
plugin.artifactId.stringValue = artifact.artifactId
if (artifact.version != null) {
plugin.version.stringValue = artifact.version
}
plugin.ensureTagExists()
return plugin
}
fun findPlugin(groupArtifact: MavenId) = domModel.build.plugins.plugins.firstOrNull { it.matches(groupArtifact) }
fun isPluginAfter(plugin: MavenDomPlugin, referencePlugin: MavenDomPlugin): Boolean {
require(plugin.parent === referencePlugin.parent) { "Plugins should be siblings" }
require(plugin !== referencePlugin)
val referenceElement = referencePlugin.xmlElement!!
var e: PsiElement = plugin.xmlElement!!
while (e !== referenceElement) {
val prev = e.prevSibling ?: return false
e = prev
}
return true
}
private fun ensurePluginAfter(plugin: MavenDomPlugin, referencePlugin: MavenDomPlugin): MavenDomPlugin {
if (!isPluginAfter(plugin, referencePlugin)) {
// rearrange
val referenceElement = referencePlugin.xmlElement!!
val newElement = referenceElement.parent.addAfter(plugin.xmlElement!!, referenceElement)
plugin.xmlTag?.delete()
return domModel.build.plugins.plugins.single { it.xmlElement == newElement }
}
return plugin
}
fun findKotlinPlugins() = domModel.build.plugins.plugins.filter { it.isKotlinMavenPlugin() }
fun findKotlinExecutions(vararg goals: String) = findKotlinExecutions().filter { it.goals.goals.any { it.rawText in goals } }
fun findKotlinExecutions() = findKotlinPlugins().flatMap { it.executions.executions }
private fun findExecutions(plugin: MavenDomPlugin) = plugin.executions.executions
fun findExecutions(plugin: MavenDomPlugin, vararg goals: String) =
findExecutions(plugin).filter { it.goals.goals.any { it.rawText in goals } }
fun addExecution(plugin: MavenDomPlugin, executionId: String, phase: String, goals: List<String>): MavenDomPluginExecution {
require(executionId.isNotEmpty()) { "executionId shouldn't be empty" }
require(phase.isNotEmpty()) { "phase shouldn't be empty" }
val execution = plugin.executions.executions.firstOrNull { it.id.stringValue == executionId } ?: plugin.executions.addExecution()
execution.id.stringValue = executionId
execution.phase.stringValue = phase
val existingGoals = execution.goals.goals.mapNotNull { it.rawText }
for (goal in goals.filter { it !in existingGoals }) {
val goalTag = execution.goals.ensureTagExists().createChildTag("goal", goal)
execution.goals.xmlTag?.add(goalTag)
}
return execution
}
fun addKotlinExecution(
module: Module,
plugin: MavenDomPlugin,
executionId: String,
phase: String,
isTest: Boolean,
goals: List<String>
) {
val execution = addExecution(plugin, executionId, phase, goals)
val sourceDirs = ModuleRootManager.getInstance(module)
.contentEntries
.flatMap { it.sourceFolders.filter { it.isRelatedSourceRoot(isTest) } }
.mapNotNull { it.file }
.mapNotNull { VfsUtilCore.getRelativePath(it, xmlFile.virtualFile.parent, '/') }
executionSourceDirs(execution, sourceDirs)
}
fun isPluginExecutionMissing(plugin: MavenPlugin?, excludedExecutionId: String, goal: String) =
plugin == null || plugin.executions.none { it.executionId != excludedExecutionId && goal in it.goals }
fun addJavacExecutions(module: Module, kotlinPlugin: MavenDomPlugin) {
val javacPlugin = ensurePluginAfter(addPlugin(MavenId("org.apache.maven.plugins", "maven-compiler-plugin", null)), kotlinPlugin)
val project: MavenProject =
MavenProjectsManager.getInstance(module.project).findProject(module) ?: run {
if (isUnitTestMode()) {
LOG.warn("WARNING: Bad project configuration in tests. Javac execution configuration was skipped.")
return
}
error("Can't find maven project for $module")
}
val plugin = project.findPlugin("org.apache.maven.plugins", "maven-compiler-plugin")
if (isExecutionEnabled(plugin, "default-compile")) {
addExecution(javacPlugin, "default-compile", "none", emptyList())
}
if (isExecutionEnabled(plugin, "default-testCompile")) {
addExecution(javacPlugin, "default-testCompile", "none", emptyList())
}
if (isPluginExecutionMissing(plugin, "default-compile", "compile")) {
addExecution(javacPlugin, "compile", DefaultPhases.Compile, listOf("compile"))
}
if (isPluginExecutionMissing(plugin, "default-testCompile", "testCompile")) {
addExecution(javacPlugin, "testCompile", DefaultPhases.TestCompile, listOf("testCompile"))
}
}
fun isExecutionEnabled(plugin: MavenPlugin?, executionId: String): Boolean {
if (plugin == null) {
return true
}
if (domModel.build.plugins.plugins.any {
it.groupId.stringValue == "org.apache.maven.plugins"
&& it.artifactId.stringValue == "maven-compiler-plugin"
&& it.executions.executions.any { it.id.stringValue == executionId && it.phase.stringValue == DefaultPhases.None }
}) {
return false
}
return plugin.executions.filter { it.executionId == executionId }.all { execution ->
execution.phase == DefaultPhases.None
}
}
fun executionSourceDirs(execution: MavenDomPluginExecution, sourceDirs: List<String>, forceSingleSource: Boolean = false) {
ensureBuild()
val isTest = execution.goals.goals.any { it.stringValue == KotlinGoals.TestCompile || it.stringValue == KotlinGoals.TestJs }
val defaultDir = if (isTest) "test" else "main"
val singleDirectoryElement = if (isTest) {
domModel.build.testSourceDirectory
} else {
domModel.build.sourceDirectory
}
if (sourceDirs.isEmpty() || sourceDirs.singleOrNull() == "src/$defaultDir/java") {
execution.configuration.xmlTag?.findSubTags("sourceDirs")?.forEach { it.deleteCascade() }
singleDirectoryElement.undefine()
} else if (sourceDirs.size == 1 && !forceSingleSource) {
singleDirectoryElement.stringValue = sourceDirs.single()
execution.configuration.xmlTag?.findSubTags("sourceDirs")?.forEach { it.deleteCascade() }
} else {
val sourceDirsTag = executionConfiguration(execution, "sourceDirs")
execution.configuration.createChildTag("sourceDirs")?.let { newSourceDirsTag ->
for (dir in sourceDirs) {
newSourceDirsTag.add(newSourceDirsTag.createChildTag("source", dir))
}
sourceDirsTag.replace(newSourceDirsTag)
}
}
}
fun executionSourceDirs(execution: MavenDomPluginExecution): List<String> {
return execution.configuration.xmlTag
?.getChildrenOfType<XmlTag>()
?.firstOrNull { it.localName == "sourceDirs" }
?.getChildrenOfType<XmlTag>()
?.map { it.getChildrenOfType<XmlText>().joinToString("") { it.text } }
?: emptyList()
}
private fun executionConfiguration(execution: MavenDomPluginExecution, name: String): XmlTag {
val configurationTag = execution.configuration.ensureTagExists()!!
val existingTag = configurationTag.findSubTags(name).firstOrNull()
if (existingTag != null) {
return existingTag
}
val newTag = configurationTag.createChildTag(name)
return configurationTag.add(newTag) as XmlTag
}
fun addPluginConfiguration(plugin: MavenDomPlugin, optionName: String, optionValue: String): XmlTag {
val configurationTag = plugin.configuration.ensureTagExists()
val existingTag = configurationTag.findFirstSubTag(optionName)
if (existingTag != null) {
existingTag.value.text = optionValue
} else {
configurationTag.add(configurationTag.createChildTag(optionName, optionValue))
}
return configurationTag
}
private fun addPluginRepository(
id: String,
name: String,
url: String,
snapshots: Boolean = false,
releases: Boolean = true
): MavenDomRepository {
ensurePluginRepositories()
return addRepository(
id,
name,
url,
snapshots,
releases,
{ domModel.pluginRepositories.pluginRepositories },
{ domModel.pluginRepositories.addPluginRepository() })
}
fun addPluginRepository(description: RepositoryDescription) {
addPluginRepository(description.id, description.name, description.url, description.isSnapshot, true)
}
private fun addLibraryRepository(
id: String,
name: String,
url: String,
snapshots: Boolean = false,
releases: Boolean = true
): MavenDomRepository {
ensureRepositories()
return addRepository(
id,
name,
url,
snapshots,
releases,
{ domModel.repositories.repositories },
{ domModel.repositories.addRepository() })
}
fun addLibraryRepository(description: RepositoryDescription) {
addLibraryRepository(description.id, description.name, description.url, description.isSnapshot, true)
}
private fun addRepository(
id: String,
name: String,
url: String,
snapshots: Boolean,
releases: Boolean,
existing: () -> List<MavenDomRepository>,
create: () -> MavenDomRepository
): MavenDomRepository {
val repository =
existing().firstOrNull { it.id.stringValue == id } ?: existing().firstOrNull { it.url.stringValue == url } ?: create()
if (repository.id.isEmpty()) {
repository.id.stringValue = id
}
if (repository.name.isEmpty()) {
repository.name.stringValue = name
}
if (repository.url.isEmpty()) {
repository.url.stringValue = url
}
repository.releases.enabled.value = repository.releases.enabled.value?.let { it || releases } ?: releases
repository.snapshots.enabled.value = repository.snapshots.enabled.value?.let { it || snapshots } ?: snapshots
repository.ensureTagExists()
return repository
}
fun findDependencies(artifact: MavenId, scope: MavenArtifactScope? = null) =
domModel.dependencies.findDependencies(artifact, scope)
fun findDependencies(artifacts: List<MavenId>, scope: MavenArtifactScope? = null): List<MavenDomDependency> {
return domModel.dependencies.findDependencies(artifacts, scope)
}
private fun ensureBuild(): XmlTag = ensureElement(projectElement, "build")
private fun ensureDependencies(): XmlTag = ensureElement(projectElement, "dependencies")
private fun ensurePluginRepositories(): XmlTag = ensureElement(projectElement, "pluginRepositories")
private fun ensureRepositories(): XmlTag = ensureElement(projectElement, "repositories")
private fun MavenDomPlugin.isKotlinMavenPlugin() = groupId.stringValue == KotlinMavenConfigurator.GROUP_ID
&& artifactId.stringValue == KotlinMavenConfigurator.MAVEN_PLUGIN_ID
private fun MavenId.withNoVersion() = MavenId(groupId, artifactId, null)
private fun MavenId.withoutJDKSpecificSuffix() = MavenId(
groupId,
artifactId?.substringBeforeLast("-jre")?.substringBeforeLast("-jdk"),
null
)
private fun ensureElement(projectElement: XmlTag, localName: String): XmlTag {
require(localName in recommendedElementsOrder) { "You can only ensure presence or the elements from the recommendation list" }
return nodesByName.getOrPut(localName) {
val tag = projectElement.createChildTag(localName, projectElement.namespace, null, false)!!
val newTag = insertTagImpl(projectElement, tag)
insertEmptyLines(newTag)
newTag
}
}
private fun insertTagImpl(projectElement: XmlTag, tag: XmlTag): XmlTag {
val middle = recommendedOrderAsList.indexOf(tag.localName)
require(middle != -1) { "You can only insert element from the recommendation list" }
for (idx in middle - 1 downTo 0) {
val reference = nodesByName[recommendedOrderAsList[idx]]
if (reference != null) {
return projectElement.addAfter(tag, reference) as XmlTag
}
}
for (idx in middle + 1..recommendedOrderAsList.lastIndex) {
val reference = nodesByName[recommendedOrderAsList[idx]]
if (reference != null) {
return projectElement.addBefore(tag, reference) as XmlTag
}
}
return projectElement.add(tag) as XmlTag
}
private fun insertEmptyLines(node: XmlTag) {
node.prevSibling?.let { before ->
if (!(before.hasEmptyLine() || before.lastChild?.hasEmptyLine() == true)) {
node.parent.addBefore(createEmptyLine(), node)
}
}
node.nextSibling?.let { after ->
if (!(after.hasEmptyLine() || after.firstChild?.hasEmptyLine() == true)) {
node.parent.addAfter(createEmptyLine(), node)
}
}
}
private fun PsiElement.hasEmptyLine() = this is PsiWhiteSpace && text.count { it == '\n' } > 1
private fun createEmptyLine(): XmlText {
return XmlElementFactory.getInstance(xmlFile.project).createTagFromText("<s>\n\n</s>").children.first { it is XmlText } as XmlText
}
private fun GenericDomValue<String>.isEmpty() = !exists() || stringValue.isNullOrEmpty()
private fun SourceFolder.isRelatedSourceRoot(isTest: Boolean): Boolean {
return if (isTest) {
rootType == JavaSourceRootType.TEST_SOURCE || rootType == TestSourceKotlinRootType
} else {
rootType == JavaSourceRootType.SOURCE || rootType == SourceKotlinRootType
}
}
@Suppress("Unused")
object DefaultPhases {
const val None = "none"
const val Validate = "validate"
const val Initialize = "initialize"
const val GenerateSources = "generate-sources"
const val ProcessSources = "process-sources"
const val GenerateResources = "generate-resources"
const val ProcessResources = "process-resources"
const val Compile = "compile"
const val ProcessClasses = "process-classes"
const val GenerateTestSources = "generate-test-sources"
const val ProcessTestSources = "process-test-sources"
const val GenerateTestResources = "generate-test-resources"
const val ProcessTestResources = "process-test-resources"
const val TestCompile = "test-compile"
const val ProcessTestClasses = "process-test-classes"
const val Test = "test"
const val PreparePackage = "prepare-package"
const val Package = "package"
const val PreIntegrationTest = "pre-integration-test"
const val IntegrationTest = "integration-test"
const val PostIntegrationTest = "post-integration-test"
const val Verify = "verify"
const val Install = "install"
const val Deploy = "deploy"
}
object KotlinGoals {
const val Compile = "compile"
const val TestCompile = "test-compile"
const val Js = "js"
const val TestJs = "test-js"
const val MetaData = "metadata"
val JvmGoals = listOf(Compile, TestCompile)
val CompileGoals = listOf(Compile, TestCompile, Js, TestJs, MetaData)
}
companion object {
private val LOG = Logger.getInstance(PomFile::class.java)
fun forFileOrNull(xmlFile: XmlFile): PomFile? =
MavenDomUtil.getMavenDomProjectModel(xmlFile.project, xmlFile.virtualFile)?.let { PomFile(xmlFile, it) }
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("We shouldn't use phase but additional compiler configuration in most cases")
fun getPhase(hasJavaFiles: Boolean, isTest: Boolean) = when {
hasJavaFiles -> when {
isTest -> DefaultPhases.ProcessTestSources
else -> DefaultPhases.ProcessSources
}
else -> when {
isTest -> DefaultPhases.TestCompile
else -> DefaultPhases.Compile
}
}
// from maven code convention: https://maven.apache.org/developers/conventions/code.html
val recommendedElementsOrder = """
<modelVersion/>
<parent/>
<groupId/>
<artifactId/>
<version/>
<packaging/>
<name/>
<description/>
<url/>
<inceptionYear/>
<organization/>
<licenses/>
<developers/>
<contributors/>
<mailingLists/>
<prerequisites/>
<modules/>
<scm/>
<issueManagement/>
<ciManagement/>
<distributionManagement/>
<properties/>
<dependencyManagement/>
<dependencies/>
<repositories/>
<pluginRepositories/>
<build/>
<reporting/>
<profiles/>
""".lines()
.map { it.trim().removePrefix("<").removeSuffix("/>").trim() }
.filter(String::isNotEmpty)
.toCollection(LinkedHashSet())
val recommendedOrderAsList = recommendedElementsOrder.toList()
}
}
fun PomFile.changeLanguageVersion(languageVersion: String?, apiVersion: String?): PsiElement? {
val kotlinPlugin = findPlugin(
MavenId(
KotlinMavenConfigurator.GROUP_ID,
KotlinMavenConfigurator.MAVEN_PLUGIN_ID,
null
)
) ?: return null
val languageElement = languageVersion?.let {
changeConfigurationOrProperty(kotlinPlugin, "languageVersion", "kotlin.compiler.languageVersion", it)
}
val apiElement = apiVersion?.let {
changeConfigurationOrProperty(kotlinPlugin, "apiVersion", "kotlin.compiler.apiVersion", it)
}
return languageElement ?: apiElement
}
internal fun MavenDomDependencies.findDependencies(artifact: MavenId, scope: MavenArtifactScope? = null) =
findDependencies(SmartList(artifact), scope)
internal fun MavenDomDependencies.findDependencies(artifacts: List<MavenId>, scope: MavenArtifactScope? = null): List<MavenDomDependency> {
return dependencies.filter { dependency ->
artifacts.any { artifact ->
dependency.matches(artifact, scope)
}
}
}
private fun MavenDomDependency.matches(artifact: MavenId, scope: MavenArtifactScope?) =
this.matches(artifact) &&
(this.scope.stringValue == scope?.name?.toLowerCaseAsciiOnly() || scope == null && this.scope.stringValue == "compile")
private fun MavenDomArtifactCoordinates.matches(artifact: MavenId) =
(artifact.groupId == null || groupId.stringValue == artifact.groupId)
&& (artifact.artifactId == null || artifactId.stringValue == artifact.artifactId)
&& (artifact.version == null || version.stringValue == artifact.version)
private fun PomFile.changeConfigurationOrProperty(
kotlinPlugin: MavenDomPlugin,
configurationTagName: String,
propertyName: String, value: String
): XmlTag {
val configuration = kotlinPlugin.configuration
if (configuration.exists()) {
val subTag = configuration.xmlTag?.findFirstSubTag(configurationTagName)
if (subTag != null) {
subTag.value.text = value
return subTag
}
}
val propertyTag = findProperty(propertyName)
if (propertyTag != null) {
val textNode = propertyTag.children.filterIsInstance<XmlText>().firstOrNull()
if (textNode != null) {
textNode.value = value
return propertyTag
}
}
return addPluginConfiguration(kotlinPlugin, configurationTagName, value)
}
fun PomFile.changeCoroutineConfiguration(value: String): PsiElement? {
val kotlinPlugin = findPlugin(
MavenId(
KotlinMavenConfigurator.GROUP_ID,
KotlinMavenConfigurator.MAVEN_PLUGIN_ID,
null
)
) ?: return null
return changeConfigurationOrProperty(kotlinPlugin, "experimentalCoroutines", "kotlin.compiler.experimental.coroutines", value)
}
fun PomFile.changeFeatureConfiguration(
feature: LanguageFeature,
state: LanguageFeature.State
): PsiElement? {
val kotlinPlugin = findPlugin(
MavenId(
KotlinMavenConfigurator.GROUP_ID,
KotlinMavenConfigurator.MAVEN_PLUGIN_ID,
null
)
) ?: return null
val configurationTag = kotlinPlugin.configuration.ensureTagExists()
val argsSubTag = configurationTag.findSubTags("args").firstOrNull()
?: run {
val childTag = configurationTag.createChildTag("args")
configurationTag.add(childTag) as XmlTag
}
argsSubTag.findSubTags("arg").filter { feature.name in it.value.text }.forEach { it.deleteCascade() }
val kotlinVersion = kotlinPlugin.version.stringValue?.let(IdeKotlinVersion::opt)
val featureArgumentString = feature.buildArgumentString(state, kotlinVersion)
val childTag = argsSubTag.createChildTag("arg", featureArgumentString)
return argsSubTag.add(childTag)
}
private fun MavenDomElement.createChildTag(name: String, value: String? = null) = xmlTag?.createChildTag(name, value)
private fun XmlTag.createChildTag(name: String, value: String? = null) = createChildTag(name, namespace, value, false)!!
private tailrec fun XmlTag.deleteCascade() {
val oldParent = this.parentTag
delete()
if (oldParent != null && oldParent.subTags.isEmpty()) {
oldParent.deleteCascade()
}
}
| plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/PomFile.kt | 169763955 |
package com.github.vhromada.catalog.facade
import com.github.vhromada.catalog.common.entity.Page
import com.github.vhromada.catalog.common.exception.InputException
import com.github.vhromada.catalog.entity.ChangeMovieRequest
import com.github.vhromada.catalog.entity.Movie
import com.github.vhromada.catalog.entity.MovieStatistics
import com.github.vhromada.catalog.filter.MultipleNameFilter
/**
* An interface represents facade for movies.
*
* @author Vladimir Hromada
*/
interface MovieFacade {
/**
* Returns page of movies for filter.
*
* @param filter filter
* @return page of movies for filter
*/
fun search(filter: MultipleNameFilter): Page<Movie>
/**
* Returns movie.
*
* @param uuid UUID
* @return movie
* @throws InputException if movie doesn't exist in data storage
*/
fun get(uuid: String): Movie
/**
* Adds movie.
* <br></br>
* Validation errors:
*
* * Czech name is null
* * Czech name is empty string
* * Original name is null
* * Original name is empty string
* * Year is null
* * Year isn't between 1940 and current year
* * Language is null
* * Subtitles are null
* * Subtitles contain null value
* * Media are null
* * Media contain null value
* * Medium is negative value
* * IMDB code isn't -1 or between 1 and 9999999
* * Genres are null
* * Genres contain null value
* * Genre is empty string
* * Language doesn't exist in data storage
* * Subtitles doesn't exist in data storage
* * Picture doesn't exist in data storage
* * Genre doesn't exist in data storage
*
* @param request request for changing movie
* @return created movie
* @throws InputException if request for changing movie isn't valid
*/
fun add(request: ChangeMovieRequest): Movie
/**
* Updates movie.
* <br></br>
* Validation errors:
*
* * Czech name is null
* * Czech name is empty string
* * Original name is null
* * Original name is empty string
* * Year is null
* * Year isn't between 1940 and current year
* * Language is null
* * Subtitles are null
* * Subtitles contain null value
* * Media are null
* * Media contain null value
* * Medium is negative value
* * IMDB code isn't -1 or between 1 and 9999999
* * Genres are null
* * Genres contain null value
* * Genre is empty string
* * Language doesn't exist in data storage
* * Subtitles doesn't exist in data storage
* * Picture doesn't exist in data storage
* * Genre doesn't exist in data storage
* * Movie doesn't exist in data storage
*
* @param uuid UUID
* @param request request for changing movie
* @return updated movie
* @throws InputException if request for changing movie isn't valid
*/
fun update(uuid: String, request: ChangeMovieRequest): Movie
/**
* Removes movie.
*
* @param uuid UUID
* @throws InputException if movie doesn't exist in data storage
*/
fun remove(uuid: String)
/**
* Duplicates data.
*
* @param uuid UUID
* @return created duplicated movie
* @throws InputException if movie doesn't exist in data storage
*/
fun duplicate(uuid: String): Movie
/**
* Returns statistics.
*
* @return statistics
*/
fun getStatistics(): MovieStatistics
}
| core/src/main/kotlin/com/github/vhromada/catalog/facade/MovieFacade.kt | 1737290200 |
package org.signal.donations
import android.net.Uri
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
/**
* An object which wraps the necessary information to access a SetupIntent or PaymentIntent
* from the Stripe API
*/
@Parcelize
data class StripeIntentAccessor(
val objectType: ObjectType,
val intentId: String,
val intentClientSecret: String
) : Parcelable {
enum class ObjectType {
NONE,
PAYMENT_INTENT,
SETUP_INTENT
}
companion object {
/**
* noActionRequired is a safe default for when there was no 3DS required,
* in order to continue a reactive payment chain.
*/
val NO_ACTION_REQUIRED = StripeIntentAccessor(ObjectType.NONE,"", "")
private const val KEY_PAYMENT_INTENT = "payment_intent"
private const val KEY_PAYMENT_INTENT_CLIENT_SECRET = "payment_intent_client_secret"
private const val KEY_SETUP_INTENT = "setup_intent"
private const val KEY_SETUP_INTENT_CLIENT_SECRET = "setup_intent_client_secret"
fun fromUri(uri: String): StripeIntentAccessor {
val parsedUri = Uri.parse(uri)
return if (parsedUri.queryParameterNames.contains(KEY_PAYMENT_INTENT)) {
StripeIntentAccessor(
ObjectType.PAYMENT_INTENT,
parsedUri.getQueryParameter(KEY_PAYMENT_INTENT)!!,
parsedUri.getQueryParameter(KEY_PAYMENT_INTENT_CLIENT_SECRET)!!
)
} else {
StripeIntentAccessor(
ObjectType.SETUP_INTENT,
parsedUri.getQueryParameter(KEY_SETUP_INTENT)!!,
parsedUri.getQueryParameter(KEY_SETUP_INTENT_CLIENT_SECRET)!!
)
}
}
}
} | donations/lib/src/main/java/org/signal/donations/StripeIntentAccessor.kt | 1732730012 |
package taiwan.no1.app.ssfm.features.chart
import android.databinding.ObservableField
import android.databinding.ObservableInt
import android.graphics.Bitmap
import android.graphics.Color
import android.view.View
import com.devrapid.kotlinknifer.glideListener
import com.devrapid.kotlinknifer.palette
import com.hwangjr.rxbus.RxBus
import taiwan.no1.app.ssfm.features.base.BaseViewModel
import taiwan.no1.app.ssfm.misc.constants.Constant.VIEWMODEL_PARAMS_ARTIST_ALBUM_NAME
import taiwan.no1.app.ssfm.misc.constants.Constant.VIEWMODEL_PARAMS_ARTIST_NAME
import taiwan.no1.app.ssfm.misc.constants.ImageSizes.LARGE
import taiwan.no1.app.ssfm.misc.constants.RxBusTag
import taiwan.no1.app.ssfm.misc.extension.gAlphaIntColor
import taiwan.no1.app.ssfm.models.entities.lastfm.AlbumEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.BaseEntity
/**
*
* @author jieyi
* @since 10/26/17
*/
class RecyclerViewTagTopAlbumViewModel(private var item: BaseEntity) : BaseViewModel() {
val artistName by lazy { ObservableField<String>() }
val thumbnail by lazy { ObservableField<String>() }
val textBackground by lazy { ObservableInt() }
val textColor by lazy { ObservableInt() }
val shadowColor by lazy { ObservableInt() }
val imageCallback = glideListener<Bitmap> {
onResourceReady = { resource, _, _, _, _ ->
resource.palette(24).let {
gAlphaIntColor(it.vibrantSwatch?.rgb ?: Color.BLACK, 0.5f).let(textBackground::set)
shadowColor.set(it.vibrantSwatch?.rgb ?: Color.BLACK)
textColor.set(it.vibrantSwatch?.bodyTextColor ?: Color.GRAY)
}
false
}
}
init {
refreshView()
}
fun setAlbumItem(item: BaseEntity) {
this.item = item
refreshView()
}
/**
* A callback event for clicking an artist to list item.
*
* @param view [android.widget.RelativeLayout]
*
* @event_to [taiwan.no1.app.ssfm.features.chart.ChartActivity.navigateToAlbumDetail]
*/
fun itemOnClick(view: View) {
(item as AlbumEntity.AlbumWithArtist).let {
RxBus.get().post(RxBusTag.VIEWMODEL_CLICK_ALBUM,
hashMapOf(VIEWMODEL_PARAMS_ARTIST_NAME to it.artist?.name,
VIEWMODEL_PARAMS_ARTIST_ALBUM_NAME to it.name))
}
}
private fun refreshView() {
(item as AlbumEntity.AlbumWithArtist).let {
artistName.set(it.name)
thumbnail.set(it.images?.get(LARGE)?.text.orEmpty())
}
}
} | app/src/main/kotlin/taiwan/no1/app/ssfm/features/chart/RecyclerViewTagTopAlbumViewModel.kt | 3645358119 |
package domain.like
import domain.interactor.SingleDisposableUseCase
import domain.recommendation.DomainRecommendationUser
import io.reactivex.Scheduler
import io.reactivex.Single
class LikeRecommendationUseCase(
private val recommendation: DomainRecommendationUser,
postExecutionScheduler: Scheduler)
: SingleDisposableUseCase<DomainLikedRecommendationAnswer>(
postExecutionScheduler = postExecutionScheduler) {
override fun buildUseCase(): Single<DomainLikedRecommendationAnswer> =
LikeRecommendationHolder.likeRecommendation.likeRecommendation(recommendation)
}
| domain/src/main/kotlin/domain/like/LikeRecommendationUseCase.kt | 3913826905 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.autoimport
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.ui.ExternalSystemIconProvider
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsActions
import javax.swing.Icon
class ProjectRefreshAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
refreshProject(project)
}
override fun update(e: AnActionEvent) {
val project = e.project
if (project == null) {
e.presentation.isEnabledAndVisible = false
return
}
val notificationAware = ExternalSystemProjectNotificationAware.getInstance(project)
val systemIds = notificationAware.getSystemIds()
if (systemIds.isNotEmpty()) {
e.presentation.text = getNotificationText(systemIds)
e.presentation.description = getNotificationDescription(systemIds)
e.presentation.icon = getNotificationIcon(systemIds)
}
e.presentation.isEnabled = notificationAware.isNotificationVisible()
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
@NlsActions.ActionText
private fun getNotificationText(systemIds: Set<ProjectSystemId>): String {
val systemsPresentation = ExternalSystemUtil.naturalJoinSystemIds(systemIds)
return ExternalSystemBundle.message("external.system.reload.notification.action.reload.text", systemsPresentation)
}
@NlsActions.ActionDescription
private fun getNotificationDescription(systemIds: Set<ProjectSystemId>): String {
val systemsPresentation = ExternalSystemUtil.naturalJoinSystemIds(systemIds)
val productName = ApplicationNamesInfo.getInstance().fullProductName
return ExternalSystemBundle.message("external.system.reload.notification.action.reload.description", systemsPresentation, productName)
}
private fun getNotificationIcon(systemIds: Set<ProjectSystemId>): Icon {
val systemId = systemIds.singleOrNull() ?: return AllIcons.Actions.BuildLoadChanges
val iconProvider = ExternalSystemIconProvider.getExtension(systemId)
return iconProvider.reloadIcon
}
init {
val productName = ApplicationNamesInfo.getInstance().fullProductName
templatePresentation.icon = AllIcons.Actions.BuildLoadChanges
templatePresentation.text = ExternalSystemBundle.message("external.system.reload.notification.action.reload.text.empty")
templatePresentation.description = ExternalSystemBundle.message("external.system.reload.notification.action.reload.description.empty", productName)
}
companion object {
fun refreshProject(project: Project) {
val projectNotificationAware = ExternalSystemProjectNotificationAware.getInstance(project)
val systemIds = projectNotificationAware.getSystemIds()
if (ExternalSystemUtil.confirmLoadingUntrustedProject(project, systemIds)) {
val projectTracker = ExternalSystemProjectTracker.getInstance(project)
projectTracker.scheduleProjectRefresh()
}
}
}
} | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectRefreshAction.kt | 2786437796 |
val <caret>foo: String = "" | plugins/kotlin/idea/tests/testData/inspectionsLocal/mayBeConstant/explicitType3.kt | 3439914566 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.fir.analysis.providers.trackers
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import org.jetbrains.kotlin.analysis.providers.createModuleWithoutDependenciesOutOfBlockModificationTracker
import org.jetbrains.kotlin.analysis.providers.createProjectWideOutOfBlockModificationTracker
import org.jetbrains.kotlin.idea.base.projectStructure.getMainKtSourceModule
import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest
import org.jetbrains.kotlin.idea.util.sourceRoots
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.junit.Assert
import java.io.File
class KotlinModuleOutOfBlockTrackerTest : AbstractMultiModuleTest() {
override fun getTestDataDirectory(): File = error("Should not be called")
override fun isFirPlugin(): Boolean = true
fun testThatModuleOutOfBlockChangeInfluenceOnlySingleModule() {
val moduleA = createModuleInTmpDir("a") {
listOf(
FileWithText("main.kt", "fun main() = 10")
)
}
val moduleB = createModuleInTmpDir("b")
val moduleC = createModuleInTmpDir("c")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val moduleCWithTracker = ModuleWithModificationTracker(moduleC)
moduleA.typeInFunctionBody("main.kt", textAfterTyping = "fun main() = hello10")
Assert.assertTrue(
"Out of block modification count for module A with out of block should change after typing, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module B without out of block should not change after typing, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module C without out of block should not change after typing, modification count is ${moduleCWithTracker.modificationCount}",
moduleCWithTracker.changed()
)
}
fun testThatDeleteSymbolInBodyDoesNotLeadToOutOfBlockChange() {
val moduleA = createModuleInTmpDir("a") {
listOf(
FileWithText(
"main.kt", "fun main() {\n" +
"val v = <caret>\n" +
"}"
)
)
}
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val file = "${moduleA.sourceRoots.first().url}/${"main.kt"}"
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!!
val ktFile = PsiManager.getInstance(moduleA.project).findFile(virtualFile) as KtFile
configureByExistingFile(virtualFile)
backspace()
PsiDocumentManager.getInstance(moduleA.project).commitAllDocuments()
Assert.assertFalse(
"Out of block modification count for module A should not change after deleting, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertEquals("fun main() {\n" +
"val v =\n" +
"}", ktFile.text)
}
fun testThatAddModifierDoesLeadToOutOfBlockChange() {
val moduleA = createModuleInTmpDir("a") {
listOf(
FileWithText(
"main.kt", "<caret>inline fun main() {}"
)
)
}
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val file = "${moduleA.sourceRoots.first().url}/${"main.kt"}"
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!!
val ktFile = PsiManager.getInstance(moduleA.project).findFile(virtualFile) as KtFile
configureByExistingFile(virtualFile)
type("private ")
PsiDocumentManager.getInstance(moduleA.project).commitAllDocuments()
Assert.assertTrue(
"Out of block modification count for module A should be changed after specifying return type, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertEquals("private inline fun main() {}", ktFile.text)
}
fun testThatInEveryModuleOutOfBlockWillHappenAfterContentRootChange() {
val moduleA = createModuleInTmpDir("a")
val moduleB = createModuleInTmpDir("b")
val moduleC = createModuleInTmpDir("c")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val moduleCWithTracker = ModuleWithModificationTracker(moduleC)
runWriteAction {
moduleA.sourceRoots.first().createChildData(/* requestor = */ null, "file.kt")
}
Assert.assertTrue(
"Out of block modification count for module A should change after content root change, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertTrue(
"Out of block modification count for module B should change after content root change, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertTrue(
"Out of block modification count for module C should change after content root change modification count is ${moduleCWithTracker.modificationCount}",
moduleCWithTracker.changed()
)
}
fun testThatNonPhysicalFileChangeNotCausingBOOM() {
val moduleA = createModuleInTmpDir("a") {
listOf(
FileWithText("main.kt", "fun main() {}")
)
}
val moduleB = createModuleInTmpDir("b")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val projectWithModificationTracker = ProjectWithModificationTracker(project)
runWriteAction {
val nonPhysicalPsi = KtPsiFactory(moduleA.project).createFile("nonPhysical", "val a = c")
nonPhysicalPsi.add(KtPsiFactory(moduleA.project).createFunction("fun x(){}"))
}
Assert.assertFalse(
"Out of block modification count for module A should not change after non physical file change, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module B should not change after non physical file change, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for project should not change after non physical file change, modification count is ${projectWithModificationTracker.modificationCount}",
projectWithModificationTracker.changed()
)
}
private fun Module.typeInFunctionBody(fileName: String, textAfterTyping: String) {
val file = "${sourceRoots.first().url}/$fileName"
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!!
val ktFile = PsiManager.getInstance(project).findFile(virtualFile) as KtFile
configureByExistingFile(virtualFile)
val singleFunction = ktFile.declarations.single() as KtNamedFunction
editor.caretModel.moveToOffset(singleFunction.bodyExpression!!.textOffset)
type("hello")
PsiDocumentManager.getInstance(project).commitAllDocuments()
Assert.assertEquals(textAfterTyping, ktFile.text)
}
abstract class WithModificationTracker(private val modificationTracker: ModificationTracker) {
private val initialModificationCount = modificationTracker.modificationCount
val modificationCount: Long get() = modificationTracker.modificationCount
fun changed(): Boolean =
modificationTracker.modificationCount != initialModificationCount
}
private class ModuleWithModificationTracker(module: Module) : WithModificationTracker(
module.getMainKtSourceModule()!!.createModuleWithoutDependenciesOutOfBlockModificationTracker(module.project)
)
private class ProjectWithModificationTracker(project: Project) : WithModificationTracker(
project.createProjectWideOutOfBlockModificationTracker()
)
} | plugins/kotlin/base/fir/analysis-api-providers/test/org/jetbrains/kotlin/idea/fir/analysis/providers/trackers/KotlinModuleOutOfBlockTrackerTest.kt | 1312469416 |
package com.intellij.cce.filter
interface ConfigurableBuilder<T> {
fun build(filterId: String): EvaluationFilterConfiguration.Configurable<T>
} | plugins/evaluation-plugin/core/src/com/intellij/cce/filter/ConfigurableBuilder.kt | 135603653 |
// 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.execution.wsl.target
import com.intellij.execution.ExecutionException
import com.intellij.execution.Platform
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.PtyCommandLine
import com.intellij.execution.target.*
import com.intellij.execution.wsl.WSLDistribution
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.sizeOrNull
import java.io.IOException
import java.nio.file.Path
import java.util.*
class WslTargetEnvironment constructor(override val request: WslTargetEnvironmentRequest,
private val distribution: WSLDistribution) : TargetEnvironment(request) {
private val myUploadVolumes: MutableMap<UploadRoot, UploadableVolume> = HashMap()
private val myDownloadVolumes: MutableMap<DownloadRoot, DownloadableVolume> = HashMap()
private val myTargetPortBindings: MutableMap<TargetPortBinding, Int> = HashMap()
private val myLocalPortBindings: MutableMap<LocalPortBinding, ResolvedPortBinding> = HashMap()
override val uploadVolumes: Map<UploadRoot, UploadableVolume>
get() = Collections.unmodifiableMap(myUploadVolumes)
override val downloadVolumes: Map<DownloadRoot, DownloadableVolume>
get() = Collections.unmodifiableMap(myDownloadVolumes)
override val targetPortBindings: Map<TargetPortBinding, Int>
get() = Collections.unmodifiableMap(myTargetPortBindings)
override val localPortBindings: Map<LocalPortBinding, ResolvedPortBinding>
get() = Collections.unmodifiableMap(myLocalPortBindings)
override val targetPlatform: TargetPlatform
get() = TargetPlatform(Platform.UNIX)
init {
for (uploadRoot in request.uploadVolumes) {
val targetRoot: String? = toLinuxPath(uploadRoot.localRootPath.toAbsolutePath().toString())
if (targetRoot != null) {
myUploadVolumes[uploadRoot] = Volume(uploadRoot.localRootPath, targetRoot)
}
}
for (downloadRoot in request.downloadVolumes) {
val localRootPath = downloadRoot.localRootPath ?: FileUtil.createTempDirectory("intellij-target.", "").toPath()
val targetRoot: String? = toLinuxPath(localRootPath.toAbsolutePath().toString())
if (targetRoot != null) {
myDownloadVolumes[downloadRoot] = Volume(localRootPath, targetRoot)
}
}
for (targetPortBinding in request.targetPortBindings) {
val theOnlyPort = targetPortBinding.target
if (targetPortBinding.local != null && targetPortBinding.local != theOnlyPort) {
throw UnsupportedOperationException("Local target's TCP port forwarder is not implemented")
}
myTargetPortBindings[targetPortBinding] = theOnlyPort
}
for (localPortBinding in request.localPortBindings) {
val host = if (distribution.version == 1) {
// Ports bound on localhost in Windows can be accessed by linux apps running in WSL1, but not in WSL2:
// https://docs.microsoft.com/en-US/windows/wsl/compare-versions#accessing-network-applications
"127.0.0.1"
}
else {
distribution.hostIp
}
val hostPort = HostPort(host, localPortBinding.local)
myLocalPortBindings[localPortBinding] = ResolvedPortBinding(hostPort, hostPort)
}
}
private fun toLinuxPath(localPath: String): String? {
val linuxPath = distribution.getWslPath(localPath)
if (linuxPath != null) {
return linuxPath
}
return convertUncPathToLinux(localPath)
}
private fun convertUncPathToLinux(localPath: String): String? {
val root: String = WSLDistribution.UNC_PREFIX + distribution.msId
val winLocalPath = FileUtil.toSystemDependentName(localPath)
if (winLocalPath.startsWith(root)) {
val linuxPath = winLocalPath.substring(root.length)
if (linuxPath.isEmpty()) {
return "/"
}
if (linuxPath.startsWith("\\")) {
return FileUtil.toSystemIndependentName(linuxPath)
}
}
return null
}
@Throws(ExecutionException::class)
override fun createProcess(commandLine: TargetedCommandLine, indicator: ProgressIndicator): Process {
val ptyOptions = request.ptyOptions
val generalCommandLine = if (ptyOptions != null) {
PtyCommandLine(commandLine.collectCommandsSynchronously()).also {
it.withOptions(ptyOptions)
}
}
else {
GeneralCommandLine(commandLine.collectCommandsSynchronously())
}
generalCommandLine.environment.putAll(commandLine.environmentVariables)
request.wslOptions.remoteWorkingDirectory = commandLine.workingDirectory
distribution.patchCommandLine(generalCommandLine, null, request.wslOptions)
return generalCommandLine.createProcess()
}
override fun shutdown() {}
private inner class Volume(override val localRoot: Path, override val targetRoot: String) : UploadableVolume, DownloadableVolume {
@Throws(IOException::class)
override fun resolveTargetPath(relativePath: String): String {
val localPath = FileUtil.toCanonicalPath(FileUtil.join(localRoot.toString(), relativePath))
return toLinuxPath(localPath)!!
}
@Throws(IOException::class)
override fun upload(relativePath: String, targetProgressIndicator: TargetProgressIndicator) {
}
@Throws(IOException::class)
override fun download(relativePath: String, progressIndicator: ProgressIndicator) {
// Synchronization may be slow -- let us wait until file size does not change
// in a reasonable amount of time
// (see https://github.com/microsoft/WSL/issues/4197)
val path = localRoot.resolve(relativePath)
var previousSize = -2L // sizeOrNull returns -1 if file does not exist
var newSize = path.sizeOrNull()
while (previousSize < newSize) {
Thread.sleep(100)
previousSize = newSize
newSize = path.sizeOrNull()
}
if (newSize == -1L) {
LOG.warn("Path $path was not found on local filesystem")
}
}
}
companion object {
val LOG = logger<WslTargetEnvironment>()
}
}
| platform/execution-impl/src/com/intellij/execution/wsl/target/WslTargetEnvironment.kt | 1326562695 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING
import com.intellij.codeInspection.ProblemHighlightType.INFORMATION
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.getLastLambdaExpression
import org.jetbrains.kotlin.idea.inspections.AssociateFunction.*
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReplaceAssociateFunctionInspection : AbstractKotlinInspection() {
companion object {
private val associateFunctionNames = listOf("associate", "associateTo")
private val associateFqNames = listOf(FqName("kotlin.collections.associate"), FqName("kotlin.sequences.associate"))
private val associateToFqNames = listOf(FqName("kotlin.collections.associateTo"), FqName("kotlin.sequences.associateTo"))
fun getAssociateFunctionAndProblemHighlightType(
dotQualifiedExpression: KtDotQualifiedExpression,
context: BindingContext = dotQualifiedExpression.analyze(BodyResolveMode.PARTIAL)
): Pair<AssociateFunction, ProblemHighlightType>? {
val callExpression = dotQualifiedExpression.callExpression ?: return null
val lambda = callExpression.lambda() ?: return null
if (lambda.valueParameters.size > 1) return null
val functionLiteral = lambda.functionLiteral
if (functionLiteral.anyDescendantOfType<KtReturnExpression> { it.labelQualifier != null }) return null
val lastStatement = functionLiteral.lastStatement() ?: return null
val (keySelector, valueTransform) = lastStatement.pair(context) ?: return null
val lambdaParameter = context[BindingContext.FUNCTION, functionLiteral]?.valueParameters?.singleOrNull() ?: return null
return when {
keySelector.isReferenceTo(lambdaParameter, context) -> {
val receiver =
dotQualifiedExpression.receiverExpression.getResolvedCall(context)?.resultingDescriptor?.returnType ?: return null
if ((KotlinBuiltIns.isArray(receiver) || KotlinBuiltIns.isPrimitiveArray(receiver)) &&
dotQualifiedExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_4
) return null
ASSOCIATE_WITH to GENERIC_ERROR_OR_WARNING
}
valueTransform.isReferenceTo(lambdaParameter, context) ->
ASSOCIATE_BY to GENERIC_ERROR_OR_WARNING
else -> {
if (functionLiteral.bodyExpression?.statements?.size != 1) return null
ASSOCIATE_BY_KEY_AND_VALUE to INFORMATION
}
}
}
private fun KtExpression.isReferenceTo(descriptor: ValueParameterDescriptor, context: BindingContext): Boolean {
return (this as? KtNameReferenceExpression)?.getResolvedCall(context)?.resultingDescriptor == descriptor
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = dotQualifiedExpressionVisitor(fun(dotQualifiedExpression) {
if (dotQualifiedExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_3) return
val callExpression = dotQualifiedExpression.callExpression ?: return
val calleeExpression = callExpression.calleeExpression ?: return
if (calleeExpression.text !in associateFunctionNames) return
val context = dotQualifiedExpression.analyze(BodyResolveMode.PARTIAL)
val fqName = callExpression.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe ?: return
val isAssociate = fqName in associateFqNames
val isAssociateTo = fqName in associateToFqNames
if (!isAssociate && !isAssociateTo) return
val (associateFunction, highlightType) = getAssociateFunctionAndProblemHighlightType(dotQualifiedExpression, context) ?: return
holder.registerProblemWithoutOfflineInformation(
calleeExpression,
KotlinBundle.message("replace.0.with.1", calleeExpression.text, associateFunction.name(isAssociateTo)),
isOnTheFly,
highlightType,
ReplaceAssociateFunctionFix(associateFunction, isAssociateTo)
)
})
}
class ReplaceAssociateFunctionFix(private val function: AssociateFunction, private val hasDestination: Boolean) : LocalQuickFix {
private val functionName = function.name(hasDestination)
override fun getName() = KotlinBundle.message("replace.with.0", functionName)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val dotQualifiedExpression = descriptor.psiElement.getStrictParentOfType<KtDotQualifiedExpression>() ?: return
val receiverExpression = dotQualifiedExpression.receiverExpression
val callExpression = dotQualifiedExpression.callExpression ?: return
val lambda = callExpression.lambda() ?: return
val lastStatement = lambda.functionLiteral.lastStatement() ?: return
val (keySelector, valueTransform) = lastStatement.pair() ?: return
val psiFactory = KtPsiFactory(dotQualifiedExpression)
if (function == ASSOCIATE_BY_KEY_AND_VALUE) {
val destination = if (hasDestination) {
callExpression.valueArguments.firstOrNull()?.getArgumentExpression() ?: return
} else {
null
}
val newExpression = psiFactory.buildExpression {
appendExpression(receiverExpression)
appendFixedText(".")
appendFixedText(functionName)
appendFixedText("(")
if (destination != null) {
appendExpression(destination)
appendFixedText(",")
}
appendLambda(lambda, keySelector)
appendFixedText(",")
appendLambda(lambda, valueTransform)
appendFixedText(")")
}
dotQualifiedExpression.replace(newExpression)
} else {
lastStatement.replace(if (function == ASSOCIATE_WITH) valueTransform else keySelector)
val newExpression = psiFactory.buildExpression {
appendExpression(receiverExpression)
appendFixedText(".")
appendFixedText(functionName)
val valueArgumentList = callExpression.valueArgumentList
if (valueArgumentList != null) {
appendValueArgumentList(valueArgumentList)
}
if (callExpression.lambdaArguments.isNotEmpty()) {
appendLambda(lambda)
}
}
dotQualifiedExpression.replace(newExpression)
}
}
private fun BuilderByPattern<KtExpression>.appendLambda(lambda: KtLambdaExpression, body: KtExpression? = lambda.bodyExpression) {
appendFixedText("{")
lambda.valueParameters.firstOrNull()?.nameAsName?.also {
appendName(it)
appendFixedText("->")
}
appendExpression(body)
appendFixedText("}")
}
private fun BuilderByPattern<KtExpression>.appendValueArgumentList(valueArgumentList: KtValueArgumentList) {
appendFixedText("(")
valueArgumentList.arguments.forEachIndexed { index, argument ->
if (index > 0) appendFixedText(",")
appendExpression(argument.getArgumentExpression())
}
appendFixedText(")")
}
companion object {
fun replaceLastStatementForAssociateFunction(callExpression: KtCallExpression, function: AssociateFunction) {
val lastStatement = callExpression.lambda()?.functionLiteral?.lastStatement() ?: return
val (keySelector, valueTransform) = lastStatement.pair() ?: return
lastStatement.replace(if (function == ASSOCIATE_WITH) valueTransform else keySelector)
}
}
}
enum class AssociateFunction(val functionName: String) {
ASSOCIATE_WITH("associateWith"), ASSOCIATE_BY("associateBy"), ASSOCIATE_BY_KEY_AND_VALUE("associateBy");
fun name(hasDestination: Boolean): String {
return if (hasDestination) "${functionName}To" else functionName
}
}
private fun KtCallExpression.lambda(): KtLambdaExpression? {
return lambdaArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression ?: getLastLambdaExpression()
}
private fun KtFunctionLiteral.lastStatement(): KtExpression? {
return bodyExpression?.statements?.lastOrNull()
}
private fun KtExpression.pair(context: BindingContext = analyze(BodyResolveMode.PARTIAL)): Pair<KtExpression, KtExpression>? {
return when (this) {
is KtBinaryExpression -> {
if (operationReference.text != "to") return null
val left = left ?: return null
val right = right ?: return null
left to right
}
is KtCallExpression -> {
if (calleeExpression?.text != "Pair") return null
if (valueArguments.size != 2) return null
if (getResolvedCall(context)?.resultingDescriptor?.containingDeclaration?.fqNameSafe != FqName("kotlin.Pair")) return null
val first = valueArguments[0]?.getArgumentExpression() ?: return null
val second = valueArguments[1]?.getArgumentExpression() ?: return null
first to second
}
else -> return null
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceAssociateFunctionInspection.kt | 3553379693 |
// WITH_RUNTIME
// IS_APPLICABLE: false
// IS_APPLICABLE_2: false
fun foo(list: List<Any>): String? {
var v: String? = null
<caret>for (o in list) {
if (bar(o as String)) {
v = o
break
}
}
return v
}
fun bar(s: String): Boolean = true | plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/smartCasts/smartCastRequired4.kt | 2938590705 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.ide.highlighter.WorkspaceFileType
import com.intellij.ide.impl.TrustedProjectSettings
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.appSystemDir
import com.intellij.openapi.components.*
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCoreUtil
import com.intellij.openapi.project.doGetProjectFileName
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.SmartList
import com.intellij.util.ThreeState
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.io.Ksuid
import com.intellij.util.io.exists
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.messages.MessageBus
import com.intellij.util.text.nullize
import org.jetbrains.annotations.NonNls
import java.nio.file.Path
import java.util.*
@NonNls internal const val PROJECT_FILE = "\$PROJECT_FILE$"
@NonNls internal const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$"
internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false)
private val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true)
// cannot be `internal`, used in Upsource
abstract class ProjectStoreBase(final override val project: Project) : ComponentStoreWithExtraComponents(), IProjectStore {
private var dirOrFile: Path? = null
private var dotIdea: Path? = null
internal fun getNameFile(): Path = directoryStorePath!!.resolve(ProjectEx.NAME_FILE)
final override var loadPolicy = StateLoadPolicy.LOAD
final override fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD
final override fun getStorageScheme() = if (dotIdea == null) StorageScheme.DEFAULT else StorageScheme.DIRECTORY_BASED
abstract override val storageManager: StateStorageManagerImpl
protected val isDirectoryBased: Boolean
get() = dotIdea != null
final override fun setOptimiseTestLoadSpeed(value: Boolean) {
loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD
}
final override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE)
final override fun getWorkspacePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE)
final override fun clearStorages() = storageManager.clearStorages()
private fun loadProjectFromTemplate(defaultProject: Project) {
val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return
LOG.runAndLogException {
val dotIdea = dotIdea
if (dotIdea != null) {
normalizeDefaultProjectElement(defaultProject, element, dotIdea)
}
else {
moveComponentConfiguration(defaultProject, element,
storagePathResolver = { /* doesn't matter, any path will be resolved as projectFilePath (see fileResolver below) */ PROJECT_FILE }) {
if (it == "workspace.xml") {
workspacePath
}
else {
dirOrFile!!
}
}
}
}
}
final override fun getProjectBasePath(): Path {
val path = dirOrFile ?: throw IllegalStateException("setPath was not yet called")
if (isDirectoryBased) {
val useParent = System.getProperty("store.basedir.parent.detection", "true").toBoolean() &&
(path.fileName?.toString()?.startsWith("${Project.DIRECTORY_STORE_FOLDER}.") ?: false)
return if (useParent) path.parent.parent else path
}
else {
return path.parent
}
}
override fun getPresentableUrl(): String {
if (isDirectoryBased) {
return (dirOrFile ?: throw IllegalStateException("setPath was not yet called")).systemIndependentPath
}
else {
return projectFilePath.systemIndependentPath
}
}
override fun getProjectWorkspaceId() = ProjectIdManager.getInstance(project).state.id
override fun setPath(file: Path, isRefreshVfsNeeded: Boolean, template: Project?) {
dirOrFile = file
val storageManager = storageManager
val isUnitTestMode = ApplicationManager.getApplication().isUnitTestMode
val macros = ArrayList<Macro>(5)
if (file.toString().endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
macros.add(Macro(PROJECT_FILE, file))
val workspacePath = file.parent.resolve("${file.fileName.toString().removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}")
macros.add(Macro(StoragePathMacros.WORKSPACE_FILE, workspacePath))
if (isUnitTestMode) {
// we don't load default state in tests as app store does because
// 1) we should not do it
// 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations)
// load state only if there are existing files
val componentStoreLoadingEnabled = project.getUserData(IProjectStore.COMPONENT_STORE_LOADING_ENABLED)
if (if (componentStoreLoadingEnabled == null) !file.exists() else !componentStoreLoadingEnabled) {
loadPolicy = StateLoadPolicy.NOT_LOAD
}
macros.add(Macro(StoragePathMacros.PRODUCT_WORKSPACE_FILE, workspacePath))
}
}
else {
val dotIdea = file.resolve(Project.DIRECTORY_STORE_FOLDER)
this.dotIdea = dotIdea
// PROJECT_CONFIG_DIR must be first macro
macros.add(Macro(PROJECT_CONFIG_DIR, dotIdea))
macros.add(Macro(StoragePathMacros.WORKSPACE_FILE, dotIdea.resolve("workspace.xml")))
macros.add(Macro(PROJECT_FILE, dotIdea.resolve("misc.xml")))
if (isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !file.exists()
macros.add(Macro(StoragePathMacros.PRODUCT_WORKSPACE_FILE, dotIdea.resolve("product-workspace.xml")))
}
}
val presentableUrl = (if (dotIdea == null) file else projectBasePath)
val cacheFileName = doGetProjectFileName(presentableUrl.systemIndependentPath, (presentableUrl.fileName ?: "").toString().toLowerCase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION), ".", ".xml")
macros.add(Macro(StoragePathMacros.CACHE_FILE, appSystemDir.resolve("workspace").resolve(cacheFileName)))
storageManager.setMacros(macros)
if (template != null) {
loadProjectFromTemplate(template)
}
if (isUnitTestMode) {
return
}
val productSpecificWorkspaceParentDir = PathManager.getConfigDir().resolve("workspace")
val projectIdManager = ProjectIdManager.getInstance(project)
var projectId = projectIdManager.state.id
if (projectId == null) {
// do not use project name as part of id, to ensure that project dir renaming also will not cause data loss
projectId = Ksuid.generate()
projectIdManager.state.id = projectId
}
val productWorkspaceFile = productSpecificWorkspaceParentDir.resolve("$projectId.xml")
macros.add(Macro(StoragePathMacros.PRODUCT_WORKSPACE_FILE, productWorkspaceFile))
storageManager.setMacros(macros)
val trustedProjectSettings = project.service<TrustedProjectSettings>()
if (trustedProjectSettings.trustedState == ThreeState.UNSURE &&
!trustedProjectSettings.hasCheckedIfOldProject &&
productWorkspaceFile.exists()) {
LOG.info("Marked the project as trusted because there are settings in $productWorkspaceFile")
trustedProjectSettings.trustedState = ThreeState.YES
}
trustedProjectSettings.hasCheckedIfOldProject = true
}
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
if (storages.isEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
if (isDirectoryBased) {
if (storages.size == 2 && ApplicationManager.getApplication().isUnitTestMode &&
isSpecialStorage(storages.first()) &&
storages[1].path == StoragePathMacros.WORKSPACE_FILE) {
return listOf(storages.first())
}
var result: MutableList<Storage>? = null
for (storage in storages) {
if (storage.path != PROJECT_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
result!!.sortWith(deprecatedComparator)
if (isDirectoryBased) {
for (providerFactory in StreamProviderFactory.EP_NAME.getIterable(project)) {
LOG.runAndLogException {
// yes, DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION is not added in this case
providerFactory.customizeStorageSpecs(component, storageManager, stateSpec, result!!, operation)?.let { return it }
}
}
}
// if we create project from default, component state written not to own storage file, but to project file,
// we don't have time to fix it properly, so, ancient hack restored
if (!isSpecialStorage(result.first())) {
result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION)
}
return result
}
}
else {
var result: MutableList<Storage>? = null
// FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry
var hasOnlyDeprecatedStorages = true
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE || isSpecialStorage(storage)) {
if (result == null) {
result = SmartList()
}
result.add(storage)
if (!storage.deprecated) {
hasOnlyDeprecatedStorages = false
}
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
if (hasOnlyDeprecatedStorages) {
result!!.add(PROJECT_FILE_STORAGE_ANNOTATION)
}
result!!.sortWith(deprecatedComparator)
return result
}
}
}
override fun isProjectFile(file: VirtualFile): Boolean {
if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file)) {
return false
}
val filePath = file.path
if (!isDirectoryBased) {
return filePath == projectFilePath.systemIndependentPath || filePath == workspacePath.systemIndependentPath
}
return VfsUtilCore.isAncestorOrSelf(projectFilePath.parent.systemIndependentPath, file)
}
override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = dotIdea?.systemIndependentPath.nullize()
final override fun getDirectoryStorePath() = dotIdea
final override fun reloadStates(componentNames: Set<String>, messageBus: MessageBus) {
runBatchUpdate(project) {
reinitComponents(componentNames)
}
}
}
private fun isSpecialStorage(storage: Storage) = isSpecialStorage(storage.path)
internal fun isSpecialStorage(collapsedPath: String): Boolean {
return collapsedPath == StoragePathMacros.CACHE_FILE || collapsedPath == StoragePathMacros.PRODUCT_WORKSPACE_FILE
} | platform/configuration-store-impl/src/ProjectStoreBase.kt | 3645626759 |
// 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.quickfix
import com.intellij.codeInsight.daemon.impl.actions.IntentionActionWithFixAllOption
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPostfixExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
abstract class ExclExclCallFix(psiElement: PsiElement) : KotlinPsiOnlyQuickFixAction<PsiElement>(psiElement) {
override fun getFamilyName(): String = text
override fun startInWriteAction(): Boolean = true
}
class RemoveExclExclCallFix(
psiElement: PsiElement
) : ExclExclCallFix(psiElement), CleanupFix, HighPriorityAction, IntentionActionWithFixAllOption {
override fun getText(): String = KotlinBundle.message("fix.remove.non.null.assertion")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val postfixExpression = element as? KtPostfixExpression ?: return
val baseExpression = postfixExpression.baseExpression ?: return
postfixExpression.replace(baseExpression)
}
companion object : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val postfixExpression = psiElement.getNonStrictParentOfType<KtPostfixExpression>() ?: return emptyList()
return listOfNotNull(RemoveExclExclCallFix(postfixExpression))
}
}
} | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/ExclExclCallFixes.kt | 625676033 |
/*
* Copyright 2017 zhangqinglian
*
* 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.zqlite.android.diycode.device.utils
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
/**
* Created by scott on 2017/8/9.
*/
object FileUtils {
fun getFilePathByUri(context: Context, uri: Uri?): String? {
if(uri == null) return null
var filePath = "unknown"//default fileName
var filePathUri: Uri = uri
try {
if (filePathUri.scheme.compareTo("content") == 0) {
if (Build.VERSION.SDK_INT == 22 || Build.VERSION.SDK_INT == 23) {
try {
val pathUri = uri.path
val newUri = pathUri.substring(pathUri.indexOf("content"),
pathUri.lastIndexOf("/ACTUAL"))
filePathUri = Uri.parse(newUri)
} catch (e: Exception) {
e.printStackTrace()
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val cursor = context.contentResolver
.query(filePathUri, arrayOf(MediaStore.Images.Media.DATA), null, null, null)
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
filePath = cursor.getString(column_index)
}
cursor.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
} else {
val cursor = context.contentResolver.query(uri, arrayOf(MediaStore.Images.Media.DATA), null, null, null)
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
filePathUri = Uri.parse(cursor.getString(column_index))
filePath = filePathUri.path
}
} catch (e: Exception) {
cursor.close()
}
}
}
} else if (uri.scheme.compareTo("file") == 0) {
filePath = filePathUri.path
} else {
filePath = filePathUri.path
}
} catch (e: Exception) {
e.printStackTrace()
return null
}
return filePath
}
}
| src/main/kotlin/com/zqlite/android/diycode/device/utils/FileUtils.kt | 3920188775 |
/*
* Copyright (c) 2016 by Todd Ginsberg
*/
package com.ginsberg.advent2016
import com.ginsberg.advent2016.utils.Common
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
class Day24Spec : Spek({
describe("day 24") {
val sampleInput = listOf(
"###########",
"#0.1.....2#",
"#.#######.#",
"#4.......3#",
"###########"
)
describe("part 1") {
it("should answer example inputs properly") {
assertThat(Day24(sampleInput).solvePart1()).isEqualTo(14)
}
it("should answer the question with provided input") {
assertThat(Day24(Common.readFile("day_24_input.txt")).solvePart1()).isEqualTo(412)
}
}
describe("part 2") {
it("should answer the question with provided input") {
assertThat(Day24(Common.readFile("day_24_input.txt")).solvePart2()).isEqualTo(664)
}
}
}
})
| src/test/kotlin/com/ginsberg/advent2016/Day24Spec.kt | 4157042960 |
// 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtConstantExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
class WrongLongSuffixFix(element: KtConstantExpression) : KotlinQuickFixAction<KtConstantExpression>(element) {
private val corrected = element.text.trimEnd('l') + 'L'
override fun getText() = KotlinBundle.message("change.to.0", corrected)
override fun getFamilyName() = KotlinBundle.message("change.to.correct.long.suffix.l")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.replace(KtPsiFactory(project).createExpression(corrected))
}
companion object Factory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction {
val casted = Errors.WRONG_LONG_SUFFIX.cast(diagnostic)
return WrongLongSuffixFix(casted.psiElement)
}
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/WrongLongSuffixFix.kt | 3375564285 |
// "Add remaining branches" "true"
// ERROR: 'when' expression must be exhaustive, add necessary 'RED', 'GREEN', 'BLUE' branches or 'else' branch instead
package u
import e.OwnEnum
import e.getOwnEnum
fun mainContext() {
val ownLocal = getOwnEnum()
when (ownLocal) {
OwnEnum.RED -> TODO()
OwnEnum.GREEN -> TODO()
OwnEnum.BLUE -> TODO()
}
} | plugins/kotlin/idea/tests/testData/quickfix/when/addRemainingBranchesAnotherPackage.after.kt | 4119673520 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.