content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
// API_VERSION: 1.3
// WITH_STDLIB
val x: Pair<String, Int> = listOf("a" to 1, "c" to 3, "b" to 2).<caret>sortedByDescending { it.second }.last() | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/sortedByDescendingLast.kt | 265794459 |
package test
class A {
fun baz() {}
fun bar() {
baz()
}
} | plugins/kotlin/idea/tests/testData/refactoring/rename/funTextOccurrences/after/test.kt | 3027779295 |
// WITH_STDLIB
fun test(): Int {
return listOf(1, 2, 3)
.<caret>filter { it > 1 }
.map { it * 2 }
.let {
it.binarySearch(1)
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/noTargetTermination2.kt | 2849229758 |
/*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.intents
import android.app.Activity
import android.app.Service
import splitties.bundle.BundleSpec
import splitties.exceptions.unsupported
import android.content.BroadcastReceiver as BR
/**
* @see ActivityIntentSpec
* @see BroadcastReceiverIntentSpec
* @see ServiceIntentSpec
*/
interface IntentSpec<T, out ExtrasSpec : BundleSpec> {
val klass: Class<T>
val extrasSpec: ExtrasSpec
}
interface ActivityIntentSpec<T : Activity, out ExtrasSpec : BundleSpec> : IntentSpec<T, ExtrasSpec>
interface BroadcastReceiverIntentSpec<T : BR, out ExtrasSpec : BundleSpec> :
IntentSpec<T, ExtrasSpec>
interface ServiceIntentSpec<T : Service, out ExtrasSpec : BundleSpec> : IntentSpec<T, ExtrasSpec>
// Activity Intent
inline fun <reified T : Activity, ExtrasSpec : BundleSpec> activitySpec(
extrasSpec: ExtrasSpec
) = object : ActivityIntentSpec<T, ExtrasSpec> {
override val klass = T::class.java
override val extrasSpec = extrasSpec
}
inline fun <reified T : Activity> activityWithoutExtrasSpec(): ActivityIntentSpec<T, Nothing> {
return object : ActivityIntentSpec<T, Nothing> {
override val klass = T::class.java
override val extrasSpec get() = unsupported()
}
}
// BroadcastReceiver Intent
inline fun <reified T : BR, ExtrasSpec : BundleSpec> receiverSpec(
extrasSpec: ExtrasSpec
) = object : BroadcastReceiverIntentSpec<T, ExtrasSpec> {
override val klass = T::class.java
override val extrasSpec = extrasSpec
}
inline fun <reified T : BR> receiverWithoutExtrasSpec(): BroadcastReceiverIntentSpec<T, Nothing> {
return object : BroadcastReceiverIntentSpec<T, Nothing> {
override val klass = T::class.java
override val extrasSpec get() = unsupported()
}
}
// Service Intent
inline fun <reified T : Service, ExtrasSpec : BundleSpec> serviceSpec(
extrasSpec: ExtrasSpec
) = object : ServiceIntentSpec<T, ExtrasSpec> {
override val klass = T::class.java
override val extrasSpec = extrasSpec
}
inline fun <reified T : Service> serviceWithoutExtrasSpec(): ServiceIntentSpec<T, Nothing> {
return object : ServiceIntentSpec<T, Nothing> {
override val klass = T::class.java
override val extrasSpec get() = unsupported()
}
}
| modules/intents/src/androidMain/kotlin/splitties/intents/IntentSpec.kt | 963461349 |
package fr.smarquis.applinks
import android.app.Application
class App : Application() {
override fun onCreate() {
super.onCreate()
Referrer.setFirstLaunch(this)
}
} | app/src/main/java/fr/smarquis/applinks/App.kt | 2238512114 |
// IS_APPLICABLE: false
fun foo() {
f(
1,
2,
g(<caret>3, 4, 5),
3
)
}
fun f(a: Int, b: Int, c: Int, d: Int): Int = 0
fun g(a: Int, b: Int, c: Int): Int = 0 | plugins/kotlin/idea/tests/testData/intentions/joinArgumentList/onNestedArgumentList.kt | 2998529696 |
package com.lucciola.haskellanywhereforandroidkt
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.lucciola.haskellanywhereforandroidkt", appContext.packageName)
}
}
| app/src/androidTest/kotlin/com/lucciola/haskellanywhereforandroidkt/ExampleInstrumentedTest.kt | 1359954320 |
fun test() {
val v: XXX<caret>
}
// ORDER: XXXNotDeprecated, XXXDeprecatedJavaClass | plugins/kotlin/completion/tests/testData/weighers/basic/DeprecatedJavaClass.kt | 803415483 |
package test
import kotlinx.parcelize.Parcelize
import kotlinx.parcelize.RawValue
import android.os.Parcelable
@Parcelize
class User(
val a: String,
val b: <error descr="[PARCELABLE_TYPE_NOT_SUPPORTED] Type is not directly supported by 'Parcelize'. Annotate the parameter type with '@RawValue' if you want it to be serialized using 'writeValue()'">Any</error>,
val c: <error descr="[PARCELABLE_TYPE_NOT_SUPPORTED] Type is not directly supported by 'Parcelize'. Annotate the parameter type with '@RawValue' if you want it to be serialized using 'writeValue()'">Any?</error>,
val d: <error descr="[PARCELABLE_TYPE_NOT_SUPPORTED] Type is not directly supported by 'Parcelize'. Annotate the parameter type with '@RawValue' if you want it to be serialized using 'writeValue()'">Map<Any, String></error>,
val e: @RawValue Any?,
val f: @RawValue Map<String, Any>,
val g: Map<String, @RawValue Any>,
val h: Map<@RawValue Any, List<@RawValue Any>>
) : Parcelable
| plugins/kotlin/compiler-plugins/parcelize/tests/testData/checker/unsupportedType.kt | 3982596933 |
package com.github.wreulicke.webflux.oauth2
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
class DemoApplicationTests {
@Test
fun contextLoads() {
}
}
| webflux-oauth2/src/test/kotlin/com/github/wreulicke/webflux/oauth2/DemoApplicationTests.kt | 3397039617 |
package org.webscene.client.html
enum class ButtonType {
BUTTON, RESET, SUBMIT
} | src/main/kotlin/org/webscene/client/html/ButtonType.kt | 1676501838 |
package info.nightscout.androidaps.dialogs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import kotlinx.android.synthetic.main.close.*
import kotlinx.android.synthetic.main.dialog_profileviewer.*
import org.json.JSONObject
class ProfileViewerDialog : DialogFragment() {
private var time: Long = 0
enum class Mode(val i: Int) {
RUNNING_PROFILE(1),
CUSTOM_PROFILE(2)
}
private var mode: Mode = Mode.RUNNING_PROFILE
private var customProfileJson: String = ""
private var customProfileName: String = ""
private var customProfileUnits: String = Constants.MGDL
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// load data from bundle
(savedInstanceState ?: arguments)?.let { bundle ->
time = bundle.getLong("time", 0)
mode = Mode.values()[bundle.getInt("mode", Mode.RUNNING_PROFILE.ordinal)]
customProfileJson = bundle.getString("customProfile", "")
customProfileUnits = bundle.getString("customProfileUnits", Constants.MGDL)
customProfileName = bundle.getString("customProfileName", "")
}
dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
isCancelable = true
dialog?.setCanceledOnTouchOutside(false)
return inflater.inflate(R.layout.dialog_profileviewer, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
close.setOnClickListener { dismiss() }
val profile: Profile?
val profileName: String?
val date: String?
when (mode) {
Mode.RUNNING_PROFILE -> {
profile = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(time)?.profileObject
profileName = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(time)?.customizedName
date = DateUtil.dateAndTimeString(TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(time)?.date
?: 0)
profileview_datelayout.visibility = View.VISIBLE
}
Mode.CUSTOM_PROFILE -> {
profile = Profile(JSONObject(customProfileJson), customProfileUnits)
profileName = customProfileName
date = ""
profileview_datelayout.visibility = View.GONE
}
}
profileview_noprofile.visibility = View.VISIBLE
profile?.let {
profileview_units.text = it.units
profileview_dia.text = MainApp.gs(R.string.format_hours, it.dia)
profileview_activeprofile.text = profileName
profileview_date.text = date
profileview_ic.text = it.icList
profileview_isf.text = it.isfList
profileview_basal.text = it.basalList
profileview_target.text = it.targetList
basal_graph.show(it)
profileview_noprofile.visibility = View.GONE
profileview_invalidprofile.visibility = if (it.isValid("ProfileViewDialog")) View.GONE else View.VISIBLE
}
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
bundle.putLong("time", time)
bundle.putInt("mode", mode.ordinal)
bundle.putString("customProfile", customProfileJson)
bundle.putString("customProfileName", customProfileName)
bundle.putString("customProfileUnits", customProfileUnits)
}
}
| app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt | 4205095597 |
package me.sieben.seventools.functions
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe
class BooleanActionTest : WordSpec() {
init {
"Boolean?.onTrue" should {
"run the block if the Boolean is true" {
var checkpoint = false
true as Boolean? onTrue { checkpoint = true }
checkpoint shouldBe true
}
"do not run the block if the Boolean is false" {
var checkpoint = false
false as Boolean? onTrue { checkpoint = true }
checkpoint shouldBe false
}
"do not run the block if the Boolean is null" {
var checkpoint = false
null as Boolean? onTrue { checkpoint = true }
checkpoint shouldBe false
}
"only the `true'-Block" {
var checkpointTrue = false
var checkpointFalse = false
var checkpointNull = false
true as Boolean? onTrue {
checkpointTrue = true
} onFalse {
checkpointFalse = true
} onNull {
checkpointNull = true
}
checkpointTrue shouldBe true
checkpointFalse shouldBe false
checkpointNull shouldBe false
}
}
"Boolean.onTrue" should {
"run the block if the Boolean is true" {
var checkpoint = false
true onTrue { checkpoint = true }
checkpoint shouldBe true
}
"do not run the block if the Boolean is false" {
var checkpoint = false
false onTrue { checkpoint = true }
checkpoint shouldBe false
}
}
"Boolean?.onFalse" should {
"run the block if the Boolean is false" {
var checkpoint = false
false as Boolean? onFalse { checkpoint = true }
checkpoint shouldBe true
}
"do not run the block if the Boolean is true" {
var checkpoint = false
true as Boolean? onFalse { checkpoint = true }
checkpoint shouldBe false
}
"do not run the block if the Boolean is null" {
var checkpoint = false
null as Boolean? onFalse { checkpoint = true }
checkpoint shouldBe false
}
"only the `false'-Block" {
var checkpointTrue = false
var checkpointFalse = false
var checkpointNull = false
false as Boolean? onTrue {
checkpointTrue = true
} onFalse {
checkpointFalse = true
} onNull {
checkpointNull = true
}
checkpointTrue shouldBe false
checkpointFalse shouldBe true
checkpointNull shouldBe false
}
}
"Boolean.onFalse" should {
"run the block if the Boolean is false" {
var checkpoint = false
false onFalse { checkpoint = true }
checkpoint shouldBe true
}
"do not run the block if the Boolean is true" {
var checkpoint = false
true onFalse { checkpoint = true }
checkpoint shouldBe false
}
}
"Boolean?.onNull" should {
"run the block if the Boolean is null" {
var checkpoint = false
null onNull { checkpoint = true }
checkpoint shouldBe true
}
"do not run the block if the Boolean is true" {
var checkpoint = false
true onNull { checkpoint = true }
checkpoint shouldBe false
}
"do not run the block if the Boolean is false" {
var checkpoint = false
false onNull { checkpoint = true }
checkpoint shouldBe false
}
"only the `null'-Block" {
var checkpointTrue = false
var checkpointFalse = false
var checkpointNull = false
null onTrue {
checkpointTrue = true
} onFalse {
checkpointFalse = true
} onNull {
checkpointNull = true
}
checkpointTrue shouldBe false
checkpointFalse shouldBe false
checkpointNull shouldBe true
}
}
}
}
| seventools/src/test/java/me/sieben/seventools/functions/BooleanActionTest.kt | 1701436354 |
// PROBLEM: none
// WITH_STDLIB
fun foo(s: String, i: Int) = s.length + i
fun test() {
val s = ""
s.let<caret> { foo(it, 1) }
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/simpleRedundantLet/functionCall2.kt | 715835366 |
package com.meltwater.puppy.rest
import com.google.common.collect.ImmutableMap.of
import com.google.gson.Gson
import com.meltwater.puppy.config.*
import org.slf4j.LoggerFactory
import java.util.*
import javax.ws.rs.client.Entity.entity
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import javax.ws.rs.core.Response.Status
class RestClientException : Exception {
constructor(s: String, e: Exception) : super(s, e)
constructor(s: String) : super(s)
}
open class RabbitRestClient(brokerAddress: String, brokerUsername: String, brokerPassword: String) {
private val log = LoggerFactory.getLogger(RabbitRestClient::class.java)
companion object {
val PATH_OVERVIEW = "api/overview"
public val PATH_VHOSTS = "api/vhosts"
val PATH_VHOSTS_SINGLE = "api/vhosts/{vhost}"
val PATH_USERS = "api/users"
val PATH_USERS_SINGLE = "api/users/{user}"
val PATH_PERMISSIONS = "api/permissions"
val PATH_PERMISSIONS_SINGLE = "api/permissions/{vhost}/{user}"
val PATH_EXCHANGES_SINGLE = "api/exchanges/{vhost}/{exchange}"
val PATH_QUEUES_SINGLE = "api/queues/{vhost}/{queue}"
val PATH_BINDINGS_VHOST = "api/bindings/{vhost}"
val PATH_BINDING_QUEUE = "api/bindings/{vhost}/e/{exchange}/q/{to}"
val PATH_BINDING_EXCHANGE = "api/bindings/{vhost}/e/{exchange}/e/{to}"
}
private val requestBuilder: RestRequestBuilder
private val parser = RabbitRestResponseParser()
private val gson = Gson()
init {
this.requestBuilder = RestRequestBuilder(brokerAddress, kotlin.Pair(brokerUsername, brokerPassword))
.withHeader("content-type", "application/json")
}
open fun ping(): Boolean {
try {
val response = requestBuilder.request(PATH_OVERVIEW).get()
return response.status == Status.OK.statusCode
} catch (e: Exception) {
return false
}
}
open fun getUsername(): String = requestBuilder.getAuthUser()
open fun getPassword(): String = requestBuilder.getAuthPass()
@Throws(RestClientException::class)
open fun getPermissions(): Map<String, PermissionsData> = parser.permissions(
expect(requestBuilder.request(PATH_PERMISSIONS).get(),
Status.OK.statusCode))
@Throws(RestClientException::class)
open fun getExchange(vhost: String,
exchange: String,
user: String,
pass: String): Optional<ExchangeData> = parser.exchange(
expectOrEmpty(requestBuilder.nextWithAuthentication(user, pass).request(PATH_EXCHANGES_SINGLE, of(
"vhost", vhost,
"exchange", exchange)).get(),
Status.OK.statusCode,
Status.NOT_FOUND.statusCode))
@Throws(RestClientException::class)
open fun getQueue(vhost: String,
queue: String,
user: String,
pass: String): Optional<QueueData> = parser.queue(
expectOrEmpty(requestBuilder.nextWithAuthentication(user, pass).request(PATH_QUEUES_SINGLE, of(
"vhost", vhost,
"queue", queue)).get(),
Status.OK.statusCode,
Status.NOT_FOUND.statusCode))
@Throws(RestClientException::class)
open fun getBindings(vhost: String,
user: String,
pass: String): Map<String, List<BindingData>> {
if (getVirtualHosts().contains(vhost)) {
return parser.bindings(
expect(requestBuilder.nextWithAuthentication(user, pass).request(PATH_BINDINGS_VHOST, of(
"vhost", vhost)).get(),
Status.OK.statusCode))
} else {
return HashMap()
}
}
@Throws(RestClientException::class)
open fun getVirtualHosts(): Map<String, VHostData> = parser.vhosts(
expect(requestBuilder.request(PATH_VHOSTS).get(),
Status.OK.statusCode))
@Throws(RestClientException::class)
open fun getUsers(): Map<String, UserData> = parser.users(
expect(requestBuilder.request(PATH_USERS).get(),
Status.OK.statusCode))
@Throws(RestClientException::class)
open fun createVirtualHost(virtualHost: String, vHostData: VHostData) {
expect(requestBuilder.request(PATH_VHOSTS_SINGLE, of("vhost", virtualHost)).put(entity(gson.toJson(vHostData), MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
}
@Throws(RestClientException::class)
open fun createUser(user: String, userData: UserData) {
require("User", user, "password", userData.password)
expect(requestBuilder.request(PATH_USERS_SINGLE, of("user", user)).put(entity(gson.toJson(of(
"password", userData.password,
"tags", if (userData.admin) "administrator" else "")), MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
}
@Throws(RestClientException::class)
open fun createPermissions(user: String, vhost: String, permissionsData: PermissionsData) {
require("Permissions", "$user@$vhost", "configure", permissionsData.configure)
require("Permissions", "$user@$vhost", "write", permissionsData.write)
require("Permissions", "$user@$vhost", "read", permissionsData.read)
expect(requestBuilder.request(PATH_PERMISSIONS_SINGLE, of(
"vhost", vhost,
"user", user)).put(entity(gson.toJson(permissionsData), MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
}
@Throws(RestClientException::class)
open fun createExchange(vhost: String,
exchange: String,
exchangeData: ExchangeData,
user: String,
pass: String) {
require("Exchange", exchange + "@" + vhost, "type", exchangeData.type)
expect(requestBuilder.nextWithAuthentication(user, pass).request(PATH_EXCHANGES_SINGLE, of(
"vhost", vhost,
"exchange", exchange)).put(entity(gson.toJson(exchangeData), MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
}
@Throws(RestClientException::class)
open fun createQueue(vhost: String, queue: String,
queueData: QueueData,
user: String,
pass: String) {
expect(requestBuilder
.nextWithAuthentication(user, pass)
.request(PATH_QUEUES_SINGLE, of(
"vhost", vhost,
"queue", queue))
.put(entity(gson.toJson(queueData),
MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
}
@Throws(RestClientException::class)
open fun createBinding(vhost: String,
exchange: String,
bindingData: BindingData,
user: String,
pass: String) {
require("Binding", "$user@$vhost", "destination", bindingData.destination)
require("Binding", "$user@$vhost", "destination_type", bindingData.destination_type)
require("Binding", "$user@$vhost", "routing_key", bindingData.routing_key)
if (bindingData.destination_type == DestinationType.queue) {
expect(requestBuilder
.nextWithAuthentication(user, pass)
.request(PATH_BINDING_QUEUE, of<String, String>(
"vhost", vhost,
"exchange", exchange,
"to", bindingData.destination))
.post(entity(gson.toJson(of<String, Any>(
"routing_key", bindingData.routing_key,
"arguments", bindingData.arguments)),
MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
} else if (bindingData.destination_type == DestinationType.exchange) {
expect(requestBuilder.nextWithAuthentication(user, pass).request(PATH_BINDING_EXCHANGE, of<String, String>(
"vhost", vhost,
"exchange", exchange,
"to", bindingData.destination)).post(entity(gson.toJson(of<String, Any>(
"routing_key", bindingData.routing_key,
"arguments", bindingData.arguments)),
MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
} else {
val error = "No destination_type specified for binding at $exchange@$vhost: ${bindingData.destination}"
log.error(error)
throw RestClientException(error)
}
}
@Throws(RestClientException::class)
private fun expect(response: Response, statusExpected: Int): Response {
if (response.status != statusExpected) {
val error = "Response with HTTP status %d %s, expected status code %d".format(response.status, response.statusInfo.reasonPhrase, statusExpected)
log.error(error)
throw RestClientException(error)
}
return response
}
@Throws(RestClientException::class)
private fun expectOrEmpty(response: Response,
statusExpected: Int,
statusEmpty: Int): Optional<Response> {
if (response.status == statusExpected) {
return Optional.of(response)
} else if (response.status == statusEmpty) {
return Optional.empty<Response>()
} else {
val error = "Response with HTTP status %d %s, expected status code %d or %s".format(response.status, response.statusInfo.reasonPhrase, statusExpected, statusEmpty)
log.error(error)
throw RestClientException(error)
}
}
@Throws(RestClientException::class)
private fun <D> require(type: String, name: String, property: String, value: D?) {
if (value == null) {
val error = "$type $name missing required field: $property"
log.error(error)
throw RestClientException(error)
}
}
}
| src/main/kotlin/com/meltwater/puppy/rest/RabbitRestClient.kt | 421005556 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.nj2k.symbols
import com.intellij.lang.jvm.JvmModifier
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiEnumConstant
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifierListOwner
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.findDeepestSuperMethodsNoWrapping
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.nj2k.isObjectOrCompanionObject
import org.jetbrains.kotlin.nj2k.psi
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
val JKSymbol.isUnresolved
get() = this is JKUnresolvedSymbol
fun JKSymbol.getDisplayFqName(): String {
fun JKSymbol.isDisplayable() = this is JKClassSymbol || this is JKPackageSymbol
if (this !is JKUniverseSymbol<*>) return fqName
return generateSequence(declaredIn?.takeIf { it.isDisplayable() }) { symbol ->
symbol.declaredIn?.takeIf { it.isDisplayable() }
}.fold(name) { acc, symbol -> "${symbol.name}.$acc" }
}
fun JKSymbol.deepestFqName(): String {
fun Any.deepestFqNameForTarget(): String? =
when (this) {
is PsiMethod -> (findDeepestSuperMethods().firstOrNull() ?: this).kotlinFqName?.asString()
is KtNamedFunction -> findDeepestSuperMethodsNoWrapping(this).firstOrNull()?.kotlinFqName?.asString()
is JKMethod -> psi<PsiElement>()?.deepestFqNameForTarget()
else -> null
}
return target.deepestFqNameForTarget() ?: fqName
}
val JKSymbol.containingClass
get() = declaredIn as? JKClassSymbol
val JKSymbol.isStaticMember
get() = when (val target = target) {
is PsiModifierListOwner -> target.hasModifier(JvmModifier.STATIC)
is KtElement -> target.getStrictParentOfType<KtClassOrObject>()
?.safeAs<KtObjectDeclaration>()
?.isCompanion() == true
is JKTreeElement ->
target.safeAs<JKOtherModifiersOwner>()?.hasOtherModifier(OtherModifier.STATIC) == true
|| target.parentOfType<JKClass>()?.isObjectOrCompanionObject == true
else -> false
}
val JKSymbol.isEnumConstant
get() = when (target) {
is JKEnumConstant -> true
is PsiEnumConstant -> true
is KtEnumEntry -> true
else -> false
}
val JKSymbol.isUnnamedCompanion
get() = when (val target = target) {
is JKClass -> target.classKind == JKClass.ClassKind.COMPANION
is KtObjectDeclaration -> target.isCompanion() && target.name == SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT.toString()
else -> false
}
| plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/symbols/utils.kt | 2732623809 |
// 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.run
import com.intellij.compiler.options.CompileStepBeforeRun
import com.intellij.execution.configurations.RunConfiguration
fun RunConfiguration.addBuildTask() {
beforeRunTasks = beforeRunTasks + CompileStepBeforeRun.MakeBeforeRunTask()
} | plugins/kotlin/run-configurations/jvm/src/org/jetbrains/kotlin/idea/run/rcUtils.kt | 1303026392 |
// 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.testFramework
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.AutoPopupController
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.execution.process.ProcessIOExecutorService
import com.intellij.ide.*
import com.intellij.ide.impl.HeadlessDataManager
import com.intellij.ide.startup.impl.StartupManagerImpl
import com.intellij.ide.structureView.StructureViewFactory
import com.intellij.ide.structureView.impl.StructureViewFactoryImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.command.impl.UndoManagerImpl
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.impl.EditorHistoryManager
import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.startup.StartupManager
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.PsiManagerImpl
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.testFramework.common.*
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.AppScheduledExecutorService
import com.intellij.util.ref.GCUtil
import com.intellij.util.ui.EDT
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.TimeUnit
class TestApplicationManager private constructor() {
companion object {
init {
initializeTestEnvironment()
}
private val ourInstance = TestApplicationManager()
private val dataManager: HeadlessDataManager
get() = DataManager.getInstance() as HeadlessDataManager
@JvmStatic
fun getInstance(): TestApplicationManager {
initTestApplication()
return ourInstance
}
@JvmStatic
fun getInstanceIfCreated(): TestApplicationManager? {
if (isApplicationInitialized) {
return ourInstance
}
else {
return null
}
}
private var testCounter = 0
@ApiStatus.Internal
@TestOnly
@JvmStatic
fun tearDownProjectAndApp(project: Project) {
if (project.isDisposed) {
return
}
val isLightProject = ProjectManagerImpl.isLight(project)
val app = ApplicationManager.getApplication()
com.intellij.testFramework.common.runAll(
{
if (isLightProject) {
project.serviceIfCreated<AutoPopupController>()?.cancelAllRequests()
}
},
{ CodeStyle.dropTemporarySettings(project) },
{ UsefulTestCase.doPostponedFormatting(project) },
{ LookupManager.hideActiveLookup(project) },
{
if (isLightProject) {
(project.serviceIfCreated<StartupManager>() as StartupManagerImpl?)?.prepareForNextTest()
}
},
{
if (isLightProject) {
LightPlatformTestCase.tearDownSourceRoot(project)
}
},
{
WriteCommandAction.runWriteCommandAction(project) {
app.serviceIfCreated<FileDocumentManager, FileDocumentManagerImpl>()?.dropAllUnsavedDocuments()
}
},
{ project.serviceIfCreated<EditorHistoryManager>()?.removeAllFiles() },
{
if (project.serviceIfCreated<PsiManager>()?.isDisposed == true) {
throw IllegalStateException("PsiManager must be not disposed")
}
},
{ LightPlatformTestCase.checkAssertions() },
{ LightPlatformTestCase.clearUncommittedDocuments(project) },
{ (UndoManager.getInstance(project) as UndoManagerImpl).dropHistoryInTests() },
{ project.serviceIfCreated<TemplateDataLanguageMappings>()?.cleanupForNextTest() },
{ (project.serviceIfCreated<PsiManager>() as PsiManagerImpl?)?.cleanupForNextTest() },
{ (project.serviceIfCreated<StructureViewFactory>() as StructureViewFactoryImpl?)?.cleanupForNextTest() },
{ waitForProjectLeakingThreads(project) },
{ dropModuleRootCaches(project) },
{
// reset data provider before disposing the project to ensure that the disposed project is not accessed
getInstanceIfCreated()?.setDataProvider(null)
},
{ ProjectManagerEx.getInstanceEx().forceCloseProject(project) },
{
if (testCounter++ % 100 == 0) {
// Some tests are written in Groovy, and running all of them may result in some 40M of memory wasted on bean data,
// so let's clear the cache occasionally to ensure it doesn't grow too big.
GCUtil.clearBeanInfoCache()
}
},
{ app.cleanApplicationStateCatching()?.let { throw it } }
)
}
private inline fun <reified T : Any, reified TI : Any> Application.serviceIfCreated(): TI? {
return this.getServiceIfCreated(T::class.java) as? TI
}
private fun dropModuleRootCaches(project: Project) {
WriteAction.runAndWait<RuntimeException> {
for (module in ModuleManager.getInstance(project).modules) {
(ModuleRootManager.getInstance(module) as ModuleRootComponentBridge).dropCaches()
}
}
}
/**
* Disposes the application (it also stops some application-related threads) and checks for project leaks.
*/
@JvmStatic
fun disposeApplicationAndCheckForLeaks() {
val edtThrowable = runInEdtAndGet {
runAllCatching(
{ PlatformTestUtil.cleanupAllProjects() },
{ EDT.dispatchAllInvocationEvents() },
{
println((AppExecutorUtil.getAppScheduledExecutorService() as AppScheduledExecutorService).statistics())
println("ProcessIOExecutorService threads created: ${(ProcessIOExecutorService.INSTANCE as ProcessIOExecutorService).threadCounter}")
},
{
val app = ApplicationManager.getApplication() as? ApplicationImpl
app?.messageBus?.syncPublisher(AppLifecycleListener.TOPIC)?.appWillBeClosed(false)
},
{ UsefulTestCase.waitForAppLeakingThreads(10, TimeUnit.SECONDS) },
{
if (ApplicationManager.getApplication() != null) {
assertNonDefaultProjectsAreNotLeaked()
}
},
{
@Suppress("SSBasedInspection")
getInstanceIfCreated()?.dispose()
},
{
EDT.dispatchAllInvocationEvents()
},
)
}
listOfNotNull(edtThrowable, runAllCatching(
{
assertDisposerEmpty()
}
)).reduceAndThrow()
}
@ApiStatus.Internal
@JvmStatic
fun waitForProjectLeakingThreads(project: Project) {
if (project is ComponentManagerImpl) {
project.stopServicePreloading()
}
(project.serviceIfCreated<GeneratedSourceFileChangeTracker>() as GeneratedSourceFileChangeTrackerImpl?)
?.cancelAllAndWait(10, TimeUnit.SECONDS)
}
@Deprecated(
message = "moved to dump.kt",
replaceWith = ReplaceWith("com.intellij.testFramework.common.publishHeapDump(fileNamePrefix)")
)
@JvmStatic
fun publishHeapDump(fileNamePrefix: String): String {
return com.intellij.testFramework.common.publishHeapDump(fileNamePrefix)
}
}
fun setDataProvider(provider: DataProvider?) {
dataManager.setTestDataProvider(provider)
}
fun setDataProvider(provider: DataProvider?, parentDisposable: Disposable?) {
dataManager.setTestDataProvider(provider, parentDisposable!!)
}
fun getData(dataId: String) = dataManager.dataContext.getData(dataId)
fun dispose() {
disposeTestApplication()
}
}
| platform/testFramework/src/com/intellij/testFramework/TestApplicationManager.kt | 1927134291 |
// WITH_RUNTIME
// IS_APPLICABLE: false
// IS_APPLICABLE_2: false
fun foo(list: List<Any>, target: MutableCollection<String>) {
<caret>for (o in list) {
if (bar(o as String)) {
target.add(o)
}
}
}
fun bar(s: String): Boolean = true | plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/smartCasts/smartCastRequired5.kt | 1690564643 |
// LANGUAGE_VERSION: 1.3
// PROBLEM: none
// WITH_RUNTIME
fun getValue(i: Int): String = ""
fun associateWithTo() {
val destination = mutableMapOf<Int, String>()
arrayOf(1).<caret>associateTo(destination) { it to getValue(it) }
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceAssociateFunction/associateWithTo/arrayVersion13.kt | 2962823294 |
package cz.bydzodo1.batchLemmatizationProcessor.model.generatingOutput
import cz.bydzodo1.batchLemmatizationProcessor.model.CommandResult
import cz.bydzodo1.batchLemmatizationProcessor.model.Settings
import cz.bydzodo1.batchLemmatizationProcessor.model.xmlContent.Token
import java.io.File
import java.io.PrintWriter
import java.util.*
class OutputFileProvider {
val sep = ";"
val date = Date().time.toString()
val fileName = "Result$date.csv"
lateinit var writer: PrintWriter
var columns: MutableList<Column> = mutableListOf()
fun outputFile(commandResults: HashMap<String, CommandResult>, outputFile: File? = null) {
var file: File? = null
if (outputFile == null){
writer = PrintWriter(fileName, "UTF-8")
file = File(fileName)
} else {
writer = PrintWriter(outputFile, "UTF-8")
file = outputFile
}
createColumns(commandResults.map { it.value })
writeHeader()
writeBody(commandResults)
println("Result file has been saved - ${file.absolutePath}")
writer.close()
}
private fun writeHeader(){
writer.print("NAZEV${sep}POVET VET${sep}POCET SLOV")
columns.forEach({
writer.print(sep + "${it.index + 1}:${it.char}")
})
writer.println()
}
private fun writeBody(commandResults: HashMap<String, CommandResult>){
commandResults.forEach({
writeRow(it.key, it.value)
})
}
private fun writeRow(fileName: String, commandResult: CommandResult){
val allTokens = mutableListOf<Token>()
commandResult.sentences.forEach({allTokens.addAll(it.tokens)})
writer.print(fileName + sep + commandResult.sentences.size + sep + allTokens.size)
columns.forEach({
val column = it
val count = allTokens.map(Token::getTags).filter { it[column.index] == column.char }.size
writer.print(sep + count)
})
writer.println()
}
private fun createColumns(commandResults: List<CommandResult>){
val allTokens = mutableListOf<Token>()
commandResults.forEach({it.sentences.forEach({allTokens.addAll(it.tokens)})})
val tagColumns = HashMap<Int, MutableSet<Char>>()
allTokens.forEach({
for (i in it.getTags().indices) {
if (tagColumns[i] == null){
tagColumns[i] = mutableSetOf()
}
tagColumns[i]!!.add(it.tag[i])
}
})
tagColumns.forEach({
val index = it.key
val tags = it.value.sorted()
for(tag in tags){
columns.add(Column(index, tag))
}
})
}
} | src/main/kt/cz/bydzodo1/batchLemmatizationProcessor/model/generatingOutput/OutputFileProvider.kt | 1394287058 |
// WITH_RUNTIME
fun test(list: List<Int>) {
val b = list.<caret>any { it != 1 }
} | plugins/kotlin/idea/tests/testData/intentions/convertFilteringFunctionWithDemorgansLaw/anyToAll/toAll/simple.kt | 232791373 |
/*
* 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.ch03
import cc.altruix.econsimtr01.IAgent
import cc.altruix.econsimtr01.ch0202.SimResRow
import org.fest.assertions.Assertions
import org.joda.time.DateTime
import org.junit.Test
import org.mockito.Mockito
import java.util.*
/**
* Created by pisarenko on 17.05.2016.
*/
class AgriculturalSimulationAccountantTests {
@Test
fun calculateFieldAreaWithCrop() {
val simParamProv =
AgriculturalSimParametersProviderWithPredefinedData(
Properties()
)
val field = Field(simParamProv)
field.put(AgriculturalSimParametersProvider.RESOURCE_AREA_WITH_CROP.id,
123.45)
val agents = listOf(field)
val out = createObjectUnderTest()
Assertions.assertThat(out.calculateFieldAreaWithCrop(agents))
.isEqualTo(123.45)
}
@Test
fun calculateEmptyFieldArea() {
val simParamProv =
AgriculturalSimParametersProviderWithPredefinedData(
Properties()
)
val field = Field(simParamProv)
field.put(AgriculturalSimParametersProvider.RESOURCE_EMPTY_AREA.id,
123.45)
val agents = listOf(field)
val out = createObjectUnderTest()
Assertions.assertThat(out.calculateEmptyFieldArea(agents))
.isEqualTo(123.45)
}
@Test
fun calculateFieldAreaWithSeeds() {
val simParamProv =
AgriculturalSimParametersProviderWithPredefinedData(
Properties()
)
val field = Field(simParamProv)
field.put(AgriculturalSimParametersProvider.RESOURCE_AREA_WITH_SEEDS.id,
123.45)
val agents = listOf(field)
val out = createObjectUnderTest()
Assertions.assertThat(out.calculateFieldAreaWithSeeds(agents))
.isEqualTo(123.45)
}
@Test
fun calculateSeedsInShack() {
val shack = Shack()
shack.put(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id,
123.45)
val agents = listOf(shack)
val out = createObjectUnderTest()
Assertions.assertThat(out.calculateSeedsInShack(agents))
.isEqualTo(123.45)
}
@Test
fun saveRowDataWiring() {
// Prepare
val resultsStorage = HashMap<DateTime,
SimResRow<AgriculturalSimulationRowField>>()
val out = Mockito.spy(
AgriculturalSimulationAccountant(
resultsStorage,
"scenario"
)
)
val agents = emptyList<IAgent>()
Mockito.doReturn(1.0).`when`(out).calculateSeedsInShack(agents)
Mockito.doReturn(2.0).`when`(out).calculateFieldAreaWithSeeds(agents)
Mockito.doReturn(3.0).`when`(out).calculateEmptyFieldArea(agents)
Mockito.doReturn(4.0).`when`(out).calculateFieldAreaWithCrop(agents)
val target = HashMap<AgriculturalSimulationRowField, Double>()
// Run method under test
out.saveRowData(agents, target)
// Verify
Assertions.assertThat(target[AgriculturalSimulationRowField
.SEEDS_IN_SHACK]).isEqualTo(1.0)
Assertions.assertThat(target[AgriculturalSimulationRowField
.FIELD_AREA_WITH_SEEDS]).isEqualTo(2.0)
Assertions.assertThat(target[AgriculturalSimulationRowField
.EMPTY_FIELD_AREA]).isEqualTo(3.0)
Assertions.assertThat(target[AgriculturalSimulationRowField
.FIELD_AREA_WITH_CROP]).isEqualTo(4.0)
}
private fun createObjectUnderTest(): AgriculturalSimulationAccountant {
val out = AgriculturalSimulationAccountant(HashMap<DateTime,
SimResRow<AgriculturalSimulationRowField>>(), "scenario")
return out
}
}
| src/test/java/cc/altruix/econsimtr01/ch03/AgriculturalSimulationAccountantTests.kt | 549745096 |
// 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.codeInsight.completion.ml
import com.intellij.codeInsight.template.macro.MacroUtil
import com.intellij.internal.ml.WordsSplitter
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING
import com.intellij.psi.scope.util.PsiScopesUtil
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.psi.util.TypeConversionUtil
import org.jetbrains.annotations.ApiStatus
import java.util.*
@ApiStatus.Internal
object JavaCompletionFeatures {
private val VARIABLES_KEY: Key<VariablesInfo> = Key.create("java.ml.completion.variables")
private val PACKAGES_KEY: Key<PackagesInfo> = Key.create("java.ml.completion.packages")
private val CHILD_CLASS_WORDS_KEY: Key<List<String>> = Key.create("java.ml.completion.child.class.name.words")
private val wordsSplitter: WordsSplitter = WordsSplitter.Builder.identifiers().build()
enum class JavaKeyword {
ABSTRACT,
BOOLEAN,
BREAK,
CASE,
CATCH,
CHAR,
CLASS,
CONST,
CONTINUE,
DOUBLE,
ELSE,
EXTENDS,
FINAL,
FINALLY,
FLOAT,
FOR,
IF,
IMPLEMENTS,
IMPORT,
INSTANCEOF,
INT,
INTERFACE,
LONG,
NEW,
PRIVATE,
PROTECTED,
PUBLIC,
RETURN,
STATIC,
SUPER,
SWITCH,
THIS,
THROW,
THROWS,
TRY,
VOID,
WHILE,
TRUE,
FALSE,
NULL,
ANOTHER;
companion object {
private val ALL_VALUES: Map<String, JavaKeyword> = values().associateBy { it.toString() }
fun getValue(text: String): JavaKeyword? = ALL_VALUES[text]
}
override fun toString(): String = name.toLowerCase(Locale.ENGLISH)
}
enum class JavaType {
VOID,
BOOLEAN,
NUMERIC,
STRING,
CHAR,
ENUM,
ARRAY,
COLLECTION,
MAP,
THROWABLE,
ANOTHER;
companion object {
fun getValue(type: PsiType): JavaType {
return when {
type == PsiType.VOID -> VOID
type == PsiType.CHAR -> CHAR
type.equalsToText(JAVA_LANG_STRING) -> STRING
TypeConversionUtil.isBooleanType(type) -> BOOLEAN
TypeConversionUtil.isNumericType(type) -> NUMERIC
type is PsiArrayType -> ARRAY
InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_COLLECTION) -> COLLECTION
InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_MAP) -> MAP
InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_LANG_THROWABLE) -> THROWABLE
TypeConversionUtil.isEnumType(type) -> ENUM
else -> ANOTHER
}
}
}
}
fun asKeyword(text: String): JavaKeyword? = JavaKeyword.getValue(text)
fun asJavaType(type: PsiType): JavaType = JavaType.getValue(type)
fun calculateChildClassWords(environment: CompletionEnvironment, childClass: PsiElement) {
val childClassWords = wordsSplitter.split(childClass.text)
environment.putUserData(CHILD_CLASS_WORDS_KEY, childClassWords)
}
fun getChildClassTokensMatchingFeature(contextFeatures: ContextFeatures, baseClassName: String): MLFeatureValue? {
contextFeatures.getUserData(CHILD_CLASS_WORDS_KEY)?.let { childClassTokens ->
val baseClassTokens = wordsSplitter.split(baseClassName)
if (baseClassTokens.isNotEmpty()) {
return MLFeatureValue.numerical(baseClassTokens.count(childClassTokens::contains).toDouble() / baseClassTokens.size)
}
}
return null
}
fun calculateVariables(environment: CompletionEnvironment) = try {
val parentClass = PsiTreeUtil.getParentOfType(environment.parameters.position, PsiClass::class.java)
val variables = getVariablesInScope(environment.parameters.position, parentClass)
val names = variables.mapNotNull { it.name }.toSet()
val types = variables.map { it.type }.toSet()
val names2types = variables.mapNotNull { variable -> variable.name?.let { Pair(it, variable.type) } }.toSet()
environment.putUserData(VARIABLES_KEY, VariablesInfo(names, types, names2types))
} catch (ignored: PsiInvalidElementAccessException) {}
fun getArgumentsVariablesMatchingFeatures(contextFeatures: ContextFeatures, method: PsiMethod): Map<String, MLFeatureValue> {
val result = mutableMapOf<String, MLFeatureValue>()
val parameters = method.parameterList.parameters
result["args_count"] = MLFeatureValue.numerical(parameters.size)
val names2types = parameters.map { Pair(it.name, it.type) }
contextFeatures.getUserData(VARIABLES_KEY)?.let { variables ->
result["args_vars_names_matches"] = MLFeatureValue.numerical(names2types.count { it.first in variables.names })
result["args_vars_types_matches"] = MLFeatureValue.numerical(names2types.count { it.second in variables.types })
result["args_vars_names_types_matches"] = MLFeatureValue.numerical(names2types.count { it in variables.names2types })
}
return result
}
fun isInQualifierExpression(environment: CompletionEnvironment): Boolean {
val parentExpressions = mutableSetOf<PsiExpression>()
var curParent = environment.parameters.position.context
while (curParent is PsiExpression) {
if (curParent is PsiReferenceExpression && parentExpressions.contains(curParent.qualifierExpression)) {
return true
}
parentExpressions.add(curParent)
curParent = curParent.parent
}
return false
}
fun isAfterMethodCall(environment: CompletionEnvironment): Boolean {
val context = environment.parameters.position.context
if (context is PsiReferenceExpression) {
val qualifier = context.qualifierExpression
return qualifier is PsiNewExpression || qualifier is PsiMethodCallExpression
}
return false
}
fun collectPackages(environment: CompletionEnvironment) {
val file = environment.parameters.originalFile as? PsiJavaFile ?: return
val packageTrie = FqnTrie.withFqn(file.packageName)
val importsTrie = FqnTrie.create()
file.importList?.importStatements?.mapNotNull { it.qualifiedName }?.forEach { importsTrie.addFqn(it) }
file.importList?.importStaticStatements?.mapNotNull { it.importReference?.qualifiedName }?.forEach { importsTrie.addFqn(it) }
environment.putUserData(PACKAGES_KEY, PackagesInfo(packageTrie, importsTrie))
}
fun getPackageMatchingFeatures(contextFeatures: ContextFeatures, psiClass: PsiClass): Map<String, MLFeatureValue> {
val packagesInfo = contextFeatures.getUserData(PACKAGES_KEY) ?: return emptyMap()
val packageName = PsiUtil.getPackageName(psiClass)
if (packageName == null || packageName.isEmpty()) return emptyMap()
val packagePartsCount = packageName.split(".").size
val result = mutableMapOf<String, MLFeatureValue>()
val packageMatchedParts = packagesInfo.packageName.matchedParts(packageName)
if (packageMatchedParts != 0) {
result["package_matched_parts"] = MLFeatureValue.numerical(packageMatchedParts)
result["package_matched_parts_relative"] = MLFeatureValue.numerical(packageMatchedParts.toDouble() / packagePartsCount)
}
val maxImportMatchedParts = packagesInfo.importPackages.matchedParts(packageName)
if (maxImportMatchedParts != 0) {
result["imports_max_matched_parts"] = MLFeatureValue.numerical(maxImportMatchedParts)
result["imports_max_matched_parts_relative"] = MLFeatureValue.numerical(maxImportMatchedParts.toDouble() / packagePartsCount)
}
return result
}
private fun getVariablesInScope(position: PsiElement, maxScope: PsiElement?, maxVariables: Int = 100): List<PsiVariable> {
val variables = mutableListOf<PsiVariable>()
val variablesProcessor = object : MacroUtil.VisibleVariablesProcessor(position, "", variables) {
override fun execute(pe: PsiElement, state: ResolveState): Boolean {
return variables.size < maxVariables && super.execute(pe, state)
}
}
PsiScopesUtil.treeWalkUp(variablesProcessor, position, maxScope)
return variables
}
private data class VariablesInfo(
val names: Set<String>,
val types: Set<PsiType>,
val names2types: Set<Pair<String, PsiType>>
)
private data class PackagesInfo(
val packageName: FqnTrie,
val importPackages: FqnTrie
)
class FqnTrie private constructor(private val level: Int) {
companion object {
fun create(): FqnTrie = FqnTrie(0)
fun withFqn(name: String): FqnTrie = create().also { it.addFqn(name) }
}
private val children = mutableMapOf<String, FqnTrie>()
fun addFqn(name: String) {
if (name.isEmpty()) return
val (prefix, postfix) = split(name)
children.getOrPut(prefix) { FqnTrie(level + 1) }.addFqn(postfix)
}
fun matchedParts(name: String): Int {
if (name.isEmpty()) return level
val (prefix, postfix) = split(name)
return children[prefix]?.matchedParts(postfix) ?: return level
}
private fun split(value: String): Pair<String, String> {
val index = value.indexOf('.')
return if (index < 0) Pair(value, "") else Pair(value.substring(0, index), value.substring(index + 1))
}
}
} | java/java-impl/src/com/intellij/codeInsight/completion/ml/JavaCompletionFeatures.kt | 2139174610 |
package com.simplemobiletools.calendar.pro.services
import android.app.IntentService
import android.content.Intent
import com.simplemobiletools.calendar.pro.extensions.cancelNotification
import com.simplemobiletools.calendar.pro.extensions.cancelPendingIntent
import com.simplemobiletools.calendar.pro.extensions.eventsDB
import com.simplemobiletools.calendar.pro.extensions.updateTaskCompletion
import com.simplemobiletools.calendar.pro.helpers.ACTION_MARK_COMPLETED
import com.simplemobiletools.calendar.pro.helpers.EVENT_ID
class MarkCompletedService : IntentService("MarkCompleted") {
@Deprecated("Deprecated in Java")
override fun onHandleIntent(intent: Intent?) {
if (intent != null && intent.action == ACTION_MARK_COMPLETED) {
val taskId = intent.getLongExtra(EVENT_ID, 0L)
val task = eventsDB.getTaskWithId(taskId)
if (task != null) {
updateTaskCompletion(task, true)
cancelPendingIntent(task.id!!)
cancelNotification(task.id!!)
}
}
}
}
| app/src/main/kotlin/com/simplemobiletools/calendar/pro/services/MarkCompletedService.kt | 2747490458 |
package de.stefanmedack.ccctv.ui.events
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.ActivityOptionsCompat
import de.stefanmedack.ccctv.R
import de.stefanmedack.ccctv.persistence.entities.Conference
import de.stefanmedack.ccctv.ui.base.BaseInjectableActivity
import de.stefanmedack.ccctv.util.FRAGMENT_ARGUMENTS
import de.stefanmedack.ccctv.util.addFragmentInTransaction
class EventsActivity : BaseInjectableActivity() {
private val EVENTS_TAG = "EVENTS_TAG"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_activity)
if (savedInstanceState == null) {
addFragmentInTransaction(
fragment = EventsFragment().apply { arguments = intent.getBundleExtra(FRAGMENT_ARGUMENTS) },
containerId = R.id.fragment,
tag = EVENTS_TAG)
}
}
companion object {
fun startForConference(activity: Activity, conference: Conference) {
val intent = Intent(activity.baseContext, EventsActivity::class.java)
intent.putExtra(FRAGMENT_ARGUMENTS, EventsFragment.getBundleForConference(
conferenceAcronym = conference.acronym,
title = conference.title,
conferenceLogoUrl = conference.logoUrl
))
activity.startActivity(intent, ActivityOptionsCompat.makeSceneTransitionAnimation(activity).toBundle())
}
fun startWithSearch(activity: Activity, searchQuery: String) {
val intent = Intent(activity.baseContext, EventsActivity::class.java)
intent.putExtra(FRAGMENT_ARGUMENTS, EventsFragment.getBundleForSearch(
searchQuery = searchQuery,
title = activity.getString(R.string.events_view_search_result_header, searchQuery)
))
activity.startActivity(intent, ActivityOptionsCompat.makeSceneTransitionAnimation(activity).toBundle())
}
}
}
| app/src/main/java/de/stefanmedack/ccctv/ui/events/EventsActivity.kt | 3457869818 |
package com.github.kerubistan.kerub.planner.steps.vm.cpuaffinity
import com.github.kerubistan.kerub.host.HostCommandExecutor
import com.github.kerubistan.kerub.planner.execution.AbstractStepExecutor
class SetCpuAffinityExecutor(private val hostExecutor: HostCommandExecutor) :
AbstractStepExecutor<SetCpuAffinity, Unit>() {
override fun perform(step: SetCpuAffinity) {
hostExecutor.execute(host = step.host) {
TODO()
}
}
override fun update(step: SetCpuAffinity, updates: Unit) {
TODO()
}
} | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/vm/cpuaffinity/SetCpuAffinityExecutor.kt | 1637613981 |
package us.nineworlds.serenity.core.logger
interface Logger {
fun initialize()
fun debug(message: String)
fun error(message: String)
fun error(message: String, error: Throwable)
fun warn(message: String)
fun info(message: String)
} | serenity-app/src/main/kotlin/us/nineworlds/serenity/core/logger/Logger.kt | 4200249747 |
/*
* Copyright 2010-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 codegen.inline.inline21
import kotlin.test.*
inline fun foo2(block2: () -> Int) : Int {
println("foo2")
return block2()
}
inline fun foo1(block1: () -> Int) : Int {
println("foo1")
return foo2(block1)
}
fun bar(block: () -> Int) : Int {
println("bar")
return foo1(block)
}
@Test fun runTest() {
println(bar { 33 })
}
| backend.native/tests/codegen/inline/inline21.kt | 1741931169 |
package com.github.kerubistan.kerub.data
import com.github.kerubistan.kerub.model.ExecutionResult
import java.util.UUID
interface ExecutionResultDao :
DaoOperations.Add<ExecutionResult, UUID>,
DaoOperations.PagedList<ExecutionResult, UUID>,
DaoOperations.SimpleSearch<ExecutionResult>
| src/main/kotlin/com/github/kerubistan/kerub/data/ExecutionResultDao.kt | 2454753466 |
// 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.spellchecker.quickfixes
import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.choice.ChoiceTitleIntentionAction
import com.intellij.codeInsight.intention.choice.ChoiceVariantIntentionAction
import com.intellij.codeInsight.intention.choice.DefaultIntentionActionWithChoice
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPointerManager
import com.intellij.refactoring.suggested.startOffset
import com.intellij.spellchecker.util.SpellCheckerBundle
class ChangeTo(typo: String, element: PsiElement, private val range: TextRange) : DefaultIntentionActionWithChoice, LazySuggestions(typo) {
private val pointer = SmartPointerManager.getInstance(element.project).createSmartPsiElementPointer(element, element.containingFile)
companion object {
@JvmStatic
val fixName: String by lazy {
SpellCheckerBundle.message("change.to.title")
}
}
private object ChangeToTitleAction : ChoiceTitleIntentionAction(fixName, fixName), HighPriorityAction
override fun getTitle(): ChoiceTitleIntentionAction = ChangeToTitleAction
private inner class ChangeToVariantAction(
override val index: Int
) : ChoiceVariantIntentionAction(), HighPriorityAction {
@NlsSafe
private var suggestion: String? = null
override fun getName(): String = suggestion ?: ""
override fun getTooltipText(): String = SpellCheckerBundle.message("change.to.tooltip", suggestion)
override fun getFamilyName(): String = fixName
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean {
val suggestions = getSuggestions(project)
if (suggestions.size <= index) return false
if (getRange(file.viewProvider.document) == null) return false
suggestion = suggestions[index]
return true
}
override fun applyFix(project: Project, file: PsiFile, editor: Editor?) {
val suggestion = suggestion ?: return
val document = file.viewProvider.document
val myRange = getRange(document) ?: return
UpdateHighlightersUtil.removeHighlightersWithExactRange(document, project, myRange)
document.replaceString(myRange.startOffset, myRange.endOffset, suggestion)
}
private fun getRange(document: Document): TextRange? {
val element = pointer.element ?: return null
val range = range.shiftRight(element.startOffset)
if (range.startOffset < 0 || range.endOffset > document.textLength) return null
val text = document.getText(range)
if (text != typo) return null
return range
}
override fun getFileModifierForPreview(target: PsiFile): FileModifier {
return this
}
override fun startInWriteAction(): Boolean = true
}
override fun getVariants(): List<ChoiceVariantIntentionAction> {
val limit = Registry.intValue("spellchecker.corrections.limit")
return (0 until limit).map { ChangeToVariantAction(it) }
}
} | spellchecker/src/com/intellij/spellchecker/quickfixes/ChangeTo.kt | 3853847732 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.integration.macrobenchmark
import android.content.Intent
import android.graphics.Point
import androidx.benchmark.macro.CompilationMode
import androidx.benchmark.macro.FrameTimingMetric
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.Until
import androidx.testutils.createCompilationParams
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@LargeTest
@RunWith(Parameterized::class)
class LazyBoxWithConstraintsScrollBenchmark(
private val compilationMode: CompilationMode
) {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
private lateinit var device: UiDevice
@Before
fun setUp() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
device = UiDevice.getInstance(instrumentation)
}
@Test
fun start() {
benchmarkRule.measureRepeated(
packageName = PACKAGE_NAME,
metrics = listOf(FrameTimingMetric()),
compilationMode = compilationMode,
iterations = 10,
setupBlock = {
val intent = Intent()
intent.action = ACTION
startActivityAndWait(intent)
}
) {
val lazyColumn = device.findObject(By.desc(CONTENT_DESCRIPTION))
// Setting a gesture margin is important otherwise gesture nav is triggered.
lazyColumn.setGestureMargin(device.displayWidth / 5)
for (i in 1..10) {
// From center we scroll 2/3 of it which is 1/3 of the screen.
lazyColumn.drag(Point(lazyColumn.visibleCenter.x, lazyColumn.visibleCenter.y / 3))
device.wait(Until.findObject(By.desc(COMPOSE_IDLE)), 3000)
}
}
}
companion object {
private const val PACKAGE_NAME = "androidx.compose.integration.macrobenchmark.target"
private const val ACTION =
"androidx.compose.integration.macrobenchmark.target.LAZY_BOX_WITH_CONSTRAINTS_ACTIVITY"
private const val CONTENT_DESCRIPTION = "IamLazy"
private const val COMPOSE_IDLE = "COMPOSE-IDLE"
@Parameterized.Parameters(name = "compilation={0}")
@JvmStatic
fun parameters() = createCompilationParams()
}
}
| compose/integration-tests/macrobenchmark/src/androidTest/java/androidx/compose/integration/macrobenchmark/LazyBoxWithConstraintsScrollBenchmark.kt | 3512898511 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.bluetooth.core
import android.bluetooth.BluetoothClass as FwkBluetoothClass
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
/**
* Represents a Bluetooth class, which describes general characteristics
* and capabilities of a device. For example, a Bluetooth class will
* specify the general device type such as a phone, a computer, or
* headset, and whether it's capable of services such as audio or telephony.
*
* <p>Every Bluetooth class is composed of zero or more service classes, and
* exactly one device class. The device class is further broken down into major
* and minor device class components.
*
* <p>{@link BluetoothClass} is useful as a hint to roughly describe a device
* (for example to show an icon in the UI), but does not reliably describe which
* Bluetooth profiles or services are actually supported by a device. Accurate
* service discovery is done through SDP requests, which are automatically
* performed when creating an RFCOMM socket with {@link
* BluetoothDevice#createRfcommSocketToServiceRecord} and {@link
* BluetoothAdapter#listenUsingRfcommWithServiceRecord}</p>
*
* <p>Use {@link BluetoothDevice#getBluetoothClass} to retrieve the class for
* a remote device.
*
* <!--
* The Bluetooth class is a 32 bit field. The format of these bits is defined at
* http://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
* (login required). This class contains that 32 bit field, and provides
* constants and methods to determine which Service Class(es) and Device Class
* are encoded in that field.
* -->
*
* @hide
*/
class BluetoothClass internal constructor(private val fwkBluetoothClass: FwkBluetoothClass) :
Bundleable {
companion object {
const val PROFILE_HEADSET = 0 // FwkBluetoothClass.PROFILE_HEADSET
const val PROFILE_A2DP = 1 // FwkBluetoothClass.PROFILE_A2DP
const val PROFILE_HID = 3 // FwkBluetoothClass.PROFILE_HID
const val PROFILE_OPP = 2
const val PROFILE_PANU = 4
private const val PROFILE_NAP = 5
private const val PROFILE_A2DP_SINK = 6
internal const val FIELD_FWK_BLUETOOTH_CLASS = 1
internal fun keyForField(field: Int): String {
return field.toString(Character.MAX_RADIX)
}
val CREATOR: Bundleable.Creator<BluetoothClass> =
object : Bundleable.Creator<BluetoothClass> {
override fun fromBundle(bundle: Bundle): BluetoothClass {
val fwkBluetoothClass = Utils.getParcelableFromBundle(
bundle,
keyForField(FIELD_FWK_BLUETOOTH_CLASS),
FwkBluetoothClass::class.java
) ?: throw IllegalArgumentException(
"Bundle doesn't include " +
"BluetoothClass instance"
)
return BluetoothClass(fwkBluetoothClass)
}
}
}
/**
* Defines all service class constants.
*
* Each [BluetoothClass] encodes zero or more service classes.
*/
object Service {
const val LIMITED_DISCOVERABILITY = FwkBluetoothClass.Service.LIMITED_DISCOVERABILITY
/** Represent devices LE audio service */
const val LE_AUDIO = FwkBluetoothClass.Service.LE_AUDIO
const val POSITIONING = FwkBluetoothClass.Service.POSITIONING
const val NETWORKING = FwkBluetoothClass.Service.NETWORKING
const val RENDER = FwkBluetoothClass.Service.RENDER
const val CAPTURE = FwkBluetoothClass.Service.CAPTURE
const val OBJECT_TRANSFER = FwkBluetoothClass.Service.OBJECT_TRANSFER
const val AUDIO = FwkBluetoothClass.Service.AUDIO
const val TELEPHONY = FwkBluetoothClass.Service.TELEPHONY
const val INFORMATION = FwkBluetoothClass.Service.INFORMATION
}
/**
* Defines all device class constants.
*
* Each [BluetoothClass] encodes exactly one device class, with
* major and minor components.
*
* The constants in [ ] represent a combination of major and minor
* device components (the complete device class). The constants in [ ] represent only major
* device classes.
*
* See [BluetoothClass.Service] for service class constants.
*/
object Device {
// Devices in the COMPUTER major class
const val COMPUTER_UNCATEGORIZED = FwkBluetoothClass.Device.COMPUTER_UNCATEGORIZED
const val COMPUTER_DESKTOP = FwkBluetoothClass.Device.COMPUTER_DESKTOP
const val COMPUTER_SERVER = FwkBluetoothClass.Device.COMPUTER_SERVER
const val COMPUTER_LAPTOP = FwkBluetoothClass.Device.COMPUTER_LAPTOP
const val COMPUTER_HANDHELD_PC_PDA = FwkBluetoothClass.Device.COMPUTER_HANDHELD_PC_PDA
const val COMPUTER_PALM_SIZE_PC_PDA = FwkBluetoothClass.Device.COMPUTER_PALM_SIZE_PC_PDA
const val COMPUTER_WEARABLE = FwkBluetoothClass.Device.COMPUTER_WEARABLE
// Devices in the PHONE major class
const val PHONE_UNCATEGORIZED = FwkBluetoothClass.Device.PHONE_UNCATEGORIZED
const val PHONE_CELLULAR = FwkBluetoothClass.Device.PHONE_CELLULAR
const val PHONE_CORDLESS = FwkBluetoothClass.Device.PHONE_CORDLESS
const val PHONE_SMART = FwkBluetoothClass.Device.PHONE_SMART
const val PHONE_MODEM_OR_GATEWAY = FwkBluetoothClass.Device.PHONE_MODEM_OR_GATEWAY
const val PHONE_ISDN = FwkBluetoothClass.Device.PHONE_ISDN
// Minor classes for the AUDIO_VIDEO major class
const val AUDIO_VIDEO_UNCATEGORIZED = FwkBluetoothClass.Device.AUDIO_VIDEO_UNCATEGORIZED
const val AUDIO_VIDEO_WEARABLE_HEADSET =
FwkBluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET
const val AUDIO_VIDEO_HANDSFREE = FwkBluetoothClass.Device.AUDIO_VIDEO_HANDSFREE
const val AUDIO_VIDEO_MICROPHONE = FwkBluetoothClass.Device.AUDIO_VIDEO_MICROPHONE
const val AUDIO_VIDEO_LOUDSPEAKER = FwkBluetoothClass.Device.AUDIO_VIDEO_LOUDSPEAKER
const val AUDIO_VIDEO_HEADPHONES = FwkBluetoothClass.Device.AUDIO_VIDEO_HEADPHONES
const val AUDIO_VIDEO_PORTABLE_AUDIO =
FwkBluetoothClass.Device.AUDIO_VIDEO_PORTABLE_AUDIO
const val AUDIO_VIDEO_CAR_AUDIO = FwkBluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO
const val AUDIO_VIDEO_SET_TOP_BOX = FwkBluetoothClass.Device.AUDIO_VIDEO_SET_TOP_BOX
const val AUDIO_VIDEO_HIFI_AUDIO = FwkBluetoothClass.Device.AUDIO_VIDEO_HIFI_AUDIO
const val AUDIO_VIDEO_VCR = FwkBluetoothClass.Device.AUDIO_VIDEO_VCR
const val AUDIO_VIDEO_VIDEO_CAMERA = FwkBluetoothClass.Device.AUDIO_VIDEO_VIDEO_CAMERA
const val AUDIO_VIDEO_CAMCORDER = FwkBluetoothClass.Device.AUDIO_VIDEO_CAMCORDER
const val AUDIO_VIDEO_VIDEO_MONITOR = FwkBluetoothClass.Device.AUDIO_VIDEO_VIDEO_MONITOR
const val AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER =
FwkBluetoothClass.Device.AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER
const val AUDIO_VIDEO_VIDEO_CONFERENCING =
FwkBluetoothClass.Device.AUDIO_VIDEO_VIDEO_CONFERENCING
const val AUDIO_VIDEO_VIDEO_GAMING_TOY =
FwkBluetoothClass.Device.AUDIO_VIDEO_VIDEO_GAMING_TOY
// Devices in the WEARABLE major class
const val WEARABLE_UNCATEGORIZED = FwkBluetoothClass.Device.WEARABLE_UNCATEGORIZED
const val WEARABLE_WRIST_WATCH = FwkBluetoothClass.Device.WEARABLE_WRIST_WATCH
const val WEARABLE_PAGER = FwkBluetoothClass.Device.WEARABLE_PAGER
const val WEARABLE_JACKET = FwkBluetoothClass.Device.WEARABLE_JACKET
const val WEARABLE_HELMET = FwkBluetoothClass.Device.WEARABLE_HELMET
const val WEARABLE_GLASSES = FwkBluetoothClass.Device.WEARABLE_GLASSES
// Devices in the TOY major class
const val TOY_UNCATEGORIZED = FwkBluetoothClass.Device.TOY_UNCATEGORIZED
const val TOY_ROBOT = FwkBluetoothClass.Device.TOY_ROBOT
const val TOY_VEHICLE = FwkBluetoothClass.Device.TOY_VEHICLE
const val TOY_DOLL_ACTION_FIGURE = FwkBluetoothClass.Device.TOY_DOLL_ACTION_FIGURE
const val TOY_CONTROLLER = FwkBluetoothClass.Device.TOY_CONTROLLER
const val TOY_GAME = FwkBluetoothClass.Device.TOY_GAME
// Devices in the HEALTH major class
const val HEALTH_UNCATEGORIZED = FwkBluetoothClass.Device.HEALTH_UNCATEGORIZED
const val HEALTH_BLOOD_PRESSURE = FwkBluetoothClass.Device.HEALTH_BLOOD_PRESSURE
const val HEALTH_THERMOMETER = FwkBluetoothClass.Device.HEALTH_THERMOMETER
const val HEALTH_WEIGHING = FwkBluetoothClass.Device.HEALTH_WEIGHING
const val HEALTH_GLUCOSE = FwkBluetoothClass.Device.HEALTH_GLUCOSE
const val HEALTH_PULSE_OXIMETER = FwkBluetoothClass.Device.HEALTH_PULSE_OXIMETER
const val HEALTH_PULSE_RATE = FwkBluetoothClass.Device.HEALTH_PULSE_RATE
const val HEALTH_DATA_DISPLAY = FwkBluetoothClass.Device.HEALTH_DATA_DISPLAY
// Devices in PERIPHERAL major class
const val PERIPHERAL_NON_KEYBOARD_NON_POINTING =
0x0500 // FwkBluetoothClass.Device.PERIPHERAL_NON_KEYBOARD_NON_POINTING
const val PERIPHERAL_KEYBOARD =
0x0540 // FwkBluetoothClass.Device.PERIPHERAL_KEYBOARD
const val PERIPHERAL_POINTING =
0x0580 // FwkBluetoothClass.Device.PERIPHERAL_POINTING
const val PERIPHERAL_KEYBOARD_POINTING =
0x05C0 // FwkBluetoothClass.Device.PERIPHERAL_KEYBOARD_POINTING
/**
* Defines all major device class constants.
*
* See [BluetoothClass.Device] for minor classes.
*/
object Major {
const val MISC = FwkBluetoothClass.Device.Major.MISC
const val COMPUTER = FwkBluetoothClass.Device.Major.COMPUTER
const val PHONE = FwkBluetoothClass.Device.Major.PHONE
const val NETWORKING = FwkBluetoothClass.Device.Major.NETWORKING
const val AUDIO_VIDEO = FwkBluetoothClass.Device.Major.AUDIO_VIDEO
const val PERIPHERAL = FwkBluetoothClass.Device.Major.PERIPHERAL
const val IMAGING = FwkBluetoothClass.Device.Major.IMAGING
const val WEARABLE = FwkBluetoothClass.Device.Major.WEARABLE
const val TOY = FwkBluetoothClass.Device.Major.TOY
const val HEALTH = FwkBluetoothClass.Device.Major.HEALTH
const val UNCATEGORIZED = FwkBluetoothClass.Device.Major.UNCATEGORIZED
}
}
/**
* Return the major device class component of this [BluetoothClass].
*
* Values returned from this function can be compared with the
* public constants in [BluetoothClass.Device.Major] to determine
* which major class is encoded in this Bluetooth class.
*
* @return major device class component
*/
val majorDeviceClass: Int
get() = fwkBluetoothClass.majorDeviceClass
/**
* Return the (major and minor) device class component of this
* [BluetoothClass].
*
* Values returned from this function can be compared with the
* public constants in [BluetoothClass.Device] to determine which
* device class is encoded in this Bluetooth class.
*
* @return device class component
*/
val deviceClass: Int
get() = fwkBluetoothClass.deviceClass
/**
* Return true if the specified service class is supported by this
* [BluetoothClass].
*
* Valid service classes are the public constants in
* [BluetoothClass.Service]. For example, [ ][BluetoothClass.Service.AUDIO].
*
* @param service valid service class
* @return true if the service class is supported
*/
fun hasService(service: Int): Boolean {
return fwkBluetoothClass.hasService(service)
}
override fun toBundle(): Bundle {
val bundle = Bundle()
bundle.putParcelable(keyForField(FIELD_FWK_BLUETOOTH_CLASS), fwkBluetoothClass)
return bundle
}
@SuppressLint("ClassVerificationFailure") // fwkBluetoothClass.doesClassMatch(profile)
fun doesClassMatch(profile: Int): Boolean {
if (Build.VERSION.SDK_INT >= 33) {
// TODO: change to Impl hierarchy when additional SDK checks are needed
return fwkBluetoothClass.doesClassMatch(profile)
}
return when (profile) {
PROFILE_A2DP -> {
if (hasService(Service.RENDER)) {
return true
}
when (deviceClass) {
Device.AUDIO_VIDEO_HIFI_AUDIO, Device.AUDIO_VIDEO_HEADPHONES,
Device.AUDIO_VIDEO_LOUDSPEAKER, Device.AUDIO_VIDEO_CAR_AUDIO -> true
else -> false
}
}
PROFILE_A2DP_SINK -> {
if (hasService(Service.CAPTURE)) {
return true
}
when (deviceClass) {
Device.AUDIO_VIDEO_HIFI_AUDIO, Device.AUDIO_VIDEO_SET_TOP_BOX,
Device.AUDIO_VIDEO_VCR -> true
else -> false
}
}
PROFILE_HEADSET -> {
if (hasService(Service.RENDER)) {
return true
}
when (deviceClass) {
Device.AUDIO_VIDEO_HANDSFREE, Device.AUDIO_VIDEO_WEARABLE_HEADSET,
Device.AUDIO_VIDEO_CAR_AUDIO -> true
else -> false
}
}
PROFILE_OPP -> {
if (hasService(Service.OBJECT_TRANSFER)) {
return true
}
when (deviceClass) {
Device.COMPUTER_UNCATEGORIZED, Device.COMPUTER_DESKTOP, Device.COMPUTER_SERVER,
Device.COMPUTER_LAPTOP, Device.COMPUTER_HANDHELD_PC_PDA,
Device.COMPUTER_PALM_SIZE_PC_PDA, Device.COMPUTER_WEARABLE,
Device.PHONE_UNCATEGORIZED, Device.PHONE_CELLULAR, Device.PHONE_CORDLESS,
Device.PHONE_SMART, Device.PHONE_MODEM_OR_GATEWAY, Device.PHONE_ISDN -> true
else -> false
}
}
PROFILE_HID -> {
majorDeviceClass == Device.Major.PERIPHERAL
}
PROFILE_NAP, PROFILE_PANU -> {
if (hasService(Service.NETWORKING)) {
true
} else majorDeviceClass == Device.Major.NETWORKING
}
else -> false
}
}
} | bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/BluetoothClass.kt | 2519054620 |
package de.droidcon.berlin2018.search
import io.reactivex.Observable
import timber.log.Timber
/**
* The default search engine that searches all registered [SearchSource]
*
* @author Hannes Dorfmann
*/
class DefaultSearchEngine(private val searchSources: List<SearchSource>) : SearchEngine {
override fun search(query: String): Observable<List<SearchableItem>> {
var errorsCount = 0
val errorCatchingSources = searchSources.map { source ->
source.search(query).onErrorReturn {
errorsCount++
Timber.e(it, "Error in SearchSource $source")
if (errorsCount < searchSources.size) {
emptyList()
} else {
throw it
}
}
}
return Observable.combineLatest(errorCatchingSources, {
/*
val result = ArrayList<SearchableItem>()
it.forEach {
result.addAll(it as List<SearchableItem>)
}
result
*/
it.flatMap { it as List<SearchableItem> }
})
}
}
| businesslogic/search/src/main/java/de/droidcon/berlin2018/search/DefaultSearchEngine.kt | 383561913 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.benchmark
import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.util.Log
import android.view.WindowManager
import android.widget.TextView
import androidx.annotation.AnyThread
import androidx.annotation.RestrictTo
import androidx.annotation.WorkerThread
import androidx.test.platform.app.InstrumentationRegistry
import java.util.concurrent.atomic.AtomicReference
import kotlin.concurrent.thread
/**
* Simple opaque activity used to reduce benchmark interference from other windows.
*
* For example, sources of potential interference:
* - live wallpaper rendering
* - homescreen widget updates
* - hotword detection
* - status bar repaints
* - running in background (some cores may be foreground-app only)
*
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class IsolationActivity : android.app.Activity() {
private var destroyed = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.isolation_activity)
// disable launch animation
overridePendingTransition(0, 0)
if (firstInit) {
if (!CpuInfo.locked && isSustainedPerformanceModeSupported()) {
@Suppress("SyntheticAccessor")
sustainedPerformanceModeInUse = true
}
application.registerActivityLifecycleCallbacks(activityLifecycleCallbacks)
// trigger the one missed lifecycle event, from registering the callbacks late
activityLifecycleCallbacks.onActivityCreated(this, savedInstanceState)
if (sustainedPerformanceModeInUse) {
// Keep at least one core busy. Together with a single threaded benchmark, this
// makes the process get multi-threaded setSustainedPerformanceMode.
//
// We want to keep to the relatively lower clocks of the multi-threaded benchmark
// mode to avoid any benchmarks running at higher clocks than any others.
//
// Note, thread names have 15 char max in Systrace
thread(name = "BenchSpinThread") {
Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST)
while (true) {
}
}
}
firstInit = false
}
val old = singleton.getAndSet(this)
if (old != null && !old.destroyed && !old.isFinishing) {
throw IllegalStateException("Only one IsolationActivity should exist")
}
findViewById<TextView>(R.id.clock_state).text = when {
CpuInfo.locked -> "Locked Clocks"
sustainedPerformanceModeInUse -> "Sustained Performance Mode"
else -> ""
}
}
override fun onResume() {
super.onResume()
@Suppress("SyntheticAccessor")
resumed = true
}
override fun onPause() {
super.onPause()
@Suppress("SyntheticAccessor")
resumed = false
}
override fun onDestroy() {
super.onDestroy()
destroyed = true
}
/** finish is ignored! we defer until [actuallyFinish] is called. */
override fun finish() {
}
public fun actuallyFinish() {
// disable close animation
overridePendingTransition(0, 0)
super.finish()
}
public companion object {
private const val TAG = "Benchmark"
internal val singleton = AtomicReference<IsolationActivity>()
private var firstInit = true
internal var sustainedPerformanceModeInUse = false
private set
public var resumed: Boolean = false
private set
@WorkerThread
public fun launchSingleton() {
val intent = Intent(Intent.ACTION_MAIN).apply {
Log.d(TAG, "launching Benchmark IsolationActivity")
setClassName(
InstrumentationRegistry.getInstrumentation().targetContext.packageName,
IsolationActivity::class.java.name
)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
InstrumentationRegistry.getInstrumentation().startActivitySync(intent)
}
@AnyThread
public fun finishSingleton() {
Log.d(TAG, "Benchmark runner being destroyed, tearing down activities")
singleton.getAndSet(null)?.apply {
runOnUiThread {
actuallyFinish()
}
}
}
internal fun isSustainedPerformanceModeSupported(): Boolean =
if (Build.VERSION.SDK_INT >= 24) {
InstrumentationRegistry
.getInstrumentation()
.isSustainedPerformanceModeSupported()
} else {
false
}
private val activityLifecycleCallbacks = object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
if (sustainedPerformanceModeInUse && Build.VERSION.SDK_INT >= 24) {
activity.setSustainedPerformanceMode(true)
}
// Forcibly wake the device, and keep the screen on to prevent benchmark failures.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
activity.requestDismissKeyguard()
activity.setShowWhenLocked()
activity.setTurnScreenOn()
activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
@Suppress("DEPRECATION")
activity.window.addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
)
}
}
override fun onActivityDestroyed(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityResumed(activity: Activity) {}
}
}
} | benchmark/benchmark-common/src/main/java/androidx/benchmark/IsolationActivity.kt | 3218581580 |
package data.account
internal object AccountComponentHolder {
lateinit var accountComponent: AccountComponent
}
| data/src/main/kotlin/data/account/AccountComponentHolder.kt | 1352463 |
package com.intellij.cce.actions
abstract class CompletionPrefixCreator(val completePrevious: Boolean) {
abstract fun getPrefix(text: String): String
}
class NoPrefixCreator : CompletionPrefixCreator(false) {
override fun getPrefix(text: String): String {
return ""
}
}
class SimplePrefixCreator(completePrevious: Boolean, private val n: Int) : CompletionPrefixCreator(completePrevious) {
override fun getPrefix(text: String): String {
return if (text.length < n) return text else text.substring(0, n)
}
}
class CapitalizePrefixCreator(completePrevious: Boolean) : CompletionPrefixCreator(completePrevious) {
override fun getPrefix(text: String): String {
return text.filterIndexed { i, ch -> i == 0 || ch.isUpperCase() }
}
} | plugins/evaluation-plugin/core/src/com/intellij/cce/actions/CompletionPrefixCreator.kt | 3178324139 |
// 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.collaboration.api.httpclient
import java.net.http.HttpRequest
open class CommonHeadersConfigurer : HttpRequestConfigurer {
protected open val commonHeaders: Map<String, String> =
mapOf("Accept-Encoding" to "gzip",
"User-Agent" to "JetBrains IDE")
final override fun configure(builder: HttpRequest.Builder): HttpRequest.Builder = builder
.apply { commonHeaders.forEach(::header) }
} | platform/collaboration-tools/src/com/intellij/collaboration/api/httpclient/CommonHeadersConfigurer.kt | 2897605138 |
/*
* Copyright (C) 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 com.example.android.dagger.registration
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.android.dagger.MyApplication
import com.example.android.dagger.R
import com.example.android.dagger.main.MainActivity
import com.example.android.dagger.registration.enterdetails.EnterDetailsFragment
import com.example.android.dagger.registration.termsandconditions.TermsAndConditionsFragment
import javax.inject.Inject
class RegistrationActivity : AppCompatActivity() {
// Stores an instance of RegistrationComponent so that its Fragments can access it
lateinit var registrationComponent: RegistrationComponent
// @Inject annotated fields will be provided by Dagger
@Inject
lateinit var registrationViewModel: RegistrationViewModel
override fun onCreate(savedInstanceState: Bundle?) {
// Creates an instance of Registration component by grabbing the factory from the app graph
registrationComponent = (application as MyApplication).appComponent
.registrationComponent().create()
// Injects this activity to the just created Registration component
registrationComponent.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_registration)
supportFragmentManager.beginTransaction()
.add(R.id.fragment_holder, EnterDetailsFragment())
.commit()
}
/**
* Callback from EnterDetailsFragment when username and password has been entered
*/
fun onDetailsEntered() {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_holder, TermsAndConditionsFragment())
.addToBackStack(TermsAndConditionsFragment::class.java.simpleName)
.commit()
}
/**
* Callback from T&CsFragment when TCs have been accepted
*/
fun onTermsAndConditionsAccepted() {
registrationViewModel.registerUser()
startActivity(Intent(this, MainActivity::class.java))
finish()
}
override fun onBackPressed() {
if (supportFragmentManager.backStackEntryCount > 0) {
supportFragmentManager.popBackStack()
} else {
super.onBackPressed()
}
}
}
| app/src/main/java/com/example/android/dagger/registration/RegistrationActivity.kt | 3320096975 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class ExplicitThisInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitExpression(expression: KtExpression) {
val thisExpression = expression.thisAsReceiverOrNull() ?: return
if (hasExplicitThis(expression)) {
holder.registerProblem(
thisExpression,
KotlinBundle.message("redundant.explicit.this"),
ExplicitThisExpressionFix(thisExpression.text)
)
}
}
}
companion object {
fun KtExpression.thisAsReceiverOrNull() = when (this) {
is KtCallableReferenceExpression -> receiverExpression as? KtThisExpression
is KtDotQualifiedExpression -> receiverExpression as? KtThisExpression
else -> null
}
fun hasExplicitThis(expression: KtExpression): Boolean {
val thisExpression = expression.thisAsReceiverOrNull() ?: return false
val reference = when (expression) {
is KtCallableReferenceExpression -> expression.callableReference
is KtDotQualifiedExpression -> expression.selectorExpression as? KtReferenceExpression
else -> null
} ?: return false
val context = expression.analyze()
val scope = expression.getResolutionScope(context) ?: return false
val referenceExpression = reference as? KtNameReferenceExpression ?: reference.getChildOfType() ?: return false
val receiverType = context[BindingContext.EXPRESSION_TYPE_INFO, thisExpression]?.type ?: return false
//we avoid overload-related problems by enforcing that there is only one candidate
val name = referenceExpression.getReferencedNameAsName()
val candidates = if (reference is KtCallExpression
|| (expression is KtCallableReferenceExpression && reference.mainReference.resolve() is KtFunction)
) {
scope.getAllAccessibleFunctions(name) +
scope.getAllAccessibleVariables(name).filter { it is LocalVariableDescriptor && it.canInvoke() }
} else {
scope.getAllAccessibleVariables(name)
}
if (referenceExpression.getCallableDescriptor() is SyntheticJavaPropertyDescriptor) {
if (candidates.map { it.containingDeclaration }.distinct().size != 1) return false
} else {
val candidate = candidates.singleOrNull() ?: return false
val extensionType = candidate.extensionReceiverParameter?.type
if (extensionType != null && extensionType != receiverType && receiverType.isSubtypeOf(extensionType)) return false
}
val expressionFactory = scope.getFactoryForImplicitReceiverWithSubtypeOf(receiverType) ?: return false
val label = thisExpression.getLabelName() ?: ""
if (!expressionFactory.matchesLabel(label)) return false
return true
}
private fun VariableDescriptor.canInvoke(): Boolean {
val declarationDescriptor = this.type.constructor.declarationDescriptor as? LazyClassDescriptor ?: return false
return declarationDescriptor.declaredCallableMembers.any { (it as? FunctionDescriptor)?.isOperator == true }
}
private fun ReceiverExpressionFactory.matchesLabel(label: String): Boolean {
val implicitLabel = expressionText.substringAfter("@", "")
return label == implicitLabel || (label == "" && isImmediate)
}
}
}
class ExplicitThisExpressionFix(private val text: String) : LocalQuickFix {
override fun getFamilyName(): String = KotlinBundle.message("explicit.this.expression.fix.family.name", text)
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val thisExpression = descriptor.psiElement as? KtThisExpression ?: return
removeExplicitThisExpression(thisExpression)
}
companion object {
fun removeExplicitThisExpression(thisExpression: KtThisExpression) {
when (val parent = thisExpression.parent) {
is KtDotQualifiedExpression -> parent.replace(parent.selectorExpression ?: return)
is KtCallableReferenceExpression -> thisExpression.delete()
}
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ExplicitThisInspection.kt | 2283730034 |
// 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.slicer
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.idea.multiplatform.setupMppProjectFromDirStructure
import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.extractMarkerOffset
import org.jetbrains.kotlin.idea.test.findFileWithCaret
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import java.io.File
abstract class AbstractSlicerMultiplatformTest : AbstractMultiModuleTest() {
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("slicer/mpp")
protected fun doTest(filePath: String) {
val testRoot = File(filePath)
setupMppProjectFromDirStructure(testRoot)
val file = project.findFileWithCaret() as KtFile
val document = PsiDocumentManager.getInstance(myProject).getDocument(file)!!
val offset = document.extractMarkerOffset(project, "<caret>")
testSliceFromOffset(file, offset) { _, rootNode ->
KotlinTestUtils.assertEqualsToFile(testRoot.resolve("results.txt"), buildTreeRepresentation(rootNode))
}
}
}
| plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/slicer/AbstractSlicerMultiplatformTest.kt | 1256617270 |
package unboxParam
fun main(args: Array<String>) {
val nullableInt = fooNullableInt()
if (nullableInt == null) {
return
}
// EXPRESSION: fooInt(nullableInt)
// RESULT: 1: I
//Breakpoint!
val a = fooInt(nullableInt)
}
fun fooNullableInt(): Int? = 1
fun fooInt(param: Int) = param | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/unboxParam.kt | 662410948 |
package org.jetbrains.completion.full.line.java.formatters
internal sealed class JavaFilesPsiCodeFormatterTest : JavaPsiCodeFormatterTest() {
protected abstract val folder: String
protected fun doTest(vararg tokens: String) {
testFile("$folder/${getTestName(true)}.java", tokens.asList(), "java")
}
internal class InsideFunctionTests : JavaFilesPsiCodeFormatterTest() {
override val folder = "inside-function"
fun testData1() = doTest("f")
fun testData2() = doTest("System", ".", "out", ".", "println", "(")
fun testData3() = doTest("f", "(", ")")
fun testData4() = doTest("System", ".", "out", ".", "println", "(", "\"main functio")
fun testData5() = doTest("in")
fun testData6() = doTest()
fun testData7() = doTest("int", "y", "=")
fun testData8() = doTest("int", "y", "=")
fun testData9() = doTest("Stream", ".", "of", "(", "1", ",", "2", ")", ".", "map", "(", "x", "->", "x", ")", ".", "forEach", "(")
fun testData10() = doTest("int", "y", "=")
fun testData11() = doTest("for", "(", "int", "i", "=", "0", ";", "i", "<", "10", ";")
fun testData12() = doTest()
fun testData13() = doTest("this", ".", "x")
fun testData14() = doTest("f", "(", ")")
fun testData15() = doTest()
}
internal class InsideClass : JavaFilesPsiCodeFormatterTest() {
override val folder = "inside-class"
fun testData1() = doTest("public", "seco")
fun testData2() = doTest("private", "int")
fun testData3() = doTest("pr")
fun testData4() = doTest()
fun testData5() = doTest("private")
fun testData6() = doTest()
fun testData7() = doTest("pri")
fun testData8() = doTest("int")
fun testData9() = doTest("in")
fun testData10() = doTest("vo")
fun testData11() = doTest("public", "vo")
fun testData12() = doTest("public", "vo")
fun testData13() = doTest("vo")
fun testData14() = doTest("void", "f", "(")
fun testData15() = doTest("void", "f", "(", "0", "<", "1", ",", "10", ",")
// TODO optimize prefix
fun testData16() = doTest("@", "Annotation1", "@", "Annotation2")
// TODO optimize prefix
fun testData17() = doTest("@", "Annotation1", "@", "Annotati")
fun testData18() = doTest("vo")
fun testData19() = doTest("public", "vo")
fun testData20() = doTest("public", "void", "g")
fun testData21() = doTest("private", "int", "x")
// TODO keep javadoc in json
fun testData22() = doTest("public", "static", "void", "mai")
}
internal class InsideFile : JavaFilesPsiCodeFormatterTest() {
override val folder = "inside-file"
fun testData1() = doTest()
fun testData2() = doTest("package", "mock_data", ".")
fun testData3() = doTest()
fun testData4() = doTest()
fun testData5() = doTest("import", "java", ".")
fun testData6() = doTest("public", "class", "Ma")
fun testData7() = doTest("public", "class", "List")
fun testData8() = doTest("public", "class", "List", "extend")
fun testData9() = doTest("public", "class", "List", "extends")
fun testData10() = doTest("imp")
fun testData11() = doTest("import")
}
}
| plugins/full-line/java/test/org/jetbrains/completion/full/line/java/formatters/JavaFilesPsiCodeFormatterTest.kt | 3221091743 |
import p1.sleep
// "Import function 'sleep'" "true"
// WITH_STDLIB
// FULL_JDK
// ERROR: Unresolved reference: sleep
/* IGNORE_FIR */
fun usage() {
sleep<caret>()
}
| plugins/kotlin/idea/tests/testData/quickfix/autoImports/memberWithTopLevelConflict.after.kt | 1727500020 |
/*
* Copyright (C) 2016 yuzumone
*
* 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 net.yuzumone.sdnmonitor.util
interface OnToggleElevationListener {
fun onToggleElevation(bool: Boolean)
} | app/src/main/kotlin/net/yuzumone/sdnmonitor/util/OnToggleElevationListener.kt | 2226913841 |
package com.dg.controls
import android.content.Context
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import android.util.AttributeSet
@Suppress("unused")
class SwipeRefreshLayoutEx : SwipeRefreshLayout
{
private var mMeasured = false
private var mHasPostponedSetRefreshing = false
private var mPreMeasureRefreshing = false
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
// There's a bug where setRefreshing(...) before onMeasure() has no effect at all.
if (!mMeasured)
{
mMeasured = true
if (mHasPostponedSetRefreshing)
{
isRefreshing = mPreMeasureRefreshing
}
}
}
override fun setRefreshing(refreshing: Boolean)
{
if (mMeasured)
{
mHasPostponedSetRefreshing = false
super.setRefreshing(refreshing)
}
else
{
// onMeasure was not called yet, so we postpone the setRefreshing until after onMeasure
mHasPostponedSetRefreshing = true
mPreMeasureRefreshing = refreshing
}
}
}
| Helpers/src/main/java/com/dg/controls/SwipeRefreshLayoutEx.kt | 1432947490 |
package io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
data class TagSuggestionResponse(
@JsonProperty("tag") val tag: String,
@JsonProperty("followers") val followers: Int
) | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/pojo/apiv2/models/TagSuggestionResponse.kt | 4242057965 |
package org.jetbrains.plugins.notebooks.visualization.outputs.impl
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.ui.IdeBorderFactory
import org.jetbrains.plugins.notebooks.visualization.outputs.NotebookOutputComponentWrapper
import org.jetbrains.plugins.notebooks.visualization.outputs.getEditorBackground
import org.jetbrains.plugins.notebooks.visualization.ui.registerEditorSizeWatcher
import org.jetbrains.plugins.notebooks.visualization.ui.textEditingAreaWidth
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.Insets
import javax.swing.JPanel
internal class SurroundingComponent private constructor(private val innerComponent: InnerComponent) : JPanel(
BorderLayout()) {
private var presetWidth = 0
init {
border = IdeBorderFactory.createEmptyBorder(Insets(10, 0, 0, 0))
add(innerComponent, BorderLayout.CENTER)
}
override fun updateUI() {
super.updateUI()
isOpaque = true
background = getEditorBackground()
}
override fun getPreferredSize(): Dimension = super.getPreferredSize().also {
it.width = presetWidth
// No need to show anything for the empty component
if (innerComponent.preferredSize.height == 0) {
it.height = 0
}
}
companion object {
@JvmStatic
fun create(
editor: EditorImpl,
innerComponent: InnerComponent,
) = SurroundingComponent(innerComponent).also {
registerEditorSizeWatcher(it) {
val oldWidth = it.presetWidth
it.presetWidth = editor.textEditingAreaWidth
if (oldWidth != it.presetWidth) {
innerComponent.revalidate()
}
}
for (wrapper in NotebookOutputComponentWrapper.EP_NAME.extensionList) {
wrapper.wrap(it)
}
}
}
} | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/outputs/impl/SurroundingComponent.kt | 1021236905 |
// 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.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.getLineNumber
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
class AddBracesIntention : SelfTargetingIntention<KtElement>(KtElement::class.java, KotlinBundle.lazyMessage("add.braces")) {
override fun isApplicableTo(element: KtElement, caretOffset: Int): Boolean {
val expression = element.getTargetExpression(caretOffset) ?: return false
if (expression is KtBlockExpression) return false
return when (val parent = expression.parent) {
is KtContainerNode -> {
val description = parent.description() ?: return false
setTextGetter(KotlinBundle.lazyMessage("add.braces.to.0.statement", description))
true
}
is KtWhenEntry -> {
setTextGetter(KotlinBundle.lazyMessage("add.braces.to.when.entry"))
true
}
else -> {
false
}
}
}
override fun applyTo(element: KtElement, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val expression = element.getTargetExpression(editor.caretModel.offset) ?: return
addBraces(element, expression)
}
private fun KtElement.getTargetExpression(caretLocation: Int): KtExpression? {
return when (this) {
is KtIfExpression -> {
val thenExpr = then ?: return null
val elseExpr = `else`
if (elseExpr != null && caretLocation >= (elseKeyword?.startOffset ?: return null)) {
elseExpr
} else {
thenExpr
}
}
is KtLoopExpression -> body
is KtWhenEntry -> expression
else -> null
}
}
companion object {
fun addBraces(element: KtElement, expression: KtExpression) {
val psiFactory = KtPsiFactory(element)
val semicolon = element.getNextSiblingIgnoringWhitespaceAndComments()?.takeIf { it.node.elementType == KtTokens.SEMICOLON }
if (semicolon != null) {
val afterSemicolon = semicolon.getNextSiblingIgnoringWhitespace()
if (semicolon.getLineNumber() == afterSemicolon?.getLineNumber())
semicolon.replace(psiFactory.createNewLine())
else
semicolon.delete()
}
val nextComment = when {
element is KtDoWhileExpression -> null // bound to the closing while
element is KtIfExpression && expression === element.then && element.`else` != null -> null // bound to else
else -> {
val nextSibling = element.getNextSiblingIgnoringWhitespace() ?: element.parent.getNextSiblingIgnoringWhitespace()
nextSibling.takeIf { it is PsiComment && it.getLineNumber() == element.getLineNumber(start = false) }
}
}
nextComment?.delete()
val allChildren = element.allChildren
val (first, last) = when (element) {
is KtIfExpression -> element.rightParenthesis to allChildren.last
is KtForExpression -> element.rightParenthesis to allChildren.last
is KtWhileExpression -> element.rightParenthesis to allChildren.last
is KtWhenEntry -> element.arrow to allChildren.last
is KtDoWhileExpression -> allChildren.first to element.whileKeyword
else -> null to null
}
val saver = if (first != null && last != null) {
val range = PsiChildRange(first, last)
CommentSaver(range).also {
range.filterIsInstance<PsiComment>().toList().forEach { it.delete() }
}
} else {
null
}
val result = expression.replace(psiFactory.createSingleStatementBlock(expression, nextComment = nextComment?.text))
when (element) {
is KtDoWhileExpression ->
// remove new line between '}' and while
(element.body?.parent?.nextSibling as? PsiWhiteSpace)?.delete()
is KtIfExpression ->
(result?.parent?.nextSibling as? PsiWhiteSpace)?.delete()
}
saver?.restore(result, forceAdjustIndent = false)
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddBracesIntention.kt | 2893056206 |
// "Create parameter 'foo'" "false"
// ACTION: Convert property initializer to getter
// ACTION: Convert to lazy property
// ACTION: Create property 'foo'
// ACTION: Do not show return expression hints
// ACTION: Rename reference
// ERROR: Unresolved reference: foo
class A {
companion object {
val test: Int = <caret>foo
}
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/parameter/inPropertyInitializerInClassObject.kt | 3478078690 |
package com.maly.presentation.event
import com.maly.domain.event.Event
import com.maly.presentation.building.BuildingModel
/**
* @author Aleksander Brzozowski
*/
class BuildingGroupEventsModel(val building: BuildingModel, val events: List<EventModel>) {
companion object {
fun of(events: List<Event>): List<BuildingGroupEventsModel> {
return events.groupBy { it.room.building }
.map { (building, events) ->
BuildingGroupEventsModel(
building = BuildingModel.map(building),
events = events.map { EventModel.of(it) }
)
}
}
}
} | src/main/kotlin/com/maly/presentation/event/BuildingGroupEventsModel.kt | 2327338408 |
// 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.diagnostic.startUpPerformanceReporter
import com.intellij.diagnostic.StartUpPerformanceService
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import it.unimi.dsi.fastutil.objects.Object2IntMaps
import java.util.concurrent.atomic.AtomicBoolean
// todo `com.intellij.internal.statistic` package should be moved out of platform-impl module to own,
// and then this will be class moved to corresponding `intellij.platform.diagnostic` module
internal class StartupMetricCollector : StartupActivity.Background {
private var wasReported = AtomicBoolean(false)
init {
val app = ApplicationManager.getApplication()
if (app.isUnitTestMode || app.isHeadlessEnvironment) {
throw ExtensionNotApplicableException.create()
}
}
override fun runActivity(project: Project) {
if (!wasReported.compareAndSet(false, true)) {
return
}
val metrics = StartUpPerformanceService.getInstance().getMetrics() ?: return
for (entry in Object2IntMaps.fastIterable(metrics)) {
StartupPerformanceCollector.logEvent(entry.key, entry.intValue)
}
}
} | platform/platform-impl/src/com/intellij/diagnostic/startUpPerformanceReporter/StartupMetricCollector.kt | 967565127 |
// FIR_IDENTICAL
// FIR_COMPARISON
package Tests
class A : java.<caret>
// EXIST: lang, util, io
// ABSENT: fun, val, var, package
| plugins/kotlin/completion/tests/testData/basic/java/JavaPackage.kt | 144353305 |
// 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 com.intellij.psi.PsiComment
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.prevLeafs
import org.jetbrains.kotlin.builtins.extractParameterNameFromFunctionTypeArgument
import org.jetbrains.kotlin.builtins.functions.FunctionInvokeDescriptor
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.core.resolveCandidates
import org.jetbrains.kotlin.idea.intentions.AddNamesInCommentToJavaCallArgumentsIntention.Companion.toCommentedParameterName
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.descriptors.JavaClassConstructorDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.util.getCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.isAnnotationConstructor
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
fun provideArgumentNameHints(element: KtCallElement): List<InlayInfo> {
if (element.valueArguments.none { it.getArgumentExpression()?.isUnclearExpression() == true }) return emptyList()
val ctx = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val call = element.getCall(ctx) ?: return emptyList()
val resolvedCall = call.getResolvedCall(ctx)
if (resolvedCall != null) {
return getArgumentNameHintsForCallCandidate(resolvedCall, call.valueArgumentList)
}
val candidates = call.resolveCandidates(ctx, element.getResolutionFacade())
if (candidates.isEmpty()) return emptyList()
candidates.singleOrNull()?.let { return getArgumentNameHintsForCallCandidate(it, call.valueArgumentList) }
return candidates.map { getArgumentNameHintsForCallCandidate(it, call.valueArgumentList) }.reduce { infos1, infos2 ->
for (index in infos1.indices) {
if (index >= infos2.size || infos1[index] != infos2[index]) {
return@reduce infos1.subList(0, index)
}
}
infos1
}
}
private fun getArgumentNameHintsForCallCandidate(
resolvedCall: ResolvedCall<out CallableDescriptor>,
valueArgumentList: KtValueArgumentList?
): List<InlayInfo> {
val resultingDescriptor = resolvedCall.resultingDescriptor
if (resultingDescriptor.hasSynthesizedParameterNames() && resultingDescriptor !is FunctionInvokeDescriptor) {
return emptyList()
}
if (resultingDescriptor.valueParameters.size == 1
&& resultingDescriptor.name == resultingDescriptor.valueParameters.single().name
) {
// method name equals to single parameter name
return emptyList()
}
return resolvedCall.valueArguments.mapNotNull { (valueParam: ValueParameterDescriptor, resolvedArg) ->
if (resultingDescriptor.isAnnotationConstructor() && valueParam.name.asString() == "value") {
return@mapNotNull null
}
if (resultingDescriptor is FunctionInvokeDescriptor &&
valueParam.type.extractParameterNameFromFunctionTypeArgument() == null
) {
return@mapNotNull null
}
if (resolvedArg == resolvedCall.valueArgumentsByIndex?.firstOrNull()
&& resultingDescriptor.valueParameters.firstOrNull()?.name == resultingDescriptor.name) {
// first argument with the same name as method name
return@mapNotNull null
}
resolvedArg.arguments.firstOrNull()?.let { arg ->
arg.getArgumentExpression()?.let { argExp ->
if (!arg.isNamed() && !argExp.isAnnotatedWithComment(valueParam, resultingDescriptor) && !valueParam.name.isSpecial && argExp.isUnclearExpression()) {
val prefix = if (valueParam.varargElementType != null) "..." else ""
val offset = if (arg == valueArgumentList?.arguments?.firstOrNull() && valueParam.varargElementType != null)
valueArgumentList.leftParenthesis?.textRange?.endOffset ?: argExp.startOffset
else
arg.getSpreadElement()?.startOffset ?: argExp.startOffset
return@mapNotNull InlayInfo(prefix + valueParam.name.identifier + ":", offset)
}
}
}
null
}
}
private fun KtExpression.isUnclearExpression() = when (this) {
is KtConstantExpression, is KtThisExpression, is KtBinaryExpression, is KtStringTemplateExpression -> true
is KtPrefixExpression -> baseExpression is KtConstantExpression && (operationToken == KtTokens.PLUS || operationToken == KtTokens.MINUS)
else -> false
}
private fun KtExpression.isAnnotatedWithComment(valueParameter: ValueParameterDescriptor, descriptor: CallableDescriptor): Boolean =
(descriptor is JavaMethodDescriptor || descriptor is JavaClassConstructorDescriptor) &&
prevLeafs
.takeWhile { it is PsiWhiteSpace || it is PsiComment }
.any { it is PsiComment && it.text == valueParameter.toCommentedParameterName() } | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/ArgumentNameHints.kt | 321872894 |
// 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.openapi.externalSystem.service.project
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.isExternalStorageEnabled
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.ExternalSystemModuleOptionsEntity
import com.intellij.workspaceModel.storage.bridgeEntities.ModifiableExternalSystemModuleOptionsEntity
import com.intellij.workspaceModel.storage.bridgeEntities.externalSystemOptions
import com.intellij.workspaceModel.storage.bridgeEntities.getOrCreateExternalSystemModuleOptions
class ExternalSystemModulePropertyManagerBridge(private val module: Module) : ExternalSystemModulePropertyManager() {
private fun findEntity(): ExternalSystemModuleOptionsEntity? {
val modelsProvider = module.getUserData(IdeModifiableModelsProviderImpl.MODIFIABLE_MODELS_PROVIDER_KEY)
val storage = if (modelsProvider != null) modelsProvider.actualStorageBuilder else (module as ModuleBridge).entityStorage.current
val moduleEntity = storage.findModuleEntity(module as ModuleBridge)
return moduleEntity?.externalSystemOptions
}
@Synchronized
private fun editEntity(action: ModifiableExternalSystemModuleOptionsEntity.() -> Unit) {
editEntity(getModuleDiff(), action)
}
@Synchronized
private fun editEntity(moduleDiff: WorkspaceEntityStorageDiffBuilder?, action: ModifiableExternalSystemModuleOptionsEntity.() -> Unit) {
module as ModuleBridge
if (moduleDiff != null) {
val moduleEntity = (moduleDiff as WorkspaceEntityStorage).findModuleEntity(module) ?: return
val options = moduleDiff.getOrCreateExternalSystemModuleOptions(moduleEntity, moduleEntity.entitySource)
moduleDiff.modifyEntity(ModifiableExternalSystemModuleOptionsEntity::class.java, options, action)
}
else {
WriteAction.runAndWait<RuntimeException> {
WorkspaceModel.getInstance(module.project).updateProjectModel { builder ->
val moduleEntity = builder.findModuleEntity(module) ?: return@updateProjectModel
val options = builder.getOrCreateExternalSystemModuleOptions(moduleEntity, moduleEntity.entitySource)
builder.modifyEntity(ModifiableExternalSystemModuleOptionsEntity::class.java, options, action)
}
}
}
}
@Synchronized
private fun updateSource() {
updateSource(getModuleDiff())
}
@Synchronized
private fun updateSource(storageBuilder: WorkspaceEntityStorageBuilder?) {
module as ModuleBridge
val storage = storageBuilder ?: module.entityStorage.current
val moduleEntity = storage.findModuleEntity(module) ?: return
val externalSystemId = moduleEntity.externalSystemOptions?.externalSystem
val entitySource = moduleEntity.entitySource
if (externalSystemId == null && entitySource is JpsFileEntitySource ||
externalSystemId != null && (entitySource as? JpsImportedEntitySource)?.externalSystemId == externalSystemId &&
entitySource.storedExternally == module.project.isExternalStorageEnabled ||
entitySource !is JpsFileEntitySource && entitySource !is JpsImportedEntitySource) {
return
}
val newSource = if (externalSystemId == null) {
(entitySource as JpsImportedEntitySource).internalFile
}
else {
val internalFile = entitySource as? JpsFileEntitySource ?: (entitySource as JpsImportedEntitySource).internalFile
JpsImportedEntitySource(internalFile, externalSystemId, module.project.isExternalStorageEnabled)
}
ModuleManagerBridgeImpl.changeModuleEntitySource(module, storage, newSource, storageBuilder)
}
override fun getExternalSystemId(): String? = findEntity()?.externalSystem
override fun getExternalModuleType(): String? = findEntity()?.externalSystemModuleType
override fun getExternalModuleVersion(): String? = findEntity()?.externalSystemModuleVersion
override fun getExternalModuleGroup(): String? = findEntity()?.externalSystemModuleGroup
override fun getLinkedProjectId(): String? = findEntity()?.linkedProjectId
override fun getRootProjectPath(): String? = findEntity()?.rootProjectPath
override fun getLinkedProjectPath(): String? = findEntity()?.linkedProjectPath
override fun isMavenized(): Boolean = getExternalSystemId() == ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID
override fun setMavenized(mavenized: Boolean) {
setMavenized(mavenized, getModuleDiff())
}
fun setMavenized(mavenized: Boolean, storageBuilder: WorkspaceEntityStorageBuilder?) {
if (mavenized) {
unlinkExternalOptions(storageBuilder)
}
editEntity(storageBuilder) {
externalSystem = if (mavenized) ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID else null
}
updateSource(storageBuilder)
}
override fun unlinkExternalOptions() {
unlinkExternalOptions(getModuleDiff())
}
private fun unlinkExternalOptions(storageBuilder: WorkspaceEntityStorageBuilder?) {
editEntity(storageBuilder) {
externalSystem = null
externalSystemModuleVersion = null
externalSystemModuleGroup = null
linkedProjectId = null
linkedProjectPath = null
rootProjectPath = null
}
updateSource(storageBuilder)
}
override fun setExternalOptions(id: ProjectSystemId, moduleData: ModuleData, projectData: ProjectData?) {
editEntity {
externalSystem = id.toString()
linkedProjectId = moduleData.id
linkedProjectPath = moduleData.linkedExternalProjectPath
rootProjectPath = projectData?.linkedExternalProjectPath ?: ""
externalSystemModuleGroup = moduleData.group
externalSystemModuleVersion = moduleData.version
}
updateSource()
}
override fun setExternalId(id: ProjectSystemId) {
editEntity {
externalSystem = id.id
}
updateSource()
}
override fun setLinkedProjectPath(path: String?) {
editEntity {
linkedProjectPath = path
}
}
override fun setRootProjectPath(path: String?) {
editEntity {
rootProjectPath = path
}
}
override fun setExternalModuleType(type: String?) {
editEntity {
externalSystemModuleType = type
}
}
override fun swapStore() {
}
private fun getModuleDiff(): WorkspaceEntityStorageBuilder? {
val modelsProvider = module.getUserData(IdeModifiableModelsProviderImpl.MODIFIABLE_MODELS_PROVIDER_KEY)
return if (modelsProvider != null) modelsProvider.actualStorageBuilder else (module as ModuleBridge).diff as? WorkspaceEntityStorageBuilder
}
} | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ExternalSystemModulePropertyManagerBridge.kt | 680331417 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.util.names
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.checkers.OptInNames
@Suppress("MemberVisibilityCanBePrivate")
object FqNames {
object OptInFqNames {
val OLD_EXPERIMENTAL_FQ_NAME = FqName("kotlin.Experimental")
val OLD_USE_EXPERIMENTAL_FQ_NAME = FqName("kotlin.UseExperimental")
val OPT_IN_FQ_NAMES = setOf(OLD_USE_EXPERIMENTAL_FQ_NAME, OptInNames.OPT_IN_FQ_NAME)
}
} | plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/base/util/names/FqNames.kt | 3082817232 |
// 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.pacelize.ide.test
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.OrderRootType
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil
import org.jetbrains.kotlin.idea.test.addRoot
import java.io.File
fun addParcelizeLibraries(module: Module) {
ConfigLibraryUtil.addLibrary(module, "androidJar") {
addRoot(File(PathManager.getCommunityHomePath(), "android/android/testData/android.jar"), OrderRootType.CLASSES)
}
ConfigLibraryUtil.addLibrary(module, "parcelizeRuntime") {
addRoot(TestKotlinArtifacts.parcelizeRuntime, OrderRootType.CLASSES)
}
ConfigLibraryUtil.addLibrary(module, "androidExtensionsRuntime") {
addRoot(TestKotlinArtifacts.androidExtensionsRuntime, OrderRootType.CLASSES)
}
}
fun removeParcelizeLibraries(module: Module) {
ConfigLibraryUtil.removeLibrary(module, "androidJar")
ConfigLibraryUtil.removeLibrary(module, "parcelizeRuntime")
ConfigLibraryUtil.removeLibrary(module, "androidExtensionsRuntime")
} | plugins/kotlin/compiler-plugins/parcelize/tests/test/org/jetbrains/kotlin/pacelize/ide/test/parcelizeTestUtil.kt | 1178085200 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.editor.wordSelection
import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
/**
* Originally from IDEA platform: CodeBlockOrInitializerSelectioner
*/
class KotlinCodeBlockSelectioner : ExtendWordSelectionHandlerBase() {
companion object {
fun canSelect(e: PsiElement) = isTarget(e) || (isBrace(e) && isTarget(e.parent))
private fun isTarget(e: PsiElement) = e is KtBlockExpression || e is KtWhenExpression
private fun isBrace(e: PsiElement): Boolean {
val elementType = e.node.elementType
return elementType == KtTokens.LBRACE || elementType == KtTokens.RBRACE
}
}
override fun canSelect(e: PsiElement) = KotlinCodeBlockSelectioner.canSelect(e)
override fun select(e: PsiElement, editorText: CharSequence, cursorOffset: Int, editor: Editor): List<TextRange> {
val result = ArrayList<TextRange>()
val block = if (isBrace(e)) e.parent else e
val start = findBlockContentStart(block)
val end = findBlockContentEnd(block)
if (end > start) {
result.addAll(expandToWholeLine(editorText, TextRange(start, end)))
}
result.addAll(expandToWholeLine(editorText, block.textRange!!))
return result
}
private fun findBlockContentStart(block: PsiElement): Int {
val element = block.allChildren
.dropWhile { it.node.elementType != KtTokens.LBRACE } // search for '{'
.drop(1) // skip it
.dropWhile { it is PsiWhiteSpace } // and skip all whitespaces
.firstOrNull() ?: block
return element.startOffset
}
private fun findBlockContentEnd(block: PsiElement): Int {
val element = block.allChildren
.toList()
.asReversed()
.asSequence()
.dropWhile { it.node.elementType != KtTokens.RBRACE } // search for '}'
.drop(1) // skip it
.dropWhile { it is PsiWhiteSpace } // and skip all whitespaces
.firstOrNull() ?: block
return element.endOffset
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/wordSelection/KotlinCodeBlockSelectioner.kt | 615853842 |
package test
inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
class A {
class X {
}
companion object {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
object O {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
class B {
}
class C {
fun test() {
X()
Y()
foo(bar)
//1.extFoo(1.extBar) // conflict
O.Y()
O.foo(O.bar)
with (O) {
Y()
foo(bar)
1.extFoo(1.extBar)
}
}
}
} | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/nonInnerToOuterClass2/after/test.kt | 3973543085 |
package io.fotoapparat.view
import io.fotoapparat.parameter.Resolution
import io.fotoapparat.parameter.ScaleType
/**
* Renders the stream from [io.fotoapparat.Fotoapparat].
*/
interface CameraRenderer {
/**
* Sets the scale type of the preview to the renderer. This method will be called from camera
* thread, so it is safe to perform blocking operations here.
*/
fun setScaleType(scaleType: ScaleType)
/**
* Sets the resolution at which the view should display the preview.
*/
fun setPreviewResolution(resolution: Resolution)
/**
* Returns the surface texture when available.
*/
fun getPreview(): Preview
}
| fotoapparat/src/main/java/io/fotoapparat/view/CameraRenderer.kt | 3812694026 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.codeInsight.template.postfix.templates
import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateProvider
import com.intellij.psi.CommonClassNames
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.codeInsight.template.postfix.GroovyPostfixTemplateUtils
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
class GrTryPostfixTemplate(provider: PostfixTemplateProvider) :
GrPostfixTemplateBase("try", "try { expr } catch(e) { ... }", GroovyPostfixTemplateUtils.getTopExpressionSelector(), provider) {
override fun getGroovyTemplateString(element: PsiElement): String {
val exceptionList = if (element is GrMethodCallExpression) {
val method = element.resolveMethod()
method?.throwsList?.referencedTypes?.mapNotNull { it?.resolve()?.qualifiedName } ?: listOf(CommonClassNames.JAVA_LANG_EXCEPTION)
} else {
listOf(CommonClassNames.JAVA_LANG_EXCEPTION)
}
val list = exceptionList.joinToString(" | ")
return """try {
__expr__
} catch ($list e) {
__END__
}"""
}
} | plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/template/postfix/templates/GrTryPostfixTemplate.kt | 1849959139 |
public inline fun <reified T> Iterable<*>.foo(): String { }
fun f(list: List<Any>): String {
return list.<caret>
}
// ELEMENT: foo
| plugins/kotlin/completion/tests/testData/handlers/smart/InsertTypeArguments.kt | 3250167609 |
// "Create actual property for module testModule_JVM (JVM)" "true"
expect var <caret>x: Int | plugins/kotlin/idea/tests/testData/multiModuleQuickFix/createActual/property/header/header.kt | 1270136882 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark.ui
import com.intellij.ide.bookmark.Bookmark
import com.intellij.ide.bookmark.BookmarkGroup
import com.intellij.ui.tree.TreeVisitor
import com.intellij.util.ui.tree.TreeUtil
import javax.swing.tree.TreePath
internal class GroupBookmarkVisitor(val group: BookmarkGroup, val bookmark: Bookmark? = null) : TreeVisitor {
override fun visit(path: TreePath) = when (path.pathCount) {
4 -> when (TreeUtil.getAbstractTreeNode(path)?.value) {
bookmark -> TreeVisitor.Action.INTERRUPT
else -> TreeVisitor.Action.SKIP_CHILDREN
}
3 -> when (TreeUtil.getAbstractTreeNode(path)?.value) {
bookmark -> TreeVisitor.Action.INTERRUPT
null -> TreeVisitor.Action.SKIP_CHILDREN
else -> TreeVisitor.Action.CONTINUE
}
2 -> when (TreeUtil.getAbstractTreeNode(path)?.value) {
group -> bookmark?.let { TreeVisitor.Action.CONTINUE } ?: TreeVisitor.Action.INTERRUPT
else -> TreeVisitor.Action.SKIP_CHILDREN
}
1 -> TreeVisitor.Action.CONTINUE
else -> TreeVisitor.Action.SKIP_CHILDREN
}
}
| platform/lang-impl/src/com/intellij/ide/bookmark/ui/GroupBookmarkVisitor.kt | 3609427191 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention
import org.jetbrains.kotlin.idea.quickfix.SpecifyTypeExplicitlyFix
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.types.typeUtil.isNothing
class FunctionWithLambdaExpressionBodyInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitNamedFunction(function: KtNamedFunction) {
check(function)
}
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
if (accessor.isSetter) return
if (accessor.returnTypeReference != null) return
check(accessor)
}
private fun check(element: KtDeclarationWithBody) {
val callableDeclaration = element.getNonStrictParentOfType<KtCallableDeclaration>() ?: return
if (callableDeclaration.typeReference != null) return
val lambda = element.bodyExpression as? KtLambdaExpression ?: return
val functionLiteral = lambda.functionLiteral
if (functionLiteral.arrow != null || functionLiteral.valueParameterList != null) return
val lambdaBody = functionLiteral.bodyBlockExpression ?: return
val used = ReferencesSearch.search(callableDeclaration).any()
val fixes = listOfNotNull(
IntentionWrapper(SpecifyTypeExplicitlyFix()),
IntentionWrapper(AddArrowIntention()),
if (!used &&
lambdaBody.statements.size == 1 &&
lambdaBody.allChildren.none { it is PsiComment }
)
RemoveBracesFix()
else
null,
if (!used) WrapRunFix() else null
)
holder.registerProblem(
lambda,
KotlinBundle.message("inspection.function.with.lambda.expression.body.display.name"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixes.toTypedArray()
)
}
}
private class AddArrowIntention : SpecifyExplicitLambdaSignatureIntention() {
override fun allowCaretInsideElement(element: PsiElement) = true
}
private class RemoveBracesFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.braces.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val lambda = descriptor.psiElement as? KtLambdaExpression ?: return
val singleStatement = lambda.functionLiteral.bodyExpression?.statements?.singleOrNull() ?: return
val replaced = lambda.replaced(singleStatement)
replaced.setTypeIfNeed()
}
}
private class WrapRunFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("wrap.run.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val lambda = descriptor.psiElement as? KtLambdaExpression ?: return
val body = lambda.functionLiteral.bodyExpression ?: return
val replaced = lambda.replaced(KtPsiFactory(lambda).createExpressionByPattern("run { $0 }", body.allChildren))
replaced.setTypeIfNeed()
}
}
}
private fun KtExpression.setTypeIfNeed() {
val declaration = getStrictParentOfType<KtCallableDeclaration>() ?: return
val type = (declaration.resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType
if (type?.isNothing() == true) {
declaration.setType(type)
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/FunctionWithLambdaExpressionBodyInspection.kt | 1488368507 |
package zielu.gittoolbox.changes
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.serviceContainer.NonInjectable
import com.jetbrains.rd.util.getOrCreate
import git4idea.repo.GitRepository
import gnu.trove.TObjectIntHashMap
import zielu.gittoolbox.util.Count
import zielu.intellij.util.ZDisposeGuard
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
internal class ChangesTrackerServiceImpl
@NonInjectable
constructor(private val facade: ChangesTrackerServiceFacade) : ChangesTrackerService, Disposable {
constructor(project: Project) : this(ChangesTrackerServiceFacade(project))
private val changeCounters: ConcurrentMap<GitRepository, ChangeCounters> = ConcurrentHashMap()
private val disposeGuard = ZDisposeGuard()
init {
facade.registerDisposable(this, facade)
facade.registerDisposable(this, disposeGuard)
}
override fun changeListChanged(changeListData: ChangeListData) {
if (disposeGuard.isActive()) {
if (changeListData.hasChanges) {
facade.getNotEmptyChangeListTimer().timeKt { handleNonEmptyChangeList(changeListData) }
} else {
handleEmptyChangeList(changeListData.id)
}
}
}
private fun handleEmptyChangeList(id: String) {
changeListRemoved(id)
}
private fun handleNonEmptyChangeList(changeListData: ChangeListData) {
val newCounts = getCountsForChangeList(changeListData)
var changed = false
// clean up committed changes
val reposNotInChangeList: MutableSet<GitRepository> = HashSet(changeCounters.keys)
reposNotInChangeList.removeAll(newCounts.keys)
reposNotInChangeList.forEach { repoNotInList ->
changeCounters.computeIfPresent(repoNotInList) { _, counters ->
if (counters.remove(changeListData.id)) {
changed = true
}
counters
}
}
// update counts
newCounts.forEach { (repo, aggregator) ->
val oldTotal = changeCounters[repo]?.total ?: 0
val newCounters = changeCounters.merge(repo, aggregator.toCounters(), this::mergeCounters)
val difference = newCounters!!.total != oldTotal
if (difference) {
changed = true
}
}
if (changed) {
facade.fireChangeCountsUpdated()
}
}
private fun getCountsForChangeList(changeListData: ChangeListData): Map<GitRepository, ChangeCountersAggregator> {
val changeCounters = HashMap<GitRepository, ChangeCountersAggregator>()
changeListData.changes
.mapNotNull { getRepoForChange(it) }
.forEach { changeCounters.getOrCreate(it, { ChangeCountersAggregator() }).increment(changeListData.id) }
return changeCounters
}
private fun getRepoForChange(change: ChangeData): GitRepository? {
return facade.getRepoForPath(change.filePath)
}
private fun mergeCounters(existingCounters: ChangeCounters, newCounters: ChangeCounters): ChangeCounters {
return existingCounters.merge(newCounters)
}
override fun changeListRemoved(id: String) {
if (disposeGuard.isActive()) {
facade.getChangeListRemovedTimer().timeKt { handleChangeListRemoved(id) }
}
}
private fun handleChangeListRemoved(id: String) {
val modified = changeCounters.values.stream()
.map { it.remove(id) }
.filter { it }
.count()
if (modified > 0) {
facade.fireChangeCountsUpdated()
}
}
override fun getChangesCount(repository: GitRepository): Count {
if (disposeGuard.isActive()) {
return changeCounters[repository]?.let { Count(it.total) } ?: Count.ZERO
}
return Count.ZERO
}
override fun getTotalChangesCount(): Count {
if (disposeGuard.isActive()) {
val total = changeCounters.values
.map { it.total }
.sum()
return Count(total)
}
return Count.ZERO
}
override fun dispose() {
changeCounters.clear()
}
}
private class ChangeCountersAggregator {
private val changeCounters = TObjectIntHashMap<String>()
fun increment(id: String) {
if (!changeCounters.increment(id)) {
changeCounters.put(id, 1)
}
}
fun toCounters(): ChangeCounters = ChangeCounters(changeCounters)
}
private class ChangeCounters(private val changeCounters: TObjectIntHashMap<String>) {
private var totalCount: Int = changeCounters.values.sum()
val total: Int
get() = totalCount
fun remove(id: String): Boolean {
synchronized(changeCounters) {
val removed = changeCounters.remove(id)
totalCount -= removed
return removed != 0
}
}
fun hasId(id: String): Boolean {
synchronized(changeCounters) {
return changeCounters.containsKey(id)
}
}
fun merge(other: ChangeCounters): ChangeCounters {
synchronized(changeCounters) {
other.changeCounters.forEachEntry { listId, count ->
changeCounters.put(listId, count)
true
}
totalCount = changeCounters.values.sum()
return this
}
}
}
| src/main/kotlin/zielu/gittoolbox/changes/ChangesTrackerServiceImpl.kt | 692962554 |
fun bar() {
<selection>A.X = 100</selection>
} | plugins/kotlin/idea/tests/testData/shortenRefs/java/staticFieldNoImports.kt | 3888670503 |
// 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.caches
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.sourceRoots
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class ImplicitPackagePrefixTest : KotlinLightCodeInsightFixtureTestCase() {
private lateinit var cacheService: PerModulePackageCacheService
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinLightProjectDescriptor.INSTANCE
override fun setUp() {
super.setUp()
cacheService = PerModulePackageCacheService.getInstance(myFixture.project)
}
private fun prefix(): String {
return cacheService.getImplicitPackagePrefix(myFixture.module.sourceRoots[0]).asString()
}
fun testSimple() {
myFixture.configureByText("foo.kt", "package com.example.foo")
assertEquals("com.example.foo", prefix())
}
fun testAmbiguous() {
myFixture.configureByText("foo.kt", "package com.example.foo")
myFixture.configureByText("bar.kt", "package com.example.bar")
assertEquals("", prefix())
}
fun testUpdateOnCreate() {
myFixture.configureByText("foo.kt", "package com.example.foo")
assertEquals("com.example.foo", prefix())
myFixture.configureByText("bar.kt", "package com.example.bar")
assertEquals("", prefix())
}
fun testUpdateOnDelete() {
myFixture.configureByText("foo.kt", "package com.example.foo")
val bar = myFixture.configureByText("bar.kt", "package com.example.bar")
assertEquals("", prefix())
myFixture.project.executeWriteCommand("") {
bar.delete()
}
assertEquals("com.example.foo", prefix())
}
fun testUpdateOnChangeContent() {
val foo = myFixture.configureByText("foo.kt", "package com.example.foo")
assertEquals("com.example.foo", prefix())
myFixture.project.executeWriteCommand("") {
foo.viewProvider.document!!.let {
it.replaceString(0, it.textLength, "package com.example.bar")
PsiDocumentManager.getInstance(project).commitDocument(it)
}
}
assertEquals("com.example.bar", prefix())
}
}
| plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/caches/ImplicitPackagePrefixTest.kt | 104958424 |
// NAME_COUNT_TO_USE_STAR_IMPORT: 1
import java.lang.Character.*
/**
* [String]
*/
fun String.some() {
System.out
UPPERCASE_LETTER
} | plugins/kotlin/idea/tests/testData/editor/optimizeImports/jvm/allUnderImports/ClassNameConflictWithinDefaultImports.kt | 493002852 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageBuilderImpl
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageImpl
import com.intellij.workspaceModel.storage.impl.assertConsistency
fun WorkspaceEntityStorage.checkConsistency() {
if (this is WorkspaceEntityStorageImpl) {
this.assertConsistency()
return
}
if (this is WorkspaceEntityStorageBuilderImpl) {
this.assertConsistency()
return
}
}
internal fun createEmptyBuilder(): WorkspaceEntityStorageBuilderImpl {
return WorkspaceEntityStorageBuilderImpl.create()
}
internal fun createBuilderFrom(storage: WorkspaceEntityStorage): WorkspaceEntityStorageBuilderImpl {
return WorkspaceEntityStorageBuilderImpl.from(storage)
}
internal inline fun makeBuilder(from: WorkspaceEntityStorage? = null, action: WorkspaceEntityStorageBuilder.() -> Unit): WorkspaceEntityStorageBuilderImpl {
val builder = if (from == null) {
createEmptyBuilder()
}
else {
createBuilderFrom(from)
}
builder.action()
return builder
}
| platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/storageTestUtils.kt | 2442543641 |
package com.github.wreulicke.flexypool.demo
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
SpringApplication.run(DemoApplication::class.java, *args)
}
| flexy-pool/src/main/kotlin/com/github/wreulicke/flexypool/demo/DemoApplication.kt | 1826391990 |
/*
* Copyright 2019-2020 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.views.dsl.material.styles
import android.content.Context
import android.view.View
import androidx.annotation.IdRes
import androidx.annotation.StyleRes
import com.google.android.material.button.MaterialButton
import splitties.views.dsl.core.NO_THEME
import splitties.views.dsl.core.styles.styledView
import splitties.views.dsl.material.R
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@JvmInline
value class ButtonMaterialComponentsStyles @PublishedApi internal constructor(
@PublishedApi internal val ctx: Context
) {
inline fun filled(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button,
id = id,
theme = theme,
initView = initView
)
}
inline fun filledWithIcon(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_Icon,
id = id,
theme = theme,
initView = initView
)
}
inline fun filledUnelevated(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_UnelevatedButton,
id = id,
theme = theme,
initView = initView
)
}
inline fun filledUnelevatedWithIcon(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_UnelevatedButton_Icon,
id = id,
theme = theme,
initView = initView
)
}
inline fun outlined(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_OutlinedButton,
id = id,
theme = theme,
initView = initView
)
}
inline fun outlinedWithIcon(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_OutlinedButton_Icon,
id = id,
theme = theme,
initView = initView
)
}
inline fun text(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_TextButton,
id = id,
theme = theme,
initView = initView
)
}
inline fun textWithIcon(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_TextButton_Icon,
id = id,
theme = theme,
initView = initView
)
}
inline fun textDialog(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_TextButton_Dialog,
id = id,
theme = theme,
initView = initView
)
}
inline fun textDialogWithIcon(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_TextButton_Dialog_Icon,
id = id,
theme = theme,
initView = initView
)
}
}
| modules/views-dsl-material/src/androidMain/kotlin/splitties/views/dsl/material/styles/ButtonMaterialComponentsStyles.kt | 2877387941 |
class X {
fun foo() {
val runnable: Runnable = object : Runnable {
var value = 10
override fun run() {
println(value)
}
}
}
} | plugins/kotlin/j2k/new/tests/testData/newJ2k/detectProperties/AnonymousClass.kt | 341082846 |
fun foo(r: Runnable){}
fun bar(){
foo(<caret>)
}
// INVOCATION_COUNT: 2
// ELEMENT_TEXT: Thread.currentThread
| plugins/kotlin/completion/tests/testData/handlers/smart/JavaStaticMethod2.kt | 1309058311 |
package com.github.jacklt.jutils.example
import android.util.Log
import com.github.jacklt.jutils.BuildConfig
import com.github.jacklt.jutils.easyfrc.EasyFRC
import java.util.concurrent.TimeUnit
object FRC : EasyFRC(devMode = BuildConfig.DEBUG) {
// Basic example
val myBoolean by boolean(false)
val myInt by int(1337)
val myLong by long(134567890123456789)
val myDouble by double(0.0)
val myString by string("Ciao")
val myByteArray by byteArray(ByteArray(0))
// Real world examples
val signup_useHint by boolean(true)
val secretFeature1_enabled by boolean(false)
val secretFeature2_enabled by boolean(true)
val cache_expireMax by long(TimeUnit.DAYS.toSeconds(7))
val logMaxLines by int(10)
val logLevel by int(Log.INFO)
init {
Log.i("FRC", toString())
}
}
| sample/src/main/java/com/github/jacklt/jutils/example/FRC.kt | 2392567270 |
package stan.androiddemo.project.weather.gson
import java.io.Serializable
/**
* Created by hugfo on 2017/7/18.
*/
class AQI:Serializable{
public var city:AQICity? = null
class AQICity{
public var aqi = ""
public var pm25 = ""
}
} | app/src/main/java/stan/androiddemo/project/weather/gson/AQI.kt | 3173880576 |
package run.smt.karafrunner.logic.installation.base
interface BaseImageInstaller {
fun install()
} | src/main/java/run/smt/karafrunner/logic/installation/base/BaseImageInstaller.kt | 4127730787 |
/**
* HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package de.treichels.hott.mdlviewer.javafx
import de.treichels.hott.mdlviewer.javafx.Model.Companion.loadModel
import de.treichels.hott.serial.FileInfo
import de.treichels.hott.serial.FileType
import javafx.beans.binding.BooleanBinding
import javafx.concurrent.Task
import javafx.event.EventType
import javafx.scene.control.SelectionMode
import javafx.scene.control.TreeCell
import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import javafx.scene.image.ImageView
import javafx.util.Callback
import tornadofx.*
/**
* @author Oliver Treichel <[email protected]>
*/
class SelectFromSdCard : SelectFromTransmitter() {
/**
* Root [TreeItem] that loads it's children dynamically.
*/
private val rootItem: TreeItem<FileInfo> = TreeItem(FileInfo.root).apply {
isExpanded = false
loading()
// Update children of this tree item when the node is expanded
addEventHandler(branchExpandedEvent) { event ->
runLater {
treeView.runAsyncWithOverlay {
transmitter!!.listDir(event.treeItem.value.path).map {
TreeItem(transmitter!!.getFileInfo(it))
}
}.success { list ->
event.treeItem.children.clear()
event.treeItem.children.addAll(list)
}
}
}
// clear all children - reload on expand
addEventHandler(branchCollapsedEvent) { event ->
event.treeItem.loading()
}
}
/**
* [TreeView] with a single root node.
*/
private val treeView = treeview(rootItem) {
cellFactory = Callback { FileInfoTreeCell() }
selectionModel.selectionMode = SelectionMode.SINGLE
setOnMouseClicked { handleDoubleClick(it) }
}
/**
* This dialog is ready when the user selects [FileInfo] node representing a .mdl file with a valid file size.
*/
override fun isReady() = object : BooleanBinding() {
override fun computeValue(): Boolean {
val item = treeView.selectionModel.selectedItem?.value
return item != null && item.type == FileType.File && item.name.endsWith(".mdl") && item.size <= 0x3000 && item.size >= 0x2000
}
init {
// invalidate this BooleanBinding when treeView selection changes
treeView.selectionModel.selectedItemProperty().addListener { _ -> invalidate() }
}
}
/**
* A [Task] that retrieves the model data for the provided [FileInfo] from the SD card in the transmitter.
*/
override fun getResult(): Task<Model>? {
val fileInfo = treeView.selectionModel.selectedItem?.value
val serialPort = this.transmitter
return if (isReady().value && fileInfo != null && serialPort != null) runAsync { loadModel(fileInfo, serialPort) } else null
}
/**
* Reload the [TreeView]
*/
override fun refreshUITask() = treeView.runAsyncWithOverlay {
rootItem.isExpanded = false
rootItem.loading()
runLater {
rootItem.isExpanded = true
}
}
init {
title = messages["select_from_sdcard_title"]
root.center = treeView
}
companion object {
private val resources = ResourceLookup(TreeFileInfo)
private val fileImage = resources.image("/File.gif")
private val openFolderImage = resources.image("/Folder_open.gif")
private val closedFolderImage = resources.image("/Folder_closed.gif")
private val rootFolderImage = resources.image("/Root.gif")
private val branchExpandedEvent: EventType<TreeItem.TreeModificationEvent<FileInfo>> = TreeItem.branchExpandedEvent()
private val branchCollapsedEvent: EventType<TreeItem.TreeModificationEvent<FileInfo>> = TreeItem.branchCollapsedEvent()
}
/**
* Add a dummy "loading ..." node
*/
private fun TreeItem<FileInfo>.loading() {
// add loading pseudo child
children.clear()
children.add(null)
}
/**
* Format [FileInfo] items in the [TreeView]
*/
private inner class FileInfoTreeCell : TreeCell<FileInfo>() {
override fun updateItem(item: FileInfo?, empty: Boolean) {
super.updateItem(item, empty)
when {
empty -> {
graphic = null
text = null
}
item == null -> {
graphic = null
text = messages["loading"]
}
item.isRoot -> {
graphic = ImageView(rootFolderImage)
text = messages["root"]
}
item.isDir -> {
if (treeItem.isExpanded) {
graphic = ImageView(openFolderImage)
} else {
graphic = ImageView(closedFolderImage)
treeItem.loading()
}
text = item.name
}
item.isFile -> {
graphic = ImageView(fileImage)
text = item.name
}
}
}
}
}
| MdlViewer/src/main/kotlin/de/treichels/hott/mdlviewer/javafx/SelectFromSdCard.kt | 2853906455 |
package <%= basePackage %>.services
import <%= basePackage %>.models.db.Widget
import <%= basePackage %>.models.dto.CreateWidgetRequest
interface WidgetService {
fun create(createWidgetRequest: CreateWidgetRequest) : Widget
fun list() : List<Widget>
}
| app/templates/src/main/kotlin/com/widgets/services/WidgetService.kt | 107196755 |
package koma.gui.element.control.skin
import javafx.beans.Observable
import javafx.beans.WeakInvalidationListener
import javafx.collections.ListChangeListener
import javafx.collections.MapChangeListener
import javafx.collections.ObservableList
import javafx.collections.WeakListChangeListener
import javafx.event.EventHandler
import javafx.scene.AccessibleAction
import javafx.scene.Node
import javafx.scene.control.Label
import javafx.scene.control.ListCell
import javafx.scene.control.ListView
import javafx.scene.input.MouseEvent
import koma.gui.element.control.KListView
import koma.gui.element.control.behavior.ListViewBehavior
import link.continuum.desktop.gui.StackPane
import mu.KotlinLogging
private val logger = KotlinLogging.logger {}
class KListViewSkin<T, I>(
control: ListView<T>,
private val kListView: KListView<T, I>
): KVirtualContainerBase<ListView<T>, I, T>(control)
where I: ListCell<T>{
public override val flow = KVirtualFlow<I, T>(
cellCreator = ::createCell,
kListView = kListView,
fixedCellSize = control.fixedCellSize.let { if (it > 0) it else null})
/**
* Region placed over the top of the flow (and possibly the header row) if
* there is no data.
*/
private var placeholderRegion: StackPane? = null
private var placeholderNode: Node? = null
private var listViewItems: ObservableList<T>? = null
private val itemsChangeListener = { _: Observable -> updateListViewItems() }
private var needCellsRebuilt = true
private var needCellsReconfigured = false
override var itemCount = -1
private val behavior: ListViewBehavior<T>?
private val propertiesMapListener = MapChangeListener<Any,Any> { c: MapChangeListener.Change<out Any, out Any> ->
val RECREATE = "recreateKey"
if (!c.wasAdded()) {
} else if (RECREATE.equals(c.getKey())) {
needCellsRebuilt = true
skinnable.requestLayout()
skinnable.properties.remove(RECREATE)
}
}
private val listViewItemsListener = ListChangeListener<T> { c ->
while (c.next()) {
if (c.wasReplaced()) {
// RT-28397: Support for when an item is replaced with itself (but
// updated internal values that should be shown visually).
// This code was updated for RT-36714 to not update all cells,
// just those affected by the change
for (i in c.from until c.to) {
flow.setCellDirty(i)
}
break
} else if (c.removedSize == itemCount) {
// RT-22463: If the user clears out an items list then we
// should reset all cells (in particular their contained
// items) such that a subsequent addition to the list of
// an item which equals the old item (but is rendered
// differently) still displays as expected (i.e. with the
// updated display, not the old display).
itemCount = 0
break
}
}
// fix for RT-37853
skinnable.edit(-1)
markItemCountDirty()
skinnable.requestLayout()
}
private val weakListViewItemsListener = WeakListChangeListener(listViewItemsListener)
private val RECREATE = "recreateKey"
init {
// install default input map for the ListView control
behavior = ListViewBehavior(control)
// control.setInputMap(behavior.getInputMap());
// init the behavior 'closures'
behavior.setOnFocusPreviousRow(Runnable { onFocusPreviousCell() })
behavior.setOnFocusNextRow (Runnable{ onFocusNextCell() })
behavior.setOnMoveToFirstCell (Runnable{
logger.debug { "KListViewSkin behavior onMoveToFirstCell" }
onMoveToFirstCell()
})
behavior.setOnMoveToLastCell (Runnable{
logger.debug { "KListViewSkin behavior onMoveToLastCell" }
onMoveToLastCell()
})
behavior.setOnSelectPreviousRow (Runnable{ onSelectPreviousCell() })
behavior.setOnSelectNextRow (Runnable{ onSelectNextCell() })
behavior.onScrollPageDown = {
logger.debug { "KListViewSkin behavior onScrollPageDown" }
flow.scrollRatio(0.8f)
}
behavior.onScrollPageUp = {
logger.debug { "KListViewSkin behavior onScrollPage up" }
flow.scrollRatio(-0.8f)
}
updateListViewItems()
// init the VirtualFlow
flow.id = "virtual-flow"
flow.isPannable = IS_PANNABLE
children.add(flow)
val ml: EventHandler<MouseEvent> = EventHandler {
// RT-15127: cancel editing on scroll. This is a bit extreme
// (we are cancelling editing on touching the scrollbars).
// This can be improved at a later date.
if (control.editingIndex > -1) {
control.edit(-1)
}
// This ensures that the list maintains the focus, even when the vbar
// and hbar controls inside the flow are clicked. Without this, the
// focus border will not be shown when the user interacts with the
// scrollbars, and more importantly, keyboard navigation won't be
// available to the user.
if (control.isFocusTraversable) {
control.requestFocus()
}
}
flow.vbar.addEventFilter(MouseEvent.MOUSE_PRESSED, ml)
updateItemCount()
control.itemsProperty().addListener(WeakInvalidationListener(itemsChangeListener))
val properties = control.properties
properties.remove(RECREATE)
properties.addListener(propertiesMapListener)
// Register listeners
registerChangeListener(control.itemsProperty()) { updateListViewItems() }
registerChangeListener(control.parentProperty()) { _ ->
if (control.parent != null && control.isVisible) {
control.requestLayout()
}
}
registerChangeListener(control.placeholderProperty()) { _ -> updatePlaceholderRegionVisibility() }
}
override fun dispose() {
super.dispose()
behavior?.dispose()
}
override fun layoutChildren(x: Double, y: Double,
w: Double, h: Double) {
super.layoutChildren(x, y, w, h)
if (needCellsRebuilt) {
flow.rebuildCells()
} else if (needCellsReconfigured) {
flow.reconfigureCells()
}
needCellsRebuilt = false
needCellsReconfigured = false
if (itemCount == 0) {
// show message overlay instead of empty listview
placeholderRegion?.apply {
isVisible = w > 0 && h > 0
resizeRelocate(x, y, w, h)
}
} else {
flow.resizeRelocate(x, y, w, h)
}
}
override fun computePrefWidth(height: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double): Double {
checkState()
if (itemCount == 0) {
if (placeholderRegion == null) {
updatePlaceholderRegionVisibility()
}
if (placeholderRegion != null) {
return placeholderRegion!!.prefWidth(height) + leftInset + rightInset
}
}
return computePrefHeight(-1.0, topInset, rightInset, bottomInset, leftInset) * 0.618033987
}
override fun computePrefHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double): Double {
return 400.0
}
override fun updateItemCount() {
val oldCount = itemCount
val newCount = if (listViewItems == null) 0 else listViewItems!!.size
itemCount = newCount
flow.setCellCount(newCount)
updatePlaceholderRegionVisibility()
if (newCount != oldCount) {
requestRebuildCells()
} else {
needCellsReconfigured = true
}
}
override fun executeAccessibleAction(action: AccessibleAction, vararg parameters: Any) {
when (action) {
AccessibleAction.SHOW_ITEM -> {
val item = parameters[0] as Node
if (item is ListCell<*>) {
val cell = item as ListCell<T>
flow.scrollTo(cell.index)
}
}
AccessibleAction.SET_SELECTED_ITEMS -> {
val items = parameters[0] as ObservableList<Node>
val sm = skinnable.selectionModel
if (sm != null) {
sm.clearSelection()
for (item in items) {
if (item is ListCell<*>) {
val cell = item as ListCell<T>
sm.select(cell.index)
}
}
}
}
else -> super.executeAccessibleAction(action, parameters)
}
}
private fun createCell(): I {
val cell: I = kListView.cellCreator()
cell.updateListView(skinnable)
return cell
}
private fun updateListViewItems() {
if (listViewItems != null) {
listViewItems!!.removeListener(weakListViewItemsListener)
}
this.listViewItems = skinnable.items
if (listViewItems != null) {
listViewItems!!.addListener(weakListViewItemsListener)
}
markItemCountDirty()
skinnable.requestLayout()
}
private fun updatePlaceholderRegionVisibility() {
val visible = itemCount == 0
if (visible) {
placeholderNode = skinnable.placeholder
if (placeholderNode == null && !EMPTY_LIST_TEXT.isEmpty()) {
placeholderNode = Label()
(placeholderNode as Label).setText(EMPTY_LIST_TEXT)
}
if (placeholderNode != null) {
if (placeholderRegion == null) {
placeholderRegion = StackPane()
placeholderRegion!!.styleClass.setAll("placeholder")
children.add(placeholderRegion)
}
placeholderRegion!!.children.setAll(placeholderNode)
}
}
flow.isVisible = !visible
if (placeholderRegion != null) {
placeholderRegion!!.isVisible = visible
}
}
private fun onFocusPreviousCell() {
val fm = skinnable.focusModel ?: return
flow.scrollTo(fm.focusedIndex)
}
private fun onFocusNextCell() {
val fm = skinnable.focusModel ?: return
flow.scrollTo(fm.focusedIndex)
}
private fun onSelectPreviousCell() {
val sm = skinnable.selectionModel ?: return
val pos = sm.selectedIndex
if (pos < 0) return
flow.scrollTo(pos)
// Fix for RT-11299
val cell = flow.firstVisibleCell
if (cell == null || pos < cell.index) {
val p = pos / itemCount.toDouble()
flow.setPosition(p)
}
}
private fun onSelectNextCell() {
val sm = skinnable.selectionModel ?: return
val pos = sm.selectedIndex
flow.scrollTo(pos)
// Fix for RT-11299
val cell = flow.lastVisibleCell
if (cell == null || cell.index < pos) {
flow.setPosition ( pos / itemCount.toDouble())
}
}
private fun onMoveToFirstCell() {
flow.scrollTo(0)
flow.setPosition(0.0)
}
private fun onMoveToLastCell() {
// SelectionModel sm = getSkinnable().getSelectionModel();
// if (sm == null) return;
//
val endPos = itemCount - 1
// sm.select(endPos);
flow.scrollTo(endPos)
flow.setPosition(1.0)
}
companion object {
// RT-34744 : IS_PANNABLE will be false unless
// javafx.scene.control.skin.ListViewSkin.pannable
// is set to true. This is done in order to make ListView functional
// on embedded systems with touch screens which do not generate scroll
// events for touch drag gestures.
private val IS_PANNABLE = false
private const val EMPTY_LIST_TEXT = "ListView.noContent"
}
}
| src/main/kotlin/koma/gui/element/control/skin/KListViewSkin.kt | 3425795388 |
package com.claraboia.bibleandroid.infrastructure
import java.util.*
/**
* Created by lucas.batagliao on 14/10/2016.
*/
open class Event<eventArg : EventArg> {
private val handlers = ArrayList<((eventArg) -> Unit)>()
operator fun plusAssign(handler: (eventArg) -> Unit) {
handlers.add(handler)
}
fun minusAssign(handler: (eventArg) -> Unit) {
handlers.remove(handler)
}
fun invoke(value: eventArg){
for(handler in handlers){
handler(value)
}
}
} | app/src/main/java/com/claraboia/bibleandroid/infrastructure/Event.kt | 1752320698 |
package com.nicologis.slack
import com.nicologis.teamcity.BuildInfo
import com.google.gson.annotations.Expose
import org.apache.commons.lang.StringUtils
import java.util.ArrayList
class SlackPayload(build: BuildInfo) {
@Expose
private var text: String
@Expose
private lateinit var channel: String
@Expose
private lateinit var username: String
@Expose
private var attachments: MutableList<Attachment>
inner class Attachment {
@Expose
var fallback: String? = null
@Expose
var pretext: String? = null
@Expose
var color: String? = null
@Expose
var fields: MutableList<AttachmentField>? = null
}
inner class AttachmentField(
@field:Expose
private var title: String,
@field:Expose
private var value: String,
@field:Expose
private var isShort: Boolean
)
fun setRecipient(recipient: String) {
this.channel = recipient
}
fun setBotName(botName: String) {
this.username = botName
}
private fun escape(s: String): String {
return s.replace("<", "<").replace(">", ">")
}
private fun escapeNewline(s: String): String {
return s.replace("\n", "\\n")
}
init {
val branch = escape(build.branchName)
val escapedBranch = if (branch.isNotEmpty()) " [$branch]" else ""
val statusText = ("<" + build.getBuildLink { x -> this.escape(x) }
+ "|" + escape(escapeNewline(build.statusText)) + ">")
val statusEmoji: String
val statusColor = build.statusColor
statusEmoji = when (statusColor) {
StatusColor.danger -> ":x: "
StatusColor.warning -> ""
StatusColor.info -> ":information_source: "
else -> ":white_check_mark: "
}
val payloadText = (statusEmoji + build.buildFullName
+ escapedBranch + " #" + build.buildNumber + " " + statusText)
this.text = payloadText
val attachment = Attachment()
attachment.color = statusColor.name
attachment.pretext = "Build Information"
attachment.fallback = payloadText
attachment.fields = ArrayList()
val encodedPrUrl = build.getEncodedPrUrl()
if (StringUtils.isNotEmpty(encodedPrUrl)) {
val prUrlField = AttachmentField("PullRequest URL", encodedPrUrl, false)
attachment.fields!!.add(prUrlField)
}
for ((key, value) in build.messages) {
val field = AttachmentField(key, value, false)
attachment.fields!!.add(field)
}
this.attachments = ArrayList()
if (!attachment.fields!!.isEmpty()) {
this.attachments.add(0, attachment)
}
}
}
| hedwig-server/src/main/java/com/nicologis/slack/SlackPayload.kt | 3925325157 |
/*
* Copyright 2020 Ren Binden
*
* 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.rpkit.banks.bukkit
import com.rpkit.banks.bukkit.bank.RPKBankProvider
import com.rpkit.banks.bukkit.bank.RPKBankProviderImpl
import com.rpkit.banks.bukkit.database.table.RPKBankTable
import com.rpkit.banks.bukkit.listener.PlayerInteractListener
import com.rpkit.banks.bukkit.listener.SignChangeListener
import com.rpkit.banks.bukkit.servlet.BankServlet
import com.rpkit.banks.bukkit.servlet.BanksServlet
import com.rpkit.banks.bukkit.servlet.CharacterServlet
import com.rpkit.banks.bukkit.servlet.StaticServlet
import com.rpkit.core.bukkit.plugin.RPKBukkitPlugin
import com.rpkit.core.database.Database
import com.rpkit.core.web.NavigationLink
import org.bstats.bukkit.Metrics
/**
* RPK banks plugin default implementation.
*/
class RPKBanksBukkit: RPKBukkitPlugin() {
private lateinit var bankProvider: RPKBankProvider
override fun onEnable() {
Metrics(this, 4378)
saveDefaultConfig()
bankProvider = RPKBankProviderImpl(this)
serviceProviders = arrayOf(
bankProvider
)
servlets = arrayOf(
BanksServlet(this),
CharacterServlet(this),
BankServlet(this),
StaticServlet(this),
com.rpkit.banks.bukkit.servlet.api.v1.BankAPIServlet(this)
)
}
override fun onPostEnable() {
core.web.navigationBar.add(NavigationLink("Banks", "/banks/"))
}
override fun registerListeners() {
registerListeners(SignChangeListener(this), PlayerInteractListener(this))
}
override fun createTables(database: Database) {
database.addTable(RPKBankTable(database, this))
}
override fun setDefaultMessages() {
messages.setDefault("bank-sign-invalid-operation", "&cThat's not a valid operation. Please use withdraw, deposit, or balance. (Line 2)")
messages.setDefault("bank-sign-invalid-currency", "&cThat's not a valid currency. Please use a valid currency. (Line 4)")
messages.setDefault("bank-withdraw-invalid-wallet-full", "&cYou cannot withdraw that amount, it would not fit in your wallet.")
messages.setDefault("bank-withdraw-invalid-not-enough-money", "&cYou cannot withdraw that amount, your bank balance is not high enough.")
messages.setDefault("bank-withdraw-valid", "&aWithdrew \$amount \$currency. Wallet balance: \$wallet-balance. Bank balance: \$bank-balance.")
messages.setDefault("bank-deposit-invalid-not-enough-money", "&cYou cannot deposit that amount, your wallet balance is not high enough.")
messages.setDefault("bank-deposit-valid", "&aDeposited \$amount \$currency. Wallet balance: \$wallet-balance. Bank balance: \$bank-balance.")
messages.setDefault("bank-balance-valid", "&aBalance: \$amount \$currency")
messages.setDefault("no-permission-bank-create", "&cYou do not have permission to create banks.")
}
} | bukkit/rpk-banks-bukkit/src/main/kotlin/com/rpkit/banks/bukkit/RPKBanksBukkit.kt | 431166202 |
package info.touchimage.demo
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.ortiz.touchview.TouchImageView
import kotlinx.android.synthetic.main.activity_single_touchimageview.*
import java.text.DecimalFormat
class SingleTouchImageViewActivity : AppCompatActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_touchimageview)
// DecimalFormat rounds to 2 decimal places.
val df = DecimalFormat("#.##")
// Set the OnTouchImageViewListener which updates edit texts with zoom and scroll diagnostics.
imageSingle.setOnTouchImageViewListener(object : TouchImageView.OnTouchImageViewListener {
override fun onMove() {
val point = imageSingle.scrollPosition
val rect = imageSingle.zoomedRect
val currentZoom = imageSingle.currentZoom
val isZoomed = imageSingle.isZoomed
scroll_position.text = "x: " + df.format(point.x.toDouble()) + " y: " + df.format(point.y.toDouble())
zoomed_rect.text = ("left: " + df.format(rect.left.toDouble()) + " top: " + df.format(rect.top.toDouble())
+ "\nright: " + df.format(rect.right.toDouble()) + " bottom: " + df.format(rect.bottom.toDouble()))
current_zoom.text = "getCurrentZoom(): $currentZoom isZoomed(): $isZoomed"
}
}
)
}
}
| app/src/main/java/info/touchimage/demo/SingleTouchImageViewActivity.kt | 3797935280 |
package ratpack.kotlin.coroutines
import io.kotest.core.spec.style.StringSpec
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import kotlinx.coroutines.delay
import ratpack.error.ServerErrorHandler
import ratpack.kotlin.test.embed.ratpack
import ratpack.test.embed.EmbeddedApp
import java.lang.Thread.sleep
import java.util.concurrent.Semaphore
import kotlin.concurrent.thread
private val threadName get() = "(thread: ${Thread.currentThread()}"
/**
* See https://github.com/gregopet/kotlin-ratpack-coroutines/blob/master/src/test/kotlin/co/petrin/kotlin/BlockingBehaviorSpec.kt
*/
class BlockingBehaviorSpec : StringSpec() {
lateinit var semaphore: Semaphore
lateinit var embeddedApp: EmbeddedApp
override suspend fun beforeTest(testCase: TestCase) {
semaphore = Semaphore(1)
embeddedApp = ratpack {
serverConfig { threads(1) }
handlers {
register {
add(ServerErrorHandler { context, throwable ->
throwable.printStackTrace()
context.response.status(500).send("CUSTOM ERROR HANDLER $throwable")
})
}
get("sleepblock") {
println("INSIDE SLEEPBLOCK HANDLER $threadName")
semaphore.release()
sleep(1000 * 5)
println("EXITING SLEEPBLOCK HANDLER $threadName")
send("SLEEP")
}
get("sleep") {
println("INSIDE SLEEP HANDLER $threadName")
semaphore.release()
println("SLEEPING ASYNC $threadName")
var message = await {
println("SLEEPING BLOCK ASYNC $threadName")
sleep(1000 * 5)
"WOKE UP"
}
println("SLEEPING ASYNC OVER $threadName")
send(message)
println("EXITING SLEEP HANDLER $threadName")
}
get("quick") {
println("INSIDE QUICK HANDLER $threadName")
delay(100)
send("ECHO $threadName")
}
get("throw") {
println("INSIDE ASYNC EXCEPTION THROWING HANDLER $threadName")
sleep(100)
println("INSIDE ASYNC EXCEPTION THROWING HANDLER, ABOUT TO THROW $threadName")
throw IllegalStateException("Except me!")
}
get("throwcatch") {
println("INSIDE ASYNC EXCEPTION THROWING AND CATCHING HANDLER $threadName")
sleep(100)
try {
println("INSIDE ASYNC EXCEPTION THROWING HANDLER, ABOUT TO THROW $threadName")
throw IllegalStateException("Except me!")
} catch (t: Throwable) {
render("Caught it")
}
}
post("echobody") {
println("INSIDE ECHOBODY HANDLER $threadName")
println("INSIDE ECHOBODY ASYNC $threadName")
val txt = request.body.await().text
println("INSIDE ECHOBODY ASYNC AFTER COROUTINE $threadName")
send(txt)
}
}
}
}
override suspend fun afterTest(testCase: TestCase, result: TestResult) {
embeddedApp.close()
}
init {
"A blocking function will clog our test app" {
var blockingSleepFinished = false
var simpleRequestFinished = false
semaphore.acquire()
thread(start = true, isDaemon = true) {
try {
embeddedApp.httpClient.getText("sleepblock").let(::println)
blockingSleepFinished = true
} catch (x: Exception) {
}
}
semaphore.acquire()
thread(start = true, isDaemon = true) {
semaphore.release()
embeddedApp.httpClient.getText("quick").let(::println)
simpleRequestFinished = true
}
semaphore.acquire()
sleep(1000)
check(!blockingSleepFinished) { "Blocking should still be computing" }
check(!simpleRequestFinished) { "Quick thread should be waiting on the blocking head" }
}
"A non-blocking function will not clog our test app" {
var blockingSleepFinished = false
var simpleRequestFinished = false
semaphore.acquire()
thread(start = true, isDaemon = true) {
try {
val response = embeddedApp.httpClient.getText("sleep")
check(response == "WOKE UP")
blockingSleepFinished = true
} catch (x: Exception) {
}
}
semaphore.acquire()
thread(start = true, isDaemon = true) {
try {
semaphore.release()
embeddedApp.httpClient.getText("quick").let(::println)
simpleRequestFinished = true
} catch (x: Exception) {
}
}
semaphore.acquire()
sleep(1000)
check(!blockingSleepFinished) { "Blocking should still be computing" }
check(simpleRequestFinished) { "Quick thread should NOT be waiting on the blocking head" }
}
"A non-blocking function will return the correct result" {
check(embeddedApp.httpClient.getText("sleep") == "WOKE UP")
}
"await() can be called on Ratpack promises" {
val requestWithBody = embeddedApp.httpClient.requestSpec { it.body.text("foobar") }
val response = requestWithBody.postText("echobody")
check(response == "foobar") { "Response $response should be 'foobar'" }
}
"exceptions are handled by Ratpack" {
val response = embeddedApp.httpClient.get("throw")
val responseText = response.body.text
check(response.status.code == 500) { "Response code should be '500' after exception, was ${response.status.code}" }
check(responseText.startsWith("CUSTOM ERROR HANDLER")) { "Server should render the error page after an exception, rendered $responseText instead" }
}
"exceptions can be caught and thus not handled by Ratpack" {
val response = embeddedApp.httpClient.get("throwcatch")
val responseText = response.body.text
check(response.status.code == 200) { "Response code should be '200' after caught exception, was ${response.status.code}" }
check(responseText == "Caught it") { "Server should have caught the exception but it rendered $responseText instead" }
}
}
}
| ratpack-kotlin-dsl/src/test/kotlin/ratpack/kotlin/coroutines/BlockingBehaviorSpec.kt | 2777288833 |
/*
* Copyright 2019 Ross Binden
*
* 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.rpkit.featureflags.bukkit.event.featureflag
import com.rpkit.core.bukkit.event.RPKBukkitEvent
import com.rpkit.featureflags.bukkit.featureflag.RPKFeatureFlag
import org.bukkit.event.Cancellable
import org.bukkit.event.HandlerList
class RPKBukkitFeatureFlagUpdateEvent(
override val featureFlag: RPKFeatureFlag
): RPKBukkitEvent(), RPKFeatureFlagUpdateEvent, Cancellable {
companion object {
@JvmStatic val handlerList = HandlerList()
}
private var cancel: Boolean = false
override fun isCancelled(): Boolean {
return cancel
}
override fun setCancelled(cancel: Boolean) {
this.cancel = cancel
}
override fun getHandlers(): HandlerList {
return handlerList
}
} | bukkit/rpk-feature-flag-lib-bukkit/src/main/kotlin/com/rpkit/featureflags/bukkit/event/featureflag/RPKBukkitFeatureFlagUpdateEvent.kt | 3105995628 |
package com.orgzly.android.db.entity
import androidx.room.*
@Entity(
tableName = "rook_urls",
indices = [
Index("url", unique = true)
]
)
data class RookUrl(
@PrimaryKey(autoGenerate = true)
val id: Long,
val url: String
)
| app/src/main/java/com/orgzly/android/db/entity/RookUrl.kt | 2055874701 |
package com.piticlistudio.playednext.data.entity.mapper.datasources.image
import com.piticlistudio.playednext.domain.model.Image
import com.piticlistudio.playednext.test.factory.GameImageFactory.Factory.makeIGDBImage
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
internal class IGDBImageMapperTest {
@Nested
@DisplayName("Given a IGDBImageMapper instance")
inner class IGDBImageMapperInstance {
private lateinit var mapper: IGDBImageMapper
@BeforeEach
internal fun setUp() {
mapper = IGDBImageMapper()
}
@Nested
@DisplayName("When we call mapFromDataLayer")
inner class MapFromDataLayerCalled {
private val model = makeIGDBImage()
private var result: Image? = null
@BeforeEach
internal fun setUp() {
result = mapper.mapFromDataLayer(model)
}
@Test
@DisplayName("Then should map result")
fun isMapped() {
assertNotNull(result)
result?.apply {
assertEquals(model.height, height)
assertEquals(model.width, width)
assertEquals(model.mediumSizeUrl, url)
}
}
}
}
} | app/src/test/java/com/piticlistudio/playednext/data/entity/mapper/datasources/image/IGDBImageMapperTest.kt | 3053137566 |
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* See LICENSE in the project root for license information.
*/
package jetbrains.buildServer.rust.inspections
import jetbrains.buildServer.agent.inspections.InspectionTypeInfo
class ClippyInspectionsParser {
private lateinit var currentType: InspectionTypeInfo
private lateinit var currentMessage: String
companion object {
val CLIPPY_WARNING = InspectionTypeInfo().apply {
id = "rust-inspection-clippy-warning"
description = "Clippy Warning"
category = "Clippy Inspection"
name = "Clippy Warning"
}
val CLIPPY_ERROR = InspectionTypeInfo().apply {
id = "rust-inspection-clippy-error"
description = "Clippy Error"
category = "Clippy Inspection"
name = "Clippy Error"
}
}
fun processLine(text: String): Inspection? {
return when {
text.startsWith("error: ") -> {
currentType = CLIPPY_ERROR
currentMessage = text.removePrefix("error: ")
null
}
text.startsWith("warning: ") -> {
currentType = CLIPPY_WARNING
currentMessage = text.removePrefix("warning: ")
null
}
text.matches("^\\s+--> .+".toRegex()) -> {
val position = text.replace("^\\s+--> ".toRegex(), "")
val split = position.split(":")
val filename = split.subList(0, split.size-2).joinToString(":")
val line = split[split.size-2]
Inspection(
type = currentType,
message = currentMessage,
file = filename,
line = line.toInt(),
severity = if (currentType == CLIPPY_ERROR) Inspection.Severity.ERROR else Inspection.Severity.WARNING
)
}
else -> null
}
}
} | plugin-rust-agent/src/main/kotlin/jetbrains/buildServer/rust/inspections/ClippyInspectionsParser.kt | 2450212460 |
package com.soywiz.kpspemu.hle
import com.soywiz.kds.*
import com.soywiz.klogger.*
import com.soywiz.kmem.*
import com.soywiz.korio.error.*
import com.soywiz.korio.lang.*
import com.soywiz.kpspemu.*
import com.soywiz.kpspemu.cpu.*
import com.soywiz.kpspemu.hle.error.*
import com.soywiz.kpspemu.hle.manager.*
import com.soywiz.kpspemu.mem.*
import com.soywiz.kpspemu.util.*
import com.soywiz.krypto.encoding.*
import kotlin.coroutines.*
import com.soywiz.korio.lang.invalidOp as invalidOp1
import kotlin.coroutines.intrinsics.*
class RegisterReader {
var pos: Int = 4
lateinit var emulator: Emulator
lateinit var cpu: CpuState
fun reset(cpu: CpuState) {
this.cpu = cpu
this.pos = 4
}
val thread: PspThread get() = cpu.thread
val mem: Memory get() = cpu.mem
val bool: Boolean get() = int != 0
val int: Int get() = this.cpu.getGpr(pos++)
val long: Long
get() {
pos = pos.nextAlignedTo(2) // Ensure register alignment
val low = this.cpu.getGpr(pos++)
val high = this.cpu.getGpr(pos++)
return (high.toLong() shl 32) or (low.toLong() and 0xFFFFFFFF)
}
val ptr: Ptr get() = MemPtr(mem, int)
val ptr8: Ptr8 get() = Ptr8(ptr)
val ptr32: Ptr32 get() = Ptr32(ptr)
val ptr64: Ptr64 get() = Ptr64(ptr)
val str: String? get() = mem.readStringzOrNull(int)
val istr: String get() = mem.readStringzOrNull(int) ?: ""
val strnn: String get() = mem.readStringzOrNull(int) ?: ""
fun <T> ptr(s: StructType<T>) = PtrStruct(s, ptr)
}
data class NativeFunction(
val name: String,
val nid: Long,
val since: Int,
val syscall: Int,
val function: (CpuState) -> Unit
)
abstract class BaseSceModule {
abstract val mmodule: SceModule
abstract val name: String
fun getByNidOrNull(nid: Int): NativeFunction? = mmodule.functions[nid]
fun getByNid(nid: Int): NativeFunction =
getByNidOrNull(nid) ?: invalidOp1("Can't find NID 0x%08X in %s".format(nid, name))
fun UNIMPLEMENTED(nid: Int): Nothing {
val func = getByNid(nid)
TODO("Unimplemented %s:0x%08X:%s".format(this.name, func.nid, func.name))
}
fun UNIMPLEMENTED(nid: Long): Nothing = UNIMPLEMENTED(nid.toInt())
}
abstract class SceSubmodule<out T : SceModule>(override val mmodule: T) : WithEmulator, BaseSceModule() {
override val name: String get() = mmodule.name
override val emulator: Emulator get() = mmodule.emulator
}
abstract class SceModule(
override val emulator: Emulator,
override val name: String,
val flags: Int = 0,
val prxFile: String = "",
val prxName: String = ""
) : WithEmulator, BaseSceModule() {
override val mmodule get() = this
inline fun <reified T : SceModule> getModuleOrNull(): T? = emulator.moduleManager.modulesByClass[T::class] as? T?
inline fun <reified T : SceModule> getModule(): T =
getModuleOrNull<T>() ?: invalidOp1("Expected to get module ${T::class.portableSimpleName}")
val loggerSuspend = Logger("SceModuleSuspend").apply {
//level = LogLevel.TRACE
}
val logger = Logger("SceModule.$name").apply {
//level = LogLevel.TRACE
}
fun registerPspModule() {
registerModule()
}
open fun stopModule() {
}
protected abstract fun registerModule(): Unit
private val rr: RegisterReader = RegisterReader()
val functions = IntMap<NativeFunction>()
fun registerFunctionRaw(function: NativeFunction) {
functions[function.nid.toInt()] = function
if (function.syscall >= 0) {
emulator.syscalls.register(function.syscall, function.name) { cpu, syscall ->
//println("REGISTERED SYSCALL $syscall")
logger.trace { "${this.name}:${function.name}" }
function.function(cpu)
}
}
}
fun registerFunctionRaw(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: (CpuState) -> Unit
) {
registerFunctionRaw(NativeFunction(name, uid, since, syscall, function))
}
fun registerFunctionRR(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: RegisterReader.(CpuState) -> Unit
) {
registerFunctionRaw(name, uid, since, syscall) {
//when (name) {
// "sceGeListUpdateStallAddr", "sceKernelLibcGettimeofday" -> Unit
// else -> println("Calling $name")
//}
try {
if (it._thread?.tracing == true) println("Calling $name from ${it._thread?.name}")
rr.reset(it)
function(rr, it)
} catch (e: Throwable) {
if (e !is EmulatorControlFlowException) {
Console.error("Error while processing '$name' :: at ${it.sPC.hex} :: $e")
}
throw e
}
}
}
fun registerFunctionVoid(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: RegisterReader.(CpuState) -> Unit
) {
registerFunctionRR(name, uid, since, syscall, function)
}
fun registerFunctionInt(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: RegisterReader.(CpuState) -> Int
) {
registerFunctionRR(name, uid, since, syscall) {
this.cpu.r2 = try {
function(it)
} catch (e: SceKernelException) {
e.errorCode
}
}
}
fun registerFunctionFloat(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: RegisterReader.(CpuState) -> Float
) {
registerFunctionRR(name, uid, since, syscall) {
this.cpu.setFpr(0, function(it))
}
}
fun registerFunctionLong(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: RegisterReader.(CpuState) -> Long
) {
registerFunctionRR(name, uid, since, syscall) {
val ret = function(it)
this.cpu.r2 = (ret ushr 0).toInt()
this.cpu.r3 = (ret ushr 32).toInt()
}
}
fun <T> registerFunctionSuspendT(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
cb: Boolean = false,
function: suspend RegisterReader.(CpuState) -> T,
resumeHandler: (CpuState, PspThread, T) -> Unit,
convertErrorToT: (Int) -> T
) {
val fullName = "${this.name}:$name"
registerFunctionRR(name, uid, since, syscall) { rrr ->
val rcpu = cpu
val rthread = thread
loggerSuspend.trace { "Suspend $name (${threadManager.summary}) : ${rcpu.summary}" }
val mfunction: suspend (RegisterReader) -> T = { function(it, rcpu) }
try {
val result = mfunction.startCoroutineUninterceptedOrReturn(this, object : Continuation<T> {
override val context: CoroutineContext = coroutineContext
override fun resumeWith(result: Result<T>) {
if (result.isSuccess) {
val value = result.getOrThrow()
resumeHandler(rcpu, thread, value)
rthread.resume()
loggerSuspend.trace { "Resumed $name with value: $value (${threadManager.summary}) : ${rcpu.summary}" }
} else {
val e = result.exceptionOrNull()!!
when (e) {
is SceKernelException -> {
resumeHandler(rcpu, thread, convertErrorToT(e.errorCode))
rthread.resume()
}
else -> {
println("ERROR at registerFunctionSuspendT.resumeWithException")
e.printStackTrace()
throw e
}
}
}
}
})
if (result == COROUTINE_SUSPENDED) {
rthread.markWaiting(WaitObject.COROUTINE(fullName), cb = cb)
if (rthread.tracing) println(" [S] Calling $name")
threadManager.suspendReturnVoid()
} else {
resumeHandler(rthread.state, rthread, result as T)
}
} catch (e: SceKernelException) {
resumeHandler(rthread.state, rthread, convertErrorToT(e.errorCode))
} catch (e: CpuBreakException) {
throw e
} catch (e: Throwable) {
println("ERROR at registerFunctionSuspendT.resumeWithException")
e.printStackTrace()
throw e
}
}
}
fun registerFunctionSuspendInt(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
cb: Boolean = false,
function: suspend RegisterReader.(CpuState) -> Int
) {
registerFunctionSuspendT<Int>(name, uid, since, syscall, cb, function,
resumeHandler = { cpu, thread, value -> cpu.r2 = value },
convertErrorToT = { it }
)
}
fun registerFunctionSuspendLong(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
cb: Boolean = false,
function: suspend RegisterReader.(CpuState) -> Long
) {
registerFunctionSuspendT<Long>(name, uid, since, syscall, cb, function, resumeHandler = { cpu, thread, value ->
cpu.r2 = (value ushr 0).toInt()
cpu.r3 = (value ushr 32).toInt()
}, convertErrorToT = { it.toLong() })
}
}
| src/commonMain/kotlin/com/soywiz/kpspemu/hle/SceModule.kt | 2901805028 |
package trypp.support.pattern.observer
import com.google.common.truth.Truth.assertThat
import org.testng.annotations.Test
class TopicTest {
class CancelParams {
var shouldCancel = false;
}
interface OpenEvents {
fun onOpening(sender: Window, params: CancelParams)
fun onOpened(sender: Window)
}
class Window {
val openEvents = Topic(OpenEvents::class)
fun open() {
val p = CancelParams()
openEvents.broadcast.onOpening(this, p)
if (!p.shouldCancel) {
openEvents.broadcast.onOpened(this)
}
}
}
@Test
fun topicsCanBeUsedToPreventOrAllowBehavior() {
val w = Window()
var allowOpen = false
var opened = false
w.openEvents += object : OpenEvents {
override fun onOpening(sender: Window, params: CancelParams) {
params.shouldCancel = !allowOpen
}
override fun onOpened(sender: Window) {
opened = true
}
}
w.open()
assertThat(opened).isFalse()
allowOpen = true
w.open()
assertThat(opened).isTrue()
}
}
| src/test/code/trypp/support/pattern/observer/TopicTest.kt | 551169019 |
/*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Adrien Béraud <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cx.ring.utils
import android.view.GestureDetector
import android.view.View.OnTouchListener
import android.view.MotionEvent
import android.annotation.SuppressLint
import android.content.Context
import android.view.View
class TouchClickListener(c: Context?, private val onClickListener: View.OnClickListener) :
GestureDetector.OnGestureListener, OnTouchListener {
private val mGestureDetector: GestureDetector = GestureDetector(c, this)
private var view: View? = null
override fun onDown(e: MotionEvent): Boolean {
return false
}
override fun onShowPress(e: MotionEvent) {}
override fun onSingleTapUp(e: MotionEvent): Boolean {
onClickListener.onClick(view)
return true
}
override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
return false
}
override fun onLongPress(e: MotionEvent) {}
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
return false
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View, event: MotionEvent): Boolean {
view = v
mGestureDetector.onTouchEvent(event)
view = null
return true
}
} | ring-android/app/src/main/java/cx/ring/utils/TouchClickListener.kt | 1134873654 |
// Licensed under the MIT license. See LICENSE file in the project root
// for full license information.
package net.dummydigit.qbranch.compiler
data class SourceCodeInfo(val path : String, val lineNo : Int) | compiler/src/main/kotlin/net/dummydigit/qbranch/compiler/SourceCodeInfo.kt | 3399345547 |
package ru.bartwell.exfilepicker.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import ru.bartwell.exfilepicker.data.FileInfo
import ru.bartwell.exfilepicker.data.config.Config
import ru.bartwell.exfilepicker.ui.theme.ExFilePickerTheme
import ru.bartwell.exfilepicker.ui.theme.ExFilePickerTypography
import ru.bartwell.exfilepicker.ui.theme.LocalColors
@Composable
internal fun MainScreen(exFilePickerConfig: Config) {
val viewModel = MainScreenViewModel(LocalContext.current, exFilePickerConfig)
val state by viewModel.stateFlow.collectAsState()
MainScreenContent(
state = state,
viewModel::onItemClick,
)
}
@Composable
private fun MainScreenContent(
state: MainScreenState,
onItemClick: (Int) -> Unit,
) {
Column(
modifier = Modifier.fillMaxSize()
) {
Text("Toolbar here")
LazyColumn(modifier = Modifier.fillMaxWidth()) {
items(state.files.size) { position ->
Item(state.files[position]) {
onItemClick(position)
}
}
}
}
}
@Composable
fun Item(
fileInfo: FileInfo,
onClick: () -> Unit
) {
Column(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 56.dp)
.clickable(onClick = onClick)
) {
Text(
text = fileInfo.fileName,
color = LocalColors.current.itemTitle,
style = ExFilePickerTypography.itemTitle
)
Text(
text = fileInfo.size.toString(),
color = LocalColors.current.itemSubtitle,
style = ExFilePickerTypography.itemSubtitle
)
}
}
@Suppress("MagicNumber")
@Preview(showBackground = true)
@Composable
private fun Preview() {
val files = listOf(
FileInfo("folder", "", "", true, 0, 0),
FileInfo("file.txt", "", "", false, 100_500, 0)
)
val config = Config()
ExFilePickerTheme(config.uiConfig) {
Surface {
MainScreenContent(
state = MainScreenState(config = config, files = files),
onItemClick = {},
)
}
}
}
| library/src/main/java/ru/bartwell/exfilepicker/ui/MainScreen.kt | 1718307143 |
package com.almapp.ucaccess.lib
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import nl.komponents.kovenant.Promise
import nl.komponents.kovenant.task
/**
* Created by patriciolopez on 05-02-16.
*/
fun Request.promise(): Promise<Triple<Request, Response, ByteArray>, Exception> = task {
response()
}
| app/src/main/java/com/almapp/ucaccess/lib/Requests.kt | 315453634 |
package me.proxer.library
import com.serjltt.moshi.adapters.FallbackEnum
import com.squareup.moshi.Moshi
import me.proxer.library.ProxerApi.Builder
import me.proxer.library.api.anime.AnimeApi
import me.proxer.library.api.apps.AppsApi
import me.proxer.library.api.chat.ChatApi
import me.proxer.library.api.comment.CommentApi
import me.proxer.library.api.forum.ForumApi
import me.proxer.library.api.info.InfoApi
import me.proxer.library.api.list.ListApi
import me.proxer.library.api.manga.MangaApi
import me.proxer.library.api.media.MediaApi
import me.proxer.library.api.messenger.MessengerApi
import me.proxer.library.api.notifications.NotificationsApi
import me.proxer.library.api.ucp.UcpApi
import me.proxer.library.api.user.UserApi
import me.proxer.library.api.users.UsersApi
import me.proxer.library.api.wiki.WikiApi
import me.proxer.library.internal.DefaultLoginTokenManager
import me.proxer.library.internal.adapter.BooleanAdapterFactory
import me.proxer.library.internal.adapter.ConferenceAdapter
import me.proxer.library.internal.adapter.ConferenceInfoAdapter
import me.proxer.library.internal.adapter.DateAdapter
import me.proxer.library.internal.adapter.DelimitedEnumSetAdapterFactory
import me.proxer.library.internal.adapter.DelimitedStringSetAdapterFactory
import me.proxer.library.internal.adapter.EnumRetrofitConverterFactory
import me.proxer.library.internal.adapter.EpisodeInfoAdapter
import me.proxer.library.internal.adapter.FixRatingDetailsAdapter
import me.proxer.library.internal.adapter.HttpUrlAdapter
import me.proxer.library.internal.adapter.NotificationAdapter
import me.proxer.library.internal.adapter.NotificationInfoAdapter
import me.proxer.library.internal.adapter.PageAdapter
import me.proxer.library.internal.adapter.ProxerResponseCallAdapterFactory
import me.proxer.library.internal.adapter.UcpSettingConstraintAdapter
import me.proxer.library.internal.adapter.UnitAdapter
import me.proxer.library.internal.interceptor.HeaderInterceptor
import me.proxer.library.internal.interceptor.HttpsEnforcingInterceptor
import me.proxer.library.internal.interceptor.LoginTokenInterceptor
import me.proxer.library.internal.interceptor.OneShotInterceptor
import me.proxer.library.internal.interceptor.RateLimitInterceptor
import me.proxer.library.util.ProxerUrls
import okhttp3.CertificatePinner
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
/**
* Entry point for access to the various APIs of Proxer.
*
* Before usage, you have to construct an instance through the [Builder].
*
* Note, that this is not a singleton. Each instance is separated from each other; You could even have instances with a
* different api key.
*
* @author Ruben Gees
*/
class ProxerApi private constructor(retrofit: Retrofit) {
companion object {
/** Special api key to enable the test mode. */
const val TEST_KEY = "test"
private val CERTIFICATES = arrayOf(
// https://censys.io/certificates/0687260331a72403d909f105e69bcf0d32e1bd2493ffc6d9206d11bcd6770739
"sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=",
// https://censys.io/certificates/16af57a9f676b0ab126095aa5ebadef22ab31119d644ac95cd4b93dbf3f26aeb
"sha256/Y9mvm0exBk1JoQ57f9Vm28jKo5lFm/woKcVxrYxu80o=",
// https://censys.io/certificates/1793927a0614549789adce2f8f34f7f0b66d0f3ae3a3b84d21ec15dbba4fadc7
"sha256/58qRu/uxh4gFezqAcERupSkRYBlBAvfcw7mEjGPLnNU=",
// https://censys.io/certificates/52f0e1c4e58ec629291b60317f074671b85d7ea80d5b07273463534b32b40234
"sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=",
// https://censys.io/certificates/96bcec06264976f37460779acf28c5a7cfe8a3c0aae11a8ffcee05c0bddf08c6
"sha256/C5+lpZ7tcVwmwQIMcRtPbsQtWLABXhQzejna0wHFr8M="
)
private const val DEFAULT_USER_AGENT = "ProxerLibJava/" + BuildConfig.VERSION
}
/**
* The respective API.
*/
val notifications = NotificationsApi(retrofit)
@JvmName("notifications") get
/**
* The respective API.
*/
val user = UserApi(retrofit)
@JvmName("user") get
/**
* The respective API.
*/
val users = UsersApi(retrofit)
@JvmName("users") get
/**
* The respective API.
*/
val info = InfoApi(retrofit)
@JvmName("info") get
/**
* The respective API.
*/
val messenger = MessengerApi(retrofit)
@JvmName("messenger") get
/**
* The respective API.
*/
val chat = ChatApi(retrofit)
@JvmName("chat") get
/**
* The respective API.
*/
val list = ListApi(retrofit)
@JvmName("list") get
/**
* The respective API.
*/
val ucp = UcpApi(retrofit)
@JvmName("ucp") get
/**
* The respective API.
*/
val anime = AnimeApi(retrofit)
@JvmName("anime") get
/**
* The respective API.
*/
val manga = MangaApi(retrofit)
@JvmName("manga") get
/**
* The respective API.
*/
val forum = ForumApi(retrofit)
@JvmName("forum") get
/**
* The respective API.
*/
val media = MediaApi(retrofit)
@JvmName("media") get
/**
* The respective API.
*/
val apps = AppsApi(retrofit)
@JvmName("apps") get
/**
* The respective API.
*/
val comment = CommentApi(retrofit)
@JvmName("comment") get
/**
* The respective API.
*/
val wiki = WikiApi(retrofit)
@JvmName("wiki") get
/**
*
* You can set customized instances of the internally used libraries: Moshi, OkHttp and Retrofit.
* Moreover you can specify your own [LoginTokenManager] and user agent.
*
* @constructor Constructs a new instance of the builder, with the passed api key.
*/
class Builder(private val apiKey: String) {
private var loginTokenManager: LoginTokenManager? = null
private var userAgent: String? = null
private var moshi: Moshi? = null
private var client: OkHttpClient? = null
private var retrofit: Retrofit? = null
private var enableRateLimitProtection: Boolean = false
/**
* Sets a custom login token manager.
*/
fun loginTokenManager(loginTokenManager: LoginTokenManager) = this.apply {
this.loginTokenManager = loginTokenManager
}
/**
* Sets a custom user agent.
*
* If not set, it will default to "ProxerLibJava/<version>"
*/
fun userAgent(userAgent: String) = this.apply { this.userAgent = userAgent }
/**
* Sets a custom Moshi instance.
*
* Note that a internally a new instance will be constructed with the adjustments included you did on your
* instance.
*/
fun moshi(moshi: Moshi) = this.apply { this.moshi = moshi }
/**
* Sets a custom OkHttp instance.
*
* Note that internally a new instance will be constructed with the adjustments included you did on your
* instance.
*/
fun client(client: OkHttpClient) = this.apply { this.client = client }
/**
* Sets a custom Retrofit instance.
*
* Note that a internally a new instance will be constructed with the adjustments included you did on your
* instance.
*/
fun retrofit(retrofit: Retrofit) = this.apply { this.retrofit = retrofit }
/**
* Enables the rate limit protection to avoid users having to fill out captchas.
*/
fun enableRateLimitProtection() = this.apply { this.enableRateLimitProtection = true }
/**
* Finally builds the [ProxerApi] with the provided adjustments.
*/
fun build(): ProxerApi {
val moshi = buildMoshi()
return ProxerApi(buildRetrofit(moshi))
}
private fun buildRetrofit(moshi: Moshi): Retrofit {
return (retrofit?.newBuilder() ?: Retrofit.Builder())
.baseUrl(ProxerUrls.apiBase)
.client(buildClient(moshi))
.addCallAdapterFactory(ProxerResponseCallAdapterFactory())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addConverterFactory(EnumRetrofitConverterFactory())
.build()
}
private fun buildClient(moshi: Moshi): OkHttpClient {
return (client?.newBuilder() ?: OkHttpClient.Builder())
.apply {
interceptors().apply {
addAll(
0,
listOf(
HeaderInterceptor(apiKey, buildUserAgent()),
LoginTokenInterceptor(buildLoginTokenManager()),
HttpsEnforcingInterceptor(),
OneShotInterceptor()
)
)
if (enableRateLimitProtection) add(4, RateLimitInterceptor(moshi, client?.cache))
}
certificatePinner(constructCertificatePinner())
}
.build()
}
private fun buildLoginTokenManager(): LoginTokenManager {
return loginTokenManager ?: DefaultLoginTokenManager()
}
private fun buildUserAgent(): String {
return userAgent ?: DEFAULT_USER_AGENT
}
private fun constructCertificatePinner(): CertificatePinner {
return CertificatePinner.Builder()
.apply { CERTIFICATES.forEach { add(ProxerUrls.webBase.host, it) } }
.build()
}
private fun buildMoshi(): Moshi {
return (moshi?.newBuilder() ?: Moshi.Builder())
.add(UnitAdapter())
.add(DateAdapter())
.add(PageAdapter())
.add(HttpUrlAdapter())
.add(ConferenceAdapter())
.add(EpisodeInfoAdapter())
.add(NotificationAdapter())
.add(ConferenceInfoAdapter())
.add(BooleanAdapterFactory())
.add(NotificationInfoAdapter())
.add(FixRatingDetailsAdapter())
.add(UcpSettingConstraintAdapter())
.add(DelimitedEnumSetAdapterFactory())
.add(DelimitedStringSetAdapterFactory())
.add(FallbackEnum.ADAPTER_FACTORY)
.build()
}
}
}
| library/src/main/kotlin/me/proxer/library/ProxerApi.kt | 503651277 |
package com.vicpin.krealmextensions
import android.support.test.runner.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import com.vicpin.krealmextensions.model.TestEntity
import com.vicpin.krealmextensions.model.TestEntityAutoPK
import com.vicpin.krealmextensions.model.TestEntityPK
import com.vicpin.krealmextensions.util.TestRealmConfigurationFactory
import io.realm.Realm
import io.realm.Sort
import io.realm.exceptions.RealmPrimaryKeyConstraintException
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
/**
* Created by victor on 10/1/17.
*/
@RunWith(AndroidJUnit4::class)
class KRealmExtensionsTests {
@get:Rule
var configFactory = TestRealmConfigurationFactory()
lateinit var realm: Realm
lateinit var latch: CountDownLatch
var latchReleased = false
@Before
fun setUp() {
val realmConfig = configFactory.createConfiguration()
realm = Realm.getInstance(realmConfig)
latch = CountDownLatch(1)
}
@After
fun tearDown() {
TestEntity().deleteAll()
TestEntityPK().deleteAll()
TestEntityAutoPK().deleteAll()
realm.close()
latchReleased = false
}
/**
* PERSISTENCE TESTS
*/
@Test
fun testPersistEntityWithCreate() {
TestEntity().create() //No exception expected
}
@Test
fun testPersistEntityWithCreateManaged() {
val result = TestEntity().createManaged(realm) //No exception expected
assertThat(result.isManaged).isTrue()
}
@Test
fun testPersistPKEntityWithCreate() {
TestEntityPK(1).create() //No exception expected
}
@Test
fun testPersistPKEntityWithCreateManaged() {
val result = TestEntityPK(1).createManaged(realm) //No exception expected
assertThat(result.isManaged).isTrue()
}
@Test(expected = IllegalArgumentException::class)
fun testPersistEntityWithCreateOrUpdateMethod() {
TestEntity().createOrUpdate() //Exception expected due to TestEntity has no primary key
}
@Test(expected = IllegalArgumentException::class)
fun testPersistEntityWithCreateOrUpdateMethodManaged() {
TestEntity().createOrUpdateManaged(realm) //Exception expected due to TestEntity has no primary key
}
fun testPersistPKEntityWithCreateOrUpdateMethod() {
TestEntityPK(1).createOrUpdate() //No exception expected
}
fun testPersistPKEntityWithCreateOrUpdateMethodManaged() {
val result = TestEntityPK(1).createOrUpdateManaged(realm) //No exception expected
assertThat(result.isManaged).isTrue()
}
@Test
fun testPersistEntityWithSaveMethod() {
TestEntity().save() //No exception expected
}
@Test
fun testPersistEntityWithSaveMethodManaged() {
val result = TestEntity().saveManaged(realm) //No exception expected
assertThat(result.isManaged)
assertThat(TestEntity().count(realm)).isEqualTo(1)
}
@Test
fun testPersistPKEntityWithSaveMethod() {
TestEntityPK(1).save() //No exception expected
}
@Test
fun testPersistPKEntityWithSaveMethodManaged() {
val result = TestEntityPK(1).saveManaged(realm) //No exception expected
assertThat(result.isManaged).isTrue()
assertThat(TestEntityPK().count(realm)).isEqualTo(1)
}
@Test(expected = RealmPrimaryKeyConstraintException::class)
fun testPersistPKEntityWithCreateMethodAndSamePrimaryKey() {
TestEntityPK(1).create() //No exception expected
TestEntityPK(1).create() //Exception expected
}
@Test(expected = RealmPrimaryKeyConstraintException::class)
fun testPersistPKEntityWithCreateMethodAndSamePrimaryKeyManaged() {
val result = TestEntityPK(1).createManaged(realm) //No exception expected
assertThat(result.isManaged).isTrue()
TestEntityPK(1).createManaged(realm) //Exception expected
}
@Test
fun testPersistPKEntityListWithSaveMethod() {
val list = listOf(TestEntityPK(1), TestEntityPK(2), TestEntityPK(3))
list.saveAll()
}
@Test
fun testPersistPKEntityListWithSaveMethodManaged() {
val list = listOf(TestEntityPK(1), TestEntityPK(2), TestEntityPK(3))
val results = list.saveAllManaged(realm)
results.forEach { assertThat(it.isManaged).isTrue() }
}
@Test
fun testCountPKEntity() {
val list = listOf(TestEntityPK(1), TestEntityPK(2), TestEntityPK(3))
list.saveAll()
assertThat(TestEntityPK().count()).isEqualTo(3)
}
@Test
fun testCountDuplicatePKEntity() {
val list = listOf(TestEntityPK(1), TestEntityPK(1), TestEntityPK(1))
list.saveAll()
assertThat(TestEntityPK().count()).isEqualTo(1)
}
@Test
fun testCountEntity() {
val list = listOf(TestEntity(), TestEntity(), TestEntity())
list.saveAll()
assertThat(TestEntity().count()).isEqualTo(3)
}
/**
* PERSISTENCE TEST WITH AUTO PRIMARY KEY
*/
@Test
fun testPersistAutoPKEntityWithSaveMethod() {
TestEntityAutoPK().save() //No exception expected
}
@Test
fun testPersistAutoPKEntityWithSaveMethodShouldHavePK() {
TestEntityAutoPK().save()
assertThat(TestEntityAutoPK().count()).isEqualTo(1)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(1)
TestEntityAutoPK().save()
assertThat(TestEntityAutoPK().count()).isEqualTo(2)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(2)
TestEntityAutoPK().save()
assertThat(TestEntityAutoPK().count()).isEqualTo(3)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(3)
}
@Test
fun testPersistAutoPkEntityWithPkShouldNotBeOverrided() {
TestEntityAutoPK(4, "").save()
assertThat(TestEntityAutoPK().count()).isEqualTo(1)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(4)
TestEntityAutoPK(10, "").save()
assertThat(TestEntityAutoPK().count()).isEqualTo(2)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(10)
TestEntityAutoPK(12, "").save()
assertThat(TestEntityAutoPK().count()).isEqualTo(3)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(12)
}
@Test
fun testPersistAutoPKEntityWithSaveManagedMethod() {
val result = TestEntityAutoPK().saveManaged(realm)
assertThat(result.isManaged)
assertThat(TestEntityAutoPK().count(realm)).isEqualTo(1)
}
@Test
fun testPersistAutoPKEntityListWithSaveMethod() {
val list = listOf(TestEntityAutoPK(), TestEntityAutoPK(), TestEntityAutoPK())
list.saveAll()
assertThat(TestEntityAutoPK().count()).isEqualTo(3)
assertThat(TestEntityAutoPK().queryFirst()?.id).isEqualTo(1)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(3)
}
@Test
fun testPersistAutoPKEntityArrayWithSaveMethod() {
val list = arrayOf(TestEntityAutoPK(), TestEntityAutoPK(), TestEntityAutoPK())
list.saveAll()
assertThat(TestEntityAutoPK().count()).isEqualTo(3)
assertThat(TestEntityAutoPK().queryFirst()?.id).isEqualTo(1)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(3)
}
@Test
fun testPersistAutoPKEntityListWithSaveManagedMethod() {
val list = listOf(TestEntityAutoPK(), TestEntityAutoPK(), TestEntityAutoPK())
list.saveAllManaged(realm)
assertThat(TestEntityAutoPK().count(realm)).isEqualTo(3)
}
@Test
fun testPersistAutoPKEntityArrayWithSavemanagedMethod() {
val list = arrayOf(TestEntityAutoPK(), TestEntityAutoPK(), TestEntityAutoPK())
list.saveAllManaged(realm)
assertThat(TestEntityAutoPK().count(realm)).isEqualTo(3)
}
@Test
fun testUpdateEntity() {
TestEntity("test").save()
TestEntity().queryAndUpdate({ equalTo("name", "test") }) {
it.name = "updated"
}
val result = TestEntity().queryFirst { equalTo("name", "updated") }
assertThat(result).isNotNull()
assertThat(result?.name).isEqualTo("updated")
}
@Test
fun testUpdatePKEntity() {
TestEntityPK(1, "test").save()
TestEntityPK().queryAndUpdate({ equalTo("name", "test") }) {
it.name = "updated"
}
val result = TestEntityPK().queryFirst { equalTo("name", "updated") }
assertThat(result).isNotNull()
assertThat(result?.name).isEqualTo("updated")
}
/**
* QUERY TESTS WITH EMPTY DB
*/
@Test
fun testQueryFirstObjectWithEmptyDBShouldReturnNull() {
assertThat(TestEntity().queryFirst()).isNull()
}
@Test
fun testAsyncQueryFirstObjectWithEmptyDBShouldReturnNull() {
block {
TestEntity().queryFirstAsync { assertThat(it).isNull(); release() }
}
}
@Test
fun testQueryLastObjectWithEmptyDBShouldReturnNull() {
assertThat(TestEntity().queryLast()).isNull()
}
@Test
fun testQueryLastObjectWithConditionAndEmptyDBShouldReturnNull() {
assertThat(TestEntity().queryLast { equalTo("name", "test") }).isNull()
}
@Test
fun testAsyncQueryLastObjectWithEmptyDBShouldReturnNull() {
block {
TestEntity().queryLastAsync { assertThat(it).isNull(); release() }
}
}
@Test
fun testAllItemsShouldReturnEmptyCollectionWhenDBIsEmpty() {
assertThat(TestEntity().queryAll()).hasSize(0)
}
@Test
fun testAllItemsAsyncShouldReturnEmptyCollectionWhenDBIsEmpty() {
block {
TestEntity().queryAllAsync { assertThat(it).hasSize(0); release() }
}
}
@Test
fun testQueryConditionalWhenDBIsEmpty() {
val result = TestEntity().query { equalTo("name", "test") }
assertThat(result).hasSize(0)
}
@Test
fun testQueryFirstItemWhenDBIsEmpty() {
val result = TestEntity().queryFirst { equalTo("name", "test") }
assertThat(result).isNull()
}
@Test
fun testQuerySortedWhenDBIsEmpty() {
val result = TestEntity().querySorted("name", Sort.ASCENDING) { equalTo("name", "test") }
assertThat(result).hasSize(0)
}
/**
* QUERY TESTS WITH POPULATED DB
*/
@Test
fun testQueryFirstItemShouldReturnFirstItemWhenDBIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
assertThat(TestEntityPK().queryFirst()).isNotNull()
assertThat(TestEntityPK().queryFirst()?.id).isEqualTo(0)
}
@Test
fun testAsyncQueryFirstItemShouldReturnFirstItemWhenDBIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
block {
TestEntityPK().queryFirstAsync {
assertThat(it).isNotNull()
assertThat(it?.id).isEqualTo(0)
release()
}
}
}
@Test
fun testQueryLastItemShouldReturnLastItemWhenDBIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
assertThat(TestEntityPK().queryLast()?.id).isEqualTo(4)
}
@Test
fun testQueryLastItemWithConditionShouldReturnLastItemWhenDBIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
assertThat(TestEntityPK().queryLast { equalToValue("id", 3) }?.id).isEqualTo(3)
}
@Test
fun testAsyncQueryLastItemShouldReturnLastItemWhenDBIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
block {
TestEntityPK().queryLastAsync {
assertThat(it).isNotNull()
release()
}
}
}
@Test
fun testQueryAllItemsShouldReturnAllItemsWhenDBIsNotEmpty() {
populateDBWithTestEntity(numItems = 5)
assertThat(TestEntity().queryAll()).hasSize(5)
}
@Test
fun testAsyncQueryAllItemsShouldReturnAllItemsWhenDBIsNotEmpty() {
populateDBWithTestEntity(numItems = 5)
block {
TestEntity().queryAllAsync { assertThat(it).hasSize(5); release() }
}
}
@Test
fun testQueryAllItemsAfterSaveCollection() {
val list = listOf(TestEntityPK(1), TestEntityPK(2), TestEntityPK(3))
list.saveAll()
assertThat(TestEntityPK().queryAll()).hasSize(3)
}
/**
* QUERY TESTS WITH WHERE STATEMENT
*/
@Test
fun testWhereQueryShouldReturnExpectedItems() {
populateDBWithTestEntityPK(numItems = 5)
val results = TestEntityPK().query { equalToValue("id", 1) }
assertThat(results).hasSize(1)
assertThat(results.first().id).isEqualTo(1)
}
@Test
fun testAsyncWhereQueryShouldReturnExpectedItems() {
populateDBWithTestEntityPK(numItems = 5)
block {
TestEntityPK().queryAsync({ equalToValue("id", 1) }) { results ->
assertThat(results).hasSize(1)
assertThat(results.first().id).isEqualTo(1)
release()
}
}
}
@Test
fun testWhereQueryShouldNotReturnAnyItem() {
populateDBWithTestEntityPK(numItems = 5)
val results = TestEntityPK().query { equalToValue("id", 6) }
assertThat(results).hasSize(0)
}
@Test
fun testAsyncWhereQueryShouldNotReturnAnyItem() {
populateDBWithTestEntityPK(numItems = 5)
block {
TestEntityPK().queryAsync({ equalToValue("id", 6) }) { results ->
assertThat(results).hasSize(0)
release()
}
}
}
@Test
fun testFirstItemWhenDbIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
val result = TestEntityPK().queryFirst { equalToValue("id", 2) }
assertThat(result).isNotNull()
assertThat(result?.id).isEqualTo(2)
}
@Test
fun testQueryAscendingShouldReturnOrderedResults() {
populateDBWithTestEntityPK(numItems = 5)
val result = TestEntityPK().querySorted("id", Sort.ASCENDING)
assertThat(result).hasSize(5)
assertThat(result.first().id).isEqualTo(0)
assertThat(result.last().id).isEqualTo(4)
}
@Test
fun testQueryDescendingShouldReturnOrderedResults() {
populateDBWithTestEntityPK(numItems = 5)
val result = TestEntityPK().querySorted("id", Sort.DESCENDING)
assertThat(result).hasSize(5)
assertThat(result.first().id).isEqualTo(4)
assertThat(result.last().id).isEqualTo(0)
}
@Test
fun testQueryDescendingWithFilterShouldReturnOrderedResults() {
populateDBWithTestEntityPK(numItems = 5)
val result = TestEntityPK().querySorted("id", Sort.DESCENDING) {
lessThan("id", 3).greaterThan("id", 0)
}
assertThat(result).hasSize(2)
assertThat(result.first().id).isEqualTo(2)
assertThat(result.last().id).isEqualTo(1)
}
/**
* DELETION TESTS
*/
@Test
fun testDeleteEntities() {
populateDBWithTestEntity(numItems = 5)
TestEntity().deleteAll()
assertThat(TestEntity().queryAll()).hasSize(0)
}
@Test
fun testDeleteEntitiesWithPK() {
populateDBWithTestEntityPK(numItems = 5)
TestEntityPK().deleteAll()
assertThat(TestEntityPK().queryAll()).hasSize(0)
}
@Test
fun testDeleteEntitiesWithStatement() {
populateDBWithTestEntityPK(numItems = 5)
TestEntityPK().delete { equalToValue("id", 1) }
assertThat(TestEntityPK().queryAll()).hasSize(4)
}
/**
* UTILITY TEST METHODS
*/
private fun populateDBWithTestEntity(numItems: Int) {
(0..numItems - 1).forEach { TestEntity().save() }
}
private fun populateDBWithTestEntityPK(numItems: Int) {
(0..numItems - 1).forEach { TestEntityPK(it.toLong()).save() }
}
private fun blockLatch() {
if (!latchReleased) {
latch.await()
}
}
private fun release() {
latchReleased = true
latch.countDown()
latch = CountDownLatch(1)
}
fun block(closure: () -> Unit) {
latchReleased = false
closure()
blockLatch()
}
}
| library-base/src/androidTest/java/com/vicpin/krealmextensions/KRealmExtensionsTests.kt | 17253271 |
package br.com.wakim.eslpodclient.data.model
import android.os.Parcel
import android.os.Parcelable
import java.util.*
data class PodcastList(var currentPageToken : String? = null, var nextPageToken : String? = null) : Parcelable {
var list : ArrayList<PodcastItem> = ArrayList()
constructor(source: Parcel) : this() {
source.readList(list, PodcastList::class.java.classLoader)
currentPageToken = source.readString()
nextPageToken = source.readString()
}
override fun writeToParcel(p0: Parcel, p1: Int) {
p0.writeTypedList(list)
p0.writeString(currentPageToken)
p0.writeString(nextPageToken)
}
override fun describeContents(): Int = 0
companion object {
@JvmField val CREATOR: Parcelable.Creator<PodcastList> = object : Parcelable.Creator<PodcastList> {
override fun createFromParcel(source: Parcel): PodcastList {
return PodcastList(source)
}
override fun newArray(size: Int): Array<PodcastList?> {
return arrayOfNulls(size)
}
}
}
}
| app/src/main/java/br/com/wakim/eslpodclient/data/model/PodcastList.kt | 489029848 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* 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:Suppress("UNUSED", "PublicApiImplicitType", "KDocMissingDocumentation")
package jp.nephy.penicillin.models
import jp.nephy.jsonkt.*
import jp.nephy.jsonkt.delegation.*
import jp.nephy.penicillin.core.session.ApiClient
data class SavedSearch(override val json: JsonObject, override val client: ApiClient): PenicillinModel {
val createdAtRaw by string("created_at")
val id by long
val idStr by string("id_str")
val name by string
val position by string
val query by string
override fun equals(other: Any?): Boolean {
return id == (other as? SavedSearch)?.id
}
override fun hashCode(): Int {
return id.hashCode()
}
}
| src/main/kotlin/jp/nephy/penicillin/models/SavedSearch.kt | 3466266571 |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl
import org.gradle.api.artifacts.dsl.DependencyLockingHandler
import org.gradle.api.initialization.dsl.ScriptHandler
/**
* Configures the dependency locking for the script dependency configurations.
*
* @since 6.1
*/
fun ScriptHandler.dependencyLocking(configuration: DependencyLockingHandler.() -> Unit) =
dependencyLocking.configuration()
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/ScriptHandlerExtensions.kt | 1405382889 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.