content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.testing import org.slf4j.* import java.net.* import java.util.* import kotlin.collections.* import kotlin.concurrent.* internal object FreePorts { private val CAPACITY = 20 private val CAPACITY_LOW = 10 private val found = Collections.synchronizedSet(HashSet<Int>()) private val free = Collections.synchronizedList(LinkedList<Int>()) init { allocate(CAPACITY) } public fun select(): Int { if (free.size < CAPACITY_LOW) { thread(name = "free-port-population") { allocate(CAPACITY - free.size) } } while (true) { try { return free.removeAt(0) } catch (expected: IndexOutOfBoundsException) { // may happen if concurrently removed allocate(CAPACITY) } } } public fun recycle(port: Int) { if (port in found && checkFreePort(port)) { free.add(port) } } private fun allocate(count: Int) { if (count <= 0) return val sockets = ArrayList<ServerSocket>() try { for (repeat in 1..count) { try { val socket = ServerSocket(0, 1) sockets.add(socket) } catch (ignore: Throwable) { log("Waiting for free ports") Thread.sleep(1000) } } } finally { sockets.removeAll { try { it.close() !found.add(it.localPort) } catch (ignore: Throwable) { true } } log("Waiting for ports cleanup") Thread.sleep(1000) sockets.forEach { free.add(it.localPort) } } } private fun checkFreePort(port: Int): Boolean { try { ServerSocket(port).close() return true } catch (unableToBind: Throwable) { return false } } private fun log(message: String) { LoggerFactory.getLogger(FreePorts::class.java).info(message) } }
ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/FreePorts.kt
1004042644
package github.jk1.smtpidea.store import github.jk1.smtpidea.server.smtp.MailSession import java.util.ArrayList import javax.swing.SwingUtilities import java.text.SimpleDateFormat import java.text.DateFormat /** * */ public object OutboxFolder : MessageFolder<MailSession>(){ private val format: DateFormat = SimpleDateFormat("DD MMM HH:mm:ss") private val columns: Array<String> = array<String>("Received", "IP", "From (Envelope)", "Recipients (Envelope)") public val mails: MutableList<MailSession> = ArrayList<MailSession>() public override fun add(message: MailSession) { SwingUtilities.invokeLater({ OutboxFolder.mails.add(message) OutboxFolder.fireTableDataChanged() }) } public override fun clear() { SwingUtilities.invokeLater({ OutboxFolder.mails.clear() OutboxFolder.fireTableDataChanged() }) } override fun getMessages() = mails override fun messageCount() = mails.size public override fun get(i: Int): MailSession { return mails.get(i) } public override fun getColumnCount() = 4 public override fun getRowCount() : Int = messageCount(); public override fun getColumnName(column: Int) = columns[column] public override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? { val info : MailSession = mails.get(rowIndex) when (columnIndex) { 0 -> return format.format(info.receivedDate) 1 -> return info.ip 2 -> return info.envelopeFrom 3 -> return info.envelopeRecipients } throw IllegalStateException("No value defined for column $columnIndex") } }
src/main/kotlin/github/jk1/smtpidea/store/OutboxFolder.kt
1411289773
package engineer.carrot.warren.warren.extension.account_notify import engineer.carrot.warren.kale.IKale import engineer.carrot.warren.warren.extension.cap.ICapExtension import engineer.carrot.warren.warren.state.JoinedChannelsState class AccountNotifyExtension(private val kale: IKale, private val channelsState: JoinedChannelsState) : ICapExtension { val handler: AccountHandler by lazy { AccountHandler(channelsState) } override fun setUp() { kale.register(handler) } override fun tearDown() { kale.unregister(handler) } }
src/main/kotlin/engineer/carrot/warren/warren/extension/account_notify/AccountNotifyExtension.kt
217432820
package org.fountainmc.api.entity.hanging import org.fountainmc.api.entity.Entity import org.fountainmc.api.entity.data.EntityData import org.fountainmc.api.entity.data.hanging.PaintingData /** * A painting that is hanging on a wall. */ interface Painting : PaintingData, HangingEntity, Entity { /** * Copy all of the mutable properties from the given data into this object. * * @param data the data to copy from * @see Entity.copyDataFrom * @see PaintingData.copyDataFrom */ override fun copyDataFrom(data: EntityData) { super<PaintingData>.copyDataFrom(data) } /** * Take a snapshot of this entity's data * * The resulting snapshot is thread-safe. * * @return a snapshot */ override fun snapshot(): PaintingData }
src/main/kotlin/org/fountainmc/api/entity/hanging/Painting.kt
3455421106
/* * 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 HTC_hand_interaction = "HTCHandInteraction".nativeClassXR("HTC_hand_interaction", type = "instance", postfix = "HTC") { documentation = """ The <a href="https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html\#XR_HTC_hand_interaction">XR_HTC_hand_interaction</a> extension. This extension defines a new interaction profile for tracked hands. """ IntConstant( "The extension specification version.", "HTC_hand_interaction_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "HTC_HAND_INTERACTION_EXTENSION_NAME".."XR_HTC_hand_interaction" ) }
modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/HTC_hand_interaction.kt
1701362000
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import core.linux.* import vulkan.* val KHR_wayland_surface = "KHRWaylandSurface".nativeClassVK("KHR_wayland_surface", type = "instance", postfix = "KHR") { javaImport("org.lwjgl.system.linux.*") documentation = """ The {@code VK_KHR_wayland_surface} extension is an instance extension. It provides a mechanism to create a {@code VkSurfaceKHR} object (defined by the {@link KHRSurface VK_KHR_surface} extension) that refers to a Wayland {@code wl_surface}, as well as a query to determine support for rendering to a Wayland compositor. <h5>VK_KHR_wayland_surface</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_KHR_wayland_surface}</dd> <dt><b>Extension Type</b></dt> <dd>Instance extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>7</dd> <dt><b>Revision</b></dt> <dd>6</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> <li>Requires {@link KHRSurface VK_KHR_surface} to be enabled</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Jesse Hall <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_wayland_surface]%20@critsec%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_wayland_surface%20extension*">critsec</a></li> <li>Ian Elliott <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_wayland_surface]%20@ianelliottus%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_wayland_surface%20extension*">ianelliottus</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2015-11-28</dd> <dt><b>IP Status</b></dt> <dd>No known IP claims.</dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Patrick Doane, Blizzard</li> <li>Jason Ekstrand, Intel</li> <li>Ian Elliott, LunarG</li> <li>Courtney Goeltzenleuchter, LunarG</li> <li>Jesse Hall, Google</li> <li>James Jones, NVIDIA</li> <li>Antoine Labour, Google</li> <li>Jon Leech, Khronos</li> <li>David Mao, AMD</li> <li>Norbert Nopper, Freescale</li> <li>Alon Or-bach, Samsung</li> <li>Daniel Rakos, AMD</li> <li>Graham Sellers, AMD</li> <li>Ray Smith, ARM</li> <li>Jeff Vigil, Qualcomm</li> <li>Chia-I Wu, LunarG</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "KHR_WAYLAND_SURFACE_SPEC_VERSION".."6" ) StringConstant( "The extension name.", "KHR_WAYLAND_SURFACE_EXTENSION_NAME".."VK_KHR_wayland_surface" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR".."1000006000" ) VkResult( "CreateWaylandSurfaceKHR", """ Create a {@code VkSurfaceKHR} object for a Wayland window. <h5>C Specification</h5> To create a {@code VkSurfaceKHR} object for a Wayland surface, call: <pre><code> ￿VkResult vkCreateWaylandSurfaceKHR( ￿ VkInstance instance, ￿ const VkWaylandSurfaceCreateInfoKHR* pCreateInfo, ￿ const VkAllocationCallbacks* pAllocator, ￿ VkSurfaceKHR* pSurface);</code></pre> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code instance} <b>must</b> be a valid {@code VkInstance} handle</li> <li>{@code pCreateInfo} <b>must</b> be a valid pointer to a valid ##VkWaylandSurfaceCreateInfoKHR structure</li> <li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid ##VkAllocationCallbacks structure</li> <li>{@code pSurface} <b>must</b> be a valid pointer to a {@code VkSurfaceKHR} handle</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_OUT_OF_HOST_MEMORY</li> <li>#ERROR_OUT_OF_DEVICE_MEMORY</li> </ul></dd> </dl> <h5>See Also</h5> ##VkAllocationCallbacks, ##VkWaylandSurfaceCreateInfoKHR """, VkInstance("instance", "the instance to associate the surface with."), VkWaylandSurfaceCreateInfoKHR.const.p("pCreateInfo", "a pointer to a ##VkWaylandSurfaceCreateInfoKHR structure containing parameters affecting the creation of the surface object."), nullable..VkAllocationCallbacks.const.p("pAllocator", "the allocator used for host memory allocated for the surface object when there is no more specific allocator available (see <a target=\"_blank\" href=\"https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\\#memory-allocation\">Memory Allocation</a>)."), Check(1)..VkSurfaceKHR.p("pSurface", "a pointer to a {@code VkSurfaceKHR} handle in which the created surface object is returned.") ) VkBool32( "GetPhysicalDeviceWaylandPresentationSupportKHR", """ Query physical device for presentation to Wayland. <h5>C Specification</h5> To determine whether a queue family of a physical device supports presentation to a Wayland compositor, call: <pre><code> ￿VkBool32 vkGetPhysicalDeviceWaylandPresentationSupportKHR( ￿ VkPhysicalDevice physicalDevice, ￿ uint32_t queueFamilyIndex, ￿ struct wl_display* display);</code></pre> <h5>Description</h5> This platform-specific function <b>can</b> be called prior to creating a surface. <h5>Valid Usage</h5> <ul> <li>{@code queueFamilyIndex} <b>must</b> be less than {@code pQueueFamilyPropertyCount} returned by {@code vkGetPhysicalDeviceQueueFamilyProperties} for the given {@code physicalDevice}</li> </ul> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li> <li>{@code display} <b>must</b> be a valid pointer to a {@code wl_display} value</li> </ul> """, VkPhysicalDevice("physicalDevice", "the physical device."), uint32_t("queueFamilyIndex", "the queue family index."), wl_display.p("display", "a pointer to the {@code wl_display} associated with a Wayland compositor.") ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/KHR_wayland_surface.kt
3637916856
/* * Rezult - KToolZ * * Copyright (c) 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @file:JvmName("ResultToolbox") package com.github.ktoolz.rezult import com.github.ktoolz.rezult.exceptions.ResultException import java.util.* import java.util.function.Consumer // ---------------------------------------------------------------- // Property extensions for lambdas to retrieve results // ---------------------------------------------------------------- /** * Property extension on lambdas with no parameters. * * Provides the same lambda but returning a [Result] of the original return type. */ val <T> (() -> T).lambdaresult: () -> Result<T> get() = { Result.of(this) } /** * Property extension on lambdas with no parameters. * * Provides a [Result] containing the value returned by the lambda execution. */ val <T> (() -> T).result: Result<T> get() = Result.of(this) /** * Extension on lambdas with no parameters. * * Provides a [Result] containing the value returned by the lambda execution. */ fun <T> (() -> T).toResult(): Result<T> = Result.of(this) /** * Property extension on lambdas with one parameter. * * Provides the same lambda but returning a [Result] of the original return type. */ val <T, A> ((A) -> T).lambdaresult: (A) -> Result<T> get() = { a -> Result.of({ this(a) }) } /** * Property extension on lambdas with two parameters. * * Provides the same lambda but returning a [Result] of the original return type. */ val <T, A, B> ((A, B) -> T).result: (A, B) -> Result<T> get() = { a, b -> Result.of({ this(a, b) }) } /** * Property extension on lambdas with three parameters. * * Provides the same lambda but returning a [Result] of the original return type. */ val <T, A, B, C> ((A, B, C) -> T).result: (A, B, C) -> Result<T> get() = { a, b, c -> Result.of({ this(a, b, c) }) } /** * Property extension on lambdas with four parameters. * * Provides the same lambda but returning a [Result] of the original return type. */ val <T, A, B, C, D> ((A, B, C, D) -> T).result: (A, B, C, D) -> Result<T> get() = { a, b, c, d -> Result.of({ this(a, b, c, d) }) } // ---------------------------------------------------------------- // Type extensions for creating results easily // ---------------------------------------------------------------- /** * Extension on any type. * * Provides a success [Result] out of the type. * * @return a [Result] object (success) linked to this type. */ fun <T> T.toResult() = Result.success(this) /** * Extension for [Exception]. * * Provides a failure [Result] out of the exception. * * @return a [Result] object (failure) linked to this [Exception]. */ fun <T : Exception, V> T.toResult() = Result.failure<V>(this) /** * Extension on any type. * * Provides a validate method allowing to validate a value from a lambda, and creates a [Result] out of the validation. * * @param[errorMessage] an error message to be used in the [Result] if the validation fails. * @param[validator] a lambda to be applied on the type and returning a [Boolean] value, validating its content. * * @return a [Result] object containing the result of the validation. */ @JvmOverloads fun <T> T.validate(errorMessage: String = "Validation error", validator: T.() -> Boolean): Result<T> = toResult().validate(errorMessage, validator) // ---------------------------------------------------------------- // Extensions for manipulating Results on few types // ---------------------------------------------------------------- /** * Extension on boolean [Result]. * * Allows to use the `!` operator on boolean [Result] directly. Will keep the [Result] status (failures won't change). * * @return a [Result] object containing the opposite [Boolean] (if success), or the same failure [Result]. */ operator fun Result<Boolean>.not() = onSuccess { Result.success(!it) } /** * Extension on boolean [Result]. * * Allows to check if a boolean [Result] is true or not. If it's true, it'll return the same result. Otherwise it'll return a failure. * * @return the same [Result] object if the boolean is true, a failure otherwise. */ fun Result<Boolean>.isTrue() = validate { this } /** * Extension on [IntRange] for [Result]. * * Allows to check if a [Result] is contained in a particular range using the `in` operator. Will keep the [Result] status (failures won't change). * * @param[value] the [Result] we'd like to see in the range. * * @return true if the [Result] value is contained in the range. */ operator fun IntRange.contains(value: Result<Int>) = value.validate { [email protected](this) }.isSuccess() // ---------------------------------------------------------------- // Definition of Result and its operations // ---------------------------------------------------------------- /** * A wrapper to any operation call. * * Allows to check if a particular call is a Success or a Failure, and chain other operations on this [Result]. * * @author jean-marc, aurelie, antoine */ sealed class Result<T> { // ---------------------------------------------------------------- // Basic operations // ---------------------------------------------------------------- /** * Defines if the [Result] is a Success. * * @return true if the [Result] is a Success. */ abstract fun isSuccess(): Boolean /** * Opposite of [isSuccess]. Defines if the [Result] is a Failure. * * @return true if the [Result] is a Failure. */ fun isFailure(): Boolean = !isSuccess() // ---------------------------------------------------------------- // Success operations // ---------------------------------------------------------------- /** * Executes an operation on a Success result, and returns a new [Result] containing that operation's response. * * @param[operation] an operation to be applied on the [Result] value, returning a new [Result] (that might have another type). * * @return the [Result] coming from the operation applied to this [Result] value. */ abstract fun <U> onSuccess(operation: (T) -> Result<U>): Result<U> /** * Executes an operation on a Success result, as if we had a `with (success)`, and returns a new [Result] containing that operation's response. * * @param[operation] an operation to be applied on the [Result] value, returning a new [Result] (that might have another type). * * @return the [Result] coming from the operation applied to this [Result] value. * * @see [onSuccess] - it does the same but is maybe a bit easier to use / more clear to use. */ fun <U> withSuccess(operation: T.() -> Result<U>) = onSuccess(operation) /** * Executes a log operation (returning nothing) on a Success result. * * @param[operation] an operation to be applied on the [Result] value, returning nothing. Basically to be used for logging purpose or something like this. * * @return the same [Result] you had in a first time. */ @JvmName("_logSuccessKotlin") fun logSuccess(operation: T.() -> Unit): Result<T> = withSuccess { [email protected] { operation() } } /** * Same as [logSuccess(operation: T.() -> Unit): Result<T>] but with a more java friendly object */ fun logSuccess(operation: Consumer<T>): Result<T> = withSuccess { [email protected] { operation.accept(this@withSuccess) } } /** * Tries to execute an operation which returns a new [Result] on a Success result. * It'll return the same first [Result] object if the operation is ok, but it'll return a failure if the operation returned a failed result. * * @param[operation] an operation to be applied on the [Result] value, returning a new [Result]. The result of this operation will be used in order to check if we should return the same object or not. * * @return the same [Result] if the operation is successful, or a failure if the operation result isn't a success. */ fun <U> tryWithSuccess(operation: T.() -> Result<U>): Result<T> = withSuccess { @Suppress("UNCHECKED_CAST") operation().let { when (it) { is Success -> this@Result else -> it as Result<T> // It's a failure so we don't care about the cast because there is no value of this type } } } // ---------------------------------------------------------------- // Failure operations // ---------------------------------------------------------------- /** * Executes an operation on a Failure exception, and returns a new [Result] containing the operation's response. * * The new [Result] must have the same type as the one you specified previously. * * @param[operation] an operation to be applied on the [Result] exception, retuning a new [Result] (with the same type). * * @return the [Result] coming from the operation applied to this [Result] exception. */ abstract fun onFailure(operation: (Throwable) -> Result<T>): Result<T> /** * Executes an operation on a Failure exception, as if we had a `with (failure)`, and returns a new [Result] containing that operation's response. * * @param[operation] an operation to be applied on the [Result] exception, returning a new [Result] (with the same type). * * @return the [Result] coming from the operation applied to this [Result] exception. */ fun withFailure(operation: Throwable.() -> Result<T>) = onFailure(operation) /** * Executes a log operation (returning nothing) on a Failure exception. * * @param[operation] an operation to be applied on the [Result] exception, returning nothing. Basically to be used for logging purpose or something like this. * * @return the same [Result] you had in a first time. */ @JvmName("_logFailureKotlin") fun logFailure(operation: Throwable.() -> Unit): Result<T> = withFailure { [email protected] { operation() } } /** * Same as [logFailure(operation: Exception.() -> Unit): Result<T>] but with a more java friendly object */ fun logFailure(operation: Consumer<Throwable>): Result<T> = withFailure { [email protected] { operation.accept(this@withFailure) } } // ---------------------------------------------------------------- // Common operations // ---------------------------------------------------------------- /** * Validates a [Result] using a simple lambda expression, and turn the [Result] in a failure if the [Result] value isn't matching a particular validation. * * Cannot be used for *false positive* where you'd like to turn an [Exception] into a Success. * * @param[errorMessage] an error message you want to specify if the validation fails - that will be used in the created failure. * @param[validator] an operation to be applied on the [Result] value validating its content that will return a [Boolean]. * * @return the same [Result] if the validation was ok, or a new [Result] failure if the validation was not ok. */ @JvmOverloads fun validate(errorMessage: String = "Validation error", validator: T.() -> Boolean): Result<T> = withSuccess { if (this.validator()) this@Result else failure(ResultException(errorMessage)) } /** * Retrieves a [Result] value (if the [Result] is a success) or will call the provided [backup] operation to retrieve a backup value. * * @param[backup] an operation allowing to retrieve a backup value in case the [Result] is a Failure. * * @return the [Result] value if the result is a Success, otherwise the result of the [backup] operation. */ abstract fun getOrElse(backup: () -> T): T /** * Retrieves a [Result] value (if the [Result] is a success) or will return the provided [backupValue]. * * @param[backupValue] a backup value to be returned in case the [Result] is a Failure. * * @return the [Result] value if the result is a Success, otherwise the provided [backupValue]. * * @see [getOrElse] - same operation using a provider. */ fun getOrElse(backupValue: T) = getOrElse({ backupValue }) /** * Calls [getOrElse] in a better looking way. * * Basically just calls [getOrElse]. * * @param[backup] a backup value to be returned in case the [Result] is a Failure. * * @return the [Result] value if the result is a Success, otherwise the provided [backup]. * * @see [getOrElse] - operation which is actually called. */ infix fun or(backup: T) = getOrElse(backup) /** * Checks if a [Result] value contains a provided [value]. Will obviously be false if the [Result] is a Failure. * * @param[value] the value you'd like to find in the [Result]. * * @return true if the [Result] is a Success and actually contains the [value], false otherwise. */ abstract operator infix fun contains(value: T): Boolean // ---------------------------------------------------------------- // Companion object // ---------------------------------------------------------------- /** * Just a simple companion object for [Result] */ companion object { // ---------------------------------------------------------------- // Helpers for creating Result objects // ---------------------------------------------------------------- /** * Creates a Success result from a value. * * @param[value] the value to be used for creating the Success object. * * @return a Success object containing the provided [value]. */ @JvmStatic fun <T> success(value: T): Result<T> = Success(value) /** * Creates a Failure result from an [Exception]. * * @param[exception] the [Exception] to be used for creating the Failure object. * * @return a Failure object containing the provided [exception]. */ @JvmStatic fun <T> failure(exception: Throwable): Result<T> = Failure(exception) /** * Creates a Failure result from a message. It'll internally wrap that message in a [ResultException]. * * @param[message] the failure message to be used for creating the [ResultException]. * * @return a Failure object containing a [ResultException] using the provided [message]. */ @JvmStatic fun <T> failure(message: String): Result<T> = Failure(ResultException(message)) // ---------------------------------------------------------------- // Methods for executing operations and creating results // ---------------------------------------------------------------- /** * Executes the provided [operation] and computes a [Result] object out of it. * * It basically catches [Exception] while executing the operation, and returns a Failure if there's an [Exception]. * * @param[operation] the operation to be executed and which will lead to a [Result] object creation. * * @return a Success object containing the result of the [operation] if there's no [Exception] raised. Otherwise it'll return a Failure containing that [Exception]. */ @JvmStatic fun <T> of(operation: () -> T): Result<T> = try { Success(operation()) } catch(e: Exception) { Failure(e) } /** * Executes all the provided [actions] and returns the first Success result if there's one. Otherwise, it'll just return a Failure. * * @param[actions] a list of operations to be executed till one is a Success. * * @return the first Success coming for the [actions] execution, a Failure if none of the [actions] creates a Success. */ @JvmStatic fun <T> chain(vararg actions: () -> Result<T>): Result<T> = try { // asSequence turn the evaluation to lazy mode actions.asSequence().map { it() }.first { it.isSuccess() } } catch (e: NoSuchElementException) { failure("All failed") } } // ---------------------------------------------------------------- // Implementation of Success object // ---------------------------------------------------------------- /** * A wrapper for any successful operation execution, containing the final result of that execution. * * @propertySuccess the actual value of the [Result]. * * @see [Result]. */ private class Success<T>(val success: T) : Result<T>() { /** * @see [Result.isSuccess]. */ override fun isSuccess() = true /** * @see [Result.onSuccess]. */ override fun <U> onSuccess(operation: (T) -> Result<U>): Result<U> = try { operation(success) } catch (e: Exception) { failure(e) } /** * @see [Result.onFailure]. */ override fun onFailure(operation: (Throwable) -> Result<T>): Result<T> = this /** * @see [Result.getOrElse]. */ override fun getOrElse(backup: () -> T): T = success /** * @see [Result.contains]. */ override fun contains(value: T): Boolean = success == value /** * Returns the value of the success in a formatted [String]. * * @return the value of the [Result] in a formatted [String]. */ override fun toString(): String = "Success[$success]" } // ---------------------------------------------------------------- // Implementation of Failure object // ---------------------------------------------------------------- /** * A wrapper for any failed operation execution, containing the [Exception] which caused the failure of that execution. * * @propertyFailure the [Exception] that caused the failure of the operation execution. * * @see [Result]. */ private class Failure<T>(val failure: Throwable) : Result<T>() { /** * @see [Result.isSuccess]. */ override fun isSuccess(): Boolean = false /** * @see [Result.onSuccess]. */ override fun <U> onSuccess(operation: (T) -> Result<U>): Result<U> = Failure(failure) /** * @see [Result.onFailure]. */ override fun onFailure(operation: (Throwable) -> Result<T>): Result<T> = try { operation(failure) } catch (e: Exception) { failure(e) } /** * @see [Result.getOrElse]. */ override fun getOrElse(backup: () -> T): T = backup() /** * @see [Result.contains]. */ override fun contains(value: T): Boolean = false /** * Returns the name of the [Exception] in a formatted [String]. * * @return the name of the [Exception] in a formatted [String]. */ override fun toString(): String = "Failure[${failure.javaClass}]" } }
src/main/kotlin/com/github/ktoolz/rezult/Result.kt
3445011583
package org.spekframework.intellij import com.intellij.execution.configurations.ConfigurationTypeBase import org.jetbrains.kotlin.idea.KotlinIcons class SpekJvmConfigurationType: ConfigurationTypeBase( "org.spekframework.spek2-jvm", "Spek 2 - JVM", "Run Spek 2 tests", KotlinIcons.SMALL_LOGO_13 ), SpekConfigurationType { init { addFactory(SpekJvmConfigurationFactory(this)) } }
spek-ide-plugin-intellij-idea/src/main/kotlin/org/spekframework/intellij/SpekJvmConfigurationType.kt
179830233
package com.gulden.unity_wallet.ui import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.os.Bundle import android.text.Spannable import android.text.SpannableString import android.text.style.BackgroundColorSpan import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.appcompat.view.ActionMode import androidx.appcompat.widget.ShareActionProvider import androidx.core.view.MenuItemCompat import com.gulden.jniunifiedbackend.ILibraryController import com.gulden.unity_wallet.* import com.gulden.unity_wallet.util.AppBaseActivity import com.gulden.unity_wallet.util.gotoWalletActivity import com.gulden.unity_wallet.util.setFauxButtonEnabledState import kotlinx.android.synthetic.main.activity_show_recovery_phrase.* import org.jetbrains.anko.sdk27.coroutines.onClick private const val TAG = "show-recovery-activity" class ShowRecoveryPhraseActivity : AppBaseActivity(), UnityCore.Observer { private val erasedWallet = UnityCore.instance.isCoreReady() //fixme: (GULDEN) Change to char[] to we can securely wipe. private var recoveryPhrase: String? = null internal var recoveryPhraseTrimmed: String? = null private var shareActionProvider: ShareActionProvider? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_show_recovery_phrase) recoveryPhrase = intent.getStringExtra(this.packageName + "recovery_phrase_with_birth") recoveryPhraseTrimmed = intent.getStringExtra(this.packageName + "recovery_phrase") recovery_phrase_text_view.run { //TODO: Reintroduce showing birth time here if/when we decide we want it in future text = recoveryPhraseTrimmed onClick { setFocusOnRecoveryPhrase() } } supportActionBar?.hide() updateView() UnityCore.instance.addObserver(this, fun (callback:() -> Unit) { runOnUiThread { callback() }}) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } override fun onDestroy() { UnityCore.instance.removeObserver(this) //fixme: (GULDEN) Securely wipe. recoveryPhrase = "" recoveryPhraseTrimmed = "" super.onDestroy() } override fun onWalletReady() { if (!erasedWallet) gotoWalletActivity(this) } override fun onWalletCreate() { // do nothing, we are supposed to sit here until the wallet was created } @Suppress("UNUSED_PARAMETER") fun onAcceptRecoveryPhrase(view: View) { // Only allow user to move on once they have acknowledged writing the recovery phrase down. if (!acknowledge_recovery_phrase.isChecked) { Toast.makeText(applicationContext, "Write down your recovery phrase", Toast.LENGTH_LONG).show() return } button_accept_recovery_phrase.visibility = View.INVISIBLE // TODO must have core started and createWallet signal Authentication.instance.chooseAccessCode( this, null, action = fun(password: CharArray) { if (UnityCore.instance.isCoreReady()) { if (ILibraryController.ContinueWalletFromRecoveryPhrase(recoveryPhrase, password.joinToString(""))) { gotoWalletActivity(this) } else { internalErrorAlert(this, "$TAG continuation failed") } } else { // Create the new wallet, a coreReady event will follow which will proceed to the main activity if (!ILibraryController.InitWalletFromRecoveryPhrase(recoveryPhrase, password.joinToString(""))) internalErrorAlert(this, "$TAG init failed") } }, cancelled = fun() {button_accept_recovery_phrase.visibility = View.VISIBLE} ) } @Suppress("UNUSED_PARAMETER") fun onAcknowledgeRecoveryPhrase(view: View) { updateView() } private fun updateView() { setFauxButtonEnabledState(button_accept_recovery_phrase, acknowledge_recovery_phrase.isChecked) } internal inner class ActionBarCallBack : ActionMode.Callback { override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { return if (item.itemId == R.id.item_copy_to_clipboard) { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("backup", recoveryPhraseTrimmed) clipboard.setPrimaryClip(clip) mode.finish() Toast.makeText(applicationContext, R.string.recovery_phrase_copy, Toast.LENGTH_LONG).show() true } else false } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.share_menu, menu) // Handle buy button val itemBuy = menu.findItem(R.id.item_buy_gulden) itemBuy.isVisible = false // Handle copy button //MenuItem itemCopy = menu.findItem(R.id.item_copy_to_clipboard); // Handle share button val itemShare = menu.findItem(R.id.action_share) shareActionProvider = ShareActionProvider(this@ShowRecoveryPhraseActivity) MenuItemCompat.setActionProvider(itemShare, shareActionProvider) val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_TEXT, recoveryPhraseTrimmed) shareActionProvider!!.setShareIntent(intent) @Suppress("DEPRECATION") val color = resources.getColor(R.color.colorPrimary) val spannableString = SpannableString(recovery_phrase_text_view.text) spannableString.setSpan(BackgroundColorSpan(color), 0, recovery_phrase_text_view.text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) recovery_phrase_text_view.text = spannableString return true } override fun onDestroyActionMode(mode: ActionMode) { shareActionProvider = null recovery_phrase_text_view.text = recoveryPhraseTrimmed ?: "" } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { return false } } private fun setFocusOnRecoveryPhrase() { startSupportActionMode(ActionBarCallBack()) } }
src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/ui/ShowRecoveryPhraseActivity.kt
3889860137
package com.ashish.movieguide.di.multibindings interface ComponentBuilder<in T, out C : AbstractComponent<T>> { fun build(): C }
app/src/main/kotlin/com/ashish/movieguide/di/multibindings/ComponentBuilder.kt
3894018160
// 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.testFramework.rules import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder import org.junit.jupiter.api.extension.AfterEachCallback import org.junit.jupiter.api.extension.BeforeEachCallback import org.junit.jupiter.api.extension.ExtensionContext import org.junit.rules.ExternalResource import org.junit.runner.Description import org.junit.runners.model.Statement import java.net.URLEncoder import java.nio.file.FileSystem import java.nio.file.Path import kotlin.properties.Delegates class InMemoryFsRule(private val windows: Boolean = false) : ExternalResource() { private var _fs: FileSystem? = null private var sanitizedName: String by Delegates.notNull() override fun apply(base: Statement, description: Description): Statement { sanitizedName = URLEncoder.encode(description.methodName, Charsets.UTF_8.name()) return super.apply(base, description) } val fs: FileSystem get() { if (_fs == null) { _fs = (if (windows) MemoryFileSystemBuilder.newWindows().setCurrentWorkingDirectory("C:\\") else MemoryFileSystemBuilder.newLinux().setCurrentWorkingDirectory("/")).build(sanitizedName) } return _fs!! } override fun after() { _fs?.close() _fs = null } } class InMemoryFsExtension(private val windows: Boolean = false) : BeforeEachCallback, AfterEachCallback { private var _fs: FileSystem? = null private var sanitizedName: String by Delegates.notNull() val root: Path get() { return fs.getPath("/") } val fs: FileSystem get() { if (_fs == null) { _fs = (if (windows) MemoryFileSystemBuilder.newWindows().setCurrentWorkingDirectory("C:\\") else MemoryFileSystemBuilder.newLinux().setCurrentWorkingDirectory("/")).build(sanitizedName) } return _fs!! } override fun beforeEach(context: ExtensionContext) { sanitizedName = URLEncoder.encode(context.displayName, Charsets.UTF_8.name()) } override fun afterEach(context: ExtensionContext) { (_fs ?: return).close() _fs = null } }
platform/testFramework/extensions/src/com/intellij/testFramework/rules/InMemoryFsRule.kt
1338378271
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.toolWindow import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.Pair import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.WindowInfo import it.unimi.dsi.fastutil.objects.Object2FloatOpenHashMap internal class ToolWindowPaneState { private val idToSplitProportion = Object2FloatOpenHashMap<String>() var maximizedProportion: Pair<ToolWindow, Int>? = null var isStripesOverlaid = false fun getPreferredSplitProportion(id: String?, defaultValue: Float): Float { val f = idToSplitProportion.getFloat(id) return if (f == 0f) defaultValue else f } fun addSplitProportion(info: WindowInfo, component: InternalDecoratorImpl?, splitter: Splitter) { if (info.isSplit && component != null) { idToSplitProportion.put(component.toolWindow.id, splitter.proportion) } } fun isMaximized(window: ToolWindow): Boolean { return maximizedProportion != null && maximizedProportion!!.first === window } }
platform/platform-impl/src/com/intellij/toolWindow/ToolWindowPaneState.kt
625451370
object ResolveFromFile { fun main() { ResolveToFile.target() } }
server/src/test/resources/hover/ResolveFromFile.kt
467155680
// ERROR: Type mismatch: inferred type is String? but String was expected class TestJava { var nullableInitializerFieldCast: String = nullableObj(3) as String? private val nullableInitializerPrivateFieldCast = nullableObj(3) as String? fun nullableObj(p: Int): Any? { return if (p > 0) "response" else null } fun testProperty() { nullableInitializerFieldCast[0] nullableInitializerPrivateFieldCast!![0] } fun testLocalVariable() { val nullableInitializerValCast = nullableObj(3) as String? nullableInitializerValCast!![0] } }
plugins/kotlin/j2k/old/tests/testData/fileOrElement/nullability/nullableInitializer2.kt
1788834171
abstract class A { abstract fun memberFunInA() abstract val memberValInA: Int inner class InnerInA class NestedInA } abstract class B : A() { abstract fun memberFunInB() abstract val memberValInB: Int inner class InnerInB class NestedInB } fun A.extensionFun(){} val A.extensionVal: Int get() = 1 fun B.extensionFunForB(){} fun Any.anyExtensionFun(){} fun String.wrongExtensionFun(){} fun globalFun(p: Int) {} val globalVal = 1 class C { fun memberFun(){} val memberVal = 1 fun A.memberExtensionFun(){} fun foo(a: A) { fun localFun(){} if (a is B) { val v = a::<caret> } } companion object { fun companionObjectFun(){} fun A.companionExtension(){} } } // EXIST: class // EXIST_JAVA_ONLY: class.java // EXIST: { itemText: "memberFunInA", attributes: "" } // EXIST: { itemText: "memberValInA", attributes: "" } // ABSENT: NestedInA // EXIST: { itemText: "extensionFun", attributes: "" } // EXIST: { itemText: "extensionVal", attributes: "" } // EXIST: { itemText: "anyExtensionFun", attributes: "" } // ABSENT: wrongExtensionFun // ABSENT: globalFun // ABSENT: globalVal // ABSENT: memberFun // ABSENT: memberVal // ABSENT: memberExtensionFun // ABSENT: localFun // ABSENT: companionObjectFun // ABSENT: companionExtension // EXIST: { itemText: "memberFunInB", attributes: "bold" } // EXIST: { itemText: "memberValInB", attributes: "bold" } // EXIST: { itemText: "InnerInB", attributes: "bold" } // EXIST: { itemText: "InnerInA", attributes: "" } // ABSENT: NestedInB // EXIST: { itemText: "extensionFunForB", attributes: "bold" }
plugins/kotlin/completion/tests/testData/basic/common/callableReference/ExpressionQualifier.kt
1127094497
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jem.imabw.ui import javafx.geometry.Pos import javafx.scene.Scene import javafx.scene.control.Label import javafx.scene.control.SplitPane import javafx.scene.control.Tooltip import javafx.scene.layout.BorderPane import javafx.scene.layout.HBox import jclp.EventBus import jclp.log.Log import jclp.text.ifNotEmpty import jclp.text.or import jem.Attributes import jem.author import jem.imabw.Imabw import jem.imabw.UISettings import jem.imabw.Workbench import jem.imabw.WorkflowEvent import jem.title import mala.App import mala.ixin.* import java.util.* class Dashboard : IApplication(UISettings), CommandHandler { private val tagId = "Dashboard" lateinit var contentPane: SplitPane lateinit var designer: AppDesigner lateinit var accelerators: Properties override fun init() { Imabw.register(this) } override fun setup(scene: Scene, appPane: AppPane) { designer = App.assets.designerFor("ui/designer.json")!! scene.stylesheets += UISettings.stylesheetUri or { App.assets.resourceFor("ui/default.css")!!.toExternalForm() } appPane.setup(designer, actionMap, menuMap) accelerators = App.assets.propertiesFor("ui/keys.properties")!! actionMap.updateAccelerators(accelerators) appPane.statusBar?.right = Indicator contentPane = SplitPane().also { split -> split.id = "main-split-pane" split.items.addAll(ContentsPane, EditorPane) split.setDividerPosition(0, 0.24) SplitPane.setResizableWithParent(ContentsPane, false) appPane.center = split } initActions() restoreState() EventBus.register<WorkflowEvent> { refreshTitle() } statusText = App.tr("status.ready") } override fun restoreState() { super.restoreState() ContentsPane.isVisible = UISettings.navigationBarVisible if (!ContentsPane.isVisible) contentPane.items.remove(0, 1) } override fun saveState() { super.saveState() UISettings.navigationBarVisible = ContentsPane.isVisible } internal fun dispose() { saveState() stage.close() } private fun initActions() { actionMap["showToolbar"]?.selectedProperty?.bindBidirectional(appPane.toolBar!!.visibleProperty()) actionMap["showStatusBar"]?.selectedProperty?.bindBidirectional(appPane.statusBar!!.visibleProperty()) actionMap["showNavigateBar"]?.selectedProperty?.bindBidirectional(ContentsPane.visibleProperty()) actionMap["toggleFullScreen"]?.let { action -> stage.fullScreenProperty().addListener { _, _, value -> action.isSelected = value } action.selectedProperty.addListener { _, _, value -> stage.isFullScreen = value } } } private fun refreshTitle() { val work = Workbench.work!! val book = work.book with(StringBuilder()) { if (work.isModified) { append("*") } append(book.title) append(" - ") book.author.ifNotEmpty { append("[") append(it.replace(Attributes.VALUE_SEPARATOR, " & ")) append("] - ") } work.path?.let { append(it) append(" - ") } append("PW Imabw ") append(Imabw.version) stage.title = toString() } } override fun handle(command: String, source: Any): Boolean { when (command) { "showToolbar", "showStatusBar", "toggleFullScreen" -> Unit // bound with property "showNavigateBar" -> { if (!ContentsPane.isVisible) { contentPane.items.remove(0, 1) } else { contentPane.items.add(0, ContentsPane) contentPane.setDividerPosition(0, 0.24) } } in editActions -> stage.scene.focusOwner.let { (it as? EditAware)?.onEdit(command) ?: Log.d(tagId) { "focused object is not editable: $it" } } else -> return false } return true } } object Indicator : HBox() { val caret = Label().apply { tooltip = Tooltip(App.tr("status.caret.toast")) } val words = Label().apply { tooltip = Tooltip(App.tr("status.words.toast")) } val mime = Label().apply { tooltip = Tooltip(App.tr("status.mime.toast")) } init { id = "indicator" alignment = Pos.CENTER BorderPane.setAlignment(this, Pos.CENTER) children.addAll(caret, words, mime) IxIn.newAction("lock").toButton(Imabw, Style.TOGGLE, hideText = true).also { children += it } IxIn.newAction("gc").toButton(Imabw, hideText = true).also { children += it } reset() } fun reset() { updateCaret(-1, -1, 0) updateWords(-1) updateMime("") } fun updateCaret(row: Int, column: Int, selection: Int) { if (row < 0) { caret.isVisible = false } else { caret.isVisible = true caret.text = when { selection > 0 -> "$row:$column/$selection" else -> "$row:$column" } } } fun updateWords(count: Int) { if (count < 0) { words.isVisible = false } else { words.isVisible = true words.text = count.toString() } } fun updateMime(type: String) { if (type.isEmpty()) { mime.isVisible = false } else { mime.isVisible = true mime.text = type } } } private val editActions = arrayOf( "undo", "redo", "cut", "copy", "paste", "delete", "selectAll", "find", "replace", "findNext", "findPrevious" ) interface EditAware { fun onEdit(command: String) }
imabw/src/main/kotlin/jem/imabw/ui/Dashboard.kt
2125154380
package com.github.codeql.utils.versions import org.jetbrains.kotlin.backend.jvm.ir.isRawType import org.jetbrains.kotlin.ir.types.IrSimpleType fun IrSimpleType.isRawType() = this.isRawType()
java/kotlin-extractor/src/main/kotlin/utils/versions/v_1_6_20/Types.kt
1727386319
package com.beust.klaxon import com.beust.klaxon.internal.ConverterFinder import java.io.* import java.nio.charset.Charset import kotlin.collections.set import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.KTypeProjection import kotlin.reflect.full.createType import kotlin.reflect.full.functions import kotlin.reflect.jvm.javaField import kotlin.reflect.jvm.javaMethod import kotlin.reflect.jvm.javaType class Klaxon( val instanceSettings: KlaxonSettings = KlaxonSettings() ) : ConverterFinder { /** * Parse a JsonReader into a JsonObject. */ @Suppress("unused") fun parseJsonObject(reader: JsonReader) = parser().parse(reader) as JsonObject /** * Parse a Reader into a JsonObject. */ @Suppress("unused") fun parseJsonObject(reader: Reader) = parser().parse(reader) as JsonObject /** * Parse a Reader into a JsonArray. */ @Suppress("unused") fun parseJsonArray(reader: Reader) = parser().parse(reader) as JsonArray<*> /** * Parse a JSON string into an object. */ @Suppress("unused") inline fun <reified T> parse(json: String): T? = maybeParse(parser(T::class).parse(StringReader(json)) as JsonObject) /** * Parse a JSON string into a List. */ @Suppress("unused") inline fun <reified T> parseArray(json: String): List<T>? = parseFromJsonArray(parser(T::class).parse(StringReader(json)) as JsonArray<*>) /** * Parse a JSON file into an object. */ @Suppress("unused") inline fun <reified T> parse(file: File): T? = FileReader(file).use { reader -> maybeParse(parser(T::class).parse(reader) as JsonObject) } /** * Parse a JSON file into a List. */ @Suppress("unused") inline fun <reified T> parseArray(file: File): List<T>? = FileReader(file).use { reader -> parseFromJsonArray(parser(T::class).parse(reader) as JsonArray<*>) } /** * Parse an InputStream into an object. */ @Suppress("unused") inline fun <reified T> parse(inputStream: InputStream): T? { return maybeParse(parser(T::class).parse(toReader(inputStream)) as JsonObject) } /** * Parse an InputStream into a List. */ @Suppress("unused") inline fun <reified T> parseArray(inputStream: InputStream): List<T>? = parseFromJsonArray(parser(T::class).parse(toReader(inputStream)) as JsonArray<*>) /** * Parse a JsonReader into an object. */ @Suppress("unused") inline fun <reified T> parse(jsonReader: JsonReader): T? { val p = parser(T::class, jsonReader.lexer, streaming = true) return maybeParse(p.parse(jsonReader) as JsonObject) } /** * Parse a JsonReader into a List. */ @Suppress("unused") inline fun <reified T> parseArray(jsonReader: JsonReader): List<T>? { val p = parser(T::class, jsonReader.lexer, streaming = true) return parseFromJsonArray(p.parse(jsonReader) as JsonArray<*>) } /** * Parse a Reader into an object. */ @Suppress("unused") inline fun <reified T> parse(reader: Reader): T? { return maybeParse(parser(T::class).parse(reader) as JsonObject) } /** * Parse a Reader into a List. */ @Suppress("unused") inline fun <reified T> parseArray(reader: Reader): List<T>? { return parseFromJsonArray(parser(T::class).parse(reader) as JsonArray<*>) } /** * Parse a JsonObject into an object. */ inline fun <reified T> parseFromJsonObject(map: JsonObject): T? = fromJsonObject(map, T::class.java, T::class) as T? inline fun <reified T> parseFromJsonArray(map: JsonArray<*>): List<T>? { val result = arrayListOf<Any?>() map.forEach { jo -> if (jo is JsonObject) { val t = parseFromJsonObject<T>(jo) if (t != null) result.add(t) else throw KlaxonException("Couldn't convert $jo") } else if (jo != null) { val converter = findConverterFromClass(T::class.java, null) val convertedValue = converter.fromJson(JsonValue(jo, null, null, this)) result.add(convertedValue) } else { throw KlaxonException("Couldn't convert $jo") } } @Suppress("UNCHECKED_CAST") return result as List<T> } inline fun <reified T> maybeParse(map: JsonObject): T? = parseFromJsonObject(map) fun toReader(inputStream: InputStream, charset: Charset = Charsets.UTF_8) = inputStream.reader(charset) @Suppress("MemberVisibilityCanBePrivate") val pathMatchers = arrayListOf<PathMatcher>() fun pathMatcher(po: PathMatcher): Klaxon { pathMatchers.add(po) return this } val propertyStrategies = arrayListOf<PropertyStrategy>() fun propertyStrategy(ps: PropertyStrategy): Klaxon { propertyStrategies.add(ps) return this } /** * A map of a path to the JSON value that this path was found at. */ private val allPaths = hashMapOf<String, Any>() inner class DefaultPathMatcher(private val paths: Set<String>) : PathMatcher { override fun pathMatches(path: String) : Boolean { return paths.contains(path) } override fun onMatch(path: String, value: Any) { allPaths[path] = value } } fun parser(kc: KClass<*>? = null, passedLexer: Lexer? = null, streaming: Boolean = false): Parser { val result = Annotations.findJsonPaths(kc) if (result.any()) { // If we found at least one @Json(path = ...), add the DefaultPathMatcher with a list // of all these paths we need to watch for (we don't want to do that if no path // matching was requested since matching these paths slows down parsing). pathMatchers.add(DefaultPathMatcher(result.toSet())) } return Parser.default(pathMatchers, passedLexer, streaming) } private val DEFAULT_CONVERTER = DefaultConverter(this, allPaths) private val converters = arrayListOf<Converter>(EnumConverter(), DEFAULT_CONVERTER) /** * Add a type converter. The converter is analyzed to find out which type it converts * and then that info is transferred to `converterMap`. Reflection is necessary to locate * the toJson() function since there is no way to define Converter in a totally generic * way that will compile. */ fun converter(converter: Converter): Klaxon { converters.add(0, converter) return this } /** * Field type converters that convert fields with a marker annotation. */ private val fieldTypeMap = hashMapOf<KClass<out Annotation>, Converter>() fun fieldConverter(annotation: KClass<out Annotation>, converter: Converter): Klaxon { fieldTypeMap[annotation] = converter return this } var fieldRenamer: FieldRenamer? = null /** * Defines a field renamer. */ fun fieldRenamer(renamer: FieldRenamer): Klaxon { fieldRenamer = renamer return this } /** * @return a converter that will turn `value` into a `JsonObject`. If a non-null property is * passed, inspect that property for annotations that would override the type converter * we need to use to convert it. */ override fun findConverter(value: Any, prop: KProperty<*>?): Converter { val result = findConverterFromClass(value::class.java, prop) log("Value: $value, converter: $result") return result } /** * Given a Kotlin class and a property where the object should be stored, returns a `Converter` for that type. */ fun findConverterFromClass(cls: Class<*>, prop: KProperty<*>?) : Converter { fun annotationsForProp(prop: KProperty<*>, kc: Class<*>): Array<out Annotation> { val result = kc.declaredFields.firstOrNull { it.name == prop.name }?.declaredAnnotations ?: arrayOf() return result } var propertyClass: Class<*>? = null val propConverter : Converter? = if (prop != null && prop.returnType.classifier is KClass<*>) { propertyClass = (prop.returnType.classifier as KClass<*>).java val dc = prop.getter.javaMethod?.declaringClass ?: prop.javaField?.declaringClass annotationsForProp(prop, dc!!).mapNotNull { fieldTypeMap[it.annotationClass] }.firstOrNull() } else { null } val result = propConverter ?: findBestConverter(cls, prop) ?: (if (propertyClass != null) findBestConverter(propertyClass, prop) else null) ?: DEFAULT_CONVERTER // That last DEFAULT_CONVERTER above is not necessary since the default converter is part of the // list of converters by default and if all other converters fail, that one will apply // (since it is associated to the Object type), however, Kotlin doesn't know that and // will assume the result is nullable without it log("findConverterFromClass $cls returning $result") return result } private fun findBestConverter(cls: Class<*>, prop: KProperty<*>?) : Converter? { val toConvert = prop?.returnType?.javaType as? Class<*> ?: cls return converters.firstOrNull { it.canConvert(toConvert) } } fun toJsonString(value: Any?, prop: KProperty<*>? = null): String = if (value == null) "null" else toJsonString(value, findConverter(value, prop)) private fun toJsonString(value: Any, converter: Any /* can be Converter or Converter */) : String { // It's not possible to safely call converter.toJson(value) since its parameter is generic, // so use reflection val toJsonMethod = converter::class.functions.firstOrNull { it.name == "toJson" } val result = if (toJsonMethod != null) { toJsonMethod.call(converter, value) as String } else { throw KlaxonException("Couldn't find a toJson() function on converter $converter") } return result } /** * Convert a JsonObject into a real value. */ fun fromJsonObject(jsonObject: JsonObject, cls: Class<*>, kc: KClass<*>): Any { // If the user provided a type converter, use it, otherwise try to instantiate the object ourselves. val classConverter = findConverterFromClass(cls, null) val types = kc.typeParameters.map { KTypeProjection.invariant(it.createType()) } val type = if (kc.typeParameters.any()) kc.createType(types) else kc.createType() return classConverter.fromJson(JsonValue(jsonObject, cls, type, this@Klaxon)) as Any } /** * Convert the parameter into a JsonObject */ @Suppress("unused") fun toJsonObject(obj: Any) = JsonValue.convertToJsonObject(obj, this) fun log(s: String) { if (Debug.verbose) println(s) } }
klaxon/src/main/kotlin/com/beust/klaxon/Klaxon.kt
1669873506
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework.assertions import com.intellij.openapi.util.text.StringUtilRt import com.intellij.util.io.readText import com.intellij.util.io.size import junit.framework.ComparisonFailure import org.assertj.core.api.AbstractStringAssert import org.assertj.core.api.PathAssert import org.assertj.core.internal.ComparatorBasedComparisonStrategy import org.assertj.core.internal.Iterables import java.nio.file.Files import java.nio.file.LinkOption import java.nio.file.Path import java.util.* class PathAssertEx(actual: Path?) : PathAssert(actual) { override fun doesNotExist(): PathAssert { isNotNull if (Files.exists(actual, LinkOption.NOFOLLOW_LINKS)) { var error = "Expecting path:\n\t${actual}\nnot to exist" if (actual.size() < 16 * 1024) { error += ", content:\n\n${actual.readText()}\n" } failWithMessage(error) } return this } override fun hasContent(expected: String) = isEqualTo(expected) fun isEqualTo(expected: String): PathAssertEx { isNotNull isRegularFile val expectedContent = expected.trimIndent() val actualContent = StringUtilRt.convertLineSeparators(actual.readText()) if (actualContent != expectedContent) { throw ComparisonFailure(null, expectedContent, actualContent) } return this } fun hasChildren(vararg names: String) { paths.assertIsDirectory(info, actual) Iterables(ComparatorBasedComparisonStrategy(Comparator<Any> { o1, o2 -> if (o1 is Path && o2 is Path) { o1.compareTo(o2) } else if (o1 is String && o2 is String) { o1.compareTo(o2) } else if (o1 is String) { if ((o2 as Path).endsWith(o1)) 0 else -1 } else { if ((o1 as Path).endsWith(o2 as String)) 0 else -1 } })) .assertContainsOnly(info, Files.newDirectoryStream(actual).use { it.toList() }, names) } } class StringAssertEx(actual: String?) : AbstractStringAssert<StringAssertEx>(actual, StringAssertEx::class.java) { fun isEqualTo(expected: Path) { isNotNull compareFileContent(actual, expected) } fun toMatchSnapshot(snapshotFile: Path) { isNotNull compareFileContent(actual, snapshotFile) } }
platform/testFramework/extensions/src/com/intellij/testFramework/assertions/PathAssertEx.kt
75621122
package com.akhbulatov.wordkeeper.presentation.ui.global.list.viewholders import android.view.View import androidx.recyclerview.widget.RecyclerView abstract class BaseViewHolder<T>(itemView: View) : RecyclerView.ViewHolder(itemView) { abstract fun bind(item: T) }
app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/global/list/viewholders/BaseViewHolder.kt
4102694078
package backend.model.posting import backend.model.UserGenerated import backend.model.BasicEntity import backend.model.user.User import backend.model.user.UserAccount import java.time.LocalDateTime import javax.persistence.* @Entity @Table(name = "postinglike") class Like : BasicEntity, UserGenerated { private constructor() : super() lateinit var date: LocalDateTime @ManyToOne(fetch = FetchType.LAZY) var user: UserAccount? = null constructor(date: LocalDateTime, user: UserAccount) : this() { this.date = date this.user = user } @PreRemove fun preRemove() { this.user = null } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Like) return false if (date != other.date) return false if (user!!.id == other.user!!.id) return false // TODO: Implement equals in UserAccount! return true } override fun getUser(): User? { return user } }
src/main/java/backend/model/posting/Like.kt
2768142674
class B: A() { override fun foo(x: Int, y: Int): Unit { } } fun box(): String { assertEquals(listOf(false, false, true), (if ((B::foo) != false) { (B::foo) } else { }).parameters.map({})) }
kotlin/kotlin-formal/examples/fuzzer/isOptional.kt-258774014.kt_minimized.kt
3841952289
// 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.core.script.configuration.utils import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Alarm import com.intellij.util.containers.HashSetQueue import org.jetbrains.kotlin.idea.base.scripting.KotlinBaseScriptingBundle import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.configuration.utils.DefaultBackgroundExecutor.Companion.PROGRESS_INDICATOR_DELAY import org.jetbrains.kotlin.idea.core.script.configuration.utils.DefaultBackgroundExecutor.Companion.PROGRESS_INDICATOR_MIN_QUEUE import org.jetbrains.kotlin.idea.core.script.scriptingDebugLog import java.util.* import javax.swing.SwingUtilities /** * Sequentially loads script configuration in background. * Loading tasks scheduled by calling [ensureScheduled]. * * Progress indicator will be shown after [PROGRESS_INDICATOR_DELAY] ms or if * more then [PROGRESS_INDICATOR_MIN_QUEUE] tasks scheduled. * * States: * silentWorker underProgressWorker * - sleep * - silent x * - silent and under progress x x * - under progress x */ internal class DefaultBackgroundExecutor( val project: Project, val manager: CompositeScriptConfigurationManager ) : BackgroundExecutor { companion object { const val PROGRESS_INDICATOR_DELAY = 1000 const val PROGRESS_INDICATOR_MIN_QUEUE = 3 } val rootsManager get() = manager.updater private val work = Any() private val queue: Queue<LoadTask> = HashSetQueue() /** * Let's fix queue size when progress bar displayed. * Progress for rest items will be counted from zero */ private var currentProgressSize: Int = 0 private var currentProgressDone: Int = 0 private var silentWorker: SilentWorker? = null private var underProgressWorker: UnderProgressWorker? = null private val longRunningAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, KotlinPluginDisposable.getInstance(project)) private var longRunningAlarmRequested = false private var inTransaction: Boolean = false private var currentFile: VirtualFile? = null class LoadTask(val key: VirtualFile, val actions: () -> Unit) { override fun equals(other: Any?) = this === other || (other is LoadTask && key == other.key) override fun hashCode() = key.hashCode() } @Synchronized override fun ensureScheduled(key: VirtualFile, actions: () -> Unit) { val task = LoadTask(key, actions) if (queue.add(task)) { scriptingDebugLog(task.key) { "added to update queue" } // If the queue is longer than PROGRESS_INDICATOR_MIN_QUEUE, show progress and cancel button if (queue.size > PROGRESS_INDICATOR_MIN_QUEUE) { requireUnderProgressWorker() } else { requireSilentWorker() if (!longRunningAlarmRequested) { longRunningAlarmRequested = true longRunningAlarm.addRequest( { longRunningAlarmRequested = false requireUnderProgressWorker() }, PROGRESS_INDICATOR_DELAY ) } } } } @Synchronized private fun requireSilentWorker() { if (silentWorker == null && underProgressWorker == null) { silentWorker = SilentWorker().also { it.start() } } } @Synchronized private fun requireUnderProgressWorker() { if (queue.isEmpty() && silentWorker == null) return silentWorker?.stopGracefully() if (underProgressWorker == null) { underProgressWorker = UnderProgressWorker().also { it.start() } restartProgressBar() updateProgress() } } @Synchronized private fun restartProgressBar() { currentProgressSize = queue.size currentProgressDone = 0 } @Synchronized fun updateProgress() { underProgressWorker?.progressIndicator?.let { it.text2 = currentFile?.path ?: "" if (queue.size == 0) { // last file it.isIndeterminate = true } else { it.isIndeterminate = false if (currentProgressDone > currentProgressSize) { restartProgressBar() } it.fraction = currentProgressDone.toDouble() / currentProgressSize.toDouble() } } } @Synchronized private fun ensureInTransaction() { if (inTransaction) return inTransaction = true rootsManager.beginUpdating() } @Synchronized private fun endBatch() { check(inTransaction) rootsManager.commit() inTransaction = false } private abstract inner class Worker { private var shouldStop = false open fun start() { ensureInTransaction() } fun stopGracefully() { shouldStop = true } protected open fun checkCancelled() = false protected abstract fun close() protected fun run() { try { while (true) { // prevent parallel work in both silent and under progress synchronized(work) { val next = synchronized(this@DefaultBackgroundExecutor) { if (shouldStop) return if (checkCancelled()) { queue.clear() endBatch() return } else if (queue.isEmpty()) { endBatch() return } queue.poll()?.also { currentFile = it.key currentProgressDone++ updateProgress() } } next?.actions?.invoke() synchronized(work) { currentFile = null } } } } finally { close() } } } private inner class UnderProgressWorker : Worker() { var progressIndicator: ProgressIndicator? = null override fun start() { super.start() object : Task.Backgroundable(project, KotlinBaseScriptingBundle.message("text.kotlin.loading.script.configuration"), true) { override fun run(indicator: ProgressIndicator) { progressIndicator = indicator updateProgress() run() } }.queue() } override fun checkCancelled(): Boolean = progressIndicator?.isCanceled == true override fun close() { synchronized(this@DefaultBackgroundExecutor) { underProgressWorker = null progressIndicator = null } } } private inner class SilentWorker : Worker() { override fun start() { super.start() // executeOnPooledThread requires read lock, and we may fail to acquire it SwingUtilities.invokeLater { BackgroundTaskUtil.executeOnPooledThread(KotlinPluginDisposable.getInstance(project)) { run() } } } override fun close() { synchronized(this@DefaultBackgroundExecutor) { silentWorker = null } } } }
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/utils/DefaultBackgroundExecutor.kt
3013505461
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.docs.features.testing.springbootapplications.autoconfiguredspringrestdocs.withwebtestclient import org.springframework.boot.test.context.TestConfiguration import org.springframework.boot.test.web.reactive.server.WebTestClientBuilderCustomizer import org.springframework.context.annotation.Bean import org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation import org.springframework.test.web.reactive.server.WebTestClient @TestConfiguration(proxyBeanMethods = false) class MyWebTestClientBuilderCustomizerConfiguration { @Bean fun restDocumentation(): WebTestClientBuilderCustomizer { return WebTestClientBuilderCustomizer { builder: WebTestClient.Builder -> builder.entityExchangeResultConsumer( WebTestClientRestDocumentation.document("{method-name}") ) } } }
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/features/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyWebTestClientBuilderCustomizerConfiguration.kt
3778886294
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildSingleSecondEntityImpl(val dataSource: ChildSingleSecondEntityData) : ChildSingleSecondEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentSingleAbEntity::class.java, ChildSingleAbstractBaseEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val commonData: String get() = dataSource.commonData override val parentEntity: ParentSingleAbEntity get() = snapshot.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this)!! override val secondData: String get() = dataSource.secondData override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ChildSingleSecondEntityData?) : ModifiableWorkspaceEntityBase<ChildSingleSecondEntity>(), ChildSingleSecondEntity.Builder { constructor() : this(ChildSingleSecondEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildSingleSecondEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isCommonDataInitialized()) { error("Field ChildSingleAbstractBaseEntity#commonData should be initialized") } if (_diff != null) { if (_diff.extractOneToAbstractOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized") } } if (!getEntityData().isSecondDataInitialized()) { error("Field ChildSingleSecondEntity#secondData should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ChildSingleSecondEntity this.entitySource = dataSource.entitySource this.commonData = dataSource.commonData this.secondData = dataSource.secondData if (parents != null) { this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var commonData: String get() = getEntityData().commonData set(value) { checkModificationAllowed() getEntityData().commonData = value changedProperty.add("commonData") } override var parentEntity: ParentSingleAbEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var secondData: String get() = getEntityData().secondData set(value) { checkModificationAllowed() getEntityData().secondData = value changedProperty.add("secondData") } override fun getEntityData(): ChildSingleSecondEntityData = result ?: super.getEntityData() as ChildSingleSecondEntityData override fun getEntityClass(): Class<ChildSingleSecondEntity> = ChildSingleSecondEntity::class.java } } class ChildSingleSecondEntityData : WorkspaceEntityData<ChildSingleSecondEntity>() { lateinit var commonData: String lateinit var secondData: String fun isCommonDataInitialized(): Boolean = ::commonData.isInitialized fun isSecondDataInitialized(): Boolean = ::secondData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSingleSecondEntity> { val modifiable = ChildSingleSecondEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildSingleSecondEntity { return getCached(snapshot) { val entity = ChildSingleSecondEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildSingleSecondEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ChildSingleSecondEntity(commonData, secondData, entitySource) { this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ParentSingleAbEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildSingleSecondEntityData if (this.entitySource != other.entitySource) return false if (this.commonData != other.commonData) return false if (this.secondData != other.secondData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildSingleSecondEntityData if (this.commonData != other.commonData) return false if (this.secondData != other.secondData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + secondData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + secondData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSingleSecondEntityImpl.kt
2232224345
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package training.featuresSuggester.settings import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.util.registry.Registry import training.featuresSuggester.suggesters.FeatureSuggester import java.time.Instant import java.time.ZoneId import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.math.min @State( name = "FeatureSuggesterSettings", storages = [Storage("FeatureSuggester.xml", roamingType = RoamingType.DISABLED)] ) class FeatureSuggesterSettings : PersistentStateComponent<FeatureSuggesterSettings> { var suggesters: MutableMap<String, Boolean> = run { val enabled = isSuggestersEnabledByDefault FeatureSuggester.suggesters.associate { internalId(it.id) to enabled }.toMutableMap() } // SuggesterId to the last time this suggestion was shown var suggestionLastShownTime: MutableMap<String, Long> = mutableMapOf() // List of timestamps (millis) of the first IDE session start for the last days var workingDays: MutableList<Long> = mutableListOf() val isAnySuggesterEnabled: Boolean get() = suggesters.any { it.value } private val isSuggestersEnabledByDefault: Boolean get() = Registry.`is`("feature.suggester.enable.suggesters", false) private fun internalId(suggesterId: String): String { return if (isSuggestersEnabledByDefault) suggesterId else suggesterId + "_" } override fun getState(): FeatureSuggesterSettings { return this } override fun loadState(state: FeatureSuggesterSettings) { // leave default settings if loading settings contains something different // needed in case when suggesters enabled default is changed val oldSettingsFound = state.suggesters.any { !suggesters.containsKey(it.key) } if (!oldSettingsFound) { suggesters = state.suggesters } suggestionLastShownTime = state.suggestionLastShownTime workingDays = state.workingDays } fun isEnabled(suggesterId: String): Boolean { return suggesters[internalId(suggesterId)] == true } fun setEnabled(suggesterId: String, enabled: Boolean) { suggesters[internalId(suggesterId)] = enabled } fun updateSuggestionShownTime(suggesterId: String) { suggestionLastShownTime[suggesterId] = System.currentTimeMillis() } fun getSuggestionLastShownTime(suggesterId: String) = suggestionLastShownTime[suggesterId] ?: 0L fun updateWorkingDays() { val curTime = System.currentTimeMillis() val lastTime = workingDays.lastOrNull() if (lastTime == null) { workingDays.add(curTime) } else if (curTime.toLocalDate() != lastTime.toLocalDate()) { val numToRemove = workingDays.size - maxSuggestingIntervalDays + 1 if (numToRemove > 0) { workingDays.subList(0, numToRemove).clear() } workingDays.add(curTime) } } /** * Return the start time of session happened [oldestDayNum] working days (when user performed any action) ago. * If there is no information about so old sessions it will return at least the current time minus [oldestDayNum] days * (it is required for migration of existing users). * So returned time always will be earlier then time [oldestDayNum] days ago. */ fun getOldestWorkingDayStartMillis(oldestDayNum: Int): Long { val simpleOldestTime = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(oldestDayNum.toLong()) return if (workingDays.isNotEmpty()) { val ind = max(0, workingDays.size - oldestDayNum) min(workingDays[ind], simpleOldestTime) } else simpleOldestTime } private fun Long.toLocalDate() = Instant.ofEpochMilli(this).atZone(ZoneId.systemDefault()).toLocalDate() companion object { @JvmStatic fun instance(): FeatureSuggesterSettings { return ApplicationManager.getApplication().getService(FeatureSuggesterSettings::class.java) } private val maxSuggestingIntervalDays: Int by lazy { FeatureSuggester.suggesters.maxOfOrNull { it.minSuggestingIntervalDays } ?: run { thisLogger().error("Failed to find registered suggesters") 14 } } } }
plugins/ide-features-trainer/src/training/featuresSuggester/settings/FeatureSuggesterSettings.kt
1213404699
// "Surround with null check" "false" // ACTION: Add 'return@bar' // ACTION: Add non-null asserted (!!) call // ACTION: Introduce local variable // ACTION: Replace 'it' with explicit parameter // ACTION: Replace with safe (?.) call // ERROR: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Foo? class Foo { fun foo(): Foo = Foo() } fun bar(f: (x: Foo?) -> Foo) {} fun test() { bar { it<caret>.foo() } }
plugins/kotlin/idea/tests/testData/quickfix/surroundWithNullCheck/inLambda2.kt
3401176047
/* * Copyright 2022 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.j2cl.junit.integration.kotlintest.data import com.google.j2cl.junit.integration.testing.testlogger.TestCaseLogger import kotlin.test.AfterTest import kotlin.test.Test /** * TestCase used for integration testing for j2cl JUnit support. * * <p>Note this test will not pass and this is intentional since we want to test test failures in * our integration tests as well. */ class ThrowsInAfterTest { @AfterTest fun after() { TestCaseLogger.log("after") throw RuntimeException("failure in after()") } @Test fun test() { TestCaseLogger.log("test") } @Test fun testOther() { TestCaseLogger.log("testOther") } }
junit/generator/javatests/com/google/j2cl/junit/integration/kotlintest/data/ThrowsInAfterTest.kt
3070663475
package org.jetbrains.haskell.debugger.protocol import org.jetbrains.haskell.debugger.parser.ShowOutput import java.util.Deque import org.jetbrains.haskell.debugger.parser.GHCiParser import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import org.jetbrains.haskell.debugger.frames.HsDebugValue import org.jetbrains.haskell.debugger.parser.LocalBinding import org.jetbrains.haskell.debugger.parser.ParseResult import org.json.simple.JSONObject import org.jetbrains.haskell.debugger.parser.EvalResult import org.jetbrains.haskell.debugger.parser.JSONConverter /** * Created by vlad on 8/1/14. */ class EvalCommand(val force: Boolean, val expression: String, callback: CommandCallback<EvalResult?>) : RealTimeCommand<EvalResult?>(callback) { override fun getText(): String = ":eval ${if (force) 1 else 0} ${expression.trim()}\n" override fun parseGHCiOutput(output: Deque<String?>) = null override fun parseJSONOutput(output: JSONObject): EvalResult? = if (JSONConverter.checkExceptionFromJSON(output) == null) JSONConverter.evalResultFromJSON(output) else null }
plugin/src/org/jetbrains/haskell/debugger/protocol/EvalCommand.kt
2203790387
// 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.intellij.plugins.markdown.editor.tables.inspections import com.intellij.codeInspection.InspectionsBundle import com.intellij.idea.TestFor import com.intellij.testFramework.InspectionTestUtil import com.intellij.testFramework.RegistryKeyRule import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixture4TestCase import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.editor.tables.TableTestUtils import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 /** * These are just sanity checks, since actual tests for reformatting are in the other files. */ @RunWith(JUnit4::class) @Suppress("MarkdownIncorrectTableFormatting") class MarkdownIncorrectTableFormattingInspectionQuickFixTest: LightPlatformCodeInsightFixture4TestCase() { @get:Rule val rule = RegistryKeyRule("markdown.tables.editing.support.enable", true) private val reformatIntentionFixText get() = MarkdownBundle.message("markdown.reformat.table.intention.text") @Test fun `works with incorrectly formatted cell`() { // language=Markdown val before = """ | none | none | |------|------| | some | some | """.trimIndent() // language=Markdown val after = """ | none | none | |------|------| | some | some | """.trimIndent() doTest(before, after) } @Test fun `works with incorrectly formatted header cell`() { // language=Markdown val before = """ | none | none | |-------:|------| | some | some | | some content | some | """.trimIndent() // language=Markdown val after = """ | none | none | |-------------:|------| | some | some | | some content | some | """.trimIndent() doTest(before, after) } @Test fun `works with incorrectly formatted separator`() { // language=Markdown val before = """ | none | none | |------|---| | some | some | """.trimIndent() // language=Markdown val after = """ | none | none | |------|------| | some | some | """.trimIndent() doTest(before, after) } @TestFor(issues = ["IDEA-305781"]) @Test fun `apply fix to whole file`() { // language=Markdown val before = """ | first | table | |------|---| | some | some | | second | table | |------|---| | some | some | """.trimIndent() // language=Markdown val after = """ | first | table | |-------|-------| | some | some | | second | table | |--------|-------| | some | some | """.trimIndent() TableTestUtils.runWithChangedSettings(myFixture.project) { myFixture.configureByText("some.md", before) val inspection = InspectionTestUtil.instantiateTool(MarkdownIncorrectTableFormattingInspection::class.java) myFixture.enableInspections(inspection) val targetText = InspectionsBundle.message("fix.all.inspection.problems.in.file", inspection.displayName); val intentions = myFixture.availableIntentions val intention = intentions.find { it.text == targetText } checkNotNull(intention) { "Failed to find fix with text '$targetText'" } myFixture.launchAction(intention) myFixture.checkResult(after) } } @Test fun `fix preview should work`() { // language=Markdown val before = """ | first | table | |------|---| | some<caret> | some | """.trimIndent() TableTestUtils.runWithChangedSettings(myFixture.project) { myFixture.configureByText("some.md", before) myFixture.enableInspections(MarkdownIncorrectTableFormattingInspection()) val fix = myFixture.getAllQuickFixes().find { it.text == reformatIntentionFixText } checkNotNull(fix) { "Failed to find fix" } myFixture.checkPreviewAndLaunchAction(fix) } } private fun doTest(content: String, after: String) { TableTestUtils.runWithChangedSettings(myFixture.project) { myFixture.configureByText("some.md", content) myFixture.enableInspections(MarkdownIncorrectTableFormattingInspection()) val fix = myFixture.getAllQuickFixes().find { it.text == reformatIntentionFixText } assertNotNull(fix) myFixture.launchAction(fix!!) myFixture.checkResult(after) } } }
plugins/markdown/test/src/org/intellij/plugins/markdown/editor/tables/inspections/MarkdownIncorrectTableFormattingInspectionQuickFixTest.kt
1558246120
package com.github.vhromada.catalog.validator import com.github.vhromada.catalog.common.exception.InputException import com.github.vhromada.catalog.utils.SeasonUtils import com.github.vhromada.catalog.utils.TestConstants import com.github.vhromada.catalog.validator.impl.SeasonValidatorImpl import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.http.HttpStatus /** * A class represents test for class [SeasonValidator]. * * @author Vladimir Hromada */ class SeasonValidatorTest { /** * Instance of [SeasonValidator] */ private lateinit var validator: SeasonValidator /** * Initializes validator. */ @BeforeEach fun setUp() { validator = SeasonValidatorImpl() } /** * Test method for [SeasonValidator.validateRequest]. */ @Test fun validateRequest() { validator.validateRequest(request = SeasonUtils.newRequest()) } /** * Test method for [SeasonValidator.validateRequest] with request with null number of season. */ @Test fun validateRequestNullNumber() { val request = SeasonUtils.newRequest() .copy(number = null) assertThatThrownBy { validator.validateRequest(request = request) } .isInstanceOf(InputException::class.java) .hasMessageContaining("SEASON_NUMBER_NULL") .hasMessageContaining("Number of season mustn't be null.") .hasFieldOrPropertyWithValue("httpStatus", HttpStatus.UNPROCESSABLE_ENTITY) } /** * Test method for [SeasonValidator.validateRequest] with request with not positive number of season. */ @Test fun validateRequestNotPositiveNumber() { val request = SeasonUtils.newRequest() .copy(number = -1) assertThatThrownBy { validator.validateRequest(request = request) } .isInstanceOf(InputException::class.java) .hasMessageContaining("SEASON_NUMBER_NOT_POSITIVE") .hasMessageContaining("Number of season must be positive number.") .hasFieldOrPropertyWithValue("httpStatus", HttpStatus.UNPROCESSABLE_ENTITY) } /** * Test method for [SeasonValidator.validateRequest] with request with null starting year. */ @Test fun validateRequestNullStartingYear() { val request = SeasonUtils.newRequest() .copy(startYear = null) assertThatThrownBy { validator.validateRequest(request = request) } .isInstanceOf(InputException::class.java) .hasMessageContaining("SEASON_START_YEAR_NULL") .hasMessageContaining("Starting year mustn't be null.") .hasFieldOrPropertyWithValue("httpStatus", HttpStatus.UNPROCESSABLE_ENTITY) } /** * Test method for [SeasonValidator.validateRequest] with request with null ending year. */ @Test fun validateRequestNullEndingYear() { val request = SeasonUtils.newRequest() .copy(endYear = null) assertThatThrownBy { validator.validateRequest(request = request) } .isInstanceOf(InputException::class.java) .hasMessageContaining("SEASON_END_YEAR_NULL") .hasMessageContaining("Ending year mustn't be null.") .hasFieldOrPropertyWithValue("httpStatus", HttpStatus.UNPROCESSABLE_ENTITY) } /** * Test method for [SeasonValidator.validateRequest] with request with bad minimum starting year and bad minimum ending year. */ @Test fun validateRequestBadMinimumYears() { val request = SeasonUtils.newRequest() .copy(startYear = TestConstants.BAD_MIN_YEAR, endYear = TestConstants.BAD_MIN_YEAR) assertThatThrownBy { validator.validateRequest(request = request) } .isInstanceOf(InputException::class.java) .hasMessageContaining(TestConstants.INVALID_STARTING_YEAR_EVENT.toString()) .hasMessageContaining(TestConstants.INVALID_ENDING_YEAR_EVENT.toString()) .hasFieldOrPropertyWithValue("httpStatus", HttpStatus.UNPROCESSABLE_ENTITY) } /** * Test method for [SeasonValidator.validateRequest] with request with bad maximum starting year and bad maximum ending year. */ @Test fun validateRequestBadMaximumYears() { val request = SeasonUtils.newRequest() .copy(startYear = TestConstants.BAD_MAX_YEAR, endYear = TestConstants.BAD_MAX_YEAR) assertThatThrownBy { validator.validateRequest(request = request) } .isInstanceOf(InputException::class.java) .hasMessageContaining(TestConstants.INVALID_STARTING_YEAR_EVENT.toString()) .hasMessageContaining(TestConstants.INVALID_ENDING_YEAR_EVENT.toString()) .hasFieldOrPropertyWithValue("httpStatus", HttpStatus.UNPROCESSABLE_ENTITY) } /** * Test method for [SeasonValidator.validateRequest] with request with starting year greater than ending yea. */ @Test fun validateRequestBadYears() { var request = SeasonUtils.newRequest() request = request.copy(startYear = request.endYear!! + 1) assertThatThrownBy { validator.validateRequest(request = request) } .isInstanceOf(InputException::class.java) .hasMessageContaining("SEASON_YEARS_NOT_VALID") .hasMessageContaining("Starting year mustn't be greater than ending year.") .hasFieldOrPropertyWithValue("httpStatus", HttpStatus.UNPROCESSABLE_ENTITY) } /** * Test method for [SeasonValidator.validateRequest] with request with null language. */ @Test fun validateRequestNullLanguage() { val request = SeasonUtils.newRequest() .copy(language = null) assertThatThrownBy { validator.validateRequest(request = request) } .isInstanceOf(InputException::class.java) .hasMessageContaining("SEASON_LANGUAGE_NULL") .hasMessageContaining("Language mustn't be null.") .hasFieldOrPropertyWithValue("httpStatus", HttpStatus.UNPROCESSABLE_ENTITY) } /** * Test method for [SeasonValidator.validateRequest] with request with null subtitles. */ @Test fun validateRequestNullSubtitles() { val request = SeasonUtils.newRequest() .copy(subtitles = null) assertThatThrownBy { validator.validateRequest(request = request) } .isInstanceOf(InputException::class.java) .hasMessageContaining("SEASON_SUBTITLES_NULL") .hasMessageContaining("Subtitles mustn't be null.") .hasFieldOrPropertyWithValue("httpStatus", HttpStatus.UNPROCESSABLE_ENTITY) } /** * Test method for [SeasonValidator.validateRequest] with request with subtitles with null value. */ @Test fun validateRequestBadSubtitles() { val request = SeasonUtils.newRequest() .copy(subtitles = listOf(null)) assertThatThrownBy { validator.validateRequest(request = request) } .isInstanceOf(InputException::class.java) .hasMessageContaining("SEASON_SUBTITLES_CONTAIN_NULL") .hasMessageContaining("Subtitles mustn't contain null value.") .hasFieldOrPropertyWithValue("httpStatus", HttpStatus.UNPROCESSABLE_ENTITY) } }
core/src/test/kotlin/com/github/vhromada/catalog/validator/SeasonValidatorTest.kt
2940313276
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package com.intellij.diagnostic.startUpPerformanceReporter import com.fasterxml.jackson.core.JsonGenerator import com.intellij.diagnostic.ActivityImpl import com.intellij.diagnostic.StartUpMeasurer import com.intellij.diagnostic.ThreadNameManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.diagnostic.Logger import com.intellij.psi.tree.IElementType import com.intellij.ui.icons.IconLoadMeasurer import com.intellij.util.io.jackson.array import com.intellij.util.io.jackson.obj import com.intellij.util.lang.ClassPath import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap import it.unimi.dsi.fastutil.objects.Object2LongMap import org.bouncycastle.crypto.generators.Argon2BytesGenerator import org.bouncycastle.crypto.params.Argon2Parameters import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType import java.lang.management.ManagementFactory import java.time.ZoneId import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.util.* import java.util.concurrent.TimeUnit internal class IdeIdeaFormatWriter(activities: Map<String, MutableList<ActivityImpl>>, private val pluginCostMap: MutableMap<String, Object2LongMap<String>>, threadNameManager: ThreadNameManager) : IdeaFormatWriter(activities, threadNameManager, StartUpPerformanceReporter.VERSION) { val publicStatMetrics = Object2IntOpenHashMap<String>() init { publicStatMetrics.defaultReturnValue(-1) } fun writeToLog(log: Logger) { stringWriter.write("\n=== Stop: StartUp Measurement ===") log.info(stringWriter.toString()) } override fun writeAppInfo(writer: JsonGenerator) { val appInfo = ApplicationInfo.getInstance() writer.writeStringField("build", appInfo.build.asStringWithoutProductCode()) writer.writeStringField("buildDate", ZonedDateTime.ofInstant(appInfo.buildDate.toInstant(), ZoneId.systemDefault()).format(DateTimeFormatter.RFC_1123_DATE_TIME)) writer.writeStringField("productCode", appInfo.build.productCode) // see CDSManager from platform-impl @Suppress("SpellCheckingInspection") if (ManagementFactory.getRuntimeMXBean().inputArguments.any { it == "-Xshare:auto" || it == "-Xshare:on" }) { writer.writeBooleanField("cds", true) } } override fun writeProjectName(writer: JsonGenerator, projectName: String) { writer.writeStringField("project", System.getProperty("idea.performanceReport.projectName") ?: safeHashValue(projectName)) } override fun writeExtraData(writer: JsonGenerator) { val stats = getClassAndResourceLoadingStats() writer.obj("classLoading") { val time = stats.getValue("classLoadingTime") writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(time)) val defineTime = stats.getValue("classDefineTime") writer.writeNumberField("searchTime", TimeUnit.NANOSECONDS.toMillis(time - defineTime)) writer.writeNumberField("defineTime", TimeUnit.NANOSECONDS.toMillis(defineTime)) writer.writeNumberField("count", stats.getValue("classRequests")) } writer.obj("resourceLoading") { writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stats.getValue("resourceLoadingTime"))) writer.writeNumberField("count", stats.getValue("resourceRequests")) } writer.obj("langLoading") { val allTypes = IElementType.enumerate(IElementType.TRUE) writer.writeNumberField("elementTypeCount", allTypes.size) } writeServiceStats(writer) writeIcons(writer) } private fun getClassAndResourceLoadingStats(): Map<String, Long> { // data from bootstrap classloader val classLoader = IdeIdeaFormatWriter::class.java.classLoader @Suppress("UNCHECKED_CAST") val stats = MethodHandles.lookup() .findVirtual(classLoader::class.java, "getLoadingStats", MethodType.methodType(Map::class.java)) .bindTo(classLoader).invokeExact() as MutableMap<String, Long> // data from core classloader val coreStats = ClassPath.getLoadingStats() if (coreStats.get("identity") != stats.get("identity")) { for (entry in coreStats.entries) { val v1 = stats.getValue(entry.key) if (v1 != entry.value) { stats.put(entry.key, v1 + entry.value) } } } return stats } override fun writeTotalDuration(writer: JsonGenerator, end: Long, timeOffset: Long): Long { val totalDurationActual = super.writeTotalDuration(writer, end, timeOffset) publicStatMetrics.put("totalDuration", totalDurationActual.toInt()) return totalDurationActual } override fun beforeActivityWrite(item: ActivityImpl, ownOrTotalDuration: Long, fieldName: String) { item.pluginId?.let { StartUpMeasurer.doAddPluginCost(it, item.category?.name ?: "unknown", ownOrTotalDuration, pluginCostMap) } if (fieldName == "items") { when (val itemName = item.name) { "splash initialization" -> { publicStatMetrics["splash"] = TimeUnit.NANOSECONDS.toMillis(ownOrTotalDuration).toInt() } "bootstrap", "app initialization" -> { publicStatMetrics[itemName] = TimeUnit.NANOSECONDS.toMillis(ownOrTotalDuration).toInt() } "project frame initialization" -> { publicStatMetrics["projectFrameVisible"] = TimeUnit.NANOSECONDS.toMillis(item.start - StartUpMeasurer.getStartTime()).toInt() } } } } } private fun writeIcons(writer: JsonGenerator) { writer.array("icons") { for (stat in IconLoadMeasurer.getStats()) { writer.obj { writer.writeStringField("name", stat.name) writer.writeNumberField("count", stat.count) writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stat.totalDuration)) } } } } private fun safeHashValue(value: String): String { val generator = Argon2BytesGenerator() generator.init(Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).build()) // 160 bit is enough for uniqueness val result = ByteArray(20) generator.generateBytes(value.toByteArray(), result, 0, result.size) return Base64.getEncoder().withoutPadding().encodeToString(result) } private fun writeServiceStats(writer: JsonGenerator) { class StatItem(val name: String) { var app = 0 var project = 0 var module = 0 } // components can be inferred from data, but to verify that items reported correctly (and because for items threshold is applied (not all are reported)) val component = StatItem("component") val service = StatItem("service") val pluginSet = PluginManagerCore.getPluginSet() for (plugin in pluginSet.getEnabledModules()) { service.app += plugin.appContainerDescriptor.services.size service.project += plugin.projectContainerDescriptor.services.size service.module += plugin.moduleContainerDescriptor.services.size component.app += plugin.appContainerDescriptor.components?.size ?: 0 component.project += plugin.projectContainerDescriptor.components?.size ?: 0 component.module += plugin.moduleContainerDescriptor.components?.size ?: 0 } writer.obj("stats") { writer.writeNumberField("plugin", pluginSet.enabledPlugins.size) for (statItem in listOf(component, service)) { writer.obj(statItem.name) { writer.writeNumberField("app", statItem.app) writer.writeNumberField("project", statItem.project) writer.writeNumberField("module", statItem.module) } } } writer.array("plugins") { for (plugin in pluginSet.enabledPlugins) { val classLoader = plugin.pluginClassLoader as? PluginAwareClassLoader ?: continue if (classLoader.loadedClassCount == 0L) { continue } writer.obj { writer.writeStringField("id", plugin.pluginId.idString) writer.writeNumberField("classCount", classLoader.loadedClassCount) writer.writeNumberField("classLoadingEdtTime", TimeUnit.NANOSECONDS.toMillis(classLoader.edtTime)) writer.writeNumberField("classLoadingBackgroundTime", TimeUnit.NANOSECONDS.toMillis(classLoader.backgroundTime)) } } } }
platform/diagnostic/src/startUpPerformanceReporter/IdeIdeaFormatWriter.kt
2068393246
/* * 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.hints.filtering import junit.framework.TestCase import org.assertj.core.api.Assertions.assertThat class MatcherTest : TestCase() { fun Matcher.assertIsMatching(fullyQualifiedMethodName: String, vararg params: String) { assertThat(isMatching(fullyQualifiedMethodName, listOf(*params))).isTrue() } fun Matcher.assertNotMatching(fullyQualifiedMethodName: String, vararg params: String) { assertThat(isMatching(fullyQualifiedMethodName, listOf(*params))).isFalse() } fun `test simple matcher`() { val matcher = MatcherConstructor.createMatcher("*.String(old*, new*)")!! matcher.assertIsMatching("java.lang.String", "oldValue", "newValue") matcher.assertIsMatching("java.lang.String", "old", "new") matcher.assertNotMatching("java.lang.String", "valueOld", "valueNew") matcher.assertNotMatching("Boolean", "old", "new") } fun `test any single param method matcher`() { val matchers = listOf(MatcherConstructor.createMatcher("*(*)")!!, MatcherConstructor.createMatcher("(*)")!!) matchers.forEach { it.assertIsMatching("java.lang.String.indexOf", "ch") it.assertIsMatching("java.lang.String.charAt", "index") it.assertIsMatching("java.lang.Boolean.valueOf", "value") it.assertNotMatching("java.lang.Boolean.substring", "from", "to") } } fun `test any with key value`() { val matcher = MatcherConstructor.createMatcher("*(key, value)")!! matcher.assertIsMatching("java.util.Map.put", "key", "value") matcher.assertIsMatching("java.util.HashMap.put", "key", "value") matcher.assertIsMatching("java.util.HashMap.putIfNeeded", "key", "value") } fun `test couple contains`() { val matcher = MatcherConstructor.createMatcher("*(first*, last*)")!! matcher.assertIsMatching("java.util.Str.subs", "firstIndex", "lastIndex") matcher.assertIsMatching("java.util.Str.subs", "first", "last") } }
platform/platform-tests/testSrc/com/intellij/codeInsight/hints/filtering/MatcherTest.kt
2629773226
package org.stepik.android.domain.course_search.analytic import org.stepik.android.domain.base.analytic.AnalyticEvent import ru.nobird.app.core.model.mapOfNotNull class CourseContentSearchedAnalyticEvent( val courseId: Long, val courseTitle: String, val query: String, val suggestion: String? = null ) : AnalyticEvent { companion object { private const val PARAM_COURSE = "course" private const val PARAM_TITLE = "title" private const val PARAM_QUERY = "query" private const val PARAM_SUGGESTION = "suggestion" } override val name: String = "Course content searched" override val params: Map<String, Any> = mapOfNotNull( PARAM_COURSE to courseId, PARAM_TITLE to courseTitle, PARAM_QUERY to query, PARAM_SUGGESTION to suggestion ) }
app/src/main/java/org/stepik/android/domain/course_search/analytic/CourseContentSearchedAnalyticEvent.kt
3696426930
/* * 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.multitenant.query import com.facebook.buck.core.path.ForwardRelativePath import com.facebook.buck.core.sourcepath.SourcePath import com.facebook.buck.multitenant.fs.FsAgnosticPath /** * Implementation of [SourcePath] that makes sense in the context of * `com.facebook.buck.multitenant`. It is designed to be used with * [com.facebook.buck.query.QueryFileTarget]. */ data class FsAgnosticSourcePath(private val path: ForwardRelativePath) : SourcePath { companion object { /** * @param path must be a normalized, relative path. */ fun of(path: String): FsAgnosticSourcePath = FsAgnosticSourcePath(FsAgnosticPath.of(path)) } override fun compareTo(other: SourcePath): Int { if (this === other) { return 0 } val classComparison = compareClasses(other) if (classComparison != 0) { return classComparison } val that = other as FsAgnosticSourcePath return path.compareTo(that.path) } override fun toString(): String = path.toString() }
src/com/facebook/buck/multitenant/query/FsAgnosticSourcePath.kt
2870554800
// 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 git4idea.branch import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.vcs.branch.BranchData import com.intellij.vcs.branch.BranchStateProvider import com.intellij.vcs.branch.LinkedBranchDataImpl import git4idea.GitVcs import git4idea.repo.GitRepositoryManager internal class GitBranchStateProvider(val project: Project) : BranchStateProvider { override fun getCurrentBranch(path: FilePath): BranchData? { if (!ProjectLevelVcsManager.getInstance(project).checkVcsIsActive(GitVcs.NAME)) return null val repository = GitRepositoryManager.getInstance(project).getRepositoryForFileQuick(path) return repository?.let { LinkedBranchDataImpl(it.root.presentableName, it.currentBranch?.name, it.currentBranch?.findTrackedBranch(it)?.name) } } }
plugins/git4idea/src/git4idea/branch/GitBranchStateProvider.kt
1727981341
package com.clock.kotlinsample.entity /** * Created by Clock on 2017/6/11. */ //使用data class声明会自动生成getters、 setters、 equals()、 hashCode()、 toString() 以及 copy()方法 data class KotlinCoder(var name: String, var id: Int)
AndroidStudio_Project/app/src/main/java/com/clock/kotlinsample/entity/KotlinCoder.kt
108476210
// 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 import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.impl.AbstractEditorTest import com.intellij.testFramework.MapDataContext import com.intellij.testFramework.TestFileType import org.junit.Test import java.awt.Dimension import java.awt.Point class PopupUtilTest : AbstractEditorTest() { @Test fun `test popups positions inside editor`() { init(""" import org.junit.Test class TestCase { @Test fun tes<caret>t() {} } """.trimIndent(), TestFileType.TEXT) val editor = editor as EditorEx editor.scrollPane.viewport.apply { viewPosition = Point(0, 0) extentSize = Dimension(500, 1000) } val logicalPosition = editor.caretModel.logicalPosition val context = MapDataContext().apply { put(PlatformDataKeys.CONTEXT_COMPONENT, editor.contentComponent) put(CommonDataKeys.EDITOR, editor) } val xyBalloonPosition = editor.logicalPositionToXY(logicalPosition) val xyPopupPosition = Point(xyBalloonPosition.x, xyBalloonPosition.y + editor.lineHeight) val balloonPosition = getBestBalloonPosition(context) val popupPosition = getBestPopupPosition(context) assertEquals(editor.lineHeight, popupPosition.point.y - balloonPosition.point.y) assertEquals(0, popupPosition.point.x - balloonPosition.point.x) assertEquals(xyBalloonPosition, balloonPosition.point) assertEquals(xyPopupPosition, popupPosition.point) } }
platform/platform-tests/testSrc/com/intellij/util/PopupUtilTest.kt
2597088996
package com.devrapid.musicdiskplayer import android.animation.ObjectAnimator import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.LinearInterpolator import com.mikhaellopez.circularimageview.CircularImageView /** * [CircleImageView] with rotated animation. * * @author jieyi * @since 7/4/17 */ open class RotatedCircleImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0): CircularImageView(context, attrs, defStyleAttr) { companion object { private const val ONE_ROUND_ROTATE_TIME = 10 private const val TIME_MILLION = 1000L private const val A_CIRCLE_ANGEL = 360f } //region Variables of setting var onClickCallback: ((RotatedCircleImageView) -> Unit)? = null // Basically this's that controlling the rotating speed. var oneRoundTime = ONE_ROUND_ROTATE_TIME.toLong() private set(value) { field = value * TIME_MILLION } var isPauseState = false //endregion private val rotateAnimator by lazy { ObjectAnimator.ofFloat(this, "rotation", 0f, A_CIRCLE_ANGEL).apply { interpolator = LinearInterpolator() duration = oneRoundTime repeatCount = Animation.INFINITE } } init { context.obtainStyledAttributes(attrs, R.styleable.RotatedCircleImageView, defStyleAttr, 0).also { oneRoundTime = it.getInteger(R.styleable.RotatedCircleImageView_rotate_sec, ONE_ROUND_ROTATE_TIME).toLong() }.recycle() setOnClickListener { rotateAnimator.let { isPauseState = when { !it.isStarted -> { it.start() false } it.isPaused -> { it.resume() false } it.isRunning -> { it.pause() true } else -> true } } onClickCallback?.let { it(this@RotatedCircleImageView) } } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val square = minOf(ViewGroup.getDefaultSize(suggestedMinimumWidth, widthMeasureSpec), ViewGroup.getDefaultSize(suggestedMinimumHeight, heightMeasureSpec)) setMeasuredDimension(square, square) } override fun onTouchEvent(e: MotionEvent): Boolean { when (e.action) { // Checking the clicking is inside of circle imageview. MotionEvent.ACTION_DOWN -> return isInCircleRange(e.x, e.y) MotionEvent.ACTION_UP -> { if (isInCircleRange(e.x, e.y)) { // After confirming the clicking is inside of the image. performClick() return true } } } return false } override fun onDetachedFromWindow() { super.onDetachedFromWindow() onClickCallback = null } /** * Start the rotating animation of the circle image. */ fun start() { // According to the state then start the animation. if (!rotateAnimator.isStarted) { rotateAnimator.start() } else if (rotateAnimator.isPaused) { rotateAnimator.resume() } else { return } isPauseState = false } /** * Stop the rotating animation of the circle image. */ fun stop() { if (rotateAnimator.isRunning) { rotateAnimator.pause() isPauseState = true } } /** * Check the position [x] & [y] is inside the circle. * * @param x x-coordination. * @param y y-coordination. * @return [true] if the position of clicking is in the circle range ; otherwise [false]. */ private fun isInCircleRange(x: Float, y: Float): Boolean = width / 2 > distance(x, y, pivotX, pivotY) /** * Calculating the distance between two positions. * * @param sX a position's x-coordination. * @param sY a position's y-coordination. * @param eX another position's x-coordination. * @param eY another position's y-coordination. * @return the distance length. */ private fun distance(sX: Float, sY: Float, eX: Float, eY: Float): Double = Math.sqrt(Math.pow((sX - eX).toDouble(), 2.0) + Math.pow((sY - eY).toDouble(), 2.0)) }
musicdiskplayer/src/main/java/com/devrapid/musicdiskplayer/RotatedCircleImageView.kt
3111807733
package mixit.util import org.junit.Test import org.junit.Assert.* /** * Unit tests for Extensions */ class ExtensionsTest { @Test fun toSlug() { assertEquals("", "".toSlug()) assertEquals("-", "---".toSlug()) assertEquals("billetterie-mixit-2017-pre-inscription", "Billetterie MiXiT 2017 : pré-inscription".toSlug()) assertEquals("mixit-2017-ticketing-pre-registration", "MiXiT 2017 ticketing: pre-registration".toSlug()) } }
src/test/kotlin/mixit/util/ExtensionsTest.kt
1774864027
/* * (C) Copyright 2019 Lukas Morawietz (https://github.com/F43nd1r) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.faendir.acra.ui.theme import com.faendir.acra.settings.LocalSettings import com.vaadin.flow.server.UIInitEvent import com.vaadin.flow.server.UIInitListener import com.vaadin.flow.spring.annotation.SpringComponent import com.vaadin.flow.spring.annotation.VaadinSessionScope import com.vaadin.flow.theme.lumo.Lumo import org.springframework.context.annotation.Lazy @VaadinSessionScope @SpringComponent @Lazy class ThemeUIListener(private val localSettings: LocalSettings) : UIInitListener { override fun uiInit(event: UIInitEvent) { event.ui.element.setAttribute("theme", if (localSettings.darkTheme) Lumo.DARK else Lumo.LIGHT) event.ui.locale = localSettings.locale } }
acrarium/src/main/kotlin/com/faendir/acra/ui/theme/ThemeUIListener.kt
2090986545
// 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.jetbrains.builtInHelp.search import org.apache.commons.compress.utils.IOUtils import org.apache.lucene.analysis.standard.StandardAnalyzer import org.apache.lucene.store.FSDirectory import org.jetbrains.annotations.NotNull import java.io.FileOutputStream import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths abstract class HelpIndexProcessor { companion object { val resources = arrayOf("_0.cfe", "_0.cfs", "_0.si", "segments_1") val STORAGE_PREFIX = "/search/" val EMPTY_RESULT = "[]" } val analyzer: StandardAnalyzer = StandardAnalyzer() fun deployIndex(): FSDirectory? { val indexDir: Path? = Files.createTempDirectory("search-index") var result: FSDirectory? = null if (indexDir != null) { for (resourceName in resources) { val input = HelpSearch::class.java.getResourceAsStream( STORAGE_PREFIX + resourceName) val fos: FileOutputStream = FileOutputStream(Paths.get(indexDir.toAbsolutePath().toString(), resourceName).toFile()) IOUtils.copy(input, fos) fos.flush() fos.close() input.close() } result = FSDirectory.open(indexDir) } return result } fun releaseIndex(indexDirectory: FSDirectory) { val path = indexDirectory.directory for (f in path.toFile().listFiles()) f.delete() Files.delete(path) } @NotNull abstract fun process(query: String, maxResults: Int): String }
plugins/built-in-help/src/com/jetbrains/builtInHelp/search/HelpIndexProcessor.kt
1708971251
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.util import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiClass import com.intellij.psi.SmartPointerManager import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.UsageSearchContext import com.intellij.psi.util.ClassUtil import com.intellij.psi.xml.XmlTag import com.intellij.util.SmartList import com.intellij.util.xml.DomManager import org.jetbrains.idea.devkit.dom.Extension import org.jetbrains.idea.devkit.dom.ExtensionPoint import java.util.* fun locateExtensionsByPsiClass(psiClass: PsiClass): List<ExtensionCandidate> { return findExtensionsByClassName(psiClass.project, ClassUtil.getJVMClassName(psiClass) ?: return emptyList()) } fun locateExtensionsByExtensionPoint(extensionPoint: ExtensionPoint): List<ExtensionCandidate> { return ExtensionByExtensionPointLocator(extensionPoint.xmlTag.project, extensionPoint, null).findCandidates() } fun locateExtensionsByExtensionPointAndId(extensionPoint: ExtensionPoint, extensionId: String): ExtensionLocator { return ExtensionByExtensionPointLocator(extensionPoint.xmlTag.project, extensionPoint, extensionId) } internal fun processExtensionDeclarations(name: String, project: Project, strictMatch: Boolean = true, callback: (Extension, XmlTag) -> Boolean) { val scope = PluginRelatedLocatorsUtils.getCandidatesScope(project) val searchWord = name.substringBeforeLast('$') if (searchWord.isEmpty()) return PsiSearchHelper.getInstance(project).processElementsWithWord( { element, offsetInElement -> val elementAtOffset = (element as? XmlTag)?.findElementAt(offsetInElement) ?: return@processElementsWithWord true if (strictMatch) { if (!elementAtOffset.textMatches(name)) { return@processElementsWithWord true } } else if (!StringUtil.contains(elementAtOffset.text, name)) { return@processElementsWithWord true } val extension = DomManager.getDomManager(project).getDomElement(element) as? Extension ?: return@processElementsWithWord true callback(extension, element) }, scope, searchWord, UsageSearchContext.IN_FOREIGN_LANGUAGES, /* case-sensitive = */ true) } private fun findExtensionsByClassName(project: Project, className: String): List<ExtensionCandidate> { val result = Collections.synchronizedList(SmartList<ExtensionCandidate>()) val smartPointerManager by lazy { SmartPointerManager.getInstance(project) } processExtensionsByClassName(project, className) { tag, _ -> result.add(ExtensionCandidate(smartPointerManager.createSmartPsiElementPointer(tag))) true } return result } internal inline fun processExtensionsByClassName(project: Project, className: String, crossinline processor: (XmlTag, ExtensionPoint) -> Boolean) { processExtensionDeclarations(className, project) { extension, tag -> extension.extensionPoint?.let { processor(tag, it) } ?: true } } internal class ExtensionByExtensionPointLocator(private val project: Project, extensionPoint: ExtensionPoint, private val extensionId: String?) : ExtensionLocator() { private val pointQualifiedName = extensionPoint.effectiveQualifiedName private fun processCandidates(processor: (XmlTag) -> Boolean) { // We must search for the last part of EP name, because for instance 'com.intellij.console.folding' extension // may be declared as <extensions defaultExtensionNs="com"><intellij.console.folding ... val epNameToSearch = StringUtil.substringAfterLast(pointQualifiedName, ".") ?: return processExtensionDeclarations(epNameToSearch, project, false /* not strict match */) { extension, tag -> val ep = extension.extensionPoint ?: return@processExtensionDeclarations true if (ep.effectiveQualifiedName == pointQualifiedName && (extensionId == null || extensionId == extension.id.stringValue)) { // stop after the first found candidate if ID is specified processor(tag) && extensionId == null } else { true } } } override fun findCandidates(): List<ExtensionCandidate> { val result = Collections.synchronizedList(SmartList<ExtensionCandidate>()) val smartPointerManager by lazy { SmartPointerManager.getInstance(project) } processCandidates { result.add(ExtensionCandidate(smartPointerManager.createSmartPsiElementPointer(it))) } return result } } sealed class ExtensionLocator { abstract fun findCandidates(): List<ExtensionCandidate> }
plugins/devkit/devkit-core/src/util/ExtensionLocator.kt
873914952
package com.igorini.kotlin.hints.functions // [Method Overload] -> Overloading methods with the reduced number of arguments can be avoided by providing default values for parameters // [Before] fun beforePrintNumber() = beforePrintNumber(0) fun beforePrintNumber(a: Int) = println("Number: $a") // [After] fun afterPrintNumber(a: Int = 0) = println("Number: $a")
src/main/kotlin/com/igorini/kotlin/hints/functions/MethodOverload.kt
3055388287
fun box(): String { var x = 1 (foo@ x)++ ++(foo@ x) if (x != 3) return "Fail: $x" return "OK" }
backend.native/tests/external/codegen/box/intrinsics/incWithLabel.kt
1412875008
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS // TODO: muted automatically, investigate should it be ran for NATIVE or not // IGNORE_BACKEND: NATIVE // Auto-generated by org.jetbrains.kotlin.generators.tests.GenerateRangesCodegenTestData. DO NOT EDIT! // WITH_RUNTIME import java.lang.Integer.MAX_VALUE as MaxI import java.lang.Integer.MIN_VALUE as MinI import java.lang.Byte.MAX_VALUE as MaxB import java.lang.Byte.MIN_VALUE as MinB import java.lang.Short.MAX_VALUE as MaxS import java.lang.Short.MIN_VALUE as MinS import java.lang.Long.MAX_VALUE as MaxL import java.lang.Long.MIN_VALUE as MinL import java.lang.Character.MAX_VALUE as MaxC import java.lang.Character.MIN_VALUE as MinC fun box(): String { val list1 = ArrayList<Int>() for (i in (MaxI - 5)..MaxI step 3) { list1.add(i) if (list1.size > 23) break } if (list1 != listOf<Int>(MaxI - 5, MaxI - 2)) { return "Wrong elements for (MaxI - 5)..MaxI step 3: $list1" } val list2 = ArrayList<Int>() for (i in (MaxB - 5).toByte()..MaxB step 3) { list2.add(i) if (list2.size > 23) break } if (list2 != listOf<Int>((MaxB - 5).toInt(), (MaxB - 2).toInt())) { return "Wrong elements for (MaxB - 5).toByte()..MaxB step 3: $list2" } val list3 = ArrayList<Int>() for (i in (MaxS - 5).toShort()..MaxS step 3) { list3.add(i) if (list3.size > 23) break } if (list3 != listOf<Int>((MaxS - 5).toInt(), (MaxS - 2).toInt())) { return "Wrong elements for (MaxS - 5).toShort()..MaxS step 3: $list3" } val list4 = ArrayList<Long>() for (i in (MaxL - 5).toLong()..MaxL step 3) { list4.add(i) if (list4.size > 23) break } if (list4 != listOf<Long>((MaxL - 5).toLong(), (MaxL - 2).toLong())) { return "Wrong elements for (MaxL - 5).toLong()..MaxL step 3: $list4" } val list5 = ArrayList<Char>() for (i in (MaxC - 5)..MaxC step 3) { list5.add(i) if (list5.size > 23) break } if (list5 != listOf<Char>((MaxC - 5), (MaxC - 2))) { return "Wrong elements for (MaxC - 5)..MaxC step 3: $list5" } return "OK" }
backend.native/tests/external/codegen/box/ranges/literal/inexactToMaxValue.kt
3286985760
package expo.modules.imagemanipulator.arguments import expo.modules.core.arguments.ReadableArguments import android.graphics.Bitmap.CompressFormat private const val KEY_BASE64 = "base64" private const val KEY_COMPRESS = "compress" private const val KEY_FORMAT = "format" data class SaveOptions( val base64: Boolean, val compress: Double, val format: CompressFormat ) { companion object { fun fromArguments(arguments: ReadableArguments): SaveOptions { val base64 = arguments.getBoolean(KEY_BASE64, false) val compress = arguments.getDouble(KEY_COMPRESS, 1.0) val format = toCompressFormat(arguments.getString(KEY_FORMAT, "jpeg")) return SaveOptions(base64, compress, format) } } } fun toCompressFormat(format: String): CompressFormat { return when (format) { "jpeg" -> CompressFormat.JPEG "png" -> CompressFormat.PNG else -> CompressFormat.JPEG } }
packages/expo-image-manipulator/android/src/main/java/expo/modules/imagemanipulator/arguments/SaveOptions.kt
2768241370
package one.two fun usage2() { with(KotlinObject.NestedObject) { Receiver().overloadsStaticExtension() } }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/fromObject/nestedObject/overloadsStaticExtension/Usage2.kt
1602508288
// !DIAGNOSTICS_NUMBER: 1 // !DIAGNOSTICS: MULTIPLE_DEFAULTS_INHERITED_FROM_SUPERTYPES_WHEN_NO_EXPLICIT_OVERRIDE interface C { fun foo(x: Int = 42) } interface D { fun foo(x: Int = 239) {} } class multipleDefaultsFromSupertypes : C, D
plugins/kotlin/idea/tests/testData/diagnosticMessage/multipleDefaultsFromSupertypes.kt
87125209
class Foo class BarFoo lateinit var f<caret> // EXIST: { itemText: "foo: Foo" } // EXIST: { itemText: "foo: BarFoo" }
plugins/kotlin/completion/tests/testData/basic/common/variableNameAndType/Lateinit.kt
3857908579
package com.jetbrains.packagesearch.intellij.plugin.gradle.configuration internal object PackageSearchGradleConfigurationDefaults { const val GradleScopes = "api,implementation,testImplementation,annotationProcessor,kapt" const val GradleDefaultScope = "implementation" }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/gradle/configuration/PackageSearchGradleConfigurationDefaults.kt
2133150476
// 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.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNullableType import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class RemoveNullableFix( element: KtNullableType, private val typeOfError: NullableKind ) : KotlinQuickFixAction<KtNullableType>(element) { enum class NullableKind(@Nls val message: String) { REDUNDANT(KotlinBundle.message("remove.redundant")), SUPERTYPE(KotlinBundle.message("text.remove.question")), USELESS(KotlinBundle.message("remove.useless")), PROPERTY(KotlinBundle.message("make.not.nullable")) } override fun getFamilyName() = KotlinBundle.message("text.remove.question") override fun getText() = typeOfError.message override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val type = element.innerType ?: error("No inner type " + element.text + ", should have been rejected in createFactory()") element.replace(type) } class Factory(private val typeOfError: NullableKind) : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtNullableType>? { val nullType = diagnostic.psiElement.getNonStrictParentOfType<KtNullableType>() if (nullType?.innerType == null) return null return RemoveNullableFix(nullType, typeOfError) } } object LATEINIT_FACTORY : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtNullableType>? { val lateinitElement = Errors.INAPPLICABLE_LATEINIT_MODIFIER.cast(diagnostic).psiElement val property = lateinitElement.getStrictParentOfType<KtProperty>() ?: return null val typeReference = property.typeReference ?: return null val typeElement = (typeReference.typeElement ?: return null) as? KtNullableType ?: return null if (typeElement.innerType == null) return null return RemoveNullableFix(typeElement, NullableKind.PROPERTY) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveNullableFix.kt
3391021360
class B : X<*>
plugins/kotlin/j2k/new/tests/testData/copyPaste/RawTypeRef.expected.kt
3004237252
fun Main.test() { this - "" }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/operators/minus/Implicit.kt
2421161739
fun f() { val (a<caret>, b) = 1 to 2 }
plugins/kotlin/idea/tests/testData/wordSelection/MultiDeclaration/0.kt
3098652030
package chat.willow.kale import chat.willow.kale.core.message.IrcMessage import chat.willow.kale.core.tag.IKaleTagRouter import chat.willow.kale.core.tag.ITagParser import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test class KaleMetadataFactoryTests { private lateinit var sut: KaleMetadataFactory private lateinit var tagRouter: IKaleTagRouter @Before fun setUp() { tagRouter = mock() sut = KaleMetadataFactory(tagRouter) } @Test fun test_process_ValidMetadata_MetadataIsCorrect() { val tagParser: ITagParser<String> = mock() val metadata = "some metadata" whenever(tagParser.parse(any())).thenReturn(metadata) whenever(tagRouter.parserFor("tag1")).thenReturn(tagParser) val result = sut.construct(IrcMessage(tags = mapOf("tag1" to "value1", "tag2" to null), command = "")) assertEquals(metadata, result[String::class]) } @Test fun test_process_InvalidMetadataLookup_MetadataIsNull() { val tagParser: ITagParser<String> = mock() val metadata = "some metadata" whenever(tagParser.parse(any())).thenReturn(metadata) whenever(tagRouter.parserFor("tag1")).thenReturn(tagParser) val result = sut.construct(IrcMessage(tags = mapOf("tag1" to "value1", "tag2" to null), command = "")) assertNull(result[Int::class]) } }
src/test/kotlin/chat/willow/kale/KaleMetadataFactoryTests.kt
3717800444
/* * Copyright 2016 Fabio Collini. * * 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 it.cosenonjaviste.daggermock.realworldappkotlin.main import dagger.Module import dagger.Provides import it.cosenonjaviste.daggermock.realworldappkotlin.OpenForTesting import it.cosenonjaviste.daggermock.realworldappkotlin.services.MainService import it.cosenonjaviste.daggermock.realworldappkotlin.services.SnackBarManager @OpenForTesting @Module class MainActivityModule(private val mainActivity: MainActivity) { @Provides fun provideSnackBarManager(): SnackBarManager { return SnackBarManager(mainActivity) } @Provides fun provideMainView(): MainView { return mainActivity } @Provides fun provideMainPresenter(mainService: MainService, view: MainView, snackBarManager: SnackBarManager): MainPresenter { return MainPresenter(mainService, view, snackBarManager) } }
RealWorldAppKotlinAllOpen/src/main/java/it/cosenonjaviste/daggermock/realworldappkotlin/main/MainActivityModule.kt
2525839089
package com.example.testModule7 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/testModule7/src/androidTest/java/com/example/testModule7/ModuleTests.kt
457145760
package com.kickstarter.ui.viewholders import com.kickstarter.databinding.ProjectSocialViewBinding import com.kickstarter.libs.transformations.CircleTransformation import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.models.User import com.squareup.picasso.Picasso class ProjectSocialViewHolder(private val binding: ProjectSocialViewBinding) : KSViewHolder(binding.root) { private var user: User? = null @Throws(Exception::class) override fun bindData(data: Any?) { user = ObjectUtils.requireNonNull(data as User?, User::class.java) } override fun onBind() { user?.avatar()?.small()?.let { Picasso.get() .load(it) .transform(CircleTransformation()) .into(binding.friendImage) } binding.friendName.text = user?.name() } }
app/src/main/java/com/kickstarter/ui/viewholders/ProjectSocialViewHolder.kt
1984107990
// 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.eval4j.jdi import com.sun.jdi.ClassObjectReference import com.sun.jdi.VirtualMachine import org.jetbrains.eval4j.* import org.jetbrains.org.objectweb.asm.Opcodes.ACC_STATIC import org.jetbrains.org.objectweb.asm.Type import org.jetbrains.org.objectweb.asm.tree.MethodNode import org.jetbrains.org.objectweb.asm.tree.analysis.Frame import com.sun.jdi.BooleanValue as jdi_BooleanValue import com.sun.jdi.ByteValue as jdi_ByteValue import com.sun.jdi.CharValue as jdi_CharValue import com.sun.jdi.DoubleValue as jdi_DoubleValue import com.sun.jdi.FloatValue as jdi_FloatValue import com.sun.jdi.IntegerValue as jdi_IntegerValue import com.sun.jdi.LongValue as jdi_LongValue import com.sun.jdi.ObjectReference as jdi_ObjectReference import com.sun.jdi.ShortValue as jdi_ShortValue import com.sun.jdi.Type as jdi_Type import com.sun.jdi.Value as jdi_Value import com.sun.jdi.VoidValue as jdi_VoidValue fun makeInitialFrame(methodNode: MethodNode, arguments: List<Value>): Frame<Value> { val isStatic = (methodNode.access and ACC_STATIC) != 0 val params = Type.getArgumentTypes(methodNode.desc) assert(arguments.size == (if (isStatic) params.size else params.size + 1)) { "Wrong number of arguments for $methodNode: $arguments" } val frame = Frame<Value>(methodNode.maxLocals, methodNode.maxStack) frame.setReturn(makeNotInitializedValue(Type.getReturnType(methodNode.desc))) var index = 0 for (arg in arguments) { frame.setLocal(index++, arg) if (arg.size == 2) { frame.setLocal(index++, NOT_A_VALUE) } } while (index < methodNode.maxLocals) { frame.setLocal(index++, NOT_A_VALUE) } return frame } class JDIFailureException(message: String?, cause: Throwable? = null) : RuntimeException(message, cause) fun jdi_ObjectReference?.asValue(): ObjectValue { return when (this) { null -> NULL_VALUE else -> ObjectValue(this, type().asType()) } } fun jdi_Value?.asValue(): Value { return when (this) { null -> NULL_VALUE is jdi_VoidValue -> VOID_VALUE is jdi_BooleanValue -> IntValue(intValue(), Type.BOOLEAN_TYPE) is jdi_ByteValue -> IntValue(intValue(), Type.BYTE_TYPE) is jdi_ShortValue -> IntValue(intValue(), Type.SHORT_TYPE) is jdi_CharValue -> IntValue(intValue(), Type.CHAR_TYPE) is jdi_IntegerValue -> IntValue(intValue(), Type.INT_TYPE) is jdi_LongValue -> LongValue(longValue()) is jdi_FloatValue -> FloatValue(floatValue()) is jdi_DoubleValue -> DoubleValue(doubleValue()) is jdi_ObjectReference -> this.asValue() else -> throw JDIFailureException("Unknown value: $this") } } fun jdi_Type.asType(): Type = Type.getType(this.signature()) val Value.jdiObj: jdi_ObjectReference? get() = this.obj() as jdi_ObjectReference? val Value.jdiClass: ClassObjectReference? get() = this.jdiObj as ClassObjectReference? fun Value.asJdiValue(vm: VirtualMachine, expectedType: Type): jdi_Value? { return when (this) { NULL_VALUE -> null VOID_VALUE -> vm.mirrorOfVoid() is IntValue -> when (expectedType) { Type.BOOLEAN_TYPE -> vm.mirrorOf(boolean) Type.BYTE_TYPE -> vm.mirrorOf(int.toByte()) Type.SHORT_TYPE -> vm.mirrorOf(int.toShort()) Type.CHAR_TYPE -> vm.mirrorOf(int.toChar()) Type.INT_TYPE -> vm.mirrorOf(int) else -> throw JDIFailureException("Unknown value type: $this") } is LongValue -> vm.mirrorOf(value) is FloatValue -> vm.mirrorOf(value) is DoubleValue -> vm.mirrorOf(value) is ObjectValue -> value as jdi_ObjectReference is NewObjectValue -> this.obj() as jdi_ObjectReference else -> throw JDIFailureException("Unknown value: $this") } }
plugins/kotlin/jvm-debugger/eval4j/src/org/jetbrains/eval4j/jdi/jdiValues.kt
1683613421
// 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.projectModel import com.intellij.openapi.roots.libraries.PersistentLibraryKind import org.jetbrains.kotlin.idea.base.platforms.KotlinCommonLibraryKind import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptLibraryKind import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR import org.jetbrains.kotlin.platform.CommonPlatforms import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.js.JsPlatforms import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.utils.Printer import java.io.File open class ProjectResolveModel(val modules: List<ResolveModule>) { open class Builder { val modules: MutableList<ResolveModule.Builder> = mutableListOf() open fun build(): ProjectResolveModel = ProjectResolveModel(modules.map { it.build() }) } } open class ResolveModule( val name: String, val root: File, val platform: TargetPlatform, val dependencies: List<ResolveDependency>, val testRoot: File? = null, val additionalCompilerArgs: String? = null ) { final override fun toString(): String { return buildString { renderDescription(Printer(this)) } } open fun renderDescription(printer: Printer) { printer.println("Module $name") printer.pushIndent() printer.println("platform=$platform") printer.println("root=${root.absolutePath}") if (testRoot != null) printer.println("testRoot=${testRoot.absolutePath}") printer.println("dependencies=${dependencies.joinToString { it.to.name }}") if (additionalCompilerArgs != null) printer.println("additionalCompilerArgs=$additionalCompilerArgs") } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ResolveModule if (name != other.name) return false return true } override fun hashCode(): Int { return name.hashCode() } open class Builder { private var state: State = State.NOT_BUILT private var cachedResult: ResolveModule? = null var name: String? = null var root: File? = null var platform: TargetPlatform? = null val dependencies: MutableList<ResolveDependency.Builder> = mutableListOf() var testRoot: File? = null var additionalCompilerArgs: String? = null open fun build(): ResolveModule { if (state == State.BUILT) return cachedResult!! require(state == State.NOT_BUILT) { "Re-building module $this with name $name (root at $root)" } state = State.BUILDING val builtDependencies = dependencies.map { it.build() } cachedResult = ResolveModule(name!!, root!!, platform!!, builtDependencies, testRoot, additionalCompilerArgs= additionalCompilerArgs) state = State.BUILT return cachedResult!! } enum class State { NOT_BUILT, BUILDING, BUILT } } } sealed class ResolveLibrary( name: String, root: File, platform: TargetPlatform, val kind: PersistentLibraryKind<*>? ) : ResolveModule(name, root, platform, emptyList()) { class Builder(val target: ResolveLibrary) : ResolveModule.Builder() { override fun build(): ResolveModule = target } } sealed class Stdlib( name: String, root: File, platform: TargetPlatform, kind: PersistentLibraryKind<*>? ) : ResolveLibrary(name, root, platform, kind) { object CommonStdlib : Stdlib( "stdlib-common", TestKotlinArtifacts.kotlinStdlibCommon, CommonPlatforms.defaultCommonPlatform, KotlinCommonLibraryKind ) object JvmStdlib : Stdlib( "stdlib-jvm", TestKotlinArtifacts.kotlinStdlib, JvmPlatforms.defaultJvmPlatform, null ) object JsStdlib : Stdlib( "stdlib-js", TestKotlinArtifacts.kotlinStdlibJs, JsPlatforms.defaultJsPlatform, KotlinJavaScriptLibraryKind ) } sealed class KotlinTest( name: String, root: File, platform: TargetPlatform, kind: PersistentLibraryKind<*>? ) : ResolveLibrary(name, root, platform, kind) { object JsKotlinTest : KotlinTest( "kotlin-test-js", TestKotlinArtifacts.kotlinTestJs, JsPlatforms.defaultJsPlatform, KotlinJavaScriptLibraryKind ) object JvmKotlinTest : KotlinTest( "kotlin-test-jvm", TestKotlinArtifacts.kotlinTestJunit, JvmPlatforms.defaultJvmPlatform, null ) object JustKotlinTest : KotlinTest( "kotlin-test", TestKotlinArtifacts.kotlinTest, JvmPlatforms.defaultJvmPlatform, null ) object Junit : KotlinTest( "junit", File("$IDEA_TEST_DATA_DIR/lib/junit-4.12.jar"), JvmPlatforms.defaultJvmPlatform, null ) } interface ResolveSdk object FullJdk : ResolveLibrary( "full-jdk", File("fake file for full jdk"), JvmPlatforms.defaultJvmPlatform, null ), ResolveSdk object MockJdk : ResolveLibrary( "mock-jdk", File("fake file for mock jdk"), JvmPlatforms.defaultJvmPlatform, null ), ResolveSdk object KotlinSdk : ResolveLibrary( "kotlin-sdk", File("fake file for kotlin sdk"), CommonPlatforms.defaultCommonPlatform, null, ), ResolveSdk open class ResolveDependency(val to: ResolveModule, val kind: Kind) { open class Builder { var to: ResolveModule.Builder = ResolveModule.Builder() var kind: Kind? = null open fun build(): ResolveDependency = ResolveDependency(to.build(), kind!!) } enum class Kind { DEPENDS_ON, DEPENDENCY, } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/projectModel/Model.kt
2948330930
package com.stefanosiano.powerful_libraries.imageviewsample import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import androidx.test.core.app.ApplicationProvider import androidx.test.platform.app.InstrumentationRegistry import androidx.test.runner.AndroidJUnitRunner import kotlin.test.BeforeTest abstract class BaseUiTest { /** Runner of the test. */ protected lateinit var runner: AndroidJUnitRunner /** Application context for the current test. */ protected lateinit var context: Context @BeforeTest fun baseSetUp() { runner = InstrumentationRegistry.getInstrumentation() as AndroidJUnitRunner context = ApplicationProvider.getApplicationContext() context.cacheDir.deleteRecursively() } } // todo check imageview equals to piv without any custom feature for setImage, setDrawable, setBitmap, setVector internal fun Bitmap?.contentEquals(b2: Bitmap?): Boolean { if (this == null && b2 == null) { return true } if (this == null || b2 == null) { return false } if (byteCount != b2.byteCount) { return false } for (i in 0 until width) { for (j in 0 until height) { val c1 = getColor(i, j) val c2 = b2.getColor(i, j) if (c1 != c2) { return false } } } return true } internal fun Drawable.createBitmap(): Bitmap { val bitmap = if (intrinsicWidth <= 0 || intrinsicHeight <= 0 || this is ColorDrawable) { Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) } else { Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888) } val canvas = Canvas(bitmap) setBounds(0, 0, canvas.width, canvas.height) draw(canvas) return bitmap }
sample/src/androidTest/java/com/stefanosiano/powerful_libraries/imageviewsample/BaseUiTest.kt
729573250
package acr.browser.lightning.browser.cleanup import acr.browser.lightning.browser.di.DatabaseScheduler import acr.browser.lightning.database.history.HistoryDatabase import acr.browser.lightning.log.Logger import acr.browser.lightning.preference.UserPreferences import acr.browser.lightning.utils.WebUtils import android.app.Activity import io.reactivex.Scheduler import javax.inject.Inject /** * Exit cleanup that should run whenever the main browser process is exiting. */ class NormalExitCleanup @Inject constructor( private val userPreferences: UserPreferences, private val logger: Logger, private val historyDatabase: HistoryDatabase, @DatabaseScheduler private val databaseScheduler: Scheduler, private val activity: Activity ) : ExitCleanup { override fun cleanUp() { if (userPreferences.clearCacheExit) { WebUtils.clearCache(activity) logger.log(TAG, "Cache Cleared") } if (userPreferences.clearHistoryExitEnabled) { WebUtils.clearHistory(activity, historyDatabase, databaseScheduler) logger.log(TAG, "History Cleared") } if (userPreferences.clearCookiesExitEnabled) { WebUtils.clearCookies() logger.log(TAG, "Cookies Cleared") } if (userPreferences.clearWebStorageExitEnabled) { WebUtils.clearWebStorage() logger.log(TAG, "WebStorage Cleared") } } companion object { const val TAG = "NormalExitCleanup" } }
app/src/main/java/acr/browser/lightning/browser/cleanup/NormalExitCleanup.kt
2874722201
package c internal fun internalFun() {}
plugins/kotlin/jps/jps-plugin/tests/testData/incremental/multiModule/jvm/circularDependencyWithAccessToInternal/module1_c2.kt
2470216300
// "Make 'Private' protected" "true" // ACTION: Make 'foo' private // ACTION: Make 'Private' public class Receiver<T> abstract class My { private class Private abstract protected fun <caret>Receiver<Private>.foo() }
plugins/kotlin/idea/tests/testData/quickfix/increaseVisibility/exposedReceiverType.kt
2143538324
class Test { class B { class C fun c(): C { return C() } } fun a() { val b = B() println(b.toString() + "") val a = 1.toString() + "0" println(b.c().toString() + "") } companion object { @JvmStatic fun main(args: Array<String>) { val p = Test().toString() + "123" } } }
plugins/kotlin/j2k/new/tests/testData/newJ2k/binaryExpression/lhsObjectPlusString.kt
4157835355
/* * 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 com.intellij.diff.comparison class CharComparisonUtilTest : ComparisonUtilTestBase() { fun testEqualStrings() { chars { ("" - "") ("" - "").default() testAll() } chars { ("x" - "x") (" " - " ").default() testAll() } chars { ("x_y_z_" - "x_y_z_") (" " - " ").default() testAll() } chars { ("_" - "_") (" " - " ").default() testAll() } chars { ("xxx" - "xxx") (" " - " ").default() testAll() } chars { ("xyz" - "xyz") (" " - " ").default() testAll() } chars { (".x!" - ".x!") (" " - " ").default() testAll() } } fun testTrivialCases() { chars { ("x" - "") ("-" - "").default() testAll() } chars { ("" - "x") ("" - "-").default() testAll() } chars { ("x" - "y") ("-" - "-").default() testAll() } chars { ("x_" - "") ("--" - "").default() ("- " - "").ignore() testAll() } chars { ("" - "x_") ("" - "--").default() ("" - "- ").ignore() testAll() } chars { ("x_" - "y_") ("- " - "- ").default() testAll() } chars { ("_x" - "_y") (" -" - " -").default() testAll() } } fun testSimpleCases() { chars { ("xyx" - "xxx") (" - " - " - ").default() testAll() } chars { ("xyyx" - "xmx") (" -- " - " - ").default() testAll() } chars { ("xyy" - "yyx") ("- " - " -").default() testAll() } chars { ("x!!" - "!!x") ("- " - " -").default() testAll() } chars { ("xyx" - "xx") (" - " - " ").default() testAll() } chars { ("xx" - "xyx") (" " - " - ").default() testAll() } chars { ("!..." - "...!") ("- " - " -").default() testAll() } } fun testWhitespaceChangesOnly() { chars { (" x y z " - "xyz") ("- - - -" - " ").default() (" " - " ").ignore() testAll() } chars { ("xyz" - " x y z ") (" " - "- - - -").default() (" " - " ").ignore() testAll() } chars { ("x " - "x") (" -" - " ").default() (" " - " ").ignore() testAll() } chars { ("x" - " x") (" " - "- ").default() (" " - " ").ignore() testAll() } chars { (" x " - "x") ("- -" - " ").default() (" " - " ").ignore() testAll() } chars { ("x" - " x ") (" " - "- -").default() (" " - " ").ignore() testAll() } } fun testWhitespaceChanges() { chars { (" x " - "z") ("---" - "-").default() (" - " - "-").ignore() testAll() } chars { ("x" - " z ") ("-" - "---").default() ("-" - " - ").ignore() testAll() } chars { (" x" - "z\t") ("--" - "--").default() (" -" - "- ").ignore() testAll() } chars { ("x " - "\tz") ("--" - "--").default() ("- " - " -").ignore() testAll() } } fun testIgnoreInnerWhitespaces() { chars { ("x z y" - "xmn") (" ----" - " --").default() (" ---" - " --").ignore() testAll() } chars { ("x y z " - "x y m ") (" - " - " - ").default() testAll() } chars { ("x y z" - "x y m ") (" -" - " --").default() (" -" - " - ").ignore() testAll() } chars { (" x y z" - " m y z") (" - " - " - ").default() testAll() } chars { ("x y z" - " m y z") ("- " - "-- ").default() ("- " - " - ").ignore() testAll() } chars { ("x y z" - "x m z") (" - " - " - ").default() testAll() } chars { ("x y z" - "x z") (" - " - " ").default() testAll() } chars { ("x z" - "x m z") (" " - " - ").default() testAll() } chars { ("x z" - "x n m z") (" " - " --- ").default() testAll() } } fun testEmptyRangePositions() { chars { ("x y" - "x zy") default(ins(2, 2, 1)) testAll() } chars { ("x y" - "xz y") default(ins(1, 1, 1)) testAll() } chars { ("x y z" - "x z") default(del(2, 2, 1)) testAll() } chars { ("x z" - "x m z") default(ins(2, 2, 1)) testAll() } chars { ("xyx" - "xx") default(del(1, 1, 1)) testAll() } chars { ("xx" - "xyx") default(ins(1, 1, 1)) testAll() } chars { ("xy" - "x") default(del(1, 1, 1)) testAll() } chars { ("x" - "xy") default(ins(1, 1, 1)) testAll() } } fun testAlgorithmSpecific() { // This is a strange example: "ignore whitespace" produces lesser matching, than "Default". // This is fine, as the main goal of "ignore whitespaces" is to reduce 'noise' of diff, and 1 change is better than 3 changes // So we actually "ignore" whitespaces during comparison, rather than "mark all whitespaces as matched". chars { ("x y z" - "xX Zz") (" - " - " - - ").default() (" - " - " -------- ").ignore() testAll() } } fun testNonDeterministicCases() { chars { ("x" - " ") ignore(del(0, 0, 1)) testIgnore() } chars { (" " - "x") ignore(ins(0, 0, 1)) testIgnore() } chars { ("x .. z" - "x y .. z") (" " - " -- ").default() (" " - " - ").ignore() default(ins(2, 2, 2)) ignore(ins(2, 2, 1)) testAll() } chars { (" x _ y _ z " - "x z") ("- ------ -" - " ").default() (" - " - " ").ignore() default(del(0, 0, 1), del(3, 2, 6), del(10, 3, 1)) ignore(del(5, 2, 1)) testAll() } chars { ("x z" - " x _ y _ z ") (" " - "- ------ -").default() (" " - " - ").ignore() default(ins(0, 0, 1), ins(2, 3, 6), ins(3, 10, 1)) ignore(ins(2, 5, 1)) testAll() } } }
platform/diff-impl/tests/com/intellij/diff/comparison/CharComparisonUtilTest.kt
403399552
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.ch0201 import cc.altruix.econsimtr01.ResourceFlow import cc.altruix.econsimtr01.shouldBe import cc.altruix.econsimtr01.simulationRunLogic import org.junit.Test import java.io.File import java.util.* /** * Created by pisarenko on 18.04.2016. */ class Sim3Tests { @Test fun test() { val flows = LinkedList<ResourceFlow>() val log = StringBuilder() val simParametersProvider = Sim3ParametersProvider( File("src/test/resources/ch0201Sim3Tests.params.pl").readText() ) val sim = Sim3( log, flows, simParametersProvider ) simulationRunLogic(sim, log, simParametersProvider.resources, flows, "src/test/resources/ch0201/sim03/Sim3Tests.test.pl.expected.txt", "src/test/resources/ch0201/sim03/Sim3Tests.test.csv.expected.txt", "src/test/resources/ch0201/sim03/Sim3Tests.test.flows.actual.png", Sim2TimeSeriesCreator() ) } @Test fun flowF8IsCreated() { val simParametersProvider = Sim3ParametersProvider( File("src/test/resources/ch0201Sim3Tests.params.pl").readText() ) simParametersProvider.flows.filter { it.id == "f8" }.count().shouldBe(1) } }
src/test/java/cc/altruix/econsimtr01/ch0201/Sim3Tests.kt
2972956599
package org.penella /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Created by alisle on 1/13/17. */ enum class MailBoxes(val mailbox : String) { NODE_CREATE_DB("node.create.db"), NODE_LIST_DBS("node.list.dbs"), STORE_ADD_STRING("store.add.string"), STORE_ADD_TRIPLE("store.add.triple"), STORE_GET_STRING("store.get.string"), STORE_GET_HASHTRIPLE("store.get.hashtriple"), STORE_GENERATE_HASH("store.generate.hash"), INDEX_ADD_TRIPLE("index.add.triple."), INDEX_GET_FIRST("index.get.first."), INDEX_GET_SECOND("index.get.second."), SHARD_GET("shard.get."), SHARD_ADD("shard.add."), SHARD_SIZE("shard.size."), ; }
src/main/java/org/penella/MailBoxes.kt
7383707
package info.dvkr.screenstream.mjpeg.state.helper import android.annotation.SuppressLint import android.content.Context import android.content.res.Resources import android.net.wifi.WifiManager import androidx.core.content.ContextCompat import com.elvishew.xlog.XLog import info.dvkr.screenstream.common.getLog import info.dvkr.screenstream.mjpeg.NetInterface import java.net.* import java.util.* @SuppressLint("WifiManagerPotentialLeak") class NetworkHelper(context: Context) { private val networkInterfaceCommonNameArray = arrayOf("lo", "eth", "lan", "wlan", "en", "p2p", "net", "ppp", "wigig", "ap", "rmnet", "rmnet_data") private val defaultWifiRegexArray: Array<Regex> = arrayOf( Regex("wlan\\d"), Regex("ap\\d"), Regex("wigig\\d"), Regex("softap\\.?\\d") ) @SuppressLint("DiscouragedApi") private val wifiRegexArray: Array<Regex> = Resources.getSystem().getIdentifier("config_tether_wifi_regexs", "array", "android").let { tetherId -> context.applicationContext.resources.getStringArray(tetherId).map { it.toRegex() }.toTypedArray() } private val wifiManager: WifiManager = ContextCompat.getSystemService(context, WifiManager::class.java)!! private fun getNetworkInterfacesWithFallBack(): Enumeration<NetworkInterface> { try { return NetworkInterface.getNetworkInterfaces() } catch (ex: Exception) { XLog.w(getLog("getNetworkInterfacesWithFallBack.getNetworkInterfaces", ex.toString())) } val netList = mutableListOf<NetworkInterface>() (0..7).forEach { index -> try { val networkInterface: NetworkInterface? = NetworkInterface.getByIndex(index) if (networkInterface != null) netList.add(networkInterface) else if (index > 3) { if (netList.isNotEmpty()) return Collections.enumeration(netList) return@forEach } } catch (ex: SocketException) { XLog.e(getLog("getNetworkInterfacesWithFallBack.getByIndex#$index:", ex.toString())) } } networkInterfaceCommonNameArray.forEach { commonName -> try { val networkInterface: NetworkInterface? = NetworkInterface.getByName(commonName) if (networkInterface != null) netList.add(networkInterface) (0..15).forEach { index -> val networkInterfaceIndexed: NetworkInterface? = NetworkInterface.getByName("$commonName$index") if (networkInterfaceIndexed != null) netList.add(networkInterfaceIndexed) } } catch (ex: SocketException) { XLog.e(getLog("getNetworkInterfacesWithFallBack.commonName#$commonName:", ex.toString())) } } return Collections.enumeration(netList) } fun getNetInterfaces( useWiFiOnly: Boolean, enableIPv6: Boolean, enableLocalHost: Boolean, localHostOnly: Boolean ): List<NetInterface> { XLog.d(getLog("getNetInterfaces", "Invoked")) val netInterfaceList = mutableListOf<NetInterface>() getNetworkInterfacesWithFallBack().asSequence() .flatMap { networkInterface -> networkInterface.inetAddresses.asSequence().filterNotNull() .filter { !it.isLinkLocalAddress && !it.isMulticastAddress } .filter { enableLocalHost || it.isLoopbackAddress.not() } .filter { localHostOnly.not() || it.isLoopbackAddress } .filter { (it is Inet4Address) || (enableIPv6 && (it is Inet6Address)) } .map { if (it is Inet6Address) Inet6Address.getByAddress(it.address) else it } .map { NetInterface(networkInterface.displayName, it) } } .filter { netInterface -> (enableLocalHost && netInterface.address.isLoopbackAddress) || useWiFiOnly.not() || ( defaultWifiRegexArray.any { it.matches(netInterface.name) } || wifiRegexArray.any { it.matches(netInterface.name) } ) } .toCollection(netInterfaceList) if (netInterfaceList.isEmpty() && wifiConnected()) netInterfaceList.add(getWiFiNetAddress()) return netInterfaceList } @Suppress("DEPRECATION") private fun wifiConnected() = wifiManager.connectionInfo.ipAddress != 0 @Suppress("DEPRECATION") private fun getWiFiNetAddress(): NetInterface { XLog.d(getLog("getWiFiNetAddress", "Invoked")) val ipInt = wifiManager.connectionInfo.ipAddress val ipByteArray = ByteArray(4) { i -> (ipInt.shr(i * 8).and(255)).toByte() } val inet4Address = InetAddress.getByAddress(ipByteArray) as Inet4Address return NetInterface("wlan0", inet4Address) } }
mjpeg/src/main/kotlin/info/dvkr/screenstream/mjpeg/state/helper/NetworkHelper.kt
1272442725
// 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.parameterInfo import com.intellij.codeInsight.hints.InlayInfo import org.jetbrains.kotlin.backend.common.descriptors.isSuspend import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.psiUtil.startOffset fun provideSuspendingCallHint(callExpression: KtCallExpression): InlayInfo? { val resolvedCall = callExpression.resolveToCall() ?: return null if (resolvedCall.candidateDescriptor.isSuspend) { return InlayInfo("#", callExpression.calleeExpression?.startOffset ?: callExpression.startOffset) } return null }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/SuspendingCallHints.kt
3054124827
@file:Suppress("SpringKotlinAutowiring") package de.holisticon.ranked.command import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.kotlin.KotlinModule import de.holisticon.ranked.command.api.CancelParticipation import de.holisticon.ranked.command.api.CheckPlayer import de.holisticon.ranked.command.api.CreatePlayer import de.holisticon.ranked.extension.defaultSmartLifecycle import de.holisticon.ranked.extension.send import de.holisticon.ranked.extension.trackingEventProcessors import de.holisticon.ranked.model.UserName import de.holisticon.ranked.model.event.internal.InitUser import mu.KLogging import org.axonframework.commandhandling.SimpleCommandBus import org.axonframework.commandhandling.gateway.CommandGateway import org.axonframework.common.jpa.EntityManagerProvider import org.axonframework.common.transaction.TransactionManager import org.axonframework.config.EventHandlingConfiguration import org.axonframework.eventhandling.tokenstore.inmemory.InMemoryTokenStore import org.axonframework.eventsourcing.eventstore.jpa.JpaEventStorageEngine import org.axonframework.messaging.interceptors.BeanValidationInterceptor import org.axonframework.messaging.interceptors.LoggingInterceptor import org.axonframework.serialization.Serializer import org.axonframework.serialization.upcasting.event.EventUpcaster import org.axonframework.serialization.upcasting.event.EventUpcasterChain import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.event.EventListener import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean import java.util.function.Consumer import javax.sql.DataSource import javax.validation.ValidatorFactory /** * This is the main spring configuration class for everything axon/command related. */ @Configuration class CommandConfiguration { companion object : KLogging() { const val REPLAY_PHASE = Int.MAX_VALUE - 10 } /** * Enable bean validation for incoming commands. */ @Autowired fun configure(bus: SimpleCommandBus, validationFactory: ValidatorFactory) { bus.registerDispatchInterceptor(BeanValidationInterceptor(validationFactory)) } @Autowired fun configure(config: EventHandlingConfiguration) { config.registerHandlerInterceptor("messageMonitor", { LoggingInterceptor() }) } /** * Provide bean validation validator. */ @Bean fun validatorFactoryBean(): ValidatorFactory = LocalValidatorFactoryBean() @Bean @Suppress("ObjectLiteralToLambda") fun onInitUser(commandGateway: CommandGateway) = object : Consumer<InitUser> { @EventListener override fun accept(user: InitUser) { val userName = UserName(user.id) with(commandGateway) { send( command = CheckPlayer(userName), success = { _, _: Any -> send<Any>(CancelParticipation(userName)) }, failure = { _, _: Throwable -> send<Any>(CreatePlayer(userName = userName, displayName = user.name, imageUrl = user.imageUrl)) } ) } } } @Bean fun tokenStore() = InMemoryTokenStore() @Bean fun jpaEventStorageEngine( serializer: Serializer, dataSource: DataSource, upcasters: List<EventUpcaster>, entityManagerProvider: EntityManagerProvider, transactionManager: TransactionManager) = JpaEventStorageEngine(serializer, EventUpcasterChain(upcasters), dataSource, entityManagerProvider, transactionManager) @Bean fun jacksonDateTime() = JavaTimeModule() @Bean fun jacksonKotlin() = KotlinModule() }
backend/command/src/main/kotlin/CommandConfiguration.kt
3355624116
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.activity.compose.samples import androidx.activity.compose.BackHandler import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.annotation.Sampled import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue @Sampled @Composable fun BackHandler() { var backPressedCount by remember { mutableStateOf(0) } BackHandler { backPressedCount++ } val dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher Button(onClick = { dispatcher.onBackPressed() }) { Text("Press Back count $backPressedCount") } }
activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/BackHandlerSample.kt
2450786600
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.screens.quiz.displayquestions import android.view.View import android.widget.CheckBox import androidx.recyclerview.widget.RecyclerView import com.app.playhvz.R import com.app.playhvz.firebase.classmodels.QuizQuestion class CorrectnessAnswerViewHolder( val view: View, val onSelect: (adapterPosition: Int) -> Unit? ) : RecyclerView.ViewHolder(view) { private val answerCheckbox = view.findViewById<CheckBox>(R.id.answer_check)!! private var answer: QuizQuestion.Answer? = null fun onBind(position: Int, answer: QuizQuestion.Answer) { this.answer = answer answerCheckbox.text = answer.text answerCheckbox.setOnClickListener { onSelect(position) } itemView.setOnClickListener { answerCheckbox.performClick() } } }
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/quiz/displayquestions/CorrectnessAnswerViewHolder.kt
1318331820
// 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.refactoring.inline import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.LocalSearchScope import com.intellij.refactoring.HelpID import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.usageView.UsageInfo import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeInliner.CodeToInline import org.jetbrains.kotlin.idea.codeInliner.PropertyUsageReplacementStrategy import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy import org.jetbrains.kotlin.idea.findUsages.ReferencesSearchScopeHelper import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.getAssignmentByLHS import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.references.ReferenceAccess import org.jetbrains.kotlin.utils.addToStdlib.safeAs class KotlinInlinePropertyProcessor( declaration: KtProperty, reference: PsiReference?, inlineThisOnly: Boolean, private val deleteAfter: Boolean, private val isWhenSubjectVariable: Boolean, editor: Editor?, private val statementToDelete: KtBinaryExpression?, project: Project, ) : AbstractKotlinInlineNamedDeclarationProcessor<KtProperty>( declaration = declaration, reference = reference, inlineThisOnly = inlineThisOnly, deleteAfter = deleteAfter && !isWhenSubjectVariable, editor = editor, project = project, ) { override fun createReplacementStrategy(): UsageReplacementStrategy? { return createReplacementStrategyForProperty(declaration, editor, myProject) } override fun postAction() { if (deleteAfter && isWhenSubjectVariable && declaration.isWritable) { declaration.initializer?.let { declaration.replace(it) } } } override fun postDeleteAction() { statementToDelete?.delete() } override fun additionalPreprocessUsages(usages: Array<out UsageInfo>, conflicts: MultiMap<PsiElement, String>) { val initializer by lazy { extractInitialization(declaration).initializerOrNull?.assignment?.left } for (usage in usages) { val expression = usage.element?.writeOrReadWriteExpression ?: continue if (expression != initializer) { conflicts.putValue(expression, KotlinBundle.message("unsupported.usage.0", expression.parent.text)) } } } class Initializer(val value: KtExpression, val assignment: KtBinaryExpression?) class Initialization private constructor( private val value: KtExpression?, private val assignment: KtBinaryExpression?, @Nls private val error: String, ) { val initializerOrNull: Initializer? get() = value?.let { Initializer(value, assignment) } fun getInitializerOrShowErrorHint(project: Project, editor: Editor?): Initializer? { val initializer = initializerOrNull if (initializer != null) return initializer CommonRefactoringUtil.showErrorHint( project, editor, error, KotlinBundle.message("title.inline.property"), HelpID.INLINE_VARIABLE, ) return null } companion object { fun createError(@Nls error: String): Initialization = Initialization( value = null, assignment = null, error = error, ) fun createInitializer(value: KtExpression, assignment: KtBinaryExpression?): Initialization = Initialization( value = value, assignment = assignment, error = "", ) } } companion object { fun extractInitialization(property: KtProperty): Initialization { val definitionScope = property.parent ?: kotlin.run { return createInitializationWithError(property.name!!, emptyList()) } val writeUsages = mutableListOf<KtExpression>() ReferencesSearchScopeHelper.search(property, LocalSearchScope(definitionScope)).forEach { val expression = it.element.writeOrReadWriteExpression ?: return@forEach writeUsages += expression } val initializerInDeclaration = property.initializer if (initializerInDeclaration != null) { if (writeUsages.isNotEmpty()) { return createInitializationWithError(property.name!!, writeUsages) } return Initialization.createInitializer(initializerInDeclaration, assignment = null) } val assignment = writeUsages.singleOrNull()?.getAssignmentByLHS()?.takeIf { it.operationToken == KtTokens.EQ } val initializer = assignment?.right if (initializer == null) { return createInitializationWithError(property.name!!, writeUsages) } return Initialization.createInitializer(initializer, assignment) } private fun createInitializationWithError(name: String, assignments: Collection<PsiElement>): Initialization { val key = if (assignments.isEmpty()) "variable.has.no.initializer" else "variable.has.no.dominating.definition" val message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message(key, name)) return Initialization.createError(message) } } } fun createReplacementStrategyForProperty( property: KtProperty, editor: Editor?, project: Project, fallbackToSuperCall: Boolean = false, ): UsageReplacementStrategy? { val getter = property.getter?.takeIf { it.hasBody() } val setter = property.setter?.takeIf { it.hasBody() } val readReplacement: CodeToInline? val writeReplacement: CodeToInline? if (getter == null && setter == null) { val value = KotlinInlinePropertyProcessor.extractInitialization(property).getInitializerOrShowErrorHint(project, editor)?.value ?: return null readReplacement = buildCodeToInline( declaration = property, bodyOrInitializer = value, isBlockBody = false, editor = editor, fallbackToSuperCall = fallbackToSuperCall, ) ?: return null writeReplacement = null } else { readReplacement = getter?.let { buildCodeToInline( declaration = getter, bodyOrInitializer = getter.bodyExpression!!, isBlockBody = getter.hasBlockBody(), editor = editor, fallbackToSuperCall = fallbackToSuperCall, ) ?: return null } writeReplacement = setter?.let { buildCodeToInline( declaration = setter, bodyOrInitializer = setter.bodyExpression!!, isBlockBody = setter.hasBlockBody(), editor = editor, fallbackToSuperCall = fallbackToSuperCall, ) ?: return null } } return PropertyUsageReplacementStrategy(readReplacement, writeReplacement) } private val PsiElement.writeOrReadWriteExpression: KtExpression? get() = this.safeAs<KtExpression>() ?.getQualifiedExpressionForSelectorOrThis() ?.takeIf { it.readWriteAccess(useResolveForReadWrite = true) != ReferenceAccess.READ }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlinePropertyProcessor.kt
1147634565
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.application.impl import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.util.lazyPub import kotlinx.coroutines.CoroutineExceptionHandler import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext /** * This is loaded using [java.util.ServiceLoader] and invoked by the Kotlin Coroutines machinery * to handle any uncaught exceptions thrown by coroutines launched in the [kotlinx.coroutines.GlobalScope]. */ class CoroutineExceptionHandlerImpl : AbstractCoroutineContextElement(CoroutineExceptionHandler), CoroutineExceptionHandler { override fun handleException(context: CoroutineContext, exception: Throwable) { if (exception is ProcessCanceledException) { return } try { LOG.error("Unhandled exception in $context", exception) } catch (ignored: Throwable) { } } companion object { private val LOG: Logger by lazyPub { Logger.getInstance(CoroutineExceptionHandlerImpl::class.java) } } }
platform/platform-impl/src/com/intellij/openapi/application/impl/CoroutineExceptionHandlerImpl.kt
236922473
// 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.legacyBridge import com.intellij.openapi.module.ModifiableModuleModel import com.intellij.workspaceModel.storage.MutableEntityStorage interface ModifiableModuleModelBridge : ModifiableModuleModel { fun prepareForCommit() fun collectChanges(): MutableEntityStorage }
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/legacyBridge/ModifiableModuleModelBridge.kt
2165665503
package com.intellij.ide.starter.report import com.intellij.ide.starter.ci.CIServer import com.intellij.ide.starter.di.di import com.intellij.ide.starter.utils.convertToHashCodeWithOnlyLetters import com.intellij.ide.starter.utils.generifyErrorMessage import org.kodein.di.direct import org.kodein.di.instance import java.nio.file.Files import java.nio.file.Path import kotlin.io.path.listDirectoryEntries object ErrorReporter { private const val MAX_TEST_NAME_LENGTH = 250 /** * Sort things out from errors directories, written by performance testing plugin * Take a look at [com.jetbrains.performancePlugin.ProjectLoaded.reportErrorsFromMessagePool] */ fun reportErrorsAsFailedTests(scriptErrorsDir: Path, contextName: String) { if (Files.isDirectory(scriptErrorsDir)) { val errorsDirectories = scriptErrorsDir.listDirectoryEntries() for (errorDir in errorsDirectories) { val messageFile = errorDir.resolve("message.txt").toFile() val stacktraceFile = errorDir.resolve("stacktrace.txt").toFile() if (messageFile.exists() && stacktraceFile.exists()) { val messageText = generifyErrorMessage(messageFile.readText().trim()) val stackTraceContent = stacktraceFile.readText().trim() var testName: String val onlyLettersHash = convertToHashCodeWithOnlyLetters(generifyErrorMessage(stackTraceContent).hashCode()) if (stackTraceContent.startsWith(messageText)) { val maxLength = (MAX_TEST_NAME_LENGTH - onlyLettersHash.length).coerceAtMost(stackTraceContent.length) val extractedTestName = stackTraceContent.substring(0, maxLength).trim() testName = "($onlyLettersHash $extractedTestName)" } else { testName = "($onlyLettersHash ${messageText.substring(0, MAX_TEST_NAME_LENGTH.coerceAtMost(messageText.length)).trim()})" } val stackTrace = """ Test: $contextName $stackTraceContent """.trimIndent().trimMargin().trim() di.direct.instance<CIServer>().reportTestFailure(testName, messageText, stackTrace) } } } } }
tools/intellij.ide.starter/src/com/intellij/ide/starter/report/ErrorReporter.kt
733549762
// 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 import com.intellij.codeInsight.CodeInsightSettings import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiFile import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.runAll import org.jetbrains.kotlin.psi.KtFile abstract class AbstractCopyPasteTest : KotlinLightCodeInsightFixtureTestCase() { private var savedImportsOnPasteSetting: Int = 0 private val DEFAULT_TO_FILE_TEXT = "package to\n\n<caret>" override fun setUp() { super.setUp() savedImportsOnPasteSetting = CodeInsightSettings.getInstance().ADD_IMPORTS_ON_PASTE CodeInsightSettings.getInstance().ADD_IMPORTS_ON_PASTE = CodeInsightSettings.YES } override fun tearDown() { runAll( ThrowableRunnable { CodeInsightSettings.getInstance().ADD_IMPORTS_ON_PASTE = savedImportsOnPasteSetting }, ThrowableRunnable { super.tearDown() } ) } protected fun configureByDependencyIfExists(dependencyFileName: String): PsiFile? { val file = testDataFile(dependencyFileName) if (!file.exists()) return null return if (dependencyFileName.endsWith(".java")) { //allow test framework to put it under right directory myFixture.addClass(FileUtil.loadFile(file, true)).containingFile } else { myFixture.configureByFile(dependencyFileName) } } protected fun configureTargetFile(fileName: String): KtFile { return if (testDataFile(fileName).exists()) { myFixture.configureByFile(fileName) as KtFile } else { myFixture.configureByText(fileName, DEFAULT_TO_FILE_TEXT) as KtFile } } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/AbstractCopyPasteTest.kt
3898770772
// 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.fir.findUsages import com.intellij.psi.PsiElement import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.findUsages.AbstractFindUsagesTest import org.jetbrains.kotlin.idea.fir.invalidateCaches import org.jetbrains.kotlin.idea.test.runAll import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.utils.IgnoreTests import java.nio.file.Paths abstract class AbstractFindUsagesFirTest : AbstractFindUsagesTest() { override fun isFirPlugin(): Boolean = true override fun tearDown() { runAll( ThrowableRunnable { project.invalidateCaches() }, ThrowableRunnable { super.tearDown() } ) } override fun <T : PsiElement> doTest(path: String) { IgnoreTests.runTestIfEnabledByFileDirective( Paths.get(path), IgnoreTests.DIRECTIVES.FIR_COMPARISON, directivePosition = IgnoreTests.DirectivePosition.LAST_LINE_IN_FILE ) { super.doTest<T>(path) } } }
plugins/kotlin/fir/test/org/jetbrains/kotlin/idea/fir/findUsages/AbstractFindUsagesFirTest.kt
3896104457
package org.penella.structures import org.slf4j.Logger import org.slf4j.LoggerFactory /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Created by alisle on 10/12/16. */ class SortedLinkList<T : Comparable<T>> { companion object { private val log: Logger = LoggerFactory.getLogger(SortedLinkList::class.java) } class Node<T : Comparable<T>>(val value: Comparable<T>) { var next: Node<T>? = null var previous: Node<T>? = null } private var head: Node<T>? = null private var tail: Node<T>? = null private var count: Long = 0 var isEmpty : Boolean = head == null fun first(): Node<T>? = head fun last(): Node<T>? = tail fun length():Long = count fun pop() : Comparable<T>? { if(count > 0) { count-- val node = head head = node?.next return node?.value } return null } fun remove() : Comparable<T>? { if(count > 0) { count-- val node = tail tail = node?.previous return node?.value } return null } fun add(insertValue: T) { var found : Boolean = false var currentNode = head; if(head == null) { val insertNode = addNode(null, null, insertValue) tail = insertNode return } while(!found) { val currentValue = currentNode?.value when(currentValue?.compareTo(insertValue)){ -1 -> { if (currentNode == tail) { val insertNode = addNode(tail, null, insertValue) tail = insertNode found = true } else { currentNode = currentNode?.next } } 0 -> found = true 1 -> { addNode(currentNode?.previous, currentNode, insertValue) found = true } } } } private fun addNode(previous: Node<T>?, next: Node<T>?, value : T ) : Node<T> { count++ val node = Node(value) node.previous = previous node.previous?.next = node node.next = next next?.previous = node if(next == head) { head = node } return node } fun get(where: Int) : Comparable<T>? { if( count > 0 && where < count) { val diff = count - where if(diff < where) { if((where + 1L) == count) { return tail?.value } var munch = count var node = tail; while(munch > where) { node = node?.previous munch-- } return node?.value } else { var munch = 0 var node = head while(munch < where) { node = node?.next munch++ } return node?.value } } return null; } }
src/main/java/org/penella/structures/SortedLinkList.kt
1828361126
package alraune.back import vgrechka.* //fun servePollForUpdates() { // val pageToUpdate = rctx.ftb.shit.pagePath // when (pageToUpdate) { // AlkPagePath.adminOrders -> { // val initiallyRenderedDatas = rctx.ftb.shit.initiallyRenderedOrderDatas // if (initiallyRenderedDatas.isEmpty()) return // // val currentOrders = AlkDB.selectOrdersWithParams(Params_barney( // addShitAfterWhere = {qb-> // qb.text("and ${AlUAOrder_Meta.uuid} in (") // for ((index, ov) in initiallyRenderedDatas.withIndex()) { // qb.param(ov.orderUUID) // if (index < initiallyRenderedDatas.lastIndex) // qb.text(",") // } // qb.text(")") // }, // limit = initiallyRenderedDatas.size, // checkLimitExactlyMatchesActualByTryingToSelectOneMore = true)) // // class ChangedPieceOfShit(val initiallyRenderedData: AlInitiallyRenderedOrderData, // val currentOrder: AlUAOrderWithParams) // val changedPiecesOfShit = mutableListOf<ChangedPieceOfShit>() // for (initiallyRenderedData in initiallyRenderedDatas) { // val currentOrder = currentOrders.find {it.entity.uuid == initiallyRenderedData.orderUUID} // if (currentOrder != null && currentOrder.entity.version > initiallyRenderedData.version.toLong()) { // changedPiecesOfShit += ChangedPieceOfShit(initiallyRenderedData, currentOrder) // } // } // // clog("------------- changed -------------\n$changedShit") // // rctx.commands += AlBackToFrontCommandPile()-{o-> // o.opcode = AlBackToFrontCommandOpcode.Eval // o.script = buildString { // ln("!function() {") // for (piece in changedPiecesOfShit) { // fun stateChangedTo(what: AlUAOrderState) = // piece.currentOrder.params.state == what && piece.initiallyRenderedData.state != what // // class Alice(val itemMarkClass: AlCSS.Pack, val labelClass: AlCSS.Pack, val labelTitle: String) // val alice = when { // stateChangedTo(AlUAOrderState.RETURNED_TO_CUSTOMER_FOR_FIXING) -> Alice( // itemMarkClass = AlCSS.carla.itemMark.danger, // labelClass = AlCSS.carla.topRightTitleLabel.danger, // labelTitle = t("TOTE", "Завернут") // ) // else -> Alice( // itemMarkClass = AlCSS.carla.itemMark.something, // labelClass = AlCSS.carla.topRightTitleLabel.something, // labelTitle = t("TOTE", "Изменен") // ) // } // ln(""" //var a = alraune //var jItem = a.byIDSingle('${AlDomid.item}-${piece.initiallyRenderedData.orderUUID}') //jItem.removeClass('${AlCSS.carla.itemMark.all.joinToString(" ")}') //jItem.addClass('${alice.itemMarkClass}') //var jExistingLabels = a.checkNoneOrSingleJQ(jItem.find('.${AlCSS.carla.topRightTitleLabel.common}'), '04eb6782-cdd5-4c25-a555-ed04300ea39e') //jExistingLabels.remove() //var jTitle = a.checkSingleJQ(jItem.find('.${AlCSS.carla.title}'), 'b38f11ea-91fb-47db-a705-9dbd8f34932d') //jTitle.append('<div class="${AlCSS.carla.topRightTitleLabel.common} ${alice.labelClass}">${alice.labelTitle}</div>') // """) // } // ln("}()") // } // } // } // else -> { // rctx.log.warn("Why the fuck do I get [${AlFrontToBackCommandOpcode.PollForUpdates}] for page [$pageToUpdate]") // } // } //}
attic/alraune/alraune-back/src/servePollForUpdates.kt
994344274
// "Create actual class for module testProjectName.mpp-bottom-actual.jsJvm18Main (Native (general)/JS/JVM (1.8))" "true" // ACTION: Convert to secondary constructor // ACTION: Create subclass package playground.second expect open class Platfo<caret>rmClass() { open fun c(a: Int, b: String) }
plugins/kotlin/idea/tests/testData/gradle/fixes/createActualForGranularSourceSetTarget/before/mpp-bottom-actual/src/commonMain/kotlin/playground/second/PlatformClass.kt
3238665051
// PROBLEM: Fewer arguments provided (0) than placeholders specified (1) // FIX: none package org.apache.logging.log4j private val logger: Logger? = null fun foo(a: Int, b: Int) { logger?.debug("<caret>test {}", Exception()) } interface Logger { fun debug(format: String, param1: Any) }
plugins/kotlin/idea/tests/testData/inspectionsLocal/logging/placeholderCountMatchesArgumentCount/log4j/debugException3.kt
3933346704
package com.elliott.a18350.irecognizer import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Handler /** * Created by 18350 on 2017/5/24 0024. * to kotlin 2017/6/6 */ class LaunchActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val time = 800 //设置等待时间,单位为毫秒,时间缩短为1秒 val handler = Handler() //当计时结束时,跳转至主界面 handler.postDelayed({ startActivity(Intent(this@LaunchActivity, MainActivity::class.java)) finish() }, time.toLong()) } }
app/src/main/kotlin/LaunchActivity.kt
1900338117
fun foo1() { /// M // We don't support function breakpoints for local functions yet fun local() { /// L println() /// L } /// L } /// L fun foo2() { /// M val local = fun() { /// L println() /// L } /// L } /// L fun foo3() { /// M val local = { /// L println() /// L } /// L } /// L fun foo4() { /// M fun local(block: () -> Unit = { println() }) {} /// *, L, λ } /// L
plugins/kotlin/jvm-debugger/test/testData/breakpointApplicability/locals.kt
487592011
// WITH_STDLIB val x = sequenceOf(1).<caret>filterIsInstance<Any>()
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/uselessCallOnCollection/FilterIsSupertypeInstanceOnSequence.kt
3166367173
data class <caret>VertexAttribute( /** * The number of components this attribute has. **/ val numComponents: Int, /** * If true and [type] is not [Gl20.FLOAT], the data will be mapped to the range -1 to 1 for signed types and * the range 0 to 1 for unsigned types. */ val normalized: Boolean ) {}
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/RemoveParameterKeepOtherCommentsBefore.kt
1907258363
package io.fotoapparat.routine.camera import android.graphics.SurfaceTexture import io.fotoapparat.exception.camera.CameraException import io.fotoapparat.hardware.CameraDevice import io.fotoapparat.hardware.Device import io.fotoapparat.hardware.orientation.OrientationSensor import io.fotoapparat.log.Logger import io.fotoapparat.parameter.ScaleType import io.fotoapparat.test.testResolution import io.fotoapparat.test.willReturn import io.fotoapparat.test.willThrow import io.fotoapparat.view.CameraRenderer import io.fotoapparat.view.Preview import io.fotoapparat.view.toPreview import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.* import org.mockito.junit.MockitoJUnitRunner import java.io.IOException import java.util.concurrent.atomic.AtomicBoolean import kotlin.test.assertFalse import kotlin.test.assertTrue @RunWith(MockitoJUnitRunner::class) internal class StartRoutineTest { @Mock lateinit var surfaceTexture: SurfaceTexture @Mock lateinit var cameraViewRenderer: CameraRenderer @Mock lateinit var orientationSensor: OrientationSensor @Mock lateinit var cameraDevice: CameraDevice @Mock lateinit var mockLogger: Logger @Mock lateinit var device: Device lateinit var preview: Preview @Before fun setUp() { preview = surfaceTexture.toPreview() } @Test fun `Start camera`() { // Given device.apply { getSelectedCamera() willReturn cameraDevice cameraRenderer willReturn cameraViewRenderer scaleType willReturn ScaleType.CenterCrop } cameraDevice.getPreviewResolution() willReturn testResolution cameraViewRenderer.getPreview() willReturn preview // When device.start(orientationSensor) // Then val inOrder = inOrder( device, cameraDevice, cameraViewRenderer ) inOrder.apply { verify(device).selectCamera() verify(cameraDevice).open() verify(device).updateCameraConfiguration(cameraDevice) verify(cameraDevice).setDisplayOrientation(orientationSensor.lastKnownOrientationState) verify(cameraViewRenderer).setScaleType(ScaleType.CenterCrop) verify(cameraViewRenderer).setPreviewResolution(testResolution) verify(cameraDevice).setDisplaySurface(preview) verify(cameraDevice).startPreview() } } @Test fun `Cannot set display surface while starting`() { // Given device.apply { getSelectedCamera() willReturn cameraDevice cameraRenderer willReturn cameraViewRenderer scaleType willReturn ScaleType.CenterCrop logger willReturn mockLogger } cameraDevice.getPreviewResolution() willReturn testResolution cameraDevice.setDisplaySurface(preview) willThrow IOException() cameraViewRenderer.getPreview() willReturn preview // When device.start(orientationSensor) // Then verify(cameraDevice, never()).startPreview() } @Test(expected = IllegalStateException::class) fun `Boot start, but camera has already started`() { // Given device.hasSelectedCamera() willReturn true // When device.bootStart( orientationSensor = orientationSensor, mainThreadErrorCallback = {} ) // Then // throw exception } @Test fun `Boot start, but camera cannot be selected`() { // Given device.getSelectedCamera() willThrow CameraException("Camera cannot be selected") val hasErrors = AtomicBoolean(false) // When device.bootStart( orientationSensor = orientationSensor, mainThreadErrorCallback = { hasErrors.set(true) } ) // Then assertTrue(hasErrors.get()) } @Test fun `Boot start`() { // Given var hasErrors = false device.apply { hasSelectedCamera() willReturn false getSelectedCamera() willReturn cameraDevice cameraRenderer willReturn cameraViewRenderer scaleType willReturn ScaleType.CenterCrop } cameraDevice.getPreviewResolution() willReturn testResolution cameraViewRenderer.getPreview() willReturn surfaceTexture.toPreview() // When device.bootStart( orientationSensor = orientationSensor, mainThreadErrorCallback = { hasErrors = true } ) // Then assertFalse(hasErrors) verify(device).start(orientationSensor) } }
fotoapparat/src/test/java/io/fotoapparat/routine/camera/StartRoutineTest.kt
1964458237
// "Suppress 'USELESS_CAST' for statement " "true" fun foo() { val arr = IntArray(1) ++arr[1 a<caret>s Int] }
plugins/kotlin/idea/tests/testData/quickfix/suppress/forStatement/prefixPlusPlus.kt
3164657824
break@label
plugins/kotlin/j2k/old/tests/testData/fileOrElement/breakStatement/breakWithLabel.kt
3579452152
// 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.vcs.commit import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.LocalChangeList internal class SingleChangeListCommitMessagePolicy(project: Project, private val initialCommitMessage: String?) : AbstractCommitMessagePolicy(project) { var defaultNameChangeListMessage: String? = null private var lastChangeListName: String? = null private val messagesToSave = mutableMapOf<String, String>() var commitMessage: String? = null private set fun init(changeList: LocalChangeList, includedChanges: List<Change>) { commitMessage = initialCommitMessage if (vcsConfiguration.CLEAR_INITIAL_COMMIT_MESSAGE) return lastChangeListName = changeList.name if (commitMessage != null) { defaultNameChangeListMessage = commitMessage } else { commitMessage = getCommitMessageFor(changeList) if (commitMessage.isNullOrBlank()) { defaultNameChangeListMessage = vcsConfiguration.LAST_COMMIT_MESSAGE commitMessage = getCommitMessageFromVcs(includedChanges) ?: defaultNameChangeListMessage } } } fun update(changeList: LocalChangeList, currentMessage: String) { commitMessage = currentMessage if (vcsConfiguration.CLEAR_INITIAL_COMMIT_MESSAGE) return if (changeList.name != lastChangeListName) { rememberMessage(currentMessage) lastChangeListName = changeList.name commitMessage = getCommitMessageFor(changeList) ?: defaultNameChangeListMessage } } fun save(commitState: ChangeListCommitState, success: Boolean) { rememberMessage(commitState.commitMessage) if (success) { vcsConfiguration.saveCommitMessage(commitState.commitMessage) val entireChangeListIncluded = commitState.changeList.changes.size == commitState.changes.size if (!entireChangeListIncluded) forgetMessage() } saveMessages() } private fun rememberMessage(message: String) = lastChangeListName?.let { messagesToSave[it] = message } private fun forgetMessage() = lastChangeListName?.let { messagesToSave -= it } private fun saveMessages() = messagesToSave.forEach { (changeListName, commitMessage) -> save(changeListName, commitMessage) } }
platform/vcs-impl/src/com/intellij/vcs/commit/SingleChangeListCommitMessagePolicy.kt
3375572440
// OPTIONS: true, false, false, true, false // PARAM_DESCRIPTOR: value-parameter n: kotlin.Int defined in foo // PARAM_DESCRIPTOR: local final fun kotlin.Int.bar(m: kotlin.Int): kotlin.Int defined in foo // PARAM_TYPES: kotlin.Int // PARAM_TYPES: kotlin.Int.(m: kotlin.Int) -> kotlin.Int fun foo(n: Int): Int { fun Int.bar(m: Int) = this * m * n return <selection>n bar (n + 1)</selection> }
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/parameters/capturedFunctions/localExtensionFunInfixCall.kt
1130985173
package org.seniorsigan.mangareader.ui.fragments import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import org.jetbrains.anko.find import org.jetbrains.anko.support.v4.onRefresh import org.jetbrains.anko.support.v4.onUiThread import org.seniorsigan.mangareader.App import org.seniorsigan.mangareader.R import org.seniorsigan.mangareader.TAG import org.seniorsigan.mangareader.adapters.ArrayListAdapter import org.seniorsigan.mangareader.adapters.MangaViewHolder import org.seniorsigan.mangareader.models.MangaItem class MangaListFragment : Fragment() { private lateinit var refresh: SwipeRefreshLayout private lateinit var listView: RecyclerView private lateinit var progressBar: ProgressBar private val adapter = ArrayListAdapter(MangaViewHolder::class.java, R.layout.manga_item) lateinit var onItemClickListener: OnItemClickListener override fun onAttach(context: Context?) { super.onAttach(context) try { onItemClickListener = activity as OnItemClickListener } catch (e: ClassCastException) { throw ClassCastException("$activity must implement OnItemClickListener"); } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.fragment_manga_list, container, false) with(rootView, { refresh = find<SwipeRefreshLayout>(R.id.refresh_manga_list) listView = find<RecyclerView>(R.id.rv_manga_list) progressBar = find<ProgressBar>(R.id.progressBar) }) listView.layoutManager = GridLayoutManager(context, 2) adapter.onItemClickListener = { manga -> onItemClickListener.onItemClick(manga) } listView.adapter = adapter return rootView } override fun onStart() { super.onStart() refresh.onRefresh { renderList() } renderList() } fun renderList() { App.mangaSearchController.findAll(App.mangaSourceRepository.currentName, { response -> if (activity == null) return@findAll onUiThread { if (response.error == null) { adapter.update(response.data) refresh.isRefreshing = false progressBar.visibility = View.GONE } else { Log.e(TAG, response.error) } } }) } interface OnItemClickListener { fun onItemClick(item: MangaItem) } }
app/src/main/java/org/seniorsigan/mangareader/ui/fragments/MangaListFragment.kt
4105541902
// 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 mobi.hsz.idea.gitignore.psi.impl import com.intellij.lang.ASTNode import com.intellij.openapi.util.text.StringUtil import mobi.hsz.idea.gitignore.IgnoreBundle.Syntax import mobi.hsz.idea.gitignore.lang.IgnoreLanguage import mobi.hsz.idea.gitignore.psi.IgnoreElementImpl import mobi.hsz.idea.gitignore.psi.IgnoreEntry import mobi.hsz.idea.gitignore.psi.IgnoreEntryFile import mobi.hsz.idea.gitignore.psi.IgnoreNegation import mobi.hsz.idea.gitignore.psi.IgnoreTypes import mobi.hsz.idea.gitignore.util.Glob /** * Custom [IgnoreElementImpl] implementation. */ abstract class IgnoreEntryExtImpl(node: ASTNode) : IgnoreElementImpl(node), IgnoreEntry { /** * Checks if the first child is negated - i.e. `!file.txt` entry. * * @return first child is negated */ override val isNegated get() = firstChild is IgnoreNegation /** * Checks if current entry is a directory - i.e. `dir/`. * * @return is directory */ val isDirectory get() = this is IgnoreEntryFile /** * Returns element syntax. * * @return syntax */ override val syntax: Syntax get() { var previous = prevSibling while (previous != null) { if (previous.node.elementType == IgnoreTypes.SYNTAX) { Syntax.find((previous as IgnoreSyntaxImpl).value.text)?.let { return it } } previous = previous.prevSibling } return (containingFile.language as IgnoreLanguage).defaultSyntax } /** * Returns entry value without leading `!` if entry is negated. * * @return entry value without `!` negation sign */ override val value get() = text.takeIf { !isNegated } ?: StringUtil.trimStart(text, "!") /** * Returns entries pattern. * * @return pattern */ override val pattern get() = Glob.createPattern(this) }
src/main/kotlin/mobi/hsz/idea/gitignore/psi/impl/IgnoreEntryExtImpl.kt
1530732990
/* * Copyright 2017 - 2022 busybusy, 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.busybusy.graylog_provider import com.busybusy.analyticskit_android.AnalyticsEvent import com.busybusy.analyticskit_android.AnalyticsKitProvider.PriorityFilter import com.busybusy.analyticskit_android.CommonEvents import com.busybusy.analyticskit_android.ContentViewEvent import com.busybusy.analyticskit_android.ErrorEvent import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import java.io.IOException import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit /** * Tests the [GraylogProvider] class. * * @author John Hunt on 6/28/17. */ class GraylogProviderTest { private lateinit var provider: GraylogProvider private val mockServer = MockWebServer() private val httpClient = OkHttpClient.Builder().build() private lateinit var callbackListener: GraylogResponseListener private var testEventHashCode = 0 private var logEventCalled = false private var loggedEventName: String? = null private lateinit var lock: CountDownLatch @Before fun setup() { lock = CountDownLatch(1) callbackListener = object : GraylogResponseListener { override fun onGraylogResponse(response: GraylogResponse) { logEventCalled = true loggedEventName = response.eventName testEventHashCode = response.eventHashCode lock.countDown() } } mockServer.enqueue(MockResponse().setResponseCode(202).setStatus("Accepted")) try { mockServer.start() } catch (e: IOException) { e.printStackTrace() } provider = GraylogProvider( client = httpClient, graylogInputUrl = "http://${mockServer.hostName}:${mockServer.port}", graylogHostName = "unit-test-android", ) provider.setCallbackHandler(callbackListener) logEventCalled = false testEventHashCode = -1 loggedEventName = null } @Test fun testSetAndGetPriorityFilter() { val filter = PriorityFilter { false } val filteringProvider = GraylogProvider( client = httpClient, graylogInputUrl = "http://${mockServer.hostName}:${mockServer.port}", graylogHostName = "unit-test-android", priorityFilter = filter ) assertThat(filteringProvider.getPriorityFilter()).isEqualTo(filter) } @Test fun test_priorityFiltering_default() { val event = AnalyticsEvent("A Test Event") .setPriority(10) .send() assertThat(provider.getPriorityFilter().shouldLog(event.priority)).isEqualTo(true) event.setPriority(-9) .send() assertThat(provider.getPriorityFilter().shouldLog(event.priority)).isEqualTo(true) } @Test fun test_priorityFiltering_custom() { val filter = PriorityFilter { priorityLevel -> priorityLevel < 10 } val filteringProvider = GraylogProvider( client = httpClient, graylogInputUrl = "http://${mockServer.hostName}:${mockServer.port}", graylogHostName = "unit-test-android", priorityFilter = filter ) val event = AnalyticsEvent("A Test Event") .setPriority(10) .send() assertThat(filteringProvider.getPriorityFilter().shouldLog(event.priority)).isEqualTo(false) event.setPriority(9) .send() assertThat(filteringProvider.getPriorityFilter().shouldLog(event.priority)).isEqualTo(true) } @Test @Throws(InterruptedException::class) fun testSendEvent_unTimed_noParams() { val event = AnalyticsEvent("Graylog Test Run No Params") provider.sendEvent(event) lock.await(50L, TimeUnit.MILLISECONDS) assertThat(logEventCalled).isEqualTo(true) assertThat(testEventHashCode).isEqualTo(event.hashCode()) assertThat(loggedEventName).isEqualTo("Graylog Test Run No Params") } @Test @Throws(InterruptedException::class) fun testSendEvent_unTimed_withParams() { val event = AnalyticsEvent("Graylog Event With Params Run") .putAttribute("some_param", "yes") .putAttribute("another_param", "yes again") provider.sendEvent(event) lock.await(50L, TimeUnit.MILLISECONDS) assertThat(loggedEventName).isEqualTo("Graylog Event With Params Run") assertThat(logEventCalled).isEqualTo(true) assertThat(testEventHashCode).isEqualTo(event.hashCode()) } @Test @Throws(InterruptedException::class) fun testLogContentViewEvent() { val event = ContentViewEvent("Test page 7") provider.sendEvent(event) lock.await(50L, TimeUnit.MILLISECONDS) assertThat(loggedEventName).isEqualTo(CommonEvents.CONTENT_VIEW) assertThat(logEventCalled).isEqualTo(true) assertThat(testEventHashCode).isEqualTo(event.hashCode()) } @Test @Throws(InterruptedException::class) fun testLogErrorEvent() { val event = ErrorEvent() .setMessage("something bad happened") .setException(EmptyStackException()) provider.sendEvent(event) lock.await(50L, TimeUnit.MILLISECONDS) assertThat(loggedEventName).isEqualTo(CommonEvents.ERROR) assertThat(logEventCalled).isEqualTo(true) assertThat(testEventHashCode).isEqualTo(event.hashCode()) } @Test fun testSendEvent_timed_noParams() { val event = AnalyticsEvent("Graylog Timed Event") .setTimed(true) provider.sendEvent(event) assertThat(logEventCalled).isEqualTo(false) } @Test fun testSendEvent_timed_withParams() { val event = AnalyticsEvent("Graylog Timed Event With Parameters") .setTimed(true) .putAttribute("some_param", "yes") .putAttribute("another_param", "yes again") provider.sendEvent(event) assertThat(logEventCalled).isEqualTo(false) } @Test @Throws(InterruptedException::class) fun testEndTimedEvent_Valid() { val event = AnalyticsEvent("Graylog Timed Event With Parameters") .setTimed(true) .putAttribute("some_param", "yes") .putAttribute("another_param", "yes again") provider.sendEvent(event) assertThat(logEventCalled).isEqualTo(false) provider.endTimedEvent(event) lock.await(50L, TimeUnit.MILLISECONDS) assertThat(loggedEventName).isEqualTo("Graylog Timed Event With Parameters") assertThat(logEventCalled).isEqualTo(true) assertThat(testEventHashCode).isEqualTo(event.hashCode()) } @Test fun test_endTimedEvent_WillThrow() { var didThrow = false val event = AnalyticsEvent("Graylog Timed Event With Parameters") .setTimed(true) try { provider.endTimedEvent(event) // attempting to end a timed event that was not started should throw an exception } catch (e: IllegalStateException) { didThrow = true } assertThat(didThrow).isEqualTo(true) } }
graylog-provider/src/test/kotlin/com/busybusy/graylog_provider/GraylogProviderTest.kt
2258129464
// GENERATED package com.fkorotkov.kubernetes.discovery.v1 import io.fabric8.kubernetes.api.model.ObjectReference as model_ObjectReference import io.fabric8.kubernetes.api.model.discovery.v1.Endpoint as v1_Endpoint fun v1_Endpoint.`targetRef`(block: model_ObjectReference.() -> Unit = {}) { if(this.`targetRef` == null) { this.`targetRef` = model_ObjectReference() } this.`targetRef`.block() }
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/discovery/v1/targetRef.kt
752982997
package ch.rmy.android.http_shortcuts.variables import ch.rmy.android.framework.extensions.showIfPossible import ch.rmy.android.framework.extensions.startActivity import ch.rmy.android.http_shortcuts.activities.variables.VariablesActivity import ch.rmy.android.http_shortcuts.usecases.GetVariablePlaceholderPickerDialogUseCase import ch.rmy.android.http_shortcuts.utils.ActivityProvider import javax.inject.Inject // TODO: Refactor this so that the dialog state that is created within is properly stored in the view state class VariableViewUtils @Inject constructor( private val getVariablePlaceholderPickerDialog: GetVariablePlaceholderPickerDialogUseCase, private val activityProvider: ActivityProvider, ) { fun bindVariableViews( editText: VariableEditText, button: VariableButton, allowEditing: Boolean = true, ) { button.setOnClickListener { getVariablePlaceholderPickerDialog.invoke( onVariableSelected = { editText.insertVariablePlaceholder(it) }, onEditVariableButtonClicked = if (allowEditing) { { VariablesActivity.IntentBuilder() .startActivity(editText.context) } } else null, ) .createDialog(activityProvider.getActivity()) .showIfPossible() } } }
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/variables/VariableViewUtils.kt
3333146701
package io.github.drmashu.koshop.action import io.github.drmashu.buri.HtmlAction import io.github.drmashu.koshop.dao.ItemDao import io.github.drmashu.koshop.dao.ItemImageDao import org.apache.logging.log4j.LogManager import javax.servlet.ServletContext import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Created by drmashu on 2015/10/17. */ public open class ItemAction(context: ServletContext, request: HttpServletRequest, response: HttpServletResponse, val itemDao: ItemDao, val itemImgDao: ItemImageDao, val id: String): HtmlAction(context, request, response) { companion object{ val logger = LogManager.getLogger(ItemAction::class.java) } init { logger.entry(request, response, itemDao, id) } /** * */ override fun get() { logger.entry() val itemId = id val item = itemDao.selectById(itemId) item.images = itemImgDao.selectByItemIdWithoutBlob(itemId).toArrayList() responseByJson(item) logger.exit() } }
src/main/kotlin/io/github/drmashu/koshop/action/ItemAction.kt
1686817406
/* * Copyright (c) 2017 Kotlin Algorithm Club * * 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 io.uuddlrlrba.ktalgs.datastructures.tree import io.uuddlrlrba.ktalgs.datastructures.Queue class BinaryTree(var value: Int, var left: BinaryTree?, var right: BinaryTree?) { constructor(value: Int): this(value, null, null) fun size(): Int { var size = 1 if (left != null) { size += left!!.size() } if (right != null) { size += right!!.size() } return size } fun height(): Int { val left = if (left == null) 0 else left!!.height() val right = if (right == null) 0 else right!!.height() return maxOf(left, right) + 1 } fun add(value: Int) { // adds the on the first empty level val queue = Queue<BinaryTree>() queue.add(this) while (!queue.isEmpty()) { val x = queue.poll() if (x.left == null) { x.left = BinaryTree(value) return } else if (x.right == null) { x.right = BinaryTree(value) return } else { queue.add(x.left!!) queue.add(x.right!!) } } } }
src/main/io/uuddlrlrba/ktalgs/datastructures/tree/BinaryTree.kt
3511792012