content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* 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.datastore
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.okio.OkioSerializer
import okio.BufferedSink
import okio.BufferedSource
import okio.EOFException
import okio.IOException
import okio.use
class TestingOkioSerializer(
val config: TestingSerializerConfig
) : OkioSerializer<Byte> {
override suspend fun readFrom(source: BufferedSource): Byte {
if (config.failReadWithCorruptionException) {
throw CorruptionException(
"CorruptionException",
IOException("I was asked to fail with corruption on reads")
)
}
if (config.failingRead) {
throw IOException("I was asked to fail on reads")
}
val read = try {
source.use {
it.readInt()
}
} catch (eof: EOFException) {
return 0
}
return read.toByte()
}
override suspend fun writeTo(t: Byte, sink: BufferedSink) {
if (config.failingWrite) {
throw IOException("I was asked to fail on writes")
}
sink.use {
it.writeInt(t.toInt())
}
}
override val defaultValue: Byte
get() = config.defaultValue
} | testutils/testutils-datastore/src/commonMain/kotlin/androidx/datastore/TestingOkioSerializer.kt | 1077311345 |
/*
* Copyright 2019 Peter Kenji Yamanaka
*
* 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.pyamsoft.padlock.list.info
import com.pyamsoft.padlock.model.list.ActivityEntry
interface LockInfoGroupView {
fun bind(
model: ActivityEntry.Group,
packageName: String
)
fun unbind()
}
| padlock/src/main/java/com/pyamsoft/padlock/list/info/LockInfoGroupView.kt | 2873315679 |
package abi44_0_0.expo.modules.sensors
import android.content.Context
import abi44_0_0.expo.modules.sensors.modules.AccelerometerModule
import abi44_0_0.expo.modules.sensors.modules.BarometerModule
import abi44_0_0.expo.modules.sensors.modules.DeviceMotionModule
import abi44_0_0.expo.modules.sensors.modules.GyroscopeModule
import abi44_0_0.expo.modules.sensors.modules.MagnetometerModule
import abi44_0_0.expo.modules.sensors.modules.MagnetometerUncalibratedModule
import abi44_0_0.expo.modules.sensors.modules.PedometerModule
import abi44_0_0.expo.modules.sensors.services.AccelerometerService
import abi44_0_0.expo.modules.sensors.services.BarometerService
import abi44_0_0.expo.modules.sensors.services.GravitySensorService
import abi44_0_0.expo.modules.sensors.services.GyroscopeService
import abi44_0_0.expo.modules.sensors.services.LinearAccelerationSensorService
import abi44_0_0.expo.modules.sensors.services.MagnetometerService
import abi44_0_0.expo.modules.sensors.services.MagnetometerUncalibratedService
import abi44_0_0.expo.modules.sensors.services.PedometerService
import abi44_0_0.expo.modules.sensors.services.RotationVectorSensorService
import abi44_0_0.expo.modules.core.BasePackage
import abi44_0_0.expo.modules.core.ExportedModule
import abi44_0_0.expo.modules.core.interfaces.InternalModule
class SensorsPackage : BasePackage() {
override fun createInternalModules(context: Context): List<InternalModule> {
return listOf<InternalModule>(
AccelerometerService(context),
BarometerService(context),
GravitySensorService(context),
GyroscopeService(context),
LinearAccelerationSensorService(context),
MagnetometerService(context),
MagnetometerUncalibratedService(context),
RotationVectorSensorService(context),
PedometerService(context)
)
}
override fun createExportedModules(context: Context): List<ExportedModule> {
return listOf<ExportedModule>(
AccelerometerModule(context),
BarometerModule(context),
GyroscopeModule(context),
DeviceMotionModule(context),
MagnetometerModule(context),
MagnetometerUncalibratedModule(context),
PedometerModule(context)
)
}
}
| android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/sensors/SensorsPackage.kt | 188806356 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
/**
* Nest imports 1 depth
*
* ```
* use a::b::foo;
* use a::b::bar;
* ```
*
* to this:
*
* ```
* use a::{
* b::foo,
* b::bar
* }
* ```
*/
class NestUseStatementsIntention : RsElementBaseIntentionAction<NestUseStatementsIntention.Context>() {
override fun getText() = "Nest use statements"
override fun getFamilyName() = text
interface Context {
val useSpecks: List<RsUseSpeck>
val root: PsiElement
val firstOldElement: PsiElement
fun createElement(path: String, project: Project): PsiElement
val oldElements: List<PsiElement>
val cursorOffset: Int
val basePath: String
}
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val useItemOnCursor = element.ancestorStrict<RsUseItem>() ?: return null
val useGroupOnCursor = element.ancestorStrict<RsUseGroup>()
val useSpeckOnCursor = element.ancestorStrict<RsUseSpeck>() ?: return null
return if (useGroupOnCursor != null) {
PathInGroup.create(useGroupOnCursor, useSpeckOnCursor)
} else {
PathInUseItem.create(useItemOnCursor, useSpeckOnCursor)
}
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val path = makeGroupedPath(ctx.basePath, ctx.useSpecks)
val inserted = ctx.root.addAfter(ctx.createElement(path, project), ctx.firstOldElement)
for (prevElement in ctx.oldElements) {
val existingComment = prevElement.childrenWithLeaves.firstOrNull() as? PsiComment
if (existingComment != null) {
ctx.root.addBefore(existingComment, inserted)
}
prevElement.delete()
}
val nextUseSpeckExists = inserted.rightSiblings.filterIsInstance<RsUseSpeck>().count() > 0
if (nextUseSpeckExists) {
ctx.root.addAfter(RsPsiFactory(project).createComma(), inserted)
}
editor.caretModel.moveToOffset(inserted!!.startOffset + ctx.cursorOffset)
}
private fun makeGroupedPath(basePath: String, useSpecks: List<RsUseSpeck>): String {
val useSpecksInGroup = useSpecks.flatMap { useSpeck ->
if (useSpeck.path?.text == basePath) {
// Remove first group
useSpeck.useGroup?.let { useGroup ->
return@flatMap useGroup.useSpeckList.map { it.text }
}
useSpeck.alias?.let { alias ->
return@flatMap listOf("self ${alias.text}")
}
}
listOf(deleteBasePath(useSpeck.text, basePath))
}
return useSpecksInGroup.joinToString(",\n", "$basePath::{\n", "\n}")
}
private fun deleteBasePath(fullPath: String, basePath: String): String {
return when {
fullPath == basePath -> "self"
fullPath.startsWith(basePath) -> fullPath.removePrefix("$basePath::")
else -> fullPath
}
}
class PathInUseItem(
private val useItem: RsUseItem,
useItems: List<RsUseItem>,
override val basePath: String
) : Context {
companion object {
fun create(useItemOnCursor: RsUseItem, useSpeck: RsUseSpeck): PathInUseItem? {
val useItemList = mutableListOf<RsUseItem>()
val basePath = useSpeck.path?.let(::getBasePathFromPath) ?: return null
val visibility = useItemOnCursor.visibility
useItemList += useItemOnCursor.leftSiblings.filterIsInstance<RsUseItem>()
.filter { it.useSpeck?.path?.let(::getBasePathFromPath) == basePath && it.visibility == visibility }
useItemList.add(useItemOnCursor)
useItemList += useItemOnCursor.rightSiblings.filterIsInstance<RsUseItem>()
.filter { it.useSpeck?.path?.let(::getBasePathFromPath) == basePath && it.visibility == visibility }
if (useItemList.size == 1) return null
return PathInUseItem(useItemOnCursor, useItemList, basePath)
}
}
override fun createElement(path: String, project: Project): PsiElement {
return RsPsiFactory(project).createUseItem(path, useItem.vis?.text ?: "")
}
override val useSpecks: List<RsUseSpeck> = useItems.mapNotNull { it.useSpeck }
override val oldElements: List<PsiElement> = useItems
override val firstOldElement: PsiElement = useItems.first()
override val root: PsiElement = useItem.parent
override val cursorOffset: Int = "use ".length
}
class PathInGroup(
useGroup: RsUseGroup,
override val useSpecks: List<RsUseSpeck>,
override val basePath: String
) : Context {
companion object {
fun create(useGroup: RsUseGroup, useSpeckOnCursor: RsUseSpeck): PathInGroup? {
val useSpeckList = mutableListOf<RsUseSpeck>()
val basePath = useSpeckOnCursor.path?.let(::getBasePathFromPath) ?: return null
useSpeckList += useSpeckOnCursor.leftSiblings.filterIsInstance<RsUseSpeck>()
.filter { it.path?.let(::getBasePathFromPath) == basePath }
useSpeckList.add(useSpeckOnCursor)
useSpeckList += useSpeckOnCursor.rightSiblings.filterIsInstance<RsUseSpeck>()
.filter { it.path?.let(::getBasePathFromPath) == basePath }
if (useSpeckList.size == 1) return null
return PathInGroup(useGroup, useSpeckList, basePath)
}
}
override fun createElement(path: String, project: Project): PsiElement {
return RsPsiFactory(project).createUseSpeck(path)
}
override val oldElements: List<PsiElement> =
useSpecks.flatMap {
val nextComma = if (it.nextSibling.elementType == RsElementTypes.COMMA) {
it.nextSibling
} else {
null
}
listOf(it, nextComma)
}.filterNotNull()
override val firstOldElement: PsiElement = useSpecks.first()
override val root = useGroup
override val cursorOffset: Int = 0
}
}
/**
* Get base path.
* If the path starts with :: contains it
*
* ex) a::b::c -> a
* ex) ::a::b::c -> ::a
*/
fun getBasePathFromPath(path: RsPath): String {
val basePath = path.basePath()
val basePathColoncolon = basePath.coloncolon
return if (basePathColoncolon != null) {
"::${basePath.referenceName.orEmpty()}"
} else {
basePath.referenceName.orEmpty()
}
}
| src/main/kotlin/org/rust/ide/intentions/NestUseStatementsIntention.kt | 3987037630 |
package com.ee.internal
import android.graphics.Point
import androidx.annotation.AnyThread
import com.ee.IBannerAd
import com.ee.IMessageBridge
import com.ee.Utils
import kotlinx.serialization.Serializable
/**
* Created by Zinge on 10/12/17.
*/
class BannerAdHelper(private val _bridge: IMessageBridge,
private val _view: IBannerAd,
private val _helper: MessageHelper) {
@Serializable
@Suppress("unused")
private class GetPositionResponse(
val x: Int,
val y: Int
)
@Serializable
private class SetPositionRequest(
val x: Int,
val y: Int
)
@Serializable
@Suppress("unused")
private class GetSizeResponse(
val width: Int,
val height: Int
)
@Serializable
private class SetSizeRequest(
val width: Int,
val height: Int
)
@AnyThread
fun registerHandlers() {
_bridge.registerHandler(_helper.isLoaded) {
Utils.toString(_view.isLoaded)
}
_bridge.registerHandler(_helper.load) {
_view.load()
""
}
_bridge.registerHandler(_helper.getPosition) {
val position = _view.position
val response = GetPositionResponse(position.x, position.y)
response.serialize()
}
_bridge.registerHandler(_helper.setPosition) { message ->
val request = deserialize<SetPositionRequest>(message)
_view.position = Point(request.x, request.y)
""
}
_bridge.registerHandler(_helper.getSize) {
val size = _view.size
val response = GetSizeResponse(size.x, size.y)
response.serialize()
}
_bridge.registerHandler(_helper.setSize) { message ->
val request = deserialize<SetSizeRequest>(message)
_view.size = Point(request.width, request.height)
""
}
_bridge.registerHandler(_helper.isVisible) {
Utils.toString(_view.isVisible)
}
_bridge.registerHandler(_helper.setVisible) { message ->
_view.isVisible = Utils.toBoolean(message)
""
}
}
@AnyThread
fun deregisterHandlers() {
_bridge.deregisterHandler(_helper.isLoaded)
_bridge.deregisterHandler(_helper.load)
_bridge.deregisterHandler(_helper.getPosition)
_bridge.deregisterHandler(_helper.setPosition)
_bridge.deregisterHandler(_helper.getSize)
_bridge.deregisterHandler(_helper.setSize)
_bridge.deregisterHandler(_helper.isVisible)
_bridge.deregisterHandler(_helper.setVisible)
}
} | src/android/ads/src/main/java/com/ee/internal/BannerAdHelper.kt | 2981617558 |
package edu.ptu.java.app_kotlin.di.hilt.app
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import dagger.hilt.android.AndroidEntryPoint
import edu.ptu.java.app_kotlin.di.hilt.app.viewmodel.HViewModel
@AndroidEntryPoint
class HFragment : Fragment(){
private val viewModel by viewModels<HViewModel>()
fun getViewModel(): ViewModel {
return viewModel
}
} | app_kotlin/src/main/java/edu/ptu/java/app_kotlin/di/hilt/app/HFragment.kt | 1041137922 |
package de.tum.`in`.tumcampusapp.component.ui.transportation.model.efa
import de.tum.`in`.tumcampusapp.component.ui.transportation.api.MvvDeparture
import org.joda.time.DateTime
import org.joda.time.Minutes
data class Departure(
val servingLine: String = "",
val direction: String = "",
val symbol: String = "",
val countDown: Int = -1,
val departureTime: DateTime = DateTime()
) {
/**
* Calculates the countDown with the real departure time and the current time
*
* @return The calculated countDown in minutes
*/
val calculatedCountDown: Int
get() = Minutes.minutesBetween(DateTime.now(), departureTime).minutes
val formattedDirection: String
get() = direction
.replace(",", ", ")
.replace("\\s+".toRegex(), " ")
companion object {
fun create(mvvDeparture: MvvDeparture): Departure {
return Departure(
mvvDeparture.servingLine.name,
mvvDeparture.servingLine.direction,
mvvDeparture.servingLine.symbol,
mvvDeparture.countdown,
mvvDeparture.dateTime
)
}
}
}
| app/src/main/java/de/tum/in/tumcampusapp/component/ui/transportation/model/efa/Departure.kt | 3503366730 |
/*
* Copyright 2018 Priyank Vasa
* 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.pvryan.easycryptsample.main
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pvryan.easycryptsample.R
import com.pvryan.easycryptsample.data.models.Card
import com.pvryan.easycryptsample.extensions.gone
import com.pvryan.easycryptsample.extensions.show
import com.transitionseverywhere.Rotate
import com.transitionseverywhere.TransitionManager
import kotlinx.android.synthetic.main.card_view_main.view.*
class MainAdapter(private val mDataset: ArrayList<Card>) : RecyclerView.Adapter<MainAdapter.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindItems(mDataset[position])
holder.itemView.buttonExpandCollapse.setOnClickListener {
TransitionManager.beginDelayedTransition(it.parent as ViewGroup, Rotate())
with(holder.itemView.tvDesc) {
if (visibility == View.VISIBLE) {
it.rotation = 0f
gone(true)
} else {
it.rotation = 180f
show(true)
}
}
}
}
override fun getItemCount() = mDataset.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.card_view_main, parent, false)
return ViewHolder(v)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(card: Card) {
itemView.tvTitle.text = card.title
itemView.tvDesc.text = card.desc
itemView.buttonAction1.text = card.actionText1
itemView.buttonAction2.text = card.actionText2
if (card.action1 == null) {
itemView.buttonAction1.visibility = View.GONE
} else {
itemView.buttonAction1.setOnClickListener(card.action1)
}
if (card.action2 == null) {
itemView.buttonAction2.visibility = View.GONE
} else {
itemView.buttonAction2.setOnClickListener(card.action2)
}
}
}
}
| appKotlin/src/main/java/com/pvryan/easycryptsample/main/MainAdapter.kt | 293276285 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.work
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class DataTest {
@Test
fun testDataExtensions() {
val data = workDataOf(
"one" to 1,
"two" to 2L,
"three" to "Three",
"four" to longArrayOf(1L, 2L)
)
assertEquals(data.getInt("one", 0), 1)
assertEquals(data.getLong("two", 0L), 2L)
assertEquals(data.getString("three"), "Three")
val longArray = data.getLongArray("four")
assertNotNull(longArray)
assertEquals(longArray!!.size, 2)
assertEquals(longArray[0], 1L)
assertEquals(longArray[1], 2L)
assertTrue(data.hasKeyWithValueOfType<Int>("one"))
assertTrue(data.hasKeyWithValueOfType<Long>("two"))
assertTrue(data.hasKeyWithValueOfType<String>("three"))
assertTrue(data.hasKeyWithValueOfType<Array<Long>>("four"))
assertFalse(data.hasKeyWithValueOfType<Any>("nothing"))
assertFalse(data.hasKeyWithValueOfType<Float>("two"))
}
}
| work/work-runtime-ktx/src/androidTest/java/androidx/work/DataTest.kt | 2130749009 |
/*
* 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.appcompat.app
import android.graphics.PixelFormat
import android.view.KeyEvent
import android.view.Window
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.appcompat.view.WindowCallbackWrapper
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.filters.SdkSuppress
import androidx.test.platform.app.InstrumentationRegistry
import junit.framework.TestCase.assertNotNull
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatcher
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.ArgumentMatchers.argThat
import org.mockito.Mockito.spy
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
@MediumTest
@RunWith(AndroidJUnit4::class)
class AppCompatWindowCallbackWrapperTest {
/**
* Regression test for b/173628052 where window callbacks are not dispatched to custom wrappers.
*/
@Test
@SdkSuppress(minSdkVersion = 23) // Mockito requires SDK 23+
fun testDispatchKeyEventToWrapper() {
ActivityScenario.launch(AppCompatInflaterDefaultActivity::class.java).let { scenario ->
val keyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU)
var callback: Window.Callback? = null
scenario.onActivity { activity ->
callback = spy(WindowCallbackWrapper(activity.window.callback))
activity.window.callback = callback
}
// Inject a key event.
InstrumentationRegistry.getInstrumentation().sendKeySync(keyEvent)
// Make sure we got the expected callbacks.
assertNotNull(callback)
verify(callback, times(2))!!.dispatchKeyEvent(argThat(SimpleKeyEventMatcher(keyEvent)))
}
}
/**
* Regression test for b/173628052 where window callbacks are not dispatched to custom wrappers.
*/
@Test
@SdkSuppress(minSdkVersion = 23) // Mockito requires SDK 23+
fun testOnContentChangedToWrapper() {
ActivityScenario.launch(AppCompatInflaterDefaultActivity::class.java).let { scenario ->
var callback: Window.Callback? = null
scenario.onActivity { activity ->
callback = spy(WindowCallbackWrapper(activity.window.callback))
activity.window.callback = callback
// Force a content change event.
activity.setContentView(android.R.layout.two_line_list_item)
}
// Make sure we got the expected callback.
assertNotNull(callback)
verify(callback, times(1))!!.onContentChanged()
}
}
/**
* Regression test for b/173628052 where window callbacks are not dispatched to custom wrappers.
*/
@Test
@SdkSuppress(minSdkVersion = 23) // Mockito requires SDK 23+
fun testOnPanelClosedWrapper() {
ActivityScenario.launch(AppCompatInflaterDefaultActivity::class.java).let { scenario ->
var callback: Window.Callback? = null
scenario.onActivity { activity ->
callback = spy(WindowCallbackWrapper(activity.window.callback))
activity.window.callback = callback
// Set up a fake application sub-panel, then close it. This is messy, but it's
// likely more reliable than displaying a real panel.
val v = FrameLayout(activity)
val st = AppCompatDelegateImpl.PanelFeatureState(
Window.FEATURE_CONTEXT_MENU
).apply {
isOpen = true
decorView = v
}
activity.windowManager.addView(v,
WindowManager.LayoutParams(0, 0,
WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL, 0,
PixelFormat.TRANSLUCENT
)
)
(activity.delegate as? AppCompatDelegateImpl)?.closePanel(st, true)
}
// Make sure we got the expected callback.
assertNotNull(callback)
verify(callback, times(1))!!.onPanelClosed(anyInt(), any())
}
}
}
class SimpleKeyEventMatcher(val keyEvent: KeyEvent) : ArgumentMatcher<KeyEvent> {
override fun matches(argument: KeyEvent?): Boolean {
return argument != null &&
argument.action == keyEvent.action &&
argument.keyCode == keyEvent.keyCode
}
}
| appcompat/appcompat/src/androidTest/java/androidx/appcompat/app/AppCompatWindowCallbackWrapperTest.kt | 1877531660 |
package androidx.compose.ui.layout
/**
* Interface holding the size and alignment lines of the measured layout, as well as the
* children positioning logic.
* [placeChildren] is the function used for positioning children. [Placeable.placeAt] should
* be called on children inside [placeChildren].
* The alignment lines can be used by the parent layouts to decide layout, and can be queried
* using the [Placeable.get] operator. Note that alignment lines will be inherited by parent
* layouts, such that indirect parents will be able to query them as well.
*/
interface MeasureResult {
val width: Int
val height: Int
val alignmentLines: Map<AlignmentLine, Int>
fun placeChildren()
} | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/layout/MeasureResult.kt | 29018705 |
/*
* 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.benchmark.macro.perfetto
internal object AudioUnderrunQuery {
private fun getFullQuery() = """
SELECT track.name, counter.value, counter.ts
FROM track
JOIN counter ON track.id = counter.track_id
WHERE track.type = 'process_counter_track' AND track.name LIKE 'nRdy%'
""".trimIndent()
data class SubMetrics(
val totalMs: Int,
val zeroMs: Int
)
fun getSubMetrics(
perfettoTraceProcessor: PerfettoTraceProcessor
): SubMetrics {
val queryResult = perfettoTraceProcessor.rawQuery(getFullQuery())
var trackName: String? = null
var lastTs: Long? = null
var totalNs: Long = 0
var zeroNs: Long = 0
queryResult
.asSequence()
.forEach { lineVals ->
if (lineVals.size != EXPECTED_COLUMN_COUNT)
throw IllegalStateException("query failed")
if (trackName == null) {
trackName = lineVals[VAL_NAME] as String?
} else if (trackName!! != lineVals[VAL_NAME]) {
throw RuntimeException("There could be only one AudioTrack per measure")
}
if (lastTs == null) {
lastTs = lineVals[VAL_TS] as Long
} else {
val frameNs = lineVals[VAL_TS] as Long - lastTs!!
lastTs = lineVals[VAL_TS] as Long
totalNs += frameNs
val frameCounter = (lineVals[VAL_VALUE] as Double).toInt()
if (frameCounter == 0)
zeroNs += frameNs
}
}
return SubMetrics((totalNs / 1_000_000).toInt(), (zeroNs / 1_000_000).toInt())
}
private const val VAL_NAME = "name"
private const val VAL_VALUE = "value"
private const val VAL_TS = "ts"
private const val EXPECTED_COLUMN_COUNT = 3
} | benchmark/benchmark-macro/src/main/java/androidx/benchmark/macro/perfetto/AudioUnderrunQuery.kt | 1066759121 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.ksp
import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSNode
import com.google.devtools.ksp.symbol.KSReferenceElement
import com.google.devtools.ksp.symbol.KSType
import com.google.devtools.ksp.symbol.KSTypeReference
import com.google.devtools.ksp.symbol.KSVisitor
import com.google.devtools.ksp.symbol.Location
import com.google.devtools.ksp.symbol.Modifier
import com.google.devtools.ksp.symbol.NonExistLocation
import com.google.devtools.ksp.symbol.Origin
/**
* Creates a new TypeReference from [this] where the resolved type [replacement] but everything
* else is the same (e.g. location).
*/
internal fun KSTypeReference.swapResolvedType(replacement: KSType): KSTypeReference {
return DelegatingTypeReference(
original = this,
resolved = replacement
)
}
/**
* Creates a [NonExistLocation] type reference for [this].
*/
internal fun KSType.createTypeReference(): KSTypeReference {
return NoLocationTypeReference(this)
}
private class DelegatingTypeReference(
val original: KSTypeReference,
val resolved: KSType
) : KSTypeReference by original {
override fun resolve() = resolved
}
private class NoLocationTypeReference(
val resolved: KSType
) : KSTypeReference {
override val annotations: Sequence<KSAnnotation>
get() = emptySequence()
override val element: KSReferenceElement?
get() = null
override val location: Location
get() = NonExistLocation
override val modifiers: Set<Modifier>
get() = emptySet()
override val origin: Origin
get() = Origin.SYNTHETIC
override val parent: KSNode?
get() = null
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitTypeReference(this, data)
}
override fun resolve(): KSType = resolved
} | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KSTypeReferenceExt.kt | 3961449995 |
package com.github.dynamicextensionsalfresco.event
/**
* @author Laurent Van der Linden
*/
public interface Event
| event-bus/src/main/kotlin/com/github/dynamicextensionsalfresco/event/Event.kt | 3595433496 |
/*
* 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.glance.appwidget.action
import android.app.Service
import android.content.ComponentName
import android.content.Intent
import androidx.glance.action.Action
internal sealed interface StartServiceAction : Action {
val isForegroundService: Boolean
}
internal class StartServiceComponentAction(
val componentName: ComponentName,
override val isForegroundService: Boolean
) : StartServiceAction
internal class StartServiceClassAction(
val serviceClass: Class<out Service>,
override val isForegroundService: Boolean
) : StartServiceAction
internal class StartServiceIntentAction(
val intent: Intent,
override val isForegroundService: Boolean
) : StartServiceAction
/**
* Creates an [Action] that launches a [Service] from the given [Intent] when triggered. The
* intent should specify a component with [Intent.setClass] or [Intent.setComponent].
*
* @param intent the intent used to launch the activity
* @param isForegroundService set to true when the provided [Service] runs in foreground. This flag
* is only used for device versions after [android.os.Build.VERSION_CODES.O] that requires
* foreground service to be launched differently
*/
fun actionStartService(intent: Intent, isForegroundService: Boolean = false): Action =
StartServiceIntentAction(intent, isForegroundService)
/**
* Creates an [Action] that launches the [Service] specified by the given [ComponentName].
*
* @param componentName component of the Service to launch
* @param isForegroundService set to true when the provided [Service] runs in foreground. This flag
* is only used for device versions after [android.os.Build.VERSION_CODES.O] that requires
* foreground service to be launched differently
*/
fun actionStartService(
componentName: ComponentName,
isForegroundService: Boolean = false
): Action = StartServiceComponentAction(componentName, isForegroundService)
/**
* Creates an [Action] that launches the specified [Service] when triggered.
*
* @param service class of the Service to launch
* @param isForegroundService set to true when the provided [Service] runs in foreground. This flag
* is only used for device versions after [android.os.Build.VERSION_CODES.O] that requires
* foreground service to be launched differently
*/
fun <T : Service> actionStartService(
service: Class<T>,
isForegroundService: Boolean = false
): Action =
StartServiceClassAction(service, isForegroundService)
/**
* Creates an [Action] that launches the specified [Service] when triggered.
*
* @param isForegroundService set to true when the provided [Service] runs in foreground. This flag
* is only used for device versions after [android.os.Build.VERSION_CODES.O] that requires
* foreground service to be launched differently.
*/
@Suppress("MissingNullability")
/* Shouldn't need to specify @NonNull. b/199284086 */
inline fun <reified T : Service> actionStartService(
isForegroundService: Boolean = false
): Action = actionStartService(T::class.java, isForegroundService)
| glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/action/StartServiceAction.kt | 693395225 |
package net.yested.bootstrap
import net.yested.HTMLComponent
import net.yested.Anchor
import net.yested.with
import net.yested.isTrue
import org.w3c.dom.events.Event
/**
* Created by jean on 25.12.2014.
*
*/
enum class AlertStyle(val code:String) {
SUCCESS("success"),
INFO("info"),
WARNING("warning"),
DANGER("danger")
}
class Alert(style: AlertStyle, dismissible: Boolean = false) : HTMLComponent("div") {
init {
clazz = "alert alert-${style.code} ${dismissible.isTrue("alert-dismissible", "")}"
if (dismissible) {
tag("button") {
clazz = "close"; "type".."button"; "data-dismiss".."alert"; "aria-label".."Close"
span {
"aria-hidden".."true"
+"×"
}
}
}
}
override fun a(clazz: String?, target: String?, href: String?, onclick: ((Event) -> Unit)?, init: Anchor.() -> Unit) {
super.a(clazz = clazz?:"alert-link", target = target, href = href, onclick = onclick, init = init)
}
}
fun HTMLComponent.alert(style: AlertStyle, dismissible: Boolean = false, init:Alert.() -> Unit) =
+(Alert(style = style, dismissible = dismissible) with { init() } )
| src/main/kotlin/net/yested/bootstrap/alerts.kt | 609453090 |
package com.dropbox.android.external.store4.impl
import com.dropbox.android.external.store4.Fetcher
import com.dropbox.android.external.store4.ResponseOrigin
import com.dropbox.android.external.store4.StoreBuilder
import com.dropbox.android.external.store4.StoreResponse.Data
import com.dropbox.android.external.store4.testutil.InMemoryPersister
import com.dropbox.android.external.store4.testutil.asSourceOfTruth
import com.dropbox.android.external.store4.testutil.getData
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@FlowPreview
@ExperimentalCoroutinesApi
@RunWith(JUnit4::class)
class ClearStoreByKeyTest {
private val testScope = TestCoroutineScope()
private val persister = InMemoryPersister<String, Int>()
@Test
fun `calling clear(key) on store with persister (no in-memory cache) deletes the entry associated with the key from the persister`() =
testScope.runBlockingTest {
val key = "key"
val value = 1
val store = StoreBuilder.from(
fetcher = Fetcher.of { value },
sourceOfTruth = persister.asSourceOfTruth()
).scope(testScope)
.disableCache()
.build()
// should receive data from network first time
assertThat(store.getData(key))
.isEqualTo(
Data(
origin = ResponseOrigin.Fetcher,
value = value
)
)
// should receive data from persister
assertThat(store.getData(key))
.isEqualTo(
Data(
origin = ResponseOrigin.SourceOfTruth,
value = value
)
)
// clear store entry by key
store.clear(key)
assertThat(persister.peekEntry(key))
.isNull()
// should fetch data from network again
assertThat(store.getData(key))
.isEqualTo(
Data(
origin = ResponseOrigin.Fetcher,
value = value
)
)
}
@Test
fun `calling clear(key) on store with in-memory cache (no persister) deletes the entry associated with the key from the in-memory cache`() =
testScope.runBlockingTest {
val key = "key"
val value = 1
val store = StoreBuilder.from<String, Int>(
fetcher = Fetcher.of { value }
).scope(testScope).build()
// should receive data from network first time
assertThat(store.getData(key))
.isEqualTo(
Data(
origin = ResponseOrigin.Fetcher,
value = value
)
)
// should receive data from cache
assertThat(store.getData(key))
.isEqualTo(
Data(
origin = ResponseOrigin.Cache,
value = value
)
)
// clear store entry by key
store.clear(key)
// should fetch data from network again
assertThat(store.getData(key))
.isEqualTo(
Data(
origin = ResponseOrigin.Fetcher,
value = value
)
)
}
@Test
fun `calling clear(key) on store has no effect on existing entries associated with other keys in the in-memory cache or persister`() =
testScope.runBlockingTest {
val key1 = "key1"
val key2 = "key2"
val value1 = 1
val value2 = 2
val store = StoreBuilder.from(
fetcher = Fetcher.of { key ->
when (key) {
key1 -> value1
key2 -> value2
else -> throw IllegalStateException("Unknown key")
}
},
sourceOfTruth = persister.asSourceOfTruth()
).scope(testScope)
.build()
// get data for both keys
store.getData(key1)
store.getData(key2)
// clear store entry for key1
store.clear(key1)
// entry for key1 is gone
assertThat(persister.peekEntry(key1))
.isNull()
// entry for key2 should still exists
assertThat(persister.peekEntry(key2))
.isEqualTo(value2)
// getting data for key1 should hit the network again
assertThat(store.getData(key1))
.isEqualTo(
Data(
origin = ResponseOrigin.Fetcher,
value = value1
)
)
// getting data for key2 should not hit the network
assertThat(store.getData(key2))
.isEqualTo(
Data(
origin = ResponseOrigin.Cache,
value = value2
)
)
}
}
| store/src/test/java/com/dropbox/android/external/store4/impl/ClearStoreByKeyTest.kt | 68723945 |
package com.dropbox.android.sample.data.model
import kotlinx.serialization.Serializable
@Serializable
data class RedditData(
val data: Data,
val kind: String
)
@Serializable
data class Children(
val data: Post
)
@Serializable
data class Data(
val children: List<Children>
)
@Serializable
data class Post(
val id: String,
val preview: Preview? = null,
val title: String,
val url: String,
val height: Int? = null,
val width: Int? = null,
) {
fun nestedThumbnail(): Image? {
return preview?.images?.getOrNull(0)?.source
}
}
@Serializable
data class Preview(
val images: List<Images>
)
@Serializable
data class Images(
val source: Image
)
@Serializable
data class Image(
val url: String,
val height: Int,
val width: Int
)
| app/src/main/java/com/dropbox/android/sample/data/model/Model.kt | 125689114 |
package org.elm.ide.refactoring
import com.intellij.lang.refactoring.RefactoringSupportProvider
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringActionHandler
class ElmRefactoringSupportProvider : RefactoringSupportProvider() {
override fun isMemberInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
// TODO [kl] eventually we will want to be more selective
return true
}
override fun getIntroduceVariableHandler(): RefactoringActionHandler? {
return ElmIntroduceVariableHandler()
}
} | src/main/kotlin/org/elm/ide/refactoring/ElmRefactoringSupportProvider.kt | 69667127 |
package com.dropbox.android.external.store4
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
fun interface Weigher<in K : Any, in V : Any> {
/**
* Returns the weight of a cache entry. There is no unit for entry weights; rather they are simply
* relative to each other.
*
* @return the weight of the entry; must be non-negative
*/
fun weigh(key: K, value: V): Int
}
internal object OneWeigher : Weigher<Any, Any> {
override fun weigh(key: Any, value: Any): Int = 1
}
/**
* MemoryPolicy holds all required info to create MemoryCache
*
*
* This class is used, in order to define the appropriate parameters for the Memory [com.dropbox.android.external.cache3.Cache]
* to be built.
*
*
* MemoryPolicy is used by a [Store]
* and defines the in-memory cache behavior.
*/
@ExperimentalTime
class MemoryPolicy<in Key : Any, in Value : Any> internal constructor(
val expireAfterWrite: Duration,
val expireAfterAccess: Duration,
val maxSize: Long,
val maxWeight: Long,
val weigher: Weigher<Key, Value>
) {
val isDefaultWritePolicy: Boolean = expireAfterWrite == DEFAULT_DURATION_POLICY
val hasWritePolicy: Boolean = expireAfterWrite != DEFAULT_DURATION_POLICY
val hasAccessPolicy: Boolean = expireAfterAccess != DEFAULT_DURATION_POLICY
val hasMaxSize: Boolean = maxSize != DEFAULT_SIZE_POLICY
val hasMaxWeight: Boolean = maxWeight != DEFAULT_SIZE_POLICY
class MemoryPolicyBuilder<Key : Any, Value : Any> {
private var expireAfterWrite = DEFAULT_DURATION_POLICY
private var expireAfterAccess = DEFAULT_DURATION_POLICY
private var maxSize: Long = DEFAULT_SIZE_POLICY
private var maxWeight: Long = DEFAULT_SIZE_POLICY
private var weigher: Weigher<Key, Value> = OneWeigher
fun setExpireAfterWrite(expireAfterWrite: Duration): MemoryPolicyBuilder<Key, Value> =
apply {
check(expireAfterAccess == DEFAULT_DURATION_POLICY) {
"Cannot set expireAfterWrite with expireAfterAccess already set"
}
this.expireAfterWrite = expireAfterWrite
}
fun setExpireAfterAccess(expireAfterAccess: Duration): MemoryPolicyBuilder<Key, Value> =
apply {
check(expireAfterWrite == DEFAULT_DURATION_POLICY) {
"Cannot set expireAfterAccess with expireAfterWrite already set"
}
this.expireAfterAccess = expireAfterAccess
}
/**
* Sets the maximum number of items ([maxSize]) kept in the cache.
*
* When [maxSize] is 0, entries will be discarded immediately and no values will be cached.
*
* If not set, cache size will be unlimited.
*/
fun setMaxSize(maxSize: Long): MemoryPolicyBuilder<Key, Value> = apply {
check(maxWeight == DEFAULT_SIZE_POLICY && weigher == OneWeigher) {
"Cannot setMaxSize when maxWeight or weigher are already set"
}
check(maxSize >= 0) { "maxSize cannot be negative" }
this.maxSize = maxSize
}
fun setWeigherAndMaxWeight(
weigher: Weigher<Key, Value>,
maxWeight: Long
): MemoryPolicyBuilder<Key, Value> = apply {
check(maxSize == DEFAULT_SIZE_POLICY) {
"Cannot setWeigherAndMaxWeight when maxSize already set"
}
check(maxWeight >= 0) { "maxWeight cannot be negative" }
this.weigher = weigher
this.maxWeight = maxWeight
}
fun build() = MemoryPolicy<Key, Value>(
expireAfterWrite = expireAfterWrite,
expireAfterAccess = expireAfterAccess,
maxSize = maxSize,
maxWeight = maxWeight,
weigher = weigher
)
}
companion object {
val DEFAULT_DURATION_POLICY: Duration = Duration.INFINITE
const val DEFAULT_SIZE_POLICY: Long = -1
fun <Key : Any, Value : Any> builder(): MemoryPolicyBuilder<Key, Value> =
MemoryPolicyBuilder()
}
}
| store/src/main/java/com/dropbox/android/external/store4/MemoryPolicy.kt | 3503606797 |
package info.metadude.android.eventfahrplan.database.models
import info.metadude.android.eventfahrplan.database.contract.FahrplanContract.AlarmsTable.Defaults.ALARM_TIME_IN_MIN_DEFAULT
import info.metadude.android.eventfahrplan.database.contract.FahrplanContract.AlarmsTable.Defaults.DEFAULT_VALUE_ID
data class Alarm(
val id: Int = DEFAULT_VALUE_ID,
val alarmTimeInMin: Int = ALARM_TIME_IN_MIN_DEFAULT,
val day: Int = -1,
val displayTime: Long = -1, // will be stored as signed integer
val sessionId: String = "",
val time: Long = -1, // will be stored as signed integer
val timeText: String = "",
val title: String = ""
)
| database/src/main/java/info/metadude/android/eventfahrplan/database/models/Alarm.kt | 2001383939 |
package org.jmailen.gradle.kotlinter.functional
import org.apache.commons.io.FileUtils
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.internal.PluginUnderTestMetadataReading
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import java.io.File
import java.nio.file.Files
abstract class WithGradleTest {
lateinit var testProjectDir: File
/**
* Not using JUnit's @TempDir, due do https://github.com/gradle/gradle/issues/12535
*/
@BeforeEach
internal fun setUpTempdir() {
testProjectDir = Files.createTempDirectory(this::class.java.simpleName).toFile()
}
@AfterEach
internal fun cleanUpTempdir() {
FileUtils.forceDeleteOnExit(testProjectDir)
}
protected fun build(vararg args: String): BuildResult = gradleRunnerFor(*args).build()
protected fun buildAndFail(vararg args: String): BuildResult = gradleRunnerFor(*args).buildAndFail()
protected abstract fun gradleRunnerFor(vararg args: String): GradleRunner
abstract class Android : WithGradleTest() {
override fun gradleRunnerFor(vararg args: String): GradleRunner {
return defaultRunner(*args)
.withPluginClasspath()
}
}
abstract class Kotlin : WithGradleTest() {
override fun gradleRunnerFor(vararg args: String): GradleRunner {
val classpath = DefaultClassPath.of(PluginUnderTestMetadataReading.readImplementationClasspath()).asFiles
val androidDependencies = listOf(
".*/com\\.android\\..*/.*".toRegex(),
".*/androidx\\..*/.*".toRegex(),
".*/com\\.google\\..*/.*".toRegex(),
)
val noAndroid = classpath.filterNot { dependency -> androidDependencies.any { it.matches(dependency.path) } }
return defaultRunner(*args)
.withPluginClasspath(noAndroid)
}
}
}
private fun WithGradleTest.defaultRunner(vararg args: String) =
GradleRunner.create()
.withProjectDir(testProjectDir)
.withArguments(args.toList() + listOf("--stacktrace", "--configuration-cache"))
.forwardOutput()
| src/test/kotlin/org/jmailen/gradle/kotlinter/functional/WithGradleTest.kt | 283086766 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.psi.mixins.impl
import com.demonwav.mcdev.nbt.lang.psi.mixins.NbttRootCompoundMixin
import com.demonwav.mcdev.nbt.tags.RootCompound
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
abstract class NbttRootCompoundImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), NbttRootCompoundMixin {
override fun getRootCompoundTag(): RootCompound {
return RootCompound(getTagName().getTagName(), getCompound().getCompoundTag().tagMap)
}
}
| src/main/kotlin/nbt/lang/psi/mixins/impl/NbttRootCompoundImplMixin.kt | 2480429999 |
/*
* Copyright (c) 2013 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.net.http
import org.andstatus.app.account.AccountConnectionData
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.context.TestSuite
import org.andstatus.app.origin.OriginType
import org.andstatus.app.util.TriState
import org.andstatus.app.util.UrlUtils
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class OAuthClientKeysTest {
@Before
fun setUp() {
TestSuite.forget()
TestSuite.initialize(this)
}
@Test
fun testKeysSave() {
val connectionData: HttpConnectionData = HttpConnectionData.Companion.fromAccountConnectionData(
AccountConnectionData.Companion.fromMyAccount( MyContextHolder.myContextHolder.getNow().accounts.getFirstPreferablySucceededForOrigin(
MyContextHolder.myContextHolder.getNow().origins.firstOfType(OriginType.PUMPIO)), TriState.UNKNOWN)
)
val consumerKey = "testConsumerKey" + System.nanoTime().toString()
val consumerSecret = "testConsumerSecret" + System.nanoTime().toString()
connectionData.originUrl = UrlUtils.fromString("https://example.com")
val keys1: OAuthClientKeys = OAuthClientKeys.Companion.fromConnectionData(connectionData)
keys1.clear()
Assert.assertEquals("Keys are cleared", false, keys1.areKeysPresent())
keys1.setConsumerKeyAndSecret(consumerKey, consumerSecret)
val keys2: OAuthClientKeys = OAuthClientKeys.Companion.fromConnectionData(connectionData)
Assert.assertEquals("Keys are loaded", true, keys2.areKeysPresent())
Assert.assertEquals(consumerKey, keys2.getConsumerKey())
Assert.assertEquals(consumerSecret, keys2.getConsumerSecret())
keys2.clear()
val keys3: OAuthClientKeys = OAuthClientKeys.Companion.fromConnectionData(connectionData)
Assert.assertEquals("Keys are cleared", false, keys3.areKeysPresent())
}
}
| app/src/androidTest/kotlin/org/andstatus/app/net/http/OAuthClientKeysTest.kt | 2792535812 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.apps.dto
import com.google.gson.annotations.SerializedName
import kotlin.String
enum class AppsGetNameCase(
val value: String
) {
@SerializedName("nom")
NOMINATIVE("nom"),
@SerializedName("gen")
GENITIVE("gen"),
@SerializedName("dat")
DATIVE("dat"),
@SerializedName("acc")
ACCUSATIVE("acc"),
@SerializedName("ins")
INSTRUMENTAL("ins"),
@SerializedName("abl")
PREPOSITIONAL("abl");
}
| api/src/main/java/com/vk/sdk/api/apps/dto/AppsGetNameCase.kt | 3840013017 |
package de.westnordost.streetcomplete.quests.max_speed
sealed class MaxSpeedAnswer
data class MaxSpeedSign(val value: SpeedMeasure) : MaxSpeedAnswer()
data class MaxSpeedZone(val value: SpeedMeasure, val countryCode: String, val roadType: String) : MaxSpeedAnswer()
data class AdvisorySpeedSign(val value: SpeedMeasure) : MaxSpeedAnswer()
data class ImplicitMaxSpeed(val countryCode: String, val roadType: String) : MaxSpeedAnswer()
object IsLivingStreet : MaxSpeedAnswer()
| app/src/main/java/de/westnordost/streetcomplete/quests/max_speed/MaxSpeedAnswer.kt | 3941121488 |
package kotliquery.action
import kotliquery.Query
import kotliquery.Row
import kotliquery.Session
data class NullableResultQueryAction<A>(
val query: Query,
val extractor: (Row) -> A?
) : QueryAction<A?> {
override fun runWithSession(session: Session): A? {
return session.single(query, extractor)
}
} | src/main/kotlin/kotliquery/action/NullableResultQueryAction.kt | 938046966 |
package info.nightscout.androidaps.plugins.pump.common.bolusInfo
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.utils.SP
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
import org.mockito.Mockito
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class DetailedBolusInfoStorageTest {
private val info1 = DetailedBolusInfo()
private val info2 = DetailedBolusInfo()
private val info3 = DetailedBolusInfo()
init {
info1.date = 1000000
info1.insulin = 3.0
info2.date = 1000001
info2.insulin = 4.0
info3.date = 2000000
info3.insulin = 5.0
}
private fun setUp() {
DetailedBolusInfoStorage.store.clear()
DetailedBolusInfoStorage.add(info1)
DetailedBolusInfoStorage.add(info2)
DetailedBolusInfoStorage.add(info3)
}
@Test
fun add() {
DetailedBolusInfoStorage.store.clear()
assertEquals(0, DetailedBolusInfoStorage.store.size)
DetailedBolusInfoStorage.add(info1)
assertEquals(1, DetailedBolusInfoStorage.store.size)
}
@Test
@PrepareForTest(MainApp::class, L::class, SP::class)
fun findDetailedBolusInfo() {
prepareMainApp()
prepareSP()
prepareLogging()
// Look for exact bolus
setUp()
var d: DetailedBolusInfo? = DetailedBolusInfoStorage.findDetailedBolusInfo(1000000, 4.0)
assertEquals(4.0, d!!.insulin, 0.01)
assertEquals(2, DetailedBolusInfoStorage.store.size)
// Look for exact bolus
setUp()
d = DetailedBolusInfoStorage.findDetailedBolusInfo(1000000, 3.0)
assertEquals(3.0, d!!.insulin, 0.01)
assertEquals(2, DetailedBolusInfoStorage.store.size)
// With less insulin (bolus not delivered completely). Should return first one matching date
setUp()
d = DetailedBolusInfoStorage.findDetailedBolusInfo(1000500, 2.0)
assertEquals(3.0, d!!.insulin, 0.01)
assertEquals(2, DetailedBolusInfoStorage.store.size)
// With less insulin (bolus not delivered completely). Should return first one matching date
setUp()
d = DetailedBolusInfoStorage.findDetailedBolusInfo(1000500, 3.5)
assertEquals(4.0, d!!.insulin, 0.01)
assertEquals(2, DetailedBolusInfoStorage.store.size)
// With more insulin should return null
setUp()
d = DetailedBolusInfoStorage.findDetailedBolusInfo(1000500, 4.5)
assertNull(d)
assertEquals(3, DetailedBolusInfoStorage.store.size)
// With more than one minute off should return null
setUp()
d = DetailedBolusInfoStorage.findDetailedBolusInfo(1070000, 4.0)
assertNull(d)
assertEquals(3, DetailedBolusInfoStorage.store.size)
// Use last, if bolus size is the same
setUp()
d = DetailedBolusInfoStorage.findDetailedBolusInfo(1070000, 5.0)
assertEquals(5.0, d!!.insulin, 0.01)
assertEquals(2, DetailedBolusInfoStorage.store.size)
}
private fun prepareMainApp() {
PowerMockito.mockStatic(MainApp::class.java)
val mainApp = Mockito.mock<MainApp>(MainApp::class.java)
Mockito.`when`(MainApp.instance()).thenReturn(mainApp)
Mockito.`when`(MainApp.gs(ArgumentMatchers.anyInt())).thenReturn("some dummy string")
}
private fun prepareSP() {
PowerMockito.mockStatic(SP::class.java)
}
private fun prepareLogging() {
PowerMockito.mockStatic(L::class.java)
Mockito.`when`(L.isEnabled(Mockito.any())).thenReturn(true)
}
} | app/src/test/java/info/nightscout/androidaps/plugins/pump/common/bolusInfo/DetailedBolusInfoStorageTest.kt | 2139293307 |
package kotliquery
import kotliquery.action.ExecuteQueryAction
import kotliquery.action.ResultQueryActionBuilder
import kotliquery.action.UpdateAndReturnGeneratedKeyQueryAction
import kotliquery.action.UpdateQueryAction
/**
* Database Query.
*/
data class Query(
val statement: String,
val params: List<Any?> = listOf(),
val paramMap: Map<String, Any?> = mapOf()
) {
val replacementMap: Map<String, List<Int>> = extractNamedParamsIndexed(statement)
val cleanStatement: String = replaceNamedParams(statement)
private fun replaceNamedParams(stmt: String): String {
return regex.replace(stmt, "?")
}
fun <A> map(extractor: (Row) -> A?): ResultQueryActionBuilder<A> {
return ResultQueryActionBuilder(this, extractor)
}
val asUpdate: UpdateQueryAction by lazy {
UpdateQueryAction(this)
}
val asUpdateAndReturnGeneratedKey: UpdateAndReturnGeneratedKeyQueryAction by lazy {
UpdateAndReturnGeneratedKeyQueryAction(this)
}
val asExecute: ExecuteQueryAction by lazy {
ExecuteQueryAction(this)
}
companion object {
private val regex = Regex("""(?<!:):(?!:)[a-zA-Z]\w+""")
internal fun extractNamedParamsIndexed(stmt: String): Map<String, List<Int>> {
return regex.findAll(stmt).mapIndexed { index, group ->
Pair(group, index)
}.groupBy({ it.first.value.substring(1) }, { it.second })
}
}
}
| src/main/kotlin/kotliquery/Query.kt | 2650977262 |
package leetcode
/**
* https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/
*/
class Problem1604 {
fun alertNames(keyName: Array<String>, keyTime: Array<String>): List<String> {
val map = mutableMapOf<String, MutableList<String>>()
for (i in keyName.indices) {
val times = map[keyName[i]] ?: mutableListOf()
times += keyTime[i]
map[keyName[i]] = times
}
val answer = mutableListOf<String>()
for ((key, value) in map) {
var i = 0
value.sort()
while (i < value.size - 2) {
val t = difference(value[i], value[i + 1]) + difference(value[i + 1], value[i + 2])
if (t <= 60) {
answer += key
break
}
i++
}
}
answer.sort()
return answer
}
private fun difference(from: String, to: String): Int {
val (fromHour, fromMinute) = from.split(":")
val (toHour, toMinute) = to.split(":")
val minute = toMinute.toInt() - fromMinute.toInt()
val hour = (toHour.toInt() - fromHour.toInt()) * 60
return minute + hour
}
}
| src/main/kotlin/leetcode/Problem1604.kt | 512734753 |
package com.reactnativenavigation.views.element.animators
import android.animation.Animator
import android.animation.ObjectAnimator
import android.graphics.PointF
import android.graphics.Rect
import android.view.View
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.drawable.ScalingUtils.InterpolatingScaleType
import com.facebook.react.views.image.ImageResizeMode
import com.facebook.react.views.image.ReactImageView
import com.reactnativenavigation.options.SharedElementTransitionOptions
import com.reactnativenavigation.utils.ViewUtils
import kotlin.math.max
import kotlin.math.roundToInt
class ReactImageMatrixAnimator(from: View, to: View) : PropertyAnimatorCreator<ReactImageView>(from, to) {
override fun shouldAnimateProperty(fromChild: ReactImageView, toChild: ReactImageView): Boolean {
return !ViewUtils.areDimensionsEqual(from, to)
}
override fun create(options: SharedElementTransitionOptions): Animator {
from as ReactImageView
with(to as ReactImageView) {
to.hierarchy.fadeDuration = 0
val parentScaleX = (from.parent as View).scaleX
val parentScalyY = (from.parent as View).scaleY
val fromBounds = calculateBounds(from, parentScaleX, parentScalyY)
hierarchy.actualImageScaleType = InterpolatingScaleType(
getScaleType(from),
getScaleType(to),
fromBounds,
calculateBounds(to),
PointF(from.width * parentScaleX / 2f, from.height * parentScalyY / 2f),
PointF(to.width / 2f, to.height / 2f)
)
to.layoutParams.width = max(from.width, to.width)
to.layoutParams.height = max(from.height, to.height)
return ObjectAnimator.ofObject({ fraction: Float, _: Any, _: Any ->
hierarchy.actualImageScaleType?.let {
(hierarchy.actualImageScaleType as? InterpolatingScaleType)?.let {
it.value = fraction
to.invalidate()
}
}
null
}, 0f, 1f)
}
}
private fun getScaleType(child: View): ScalingUtils.ScaleType {
return getScaleType(
child as ReactImageView, child.hierarchy.actualImageScaleType ?: ImageResizeMode.defaultValue()
)
}
private fun getScaleType(child: ReactImageView, scaleType: ScalingUtils.ScaleType): ScalingUtils.ScaleType {
if (scaleType is InterpolatingScaleType) return getScaleType(child, scaleType.scaleTypeTo)
return scaleType
}
private fun calculateBounds(view: View, parentScaleX: Float = 1f, parentScaleY: Float = 1f) =
Rect(
0,
0,
(view.width * parentScaleX).roundToInt(),
(view.height * parentScaleY).roundToInt()
)
}
| lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/ReactImageMatrixAnimator.kt | 214806865 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// FULL_JDK
package test
import java.lang.reflect.Modifier
private val prop = "O"
private fun test() = "K"
fun box(): String {
val clazz = Class.forName("test.PrivateVisibilityKt")
if (!Modifier.isPrivate(clazz.getDeclaredMethod("test").modifiers))
return "Private top level function should be private"
if (!Modifier.isPrivate(clazz.getDeclaredField("prop").modifiers))
return "Backing field for private top level property should be private"
return "OK"
}
| backend.native/tests/external/codegen/box/topLevelPrivate/privateVisibility.kt | 4129483605 |
package org.stepik.android.domain.magic_links.interactor
import io.reactivex.Single
import org.stepic.droid.configuration.EndpointResolver
import org.stepik.android.domain.magic_links.model.MagicLink
import org.stepik.android.domain.magic_links.repository.MagicLinksRepository
import javax.inject.Inject
class MagicLinkInteractor
@Inject
constructor(
private val endpointResolver: EndpointResolver,
private val magicLinksRepository: MagicLinksRepository
) {
/**
* Creates magic link for given absolute or relative [url] on stepik domain
*/
fun createMagicLink(url: String): Single<MagicLink> =
magicLinksRepository
.createMagicLink(url.removePrefix(endpointResolver.getBaseUrl()))
} | app/src/main/java/org/stepik/android/domain/magic_links/interactor/MagicLinkInteractor.kt | 657929671 |
package com.github.skuznets0v.metro.config
import org.springframework.context.annotation.Configuration
import org.springframework.messaging.simp.config.MessageBrokerRegistry
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker
import org.springframework.web.socket.config.annotation.StompEndpointRegistry
@Configuration
@EnableWebSocketMessageBroker
class StompConfig : AbstractWebSocketMessageBrokerConfigurer() {
override fun configureMessageBroker(registry: MessageBrokerRegistry) {
registry.apply {
setApplicationDestinationPrefixes("/app")
enableStompBrokerRelay("/topic")
}
}
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
registry.addEndpoint("/").setAllowedOrigins("*").withSockJS()
}
/* @Bean
fun amqpTemplate() = RabbitTemplate().apply {
exchange = "amq.topic"
}*/
}
| websocket/src/main/kotlin/com/github/skuznets0v/metro/config/StompConfig.kt | 551241195 |
// FILE: 1.kt
package test
public inline fun <R> doCall(block: ()-> R) : R {
return block()
}
// FILE: 2.kt
import test.*
fun test1(local: Int, nonLocal: String, doNonLocal: Boolean): String {
val localResult = doCall {
if (doNonLocal) {
return nonLocal
}
local
}
if (localResult == 11) {
return "OK_LOCAL"
}
else {
return "LOCAL_FAILED"
}
}
fun test2(local: Int, nonLocal: String, doNonLocal: Boolean): String {
val localResult = doCall {
if (doNonLocal) {
return@test2 nonLocal
}
local
}
if (localResult == 11) {
return "OK_LOCAL"
}
else {
return "LOCAL_FAILED"
}
}
fun box(): String {
var test1 = test1(11, "fail", false)
if (test1 != "OK_LOCAL") return "test1: ${test1}"
test1 = test1(-1, "OK_NONLOCAL", true)
if (test1 != "OK_NONLOCAL") return "test2: ${test1}"
var test2 = test2(11, "fail", false)
if (test2 != "OK_LOCAL") return "test1: ${test2}"
test2 = test2(-1, "OK_NONLOCAL", true)
if (test2 != "OK_NONLOCAL") return "test2: ${test2}"
return "OK"
}
| backend.native/tests/external/codegen/boxInline/nonLocalReturns/simple.kt | 3679321968 |
/*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.gist
import giuliolodi.gitnav.di.scope.PerActivity
import giuliolodi.gitnav.ui.base.BaseContract
import org.eclipse.egit.github.core.Gist
import org.eclipse.egit.github.core.GistFile
/**
* Created by giulio on 03/07/2017.
*/
interface GistFilesContract {
interface View : BaseContract.View {
fun showGist(gist: Gist)
fun showLoading()
fun hideLoading()
fun showNoConnectionError()
fun showError(error: String)
fun intentToFileViewerActivity(gistFile: GistFile)
}
@PerActivity
interface Presenter<V: GistFilesContract.View> : BaseContract.Presenter<V> {
fun subscribe(isNetworkAvailable: Boolean, gistId: String)
fun getGist(gistId: String)
fun onGistFileClick(gistFile: GistFile)
}
} | app/src/main/java/giuliolodi/gitnav/ui/gist/GistFilesContract.kt | 1917728766 |
package nl.shadowlink.tools.shadowlib.water
import nl.shadowlink.tools.io.Vector3D
/**
* @author Shadow-Link
*/
class WaterPoint(line: String) {
@JvmField
var coord: Vector3D
var speedX: Float
var speedY: Float
var unknown: Float
var waveHeight: Float
init {
val split = line.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
coord = Vector3D(
java.lang.Float.valueOf(split[0]), java.lang.Float.valueOf(split[1]), java.lang.Float.valueOf(
split[2]
)
)
speedX = java.lang.Float.valueOf(split[3])
speedY = java.lang.Float.valueOf(split[4])
unknown = java.lang.Float.valueOf(split[5])
waveHeight = java.lang.Float.valueOf(split[6])
}
} | src/main/java/nl/shadowlink/tools/shadowlib/water/WaterPoint.kt | 2632614465 |
package com.gkzxhn.mygithub.extension
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v7.widget.Toolbar
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.gkzxhn.mygithub.di.module.GlideApp
/**
* Created by 方 on 2017/10/26.
*/
fun Toolbar.loadIcon(context: Context, url: String, errorRes: Int) {
GlideApp.with(context)
.load(url)
.transition(DrawableTransitionOptions.withCrossFade())
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.apply(RequestOptions.circleCropTransform())
.listener(object : RequestListener<Drawable> {
override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
return false
}
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
[email protected](errorRes)
return true
}
}).into(object : SimpleTarget<Drawable>() {
override fun onResourceReady(resource: Drawable?, transition: Transition<in Drawable>?) {
[email protected](resource)
}
})
} | app/src/main/java/com/gkzxhn/mygithub/extension/ToolbarExtensions.kt | 3307980568 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.annotations.ApiStatus
import java.util.*
/**
* Use this class to determine how modules show by organized in a tree. It supports the both ways of module grouping: the old one where
* groups are specified explicitly and the new one where modules are grouped accordingly to their qualified names.
*
* @author nik
*/
@ApiStatus.Experimental
abstract class ModuleGrouper {
/**
* Returns names of parent groups for a module
*/
abstract fun getGroupPath(module: Module): List<String>
/**
* Returns names of parent groups for a module
*/
abstract fun getGroupPath(description: ModuleDescription): List<String>
/**
* Returns name which should be used for a module when it's shown under its group
*/
abstract fun getShortenedName(module: Module): String
abstract fun getShortenedNameByFullModuleName(name: String): String
abstract fun getGroupPathByModuleName(name: String): List<String>
/**
* If [module] itself can be considered as a group, returns its groups. Otherwise returns null.
*/
abstract fun getModuleAsGroupPath(module: Module): List<String>?
/**
* If [description] itself can be considered as a group, returns its groups. Otherwise returns null.
*/
abstract fun getModuleAsGroupPath(description: ModuleDescription): List<String>?
abstract fun getAllModules(): Array<Module>
companion object {
@JvmStatic
@JvmOverloads
fun instanceFor(project: Project, moduleModel: ModifiableModuleModel? = null): ModuleGrouper {
val hasGroups = moduleModel?.hasModuleGroups() ?: ModuleManager.getInstance(project).hasModuleGroups()
if (!isQualifiedModuleNamesEnabled(project) || hasGroups) {
return ExplicitModuleGrouper(project, moduleModel)
}
return QualifiedNameGrouper(project, moduleModel)
}
}
}
fun isQualifiedModuleNamesEnabled(project: Project) = Registry.`is`("project.qualified.module.names") &&
!ModuleManager.getInstance(project).hasModuleGroups()
private abstract class ModuleGrouperBase(protected val project: Project, protected val model: ModifiableModuleModel?) : ModuleGrouper() {
override fun getAllModules(): Array<Module> = model?.modules ?: ModuleManager.getInstance(project).modules
protected fun getModuleName(module: Module) = model?.getNewName(module) ?: module.name
override fun getShortenedName(module: Module) = getShortenedNameByFullModuleName(getModuleName(module))
}
private class QualifiedNameGrouper(project: Project, model: ModifiableModuleModel?) : ModuleGrouperBase(project, model) {
override fun getGroupPath(module: Module): List<String> {
return getGroupPathByModuleName(getModuleName(module))
}
override fun getGroupPath(description: ModuleDescription) = getGroupPathByModuleName(description.name)
override fun getShortenedNameByFullModuleName(name: String) = StringUtil.getShortName(name)
override fun getGroupPathByModuleName(name: String) = name.split('.').dropLast(1)
override fun getModuleAsGroupPath(module: Module) = getModuleName(module).split('.')
override fun getModuleAsGroupPath(description: ModuleDescription) = description.name.split('.')
}
private class ExplicitModuleGrouper(project: Project, model: ModifiableModuleModel?): ModuleGrouperBase(project, model) {
override fun getGroupPath(module: Module): List<String> {
val path = if (model != null) model.getModuleGroupPath(module) else ModuleManager.getInstance(project).getModuleGroupPath(module)
return if (path != null) Arrays.asList(*path) else emptyList()
}
override fun getGroupPath(description: ModuleDescription) = when (description) {
is LoadedModuleDescription -> getGroupPath(description.module)
is UnloadedModuleDescription -> description.groupPath
else -> throw IllegalArgumentException(description.javaClass.name)
}
override fun getShortenedNameByFullModuleName(name: String) = name
override fun getGroupPathByModuleName(name: String): List<String> = emptyList()
override fun getModuleAsGroupPath(module: Module) = null
override fun getModuleAsGroupPath(description: ModuleDescription) = null
}
| platform/projectModel-api/src/com/intellij/openapi/module/ModuleGrouper.kt | 298600425 |
package com.mindera.skeletoid.rxjava.bindings.interfaces
interface IRxBindings {
fun setupRxBindings()
/**
* Clear is meant to be used onPause for example, just to clear current disposables that can
* be reused. This follows the same pattern as the clear() method of disposables
*/
fun clearRxBindings()
/**
* Dispose is meant to be used on final states: like onStop / onDestroy it's irreversible
* This follows the same pattern as the dispose() method of disposables
*/
fun disposeRxBindings()
} | rxjava/src/main/kotlin/com/mindera/skeletoid/rxjava/bindings/interfaces/IRxBindings.kt | 2225143933 |
@file:Suppress("DEPRECATION")
package info.nightscout.androidaps.complications
import android.app.PendingIntent
import android.support.wearable.complications.ComplicationData
import android.support.wearable.complications.ComplicationText
import dagger.android.AndroidInjection
import info.nightscout.androidaps.data.RawDisplayData
import info.nightscout.androidaps.interaction.utils.DisplayFormat
import info.nightscout.androidaps.interaction.utils.SmallestDoubleString
import info.nightscout.shared.logging.LTag
import kotlin.math.max
/*
* Created by dlvoy on 2019-11-12
*/
class BrCobIobComplication : BaseComplicationProviderService() {
// Not derived from DaggerService, do injection here
override fun onCreate() {
AndroidInjection.inject(this)
super.onCreate()
}
override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
var complicationData: ComplicationData? = null
if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
val cob = SmallestDoubleString(raw.status.cob, SmallestDoubleString.Units.USE).minimise(DisplayFormat.MIN_FIELD_LEN_COB)
val iob = SmallestDoubleString(raw.status.iobSum, SmallestDoubleString.Units.USE).minimise(max(DisplayFormat.MIN_FIELD_LEN_IOB, DisplayFormat.MAX_FIELD_LEN_SHORT - 1 - cob.length))
val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
.setShortText(ComplicationText.plainText(displayFormat.basalRateSymbol() + raw.status.currentBasal))
.setShortTitle(ComplicationText.plainText("$cob $iob"))
.setTapAction(complicationPendingIntent)
complicationData = builder.build()
} else {
aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
}
return complicationData
}
override fun getProviderCanonicalName(): String = BrCobIobComplication::class.java.canonicalName!!
}
| wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.kt | 881051575 |
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package khttp.extensions
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class ExtensionsSpec : Spek({
describe("a ByteArray") {
val string = "\"Goddammit\", he said\nThis is a load of bullshit.\r\nPlease, just kill me now.\r"
val byteArray = string.toByteArray()
context("splitting by lines") {
val split = byteArray.splitLines().map { it.toString(Charsets.UTF_8) }
val expected = string.split(Regex("(\r\n|\r|\n)"))
it("should be split by lines") {
assertEquals(expected, split)
}
}
context("splitting by the letter e") {
val splitBy = "e"
val split = byteArray.split(splitBy.toByteArray()).map { it.toString(Charsets.UTF_8) }
val expected = string.split(splitBy)
it("should be split correctly") {
assertEquals(expected, split)
}
}
context("splitting by is") {
val splitBy = "is"
val split = byteArray.split(splitBy.toByteArray()).map { it.toString(Charsets.UTF_8) }
val expected = string.split(splitBy)
it("should be split correctly") {
assertEquals(expected, split)
}
}
}
describe("an empty ByteArray") {
val empty = ByteArray(0)
context("splitting by lines") {
val split = empty.splitLines()
it("should be empty") {
assertEquals(0, split.size)
}
}
context("splitting by anything") {
val split = empty.split(ByteArray(0))
it("should have one element") {
assertEquals(1, split.size)
}
it("the element should be empty") {
assertTrue(split[0].isEmpty())
}
}
}
})
| src/test/kotlin/khttp/extensions/ExtensionsSpec.kt | 2644112691 |
package abi43_0_0.expo.modules
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import androidx.collection.ArrayMap
import abi43_0_0.com.facebook.react.ReactActivity
import abi43_0_0.com.facebook.react.ReactActivityDelegate
import abi43_0_0.com.facebook.react.ReactInstanceManager
import abi43_0_0.com.facebook.react.ReactNativeHost
import abi43_0_0.com.facebook.react.ReactRootView
import abi43_0_0.com.facebook.react.modules.core.PermissionListener
import java.lang.reflect.Method
class ReactActivityDelegateWrapper(
private val activity: ReactActivity,
private val delegate: ReactActivityDelegate
) : ReactActivityDelegate(activity, null) {
private val reactActivityLifecycleListeners = ExpoModulesPackage.packageList
.flatMap { it.createReactActivityLifecycleListeners(activity) }
private val methodMap: ArrayMap<String, Method> = ArrayMap()
//region ReactActivityDelegate
override fun getLaunchOptions(): Bundle? {
return invokeDelegateMethod("getLaunchOptions")
}
override fun createRootView(): ReactRootView {
return invokeDelegateMethod("createRootView")
}
override fun getReactNativeHost(): ReactNativeHost {
return invokeDelegateMethod("getReactNativeHost")
}
override fun getReactInstanceManager(): ReactInstanceManager {
return delegate.reactInstanceManager
}
override fun getMainComponentName(): String {
return delegate.mainComponentName
}
override fun loadApp(appKey: String?) {
return invokeDelegateMethod("loadApp", arrayOf(String::class.java), arrayOf(appKey))
}
override fun onCreate(savedInstanceState: Bundle?) {
invokeDelegateMethod<Unit, Bundle?>("onCreate", arrayOf(Bundle::class.java), arrayOf(savedInstanceState))
reactActivityLifecycleListeners.forEach { listener ->
listener.onCreate(activity, savedInstanceState)
}
}
override fun onResume() {
invokeDelegateMethod<Unit>("onResume")
reactActivityLifecycleListeners.forEach { listener ->
listener.onResume(activity)
}
}
override fun onPause() {
reactActivityLifecycleListeners.forEach { listener ->
listener.onPause(activity)
}
return invokeDelegateMethod("onPause")
}
override fun onDestroy() {
reactActivityLifecycleListeners.forEach { listener ->
listener.onDestroy(activity)
}
return invokeDelegateMethod("onDestroy")
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
delegate.onActivityResult(requestCode, resultCode, data)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
return delegate.onKeyDown(keyCode, event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
return delegate.onKeyUp(keyCode, event)
}
override fun onKeyLongPress(keyCode: Int, event: KeyEvent?): Boolean {
return delegate.onKeyLongPress(keyCode, event)
}
override fun onBackPressed(): Boolean {
return delegate.onBackPressed()
}
override fun onNewIntent(intent: Intent?): Boolean {
return delegate.onNewIntent(intent)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
delegate.onWindowFocusChanged(hasFocus)
}
override fun requestPermissions(permissions: Array<out String>?, requestCode: Int, listener: PermissionListener?) {
delegate.requestPermissions(permissions, requestCode, listener)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>?, grantResults: IntArray?) {
delegate.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun getContext(): Context {
return invokeDelegateMethod("getContext")
}
override fun getPlainActivity(): Activity {
return invokeDelegateMethod("getPlainActivity")
}
//endregion
//region Internals
private fun <T> invokeDelegateMethod(name: String): T {
var method = methodMap[name]
if (method == null) {
method = ReactActivityDelegate::class.java.getDeclaredMethod(name)
method.isAccessible = true
methodMap[name] = method
}
return method!!.invoke(delegate) as T
}
private fun <T, A> invokeDelegateMethod(
name: String,
argTypes: Array<Class<*>>,
args: Array<A>
): T {
var method = methodMap[name]
if (method == null) {
method = ReactActivityDelegate::class.java.getDeclaredMethod(name, *argTypes)
method.isAccessible = true
methodMap[name] = method
}
return method!!.invoke(delegate, *args) as T
}
//endregion
}
| android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/ReactActivityDelegateWrapper.kt | 3057623391 |
package io.github.notsyncing.lightfur.ql.permission
import io.github.notsyncing.lightfur.entity.EntityModel
class QueryPermissions {
companion object {
val ALL = QueryPermissions()
}
val allowEntities = mutableListOf<EntityPermission<*>>()
fun <T: EntityModel> entity(entityModel: T, f: (EntityPermission<T>) -> Unit = { it.all() }): QueryPermissions {
val ent = EntityPermission(entityModel)
f(ent)
allowEntities.add(ent)
return this
}
} | lightfur-ql/src/main/kotlin/io/github/notsyncing/lightfur/ql/permission/QueryPermissions.kt | 177461379 |
package net.dean.jraw.references
import net.dean.jraw.RedditClient
import net.dean.jraw.models.KindConstants
/** A reference to a reply to a submission or another comment */
class CommentReference(reddit: RedditClient, id: String) : PublicContributionReference(reddit, id, KindConstants.COMMENT)
| lib/src/main/kotlin/net/dean/jraw/references/CommentReference.kt | 1747540789 |
/*
* Copyright 2018 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.buildtransformer.util
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit
class Stopwatch {
val logger: Logger = LoggerFactory.getLogger("realm-stopwatch")
var start: Long = -1L
var lastSplit: Long = -1L
lateinit var label: String
/**
* Start the stopwatch.
*/
fun start(label: String) {
if (start != -1L) {
throw IllegalStateException("Stopwatch was already started");
}
this.label = label
start = System.nanoTime();
lastSplit = start;
}
/**
* Reports the split time.
*
* @param label Label to use when printing split time
* @param reportDiffFromLastSplit if `true` report the time from last split instead of the start
*/
fun splitTime(label: String, reportDiffFromLastSplit: Boolean = true) {
val split = System.nanoTime()
val diff = if (reportDiffFromLastSplit) { split - lastSplit } else { split - start }
lastSplit = split;
logger.debug("$label: ${TimeUnit.NANOSECONDS.toMillis(diff)} ms.")
}
/**
* Stops the timer and report the result.
*/
fun stop() {
val stop = System.nanoTime()
val diff = stop - start
logger.debug("$label: ${TimeUnit.NANOSECONDS.toMillis(diff)} ms.")
}
} | library-build-transformer/src/main/kotlin/io/realm/buildtransformer/util/Stopwatch.kt | 3895759356 |
package io.realm.mongodb.sync
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import io.realm.*
import io.realm.admin.ServerAdmin
import io.realm.entities.*
import io.realm.kotlin.syncSession
import io.realm.log.LogLevel
import io.realm.log.RealmLog
import io.realm.mongodb.User
import io.realm.mongodb.registerUserAndLogin
import io.realm.rule.BlockingLooperThread
import org.junit.runner.RunWith
import io.realm.kotlin.where
import io.realm.mongodb.close
import org.junit.*
import org.junit.Assert.*
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicInteger
import kotlin.random.Random
import kotlin.test.assertFailsWith
/**
* Integration smoke tests for Flexible Sync. This is not intended to cover all cases, but just
* test common scenarios.
*/
@RunWith(AndroidJUnit4::class)
class FlexibleSyncIntegrationTests {
@get:Rule
val configFactory = TestSyncConfigurationFactory()
private val looperThread = BlockingLooperThread()
private lateinit var app: TestApp
private lateinit var serverAdmin: ServerAdmin
private lateinit var realmConfig: SyncConfiguration
private lateinit var realm: Realm
private lateinit var user: User
private var section: Int = 0
@Before
fun setUp() {
Realm.init(InstrumentationRegistry.getInstrumentation().targetContext)
RealmLog.setLevel(LogLevel.ALL)
app = TestApp(appName = TEST_APP_3)
user = app.registerUserAndLogin(TestHelper.getRandomEmail(), "SECRET_PASSWORD")
serverAdmin = ServerAdmin(app).apply {
enableFlexibleSync() // Currently required because importing doesn't work
}
section = Random.nextInt() // Generate random section to allow replays of unit tests
}
@After
fun tearDown() {
if (this::app.isInitialized) {
app.close()
}
}
@Test
fun downloadInitialData() {
// Upload data from user 1
val user1 = app.registerUserAndLogin(TestHelper.getRandomEmail(), "123456")
val config1 = configFactory.createFlexibleSyncConfigurationBuilder(user1)
.schema(FlexSyncColor::class.java)
.build()
val realm1 = Realm.getInstance(config1)
val subs = realm1.subscriptions.update {
it.add(Subscription.create(realm1.where<FlexSyncColor>().equalTo("section", section)))
}
assertTrue(subs.waitForSynchronization())
realm1.executeTransaction {
it.insert(FlexSyncColor(section).apply { color = "red" })
it.insert(FlexSyncColor(section).apply { color = "blue" })
}
realm1.syncSession.uploadAllLocalChanges()
realm1.close()
// Download data from user 2
val user2 = app.registerUserAndLogin(TestHelper.getRandomEmail(), "123456")
val config2 = configFactory.createFlexibleSyncConfigurationBuilder(user2)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
realm.where<FlexSyncColor>()
.equalTo("section", section)
.equalTo("color", "blue")
)
)
}
.waitForInitialRemoteData()
.build()
val realm2 = Realm.getInstance(config2)
assertEquals(1, realm2.where<FlexSyncColor>().equalTo("color", "blue").count())
realm2.close()
}
@Test
fun clientResetIfNoSubscriptionWhenWriting() = looperThread.runBlocking {
val user = app.registerUserAndLogin(TestHelper.getRandomEmail(), "123456")
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
realm.executeTransaction {
assertFailsWith<RuntimeException> { it.insert(FlexSyncColor().apply { color = "red" }) }
looperThread.testComplete()
}
}
@Test
fun dataIsDeletedWhenSubscriptionIsRemoved() {
val user = app.registerUserAndLogin(TestHelper.getRandomEmail(), "123456")
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub", realm.where<FlexSyncColor>()
.equalTo("section", section)
.beginGroup()
.equalTo("color", "red")
.or()
.equalTo("color", "blue")
.endGroup()
)
)
}
.build()
val realm = Realm.getInstance(config)
realm.executeTransaction {
it.insert(FlexSyncColor(section).apply { color = "red" })
it.insert(FlexSyncColor(section).apply { color = "blue" })
}
assertEquals(2, realm.where<FlexSyncColor>().count())
val subscriptions = realm.subscriptions
subscriptions.update {
it.addOrUpdate(
Subscription.create(
"sub", realm.where<FlexSyncColor>()
.equalTo("section", section)
.equalTo("color", "red")
)
)
}
assertTrue(subscriptions.waitForSynchronization())
realm.refresh()
assertEquals(1, realm.where<FlexSyncColor>().count())
realm.close()
}
@Test
fun errorHandler_discardUnsyncedChangesStrategyReported() = looperThread.runBlocking {
val latch = CountDownLatch(2)
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object : DiscardUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
assertTrue(realm.isFrozen)
assertEquals(1, realm.where<FlexSyncColor>().count())
latch.countDown()
}
override fun onAfterReset(before: Realm, after: Realm) {
assertTrue(before.isFrozen)
assertFalse(after.isFrozen)
assertEquals(1, before.where<FlexSyncColor>().count())
assertEquals(0, after.where<FlexSyncColor>().count())
//Validate we can move data to the reset Realm.
after.executeTransaction {
it.insert(before.where<FlexSyncColor>().findFirst()!!)
}
assertEquals(1, after.where<FlexSyncColor>().count())
latch.countDown()
}
@Deprecated("Deprecated in favor of onManualResetFallback")
override fun onError(session: SyncSession, error: ClientResetRequiredError) {
fail("This test case was not supposed to trigger DiscardUnsyncedChangesStrategy::onError()")
}
override fun onManualResetFallback(
session: SyncSession,
error: ClientResetRequiredError
) {
fail("This test case was not supposed to trigger DiscardUnsyncedChangesStrategy::onManualResetFallback()")
}
})
.modules(ColorSyncSchema())
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
looperThread.testComplete(latch)
}
@Test
fun clientReset_discardUnsyncedChangesStrategy_fallback_userException_onBeforeReset() = looperThread.runBlocking {
val latch = CountDownLatch(2)
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object : DiscardUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
throw RuntimeException()
}
override fun onAfterReset(before: Realm, after: Realm) {
fail("This test case was not supposed to trigger DiscardUnsyncedChangesStrategy::onAfterReset()")
}
@Deprecated("Deprecated in favor of onManualResetFallback")
override fun onError(session: SyncSession, error: ClientResetRequiredError) {
latch.countDown()
}
override fun onManualResetFallback(
session: SyncSession,
error: ClientResetRequiredError
) {
validateManualResetIsAvailable(session, error)
latch.countDown()
}
})
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
looperThread.testComplete(latch)
}
@Test
fun clientReset_discardUnsyncedChangesStrategy_fallback_userException_onAfterReset() = looperThread.runBlocking {
val latch = CountDownLatch(2)
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object : DiscardUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
assertNotNull(realm)
}
override fun onAfterReset(before: Realm, after: Realm) {
throw RuntimeException()
}
@Deprecated("Deprecated in favor of onManualResetFallback")
override fun onError(session: SyncSession, error: ClientResetRequiredError) {
latch.countDown()
}
override fun onManualResetFallback(
session: SyncSession,
error: ClientResetRequiredError
) {
validateManualResetIsAvailable(session, error)
latch.countDown()
}
})
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
looperThread.testComplete(latch)
}
@Test
fun errorHandler_automaticRecoveryStrategy() = looperThread.runBlocking {
val latch = CountDownLatch(2)
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object : RecoverUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
assertTrue(realm.isFrozen)
assertEquals(1, realm.where<FlexSyncColor>().count())
latch.countDown()
}
override fun onAfterReset(before: Realm, after: Realm) {
assertEquals(1, before.where<FlexSyncColor>().count())
assertEquals(1, after.where<FlexSyncColor>().count())
latch.countDown()
}
override fun onManualResetFallback(session: SyncSession, error: ClientResetRequiredError) {
fail("This test case was not supposed to trigger AutomaticRecoveryStrategy::onManualResetFallback()")
}
})
.modules(ColorSyncSchema())
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
looperThread.testComplete(latch)
}
@Test
fun clientReset_recoverUnsyncedChangesStrategy_fallback_userException_onBeforeReset() = looperThread.runBlocking {
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object : RecoverUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
throw RuntimeException()
}
override fun onAfterReset(before: Realm, after: Realm) {
fail("This test case was not supposed to trigger RecoverUnsyncedChangesStrategy::onAfterReset()")
}
override fun onManualResetFallback(
session: SyncSession,
error: ClientResetRequiredError
) {
validateManualResetIsAvailable(session, error)
looperThread.testComplete()
}
})
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
}
@Test
fun clientReset_recoverUnsyncedChangesStrategy_fallback_userException_onAfterReset() = looperThread.runBlocking {
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object : RecoverUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
assertNotNull(realm)
}
override fun onAfterReset(before: Realm, after: Realm) {
throw RuntimeException()
}
override fun onManualResetFallback(
session: SyncSession,
error: ClientResetRequiredError
) {
validateManualResetIsAvailable(session, error)
looperThread.testComplete()
}
})
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
}
@Test
fun errorHandler_automaticRecoveryOrDiscardStrategy() = looperThread.runBlocking {
val latch = CountDownLatch(2)
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object :
RecoverOrDiscardUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
assertTrue(realm.isFrozen)
assertEquals(1, realm.where<FlexSyncColor>().count())
latch.countDown()
}
override fun onAfterRecovery(before: Realm, after: Realm) {
assertEquals(1, before.where<FlexSyncColor>().count())
assertEquals(1, after.where<FlexSyncColor>().count())
latch.countDown()
}
override fun onAfterDiscard(before: Realm, after: Realm) {
fail("This test case was not supposed to trigger AutomaticRecoveryOrDiscardUnsyncedChangesStrategy::onAfterDiscard()")
}
override fun onManualResetFallback(session: SyncSession, error: ClientResetRequiredError) {
fail("This test case was not supposed to trigger AutomaticRecoveryStrategy::onManualResetFallback()")
}
})
.modules(ColorSyncSchema())
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
looperThread.testComplete(latch)
}
@Test
fun errorHandler_automaticRecoveryOrDiscardStrategy_discardsLocal() = looperThread.runBlocking {
val latch = CountDownLatch(2)
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object :
RecoverOrDiscardUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
assertTrue(realm.isFrozen)
assertEquals(1, realm.where<FlexSyncColor>().count())
latch.countDown()
}
override fun onAfterRecovery(before: Realm, after: Realm) {
fail("This test case was not supposed to trigger AutomaticRecoveryOrDiscardUnsyncedChangesStrategy::onAfterRecovery()")
}
override fun onAfterDiscard(before: Realm, after: Realm) {
assertTrue(before.isFrozen)
assertFalse(after.isFrozen)
assertEquals(1, before.where<FlexSyncColor>().count())
assertEquals(0, after.where<FlexSyncColor>().count())
//Validate we can move data to the reset Realm.
after.executeTransaction {
it.insert(before.where<FlexSyncColor>().findFirst()!!)
}
assertEquals(1, after.where<FlexSyncColor>().count())
latch.countDown()
}
override fun onManualResetFallback(session: SyncSession, error: ClientResetRequiredError) {
fail("This test case was not supposed to trigger AutomaticRecoveryOrDiscardUnsyncedChangesStrategy::onManualResetFallback()")
}
})
.modules(ColorSyncSchema())
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession, withRecoveryModeEnabled = false) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
looperThread.testComplete(latch)
}
@Test
fun clientReset_recoverOrDiscardUnsyncedChangesStrategy_fallback_userException_onBeforeReset() = looperThread.runBlocking {
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object : RecoverOrDiscardUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
throw RuntimeException()
}
override fun onAfterRecovery(before: Realm, after: Realm) {
fail("This test case was not supposed to trigger RecoverOrDiscardUnsyncedChangesStrategy::onAfterRecovery()")
}
override fun onAfterDiscard(before: Realm, after: Realm) {
fail("This test case was not supposed to trigger RecoverOrDiscardUnsyncedChangesStrategy::onAfterDiscard()")
}
override fun onManualResetFallback(
session: SyncSession,
error: ClientResetRequiredError
) {
validateManualResetIsAvailable(session, error)
looperThread.testComplete()
}
})
.modules(ObjectSyncSchema())
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
}
@Test
fun clientReset_recoverOrDiscardUnsyncedChangesStrategy_fallback_userException_onAfterRecovery() = looperThread.runBlocking {
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object : RecoverOrDiscardUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
assertNotNull(realm)
}
override fun onAfterRecovery(before: Realm, after: Realm) {
throw RuntimeException()
}
override fun onAfterDiscard(before: Realm, after: Realm) {
fail("This test case was not supposed to trigger RecoverOrDiscardUnsyncedChangesStrategy::onAfterDiscard()")
}
override fun onManualResetFallback(
session: SyncSession,
error: ClientResetRequiredError
) {
validateManualResetIsAvailable(session, error)
looperThread.testComplete()
}
})
.modules(ObjectSyncSchema())
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
}
@Test
fun clientReset_recoverOrDiscardUnsyncedChangesStrategy_fallback_userException_onAfterDiscard() = looperThread.runBlocking {
val config = configFactory.createFlexibleSyncConfigurationBuilder(user)
.schema(FlexSyncColor::class.java)
.initialSubscriptions { realm, subscriptions ->
subscriptions.add(
Subscription.create(
"sub",
realm.where<FlexSyncColor>().equalTo("section", section)
)
)
}
.syncClientResetStrategy(object : RecoverOrDiscardUnsyncedChangesStrategy {
override fun onBeforeReset(realm: Realm) {
assertNotNull(realm)
}
override fun onAfterRecovery(before: Realm, after: Realm) {
fail("This test case was not supposed to trigger RecoverOrDiscardUnsyncedChangesStrategy::onAfterRecovery()")
}
override fun onAfterDiscard(before: Realm, after: Realm) {
throw RuntimeException()
}
override fun onManualResetFallback(
session: SyncSession,
error: ClientResetRequiredError
) {
validateManualResetIsAvailable(session, error)
looperThread.testComplete()
}
})
.modules(ObjectSyncSchema())
.build()
val realm = Realm.getInstance(config)
looperThread.closeAfterTest(realm)
serverAdmin.triggerClientReset(realm.syncSession, withRecoveryModeEnabled = false) {
realm.executeTransaction {
realm.copyToRealm(FlexSyncColor().apply {
this.section = [email protected]
})
}
assertEquals(1, realm.where<FlexSyncColor>().count())
}
}
} | realm/realm-library/src/androidTestObjectServer/kotlin/io/realm/mongodb/sync/FlexibleSyncIntegrationTests.kt | 2996768000 |
// 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.workspaceModel.storage
import com.intellij.workspaceModel.storage.entities.test.api.SampleEntity
import com.intellij.workspaceModel.storage.entities.test.addSampleEntity
import com.intellij.workspaceModel.storage.entities.test.api.modifyEntity
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
class WorkspaceEntityEqualityTest {
private lateinit var builderOne: MutableEntityStorage
private lateinit var builderTwo: MutableEntityStorage
@Before
fun setUp() {
builderOne = MutableEntityStorage.create()
builderTwo = MutableEntityStorage.create()
}
@Test
fun `equality from different stores`() {
val entityOne = builderOne.addSampleEntity("Data")
val entityTwo = builderTwo.addSampleEntity("Data")
assertNotEquals(entityOne, entityTwo)
}
@Test
fun `equality modified entity in builder`() {
val entityOne = builderOne.addSampleEntity("Data")
val entityTwo = builderOne.modifyEntity(entityOne) {
stringProperty = "AnotherData"
}
assertEquals(entityOne, entityTwo)
}
@Test
fun `equality modified entity`() {
builderOne.addSampleEntity("Data")
val storage = builderOne.toSnapshot()
val entityOne = storage.entities(SampleEntity::class.java).single()
val builder = storage.toBuilder()
builder.modifyEntity(entityOne) {
stringProperty = "AnotherData"
}
val entityTwo = builder.toSnapshot().entities(SampleEntity::class.java).single()
assertNotEquals(entityOne, entityTwo)
}
@Test
fun `equality modified another entity`() {
builderOne.addSampleEntity("Data1")
builderOne.addSampleEntity("Data2")
val storage = builderOne.toSnapshot()
val entityOne = storage.entities(SampleEntity::class.java).single { it.stringProperty == "Data1" }
val entityForModification = storage.entities(SampleEntity::class.java).single { it.stringProperty == "Data2" }
val builder = storage.toBuilder()
builder.modifyEntity(entityForModification) {
stringProperty = "AnotherData"
}
val entityTwo = builder.toSnapshot().entities(SampleEntity::class.java).single { it.stringProperty == "Data1" }
assertEquals(entityOne, entityTwo)
}
@Test
fun `equality in set`() {
builderOne.addSampleEntity("Data1")
builderOne.addSampleEntity("Data2")
val checkSet = HashSet<SampleEntity>()
var storage = builderOne.toSnapshot()
val entityOne = storage.entities(SampleEntity::class.java).single { it.stringProperty == "Data1" }
checkSet += entityOne
var entityForModification = storage.entities(SampleEntity::class.java).single { it.stringProperty == "Data2" }
var builder = storage.toBuilder()
builder.modifyEntity(entityForModification) {
stringProperty = "AnotherData"
}
storage = builder.toSnapshot()
val entityTwo = storage.entities(SampleEntity::class.java).single { it.stringProperty == "Data1" }
assertTrue(entityTwo in checkSet)
entityForModification = storage.entities(SampleEntity::class.java).single { it.stringProperty == "Data1" }
builder = storage.toBuilder()
builder.modifyEntity(entityForModification) {
stringProperty = "AnotherData2"
}
val entityThree = builder.toSnapshot().entities(SampleEntity::class.java).single { it.stringProperty == "AnotherData2" }
assertFalse(entityThree in checkSet)
}
} | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/WorkspaceEntityEqualityTest.kt | 427890732 |
package com.fsck.k9.preferences.migrations
import android.database.sqlite.SQLiteDatabase
import com.fsck.k9.ServerSettingsSerializer
import com.fsck.k9.mail.filter.Base64
import com.fsck.k9.preferences.migrations.migration12.ImapStoreUriDecoder
import com.fsck.k9.preferences.migrations.migration12.Pop3StoreUriDecoder
import com.fsck.k9.preferences.migrations.migration12.SmtpTransportUriDecoder
import com.fsck.k9.preferences.migrations.migration12.WebDavStoreUriDecoder
/**
* Convert server settings from the old URI format to the new JSON format
*/
class StorageMigrationTo12(
private val db: SQLiteDatabase,
private val migrationsHelper: StorageMigrationsHelper
) {
private val serverSettingsSerializer = ServerSettingsSerializer()
fun removeStoreAndTransportUri() {
val accountUuidsListValue = migrationsHelper.readValue(db, "accountUuids")
if (accountUuidsListValue == null || accountUuidsListValue.isEmpty()) {
return
}
val accountUuids = accountUuidsListValue.split(",")
for (accountUuid in accountUuids) {
convertStoreUri(accountUuid)
convertTransportUri(accountUuid)
}
}
private fun convertStoreUri(accountUuid: String) {
val storeUri = migrationsHelper.readValue(db, "$accountUuid.storeUri")?.base64Decode() ?: return
val serverSettings = when {
storeUri.startsWith("imap") -> ImapStoreUriDecoder.decode(storeUri)
storeUri.startsWith("pop3") -> Pop3StoreUriDecoder.decode(storeUri)
storeUri.startsWith("webdav") -> WebDavStoreUriDecoder.decode(storeUri)
else -> error("Unsupported account type")
}
val json = serverSettingsSerializer.serialize(serverSettings)
migrationsHelper.insertValue(db, "$accountUuid.incomingServerSettings", json)
migrationsHelper.writeValue(db, "$accountUuid.storeUri", null)
}
private fun convertTransportUri(accountUuid: String) {
val transportUri = migrationsHelper.readValue(db, "$accountUuid.transportUri")?.base64Decode() ?: return
val serverSettings = when {
transportUri.startsWith("smtp") -> SmtpTransportUriDecoder.decodeSmtpUri(transportUri)
transportUri.startsWith("webdav") -> WebDavStoreUriDecoder.decode(transportUri)
else -> error("Unsupported account type")
}
val json = serverSettingsSerializer.serialize(serverSettings)
migrationsHelper.insertValue(db, "$accountUuid.outgoingServerSettings", json)
migrationsHelper.writeValue(db, "$accountUuid.transportUri", null)
}
private fun String.base64Decode() = Base64.decode(this)
}
| app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo12.kt | 2481566517 |
package org.hexworks.zircon.api.builder.application
import org.hexworks.zircon.api.application.ModifierSupport
import org.hexworks.zircon.api.builder.Builder
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.modifier.TextureTransformModifier
import org.hexworks.zircon.api.tileset.TextureTransformer
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.internal.dsl.ZirconDsl
import org.hexworks.zircon.internal.tileset.impl.DefaultTextureTransformer
import kotlin.reflect.KClass
import kotlin.jvm.JvmStatic
@ZirconDsl
class ModifierSupportBuilder<T : Any> private constructor(
var modifierType: KClass<out TextureTransformModifier>? = null,
var targetType: KClass<T>? = null,
var transformerFunction: ((texture: TileTexture<T>, tile: Tile) -> TileTexture<T>)? = null,
var transformer: TextureTransformer<T>? = null
) : Builder<ModifierSupport<T>> {
override fun createCopy() = ModifierSupportBuilder(
modifierType = modifierType,
targetType = targetType,
transformerFunction = transformerFunction
)
override fun build(): ModifierSupport<T> {
requireNotNull(targetType) {
"Target type is missing."
}
requireNotNull(modifierType) {
"Modifier type is missing"
}
require(transformerFunction != null || transformer != null) {
"Transformer is missing."
}
return ModifierSupport(
modifierType = modifierType!!,
targetType = targetType!!,
transformer = transformer ?: DefaultTextureTransformer(targetType!!, transformerFunction!!)
)
}
companion object {
@JvmStatic
fun <T : Any> newBuilder() = ModifierSupportBuilder<T>()
}
}
| zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/application/ModifierSupportBuilder.kt | 602101566 |
package org.gradle.kotlin.dsl.plugins.dsl
import org.gradle.kotlin.dsl.fixtures.AbstractPluginTest
import org.gradle.kotlin.dsl.fixtures.containsMultiLineString
import org.gradle.kotlin.dsl.fixtures.normalisedPath
import org.gradle.kotlin.dsl.support.expectedKotlinDslPluginsVersion
import org.gradle.test.fixtures.file.LeaksFileHandles
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.not
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
@LeaksFileHandles("Kotlin Compiler Daemon working directory")
class KotlinDslPluginTest : AbstractPluginTest() {
@Test
fun `warns on unexpected kotlin-dsl plugin version`() {
// The test applies the in-development version of the kotlin-dsl
// which, by convention, it is always ahead of the version expected by
// the in-development version of Gradle
// (see publishedKotlinDslPluginsVersion in kotlin-dsl.gradle.kts)
withKotlinDslPlugin()
withDefaultSettings().appendText(
"""
rootProject.name = "forty-two"
"""
)
val appliedKotlinDslPluginsVersion = futurePluginVersions["org.gradle.kotlin.kotlin-dsl"]
build("help").apply {
assertOutputContains(
"This version of Gradle expects version '$expectedKotlinDslPluginsVersion' of the `kotlin-dsl` plugin but version '$appliedKotlinDslPluginsVersion' has been applied to root project 'forty-two'."
)
}
}
@Test
fun `gradle kotlin dsl api dependency is added`() {
withKotlinDslPlugin()
withFile(
"src/main/kotlin/code.kt",
"""
// src/main/kotlin
import org.gradle.kotlin.dsl.GradleDsl
// src/generated
import org.gradle.kotlin.dsl.embeddedKotlinVersion
"""
)
val result = build("classes")
result.assertTaskExecuted(":compileKotlin")
}
@Test
fun `gradle kotlin dsl api is available for test implementation`() {
assumeNonEmbeddedGradleExecuter() // Requires a Gradle distribution on the test-under-test classpath, but gradleApi() does not offer the full distribution
ignoreKotlinDaemonJvmDeprecationWarningsOnJdk16()
withBuildScript(
"""
plugins {
`kotlin-dsl`
}
$repositoriesBlock
dependencies {
testImplementation("junit:junit:4.13")
}
"""
)
withFile(
"src/main/kotlin/code.kt",
"""
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.embeddedKotlinVersion
class MyPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.run {
println("Plugin Using Embedded Kotlin " + embeddedKotlinVersion)
}
}
}
"""
)
withFile(
"src/test/kotlin/test.kt",
"""
import org.gradle.testfixtures.ProjectBuilder
import org.junit.Test
import org.gradle.kotlin.dsl.*
class MyTest {
@Test
fun `my test`() {
ProjectBuilder.builder().build().run {
apply<MyPlugin>()
}
}
}
"""
)
assertThat(
outputOf("test", "-i"),
containsString("Plugin Using Embedded Kotlin ")
)
}
@Test
fun `gradle kotlin dsl api is available in test-kit injected plugin classpath`() {
assumeNonEmbeddedGradleExecuter() // requires a full distribution to run tests with test kit
ignoreKotlinDaemonJvmDeprecationWarningsOnJdk16()
withBuildScript(
"""
plugins {
`kotlin-dsl`
}
$repositoriesBlock
dependencies {
testImplementation("junit:junit:4.13")
testImplementation("org.hamcrest:hamcrest-library:1.3")
testImplementation(gradleTestKit())
}
gradlePlugin {
plugins {
register("myPlugin") {
id = "my-plugin"
implementationClass = "my.MyPlugin"
}
}
}
"""
)
withFile(
"src/main/kotlin/my/code.kt",
"""
package my
import org.gradle.api.*
import org.gradle.kotlin.dsl.*
class MyPlugin : Plugin<Project> {
override fun apply(project: Project) {
println("Plugin Using Embedded Kotlin " + embeddedKotlinVersion)
}
}
"""
)
withFile(
"src/test/kotlin/test.kt",
"""
import java.io.File
import org.gradle.testkit.runner.GradleRunner
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class MyTest {
@JvmField @Rule val temporaryFolder = TemporaryFolder()
val projectRoot by lazy {
File(temporaryFolder.root, "test").apply { mkdirs() }
}
@Test
fun `my test`() {
// given:
File(projectRoot, "build.gradle.kts")
.writeText("plugins { id(\"my-plugin\") }")
// and:
System.setProperty("org.gradle.daemon.idletimeout", "1000")
System.setProperty("org.gradle.daemon.registry.base", "${existing("daemons-registry").normalisedPath}")
File(projectRoot, "gradle.properties").writeText("org.gradle.jvmargs=-Xmx128m")
// and:
val runner = GradleRunner.create()
.withGradleInstallation(File("${distribution.gradleHomeDir.normalisedPath}"))
.withTestKitDir(File("${executer.gradleUserHomeDir.normalisedPath}"))
.withProjectDir(projectRoot)
.withPluginClasspath()
.forwardOutput()
// when:
val result = runner.withArguments("help").build()
// then:
require("Plugin Using Embedded Kotlin " in result.output)
}
}
"""
)
assertThat(
outputOf("test", "-i"),
containsString("Plugin Using Embedded Kotlin ")
)
}
@Test
fun `sam-with-receiver kotlin compiler plugin is applied to production code`() {
withKotlinDslPlugin()
withFile(
"src/main/kotlin/code.kt",
"""
import org.gradle.api.Plugin
import org.gradle.api.Project
class MyPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.run {
copy {
from("build.gradle.kts")
into("build/build.gradle.kts.copy")
}
}
}
}
"""
)
val result = build("classes")
result.assertTaskExecuted(":compileKotlin")
}
@Test
fun `can use SAM conversions for Kotlin functions without warnings`() {
withBuildExercisingSamConversionForKotlinFunctions()
build("test").apply {
assertThat(
output.also(::println),
containsMultiLineString(
"""
STRING
foo
bar
"""
)
)
assertThat(
output,
not(containsString(samConversionForKotlinFunctions))
)
}
}
@Test
fun `nags user about experimentalWarning deprecation`() {
withBuildExercisingSamConversionForKotlinFunctions(
"kotlinDslPluginOptions.experimentalWarning.set(false)"
)
executer.expectDeprecationWarning(
"The KotlinDslPluginOptions.experimentalWarning property has been deprecated. " +
"This is scheduled to be removed in Gradle 8.0. " +
"Flag has no effect since `kotlin-dsl` no longer relies on experimental features."
)
build("test").apply {
assertThat(
output.also(::println),
containsMultiLineString(
"""
STRING
foo
bar
"""
)
)
assertThat(
output,
not(containsString(samConversionForKotlinFunctions))
)
}
}
private
fun withBuildExercisingSamConversionForKotlinFunctions(buildSrcScript: String = "") {
withDefaultSettingsIn("buildSrc")
withBuildScriptIn(
"buildSrc",
"""
plugins {
`kotlin-dsl`
}
$repositoriesBlock
$buildSrcScript
"""
)
withFile(
"buildSrc/src/main/kotlin/my.kt",
"""
package my
// Action<T> is a SAM with receiver
fun <T : Any> applyActionTo(value: T, action: org.gradle.api.Action<T>) = action.execute(value)
// NamedDomainObjectFactory<T> is a regular SAM
fun <T> create(name: String, factory: org.gradle.api.NamedDomainObjectFactory<T>): T = factory.create(name)
fun <T : Any> createK(type: kotlin.reflect.KClass<T>, factory: org.gradle.api.NamedDomainObjectFactory<T>): T = factory.create(type.simpleName!!)
fun test() {
// Implicit SAM conversion in regular source
println(createK(String::class) { it.toUpperCase() })
println(create("FOO") { it.toLowerCase() })
// Implicit SAM with receiver conversion in regular source
applyActionTo("BAR") {
println(toLowerCase())
}
}
"""
)
withBuildScript(
"""
task("test") {
doLast { my.test() }
}
"""
)
}
private
fun outputOf(vararg arguments: String) =
build(*arguments).output
}
private
const val samConversionForKotlinFunctions = "-XXLanguage:+SamConversionForKotlinFunctions"
| subprojects/kotlin-dsl-plugins/src/integTest/kotlin/org/gradle/kotlin/dsl/plugins/dsl/KotlinDslPluginTest.kt | 246995649 |
/**
* This file is part of lavagna.
* lavagna 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.
* lavagna 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 lavagna. If not, see //www.gnu.org/licenses/>.
*/
package io.lavagna.model
import ch.digitalfondue.npjt.ConstructorAnnotationRowMapper.Column
class CardDataIdAndOrder(@Column("CARD_DATA_ID") first: Int, @Column("CARD_DATA_ORDER") second: Int) : Pair<Int, Int>(first, second)
| src/main/java/io/lavagna/model/CardDataIdAndOrder.kt | 4121532097 |
package org.hexworks.zircon.internal.component.data
import org.hexworks.cobalt.databinding.api.extension.toProperty
import org.hexworks.cobalt.databinding.api.property.Property
import org.hexworks.zircon.api.ComponentAlignments
import org.hexworks.zircon.api.component.AlignmentStrategy
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.component.ComponentStyleSet
import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer
import org.hexworks.zircon.api.component.renderer.ComponentPostProcessor
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.internal.component.renderer.NoOpComponentRenderer
/**
* Contains all the common data for component builders.
*/
data class CommonComponentProperties<T : Component>(
var name: String = "",
var alignmentStrategy: AlignmentStrategy = ComponentAlignments.positionalAlignment(0, 0),
var decorationRenderers: List<ComponentDecorationRenderer> = listOf(),
var preferredContentSize: Size = Size.unknown(),
var preferredSize: Size = Size.unknown(),
var componentRenderer: ComponentRenderer<out T> = NoOpComponentRenderer(),
var postProcessors: List<ComponentPostProcessor<T>> = listOf(),
var updateOnAttach: Boolean = true,
// can be changed runtime
val themeProperty: Property<ColorTheme> = ColorTheme.unknown().toProperty(),
val componentStyleSetProperty: Property<ComponentStyleSet> = ComponentStyleSet.unknown().toProperty(),
val tilesetProperty: Property<TilesetResource> = TilesetResource.unknown().toProperty(),
val hiddenProperty: Property<Boolean> = false.toProperty(),
val disabledProperty: Property<Boolean> = false.toProperty()
) {
var theme: ColorTheme by themeProperty.asDelegate()
var componentStyleSet: ComponentStyleSet by componentStyleSetProperty.asDelegate()
var tileset: TilesetResource by tilesetProperty.asDelegate()
var isHidden: Boolean by hiddenProperty.asDelegate()
var isDisabled: Boolean by disabledProperty.asDelegate()
}
| zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/data/CommonComponentProperties.kt | 4183791389 |
package org.wordpress.android.util.config
import org.wordpress.android.BuildConfig
import org.wordpress.android.annotation.Feature
import javax.inject.Inject
@Feature(JetpackPoweredBottomSheetFeatureConfig.JETPACK_POWERED_BOTTOM_SHEET_REMOTE_FIELD, false)
class JetpackPoweredBottomSheetFeatureConfig @Inject constructor(
appConfig: AppConfig
) : FeatureConfig(
appConfig,
BuildConfig.JETPACK_POWERED_BOTTOM_SHEET,
JETPACK_POWERED_BOTTOM_SHEET_REMOTE_FIELD
) {
companion object {
const val JETPACK_POWERED_BOTTOM_SHEET_REMOTE_FIELD = "jetpack_powered_bottom_sheet_remote_field"
}
}
| WordPress/src/main/java/org/wordpress/android/util/config/JetpackPoweredBottomSheetFeatureConfig.kt | 1451640346 |
package com.leantechstacks.jcart.bo.entities
import javax.persistence.*
@Entity
@Table(name = "vendors")
class Vendor()
{
@Id
@SequenceGenerator(name = "vendor_generator", sequenceName = "vendor_sequence", initialValue = 100)
@GeneratedValue(generator = "vendor_generator")
var id: Long = 0
@Column(nullable = false)
var name: String = ""
constructor(id: Long) :this() {
this.id = id
}
constructor(id: Long, name: String) :this() {
this.id = id
this.name = name
}
}
| src/main/kotlin/com/leantechstacks/jcart/bo/entities/Vendor.kt | 2809051448 |
package org.wordpress.android.ui.mysite.items.listitem
import android.text.TextUtils
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.ui.mysite.MySiteCardAndItem
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Item.ListItem
import org.wordpress.android.ui.mysite.MySiteViewModel
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.ACTIVITY_LOG
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.ADMIN
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.BACKUP
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.DOMAINS
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.JETPACK_SETTINGS
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.PAGES
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.PEOPLE
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.PLAN
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.PLUGINS
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.SCAN
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.SHARING
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.SITE_SETTINGS
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.THEMES
import org.wordpress.android.ui.plugins.PluginUtilsWrapper
import org.wordpress.android.ui.themes.ThemeBrowserUtils
import org.wordpress.android.ui.utils.ListItemInteraction
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.BuildConfigWrapper
import org.wordpress.android.util.DateTimeUtils
import org.wordpress.android.util.SiteUtilsWrapper
import org.wordpress.android.util.config.SiteDomainsFeatureConfig
import java.util.GregorianCalendar
import java.util.TimeZone
import javax.inject.Inject
class SiteListItemBuilder @Inject constructor(
private val accountStore: AccountStore,
private val pluginUtilsWrapper: PluginUtilsWrapper,
private val siteUtilsWrapper: SiteUtilsWrapper,
private val buildConfigWrapper: BuildConfigWrapper,
private val themeBrowserUtils: ThemeBrowserUtils,
private val siteDomainsFeatureConfig: SiteDomainsFeatureConfig
) {
fun buildActivityLogItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
val isWpComOrJetpack = siteUtilsWrapper.isAccessedViaWPComRest(
site
) || site.isJetpackConnected
return if (site.hasCapabilityManageOptions && isWpComOrJetpack && !site.isWpForTeamsSite) {
ListItem(
R.drawable.ic_gridicons_clipboard_white_24dp,
UiStringRes(R.string.activity_log),
onClick = ListItemInteraction.create(ACTIVITY_LOG, onClick)
)
} else null
}
fun buildBackupItemIfAvailable(onClick: (ListItemAction) -> Unit, isBackupAvailable: Boolean = false): ListItem? {
return if (isBackupAvailable) {
ListItem(
R.drawable.ic_gridicons_cloud_upload_white_24dp,
UiStringRes(R.string.backup),
onClick = ListItemInteraction.create(BACKUP, onClick)
)
} else null
}
fun buildScanItemIfAvailable(onClick: (ListItemAction) -> Unit, isScanAvailable: Boolean = false): ListItem? {
return if (isScanAvailable) {
ListItem(
R.drawable.ic_baseline_security_white_24dp,
UiStringRes(R.string.scan),
onClick = ListItemInteraction.create(SCAN, onClick)
)
} else null
}
fun buildJetpackItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
val jetpackSettingsVisible = site.isJetpackConnected && // jetpack is installed and connected
!site.isWPComAtomic &&
siteUtilsWrapper.isAccessedViaWPComRest(site) && // is using .com login
site.hasCapabilityManageOptions // has permissions to manage the site
return if (jetpackSettingsVisible) {
ListItem(
R.drawable.ic_cog_white_24dp,
UiStringRes(R.string.my_site_btn_jetpack_settings),
onClick = ListItemInteraction.create(JETPACK_SETTINGS, onClick)
)
} else null
}
@Suppress("ComplexCondition")
fun buildPlanItemIfAvailable(
site: SiteModel,
showFocusPoint: Boolean,
onClick: (ListItemAction) -> Unit
): ListItem? {
val planShortName = site.planShortName
return if (!TextUtils.isEmpty(planShortName) &&
site.hasCapabilityManageOptions &&
!site.isWpForTeamsSite &&
(site.isWPCom || site.isAutomatedTransfer)) {
ListItem(
R.drawable.ic_plans_white_24dp,
UiStringRes(R.string.plan),
secondaryText = UiStringText(planShortName),
onClick = ListItemInteraction.create(PLAN, onClick),
showFocusPoint = showFocusPoint
)
} else null
}
fun buildPagesItemIfAvailable(
site: SiteModel,
onClick: (ListItemAction) -> Unit,
showFocusPoint: Boolean
): ListItem? {
return if (site.isSelfHostedAdmin || site.hasCapabilityEditPages) {
ListItem(
R.drawable.ic_pages_white_24dp,
UiStringRes(R.string.my_site_btn_site_pages),
onClick = ListItemInteraction.create(PAGES, onClick),
showFocusPoint = showFocusPoint
)
} else null
}
fun buildAdminItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
return if (shouldShowWPAdmin(site)) {
ListItem(
R.drawable.ic_wordpress_white_24dp,
UiStringRes(R.string.my_site_btn_view_admin),
secondaryIcon = R.drawable.ic_external_white_24dp,
onClick = ListItemInteraction.create(ADMIN, onClick)
)
} else null
}
fun buildPeopleItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
return if (site.hasCapabilityListUsers) {
ListItem(
R.drawable.ic_user_white_24dp,
UiStringRes(R.string.people),
onClick = ListItemInteraction.create(PEOPLE, onClick)
)
} else null
}
fun buildPluginItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
return if (pluginUtilsWrapper.isPluginFeatureAvailable(site)) {
ListItem(
R.drawable.ic_plugins_white_24dp,
UiStringRes(R.string.my_site_btn_plugins),
onClick = ListItemInteraction.create(PLUGINS, onClick)
)
} else null
}
fun buildShareItemIfAvailable(
site: SiteModel,
onClick: (ListItemAction) -> Unit,
showFocusPoint: Boolean = false
): ListItem? {
return if (site.supportsSharing()) {
ListItem(
R.drawable.ic_share_white_24dp,
UiStringRes(R.string.my_site_btn_sharing),
showFocusPoint = showFocusPoint,
onClick = ListItemInteraction.create(SHARING, onClick)
)
} else null
}
fun buildDomainsItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
return if (
buildConfigWrapper.isJetpackApp &&
siteDomainsFeatureConfig.isEnabled() &&
site.hasCapabilityManageOptions
) {
ListItem(
R.drawable.ic_domains_white_24dp,
UiStringRes(R.string.my_site_btn_domains),
onClick = ListItemInteraction.create(DOMAINS, onClick)
)
} else null
}
fun buildSiteSettingsItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
return if (site.hasCapabilityManageOptions || !siteUtilsWrapper.isAccessedViaWPComRest(site)) {
ListItem(
R.drawable.ic_cog_white_24dp,
UiStringRes(R.string.my_site_btn_site_settings),
onClick = ListItemInteraction.create(SITE_SETTINGS, onClick)
)
} else null
}
private fun shouldShowWPAdmin(site: SiteModel): Boolean {
return if (!site.isWPCom) {
true
} else {
val dateCreated = DateTimeUtils.dateFromIso8601(
accountStore.account
.date
)
val calendar = GregorianCalendar(HIDE_WP_ADMIN_YEAR, HIDE_WP_ADMIN_MONTH, HIDE_WP_ADMIN_DAY)
calendar.timeZone = TimeZone.getTimeZone(MySiteViewModel.HIDE_WP_ADMIN_GMT_TIME_ZONE)
dateCreated == null || dateCreated.before(calendar.time)
}
}
fun buildThemesItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): MySiteCardAndItem? {
return if (themeBrowserUtils.isAccessible(site)) {
ListItem(
R.drawable.ic_themes_white_24dp,
UiStringRes(R.string.themes),
onClick = ListItemInteraction.create(THEMES, onClick)
)
} else null
}
companion object {
const val HIDE_WP_ADMIN_YEAR = 2015
const val HIDE_WP_ADMIN_MONTH = 9
const val HIDE_WP_ADMIN_DAY = 7
}
}
| WordPress/src/main/java/org/wordpress/android/ui/mysite/items/listitem/SiteListItemBuilder.kt | 1828460903 |
package test
expect interface Closable {
fun <caret>close()
}
expect class MyStream : Closable {}
open class MyImpl : Closable {
override fun close() {}
}
// REF: [testModule_Common] (in test.MyImpl).close()
| plugins/kotlin/idea/tests/testData/navigation/implementations/multiModule/actualTypeAliasWithAnonymousSubclass/common/common.kt | 352079423 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.move.moveClassesOrPackages
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.moveClassesOrPackages.JavaMoveClassesOrPackagesHandler
class KotlinAwareJavaMoveClassesOrPackagesHandler : JavaMoveClassesOrPackagesHandler() {
override fun createMoveClassesOrPackagesToNewDirectoryDialog(
directory: PsiDirectory,
elementsToMove: Array<out PsiElement>,
moveCallback: MoveCallback?
) = KotlinAwareMoveClassesOrPackagesToNewDirectoryDialog(directory, elementsToMove, moveCallback)
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveClassesOrPackages/KotlinAwareJavaMoveClassesOrPackagesHandler.kt | 1121789918 |
var name: String = ""
@java.lang.Deprecated
get() { TODO() }
set(value) { TODO() }
// ANNOTATION: java.lang.Deprecated
// SEARCH: method:getName | plugins/kotlin/idea/tests/testData/search/annotations/testAnnotationsOnPropertyAccessor.kt | 892113534 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.k2.codeinsight.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import org.jetbrains.kotlin.analysis.api.calls.singleFunctionCallOrNull
import org.jetbrains.kotlin.analysis.api.calls.symbol
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.AbstractKotlinApplicatorBasedIntention
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicator
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.inputProvider
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddArgumentNamesApplicators
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtLambdaArgument
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class AddNamesToFollowingArgumentsIntention :
AbstractKotlinApplicatorBasedIntention<KtValueArgument, AddArgumentNamesApplicators.MultipleArgumentsInput>(KtValueArgument::class),
LowPriorityAction {
override fun getApplicabilityRange() = ApplicabilityRanges.VALUE_ARGUMENT_EXCLUDING_LAMBDA
override fun getApplicator() = applicator<KtValueArgument, AddArgumentNamesApplicators.MultipleArgumentsInput> {
familyAndActionName(KotlinBundle.lazyMessage("add.names.to.this.argument.and.following.arguments"))
isApplicableByPsi { element ->
// Not applicable when lambda is trailing lambda after argument list (e.g., `run { }`); element is a KtLambdaArgument.
// May be applicable when lambda is inside an argument list (e.g., `run({ })`); element is a KtValueArgument in this case.
if (element.isNamed() || element is KtLambdaArgument) {
return@isApplicableByPsi false
}
val argumentList = element.parent as? KtValueArgumentList ?: return@isApplicableByPsi false
// Shadowed by HLAddNamesToCallArgumentsIntention
if (argumentList.arguments.firstOrNull() == element) return@isApplicableByPsi false
// Shadowed by HLAddNameToArgumentIntention
if (argumentList.arguments.lastOrNull { !it.isNamed() } == element) return@isApplicableByPsi false
true
}
applyTo { element, input, project, editor ->
val callElement = element.parent?.safeAs<KtValueArgumentList>()?.parent as? KtCallElement
callElement?.let { AddArgumentNamesApplicators.multipleArgumentsApplicator.applyTo(it, input, project, editor) }
}
}
override fun getInputProvider() = inputProvider { element: KtValueArgument ->
val argumentList = element.parent as? KtValueArgumentList ?: return@inputProvider null
val callElement = argumentList.parent as? KtCallElement ?: return@inputProvider null
val resolvedCall = callElement.resolveCall().singleFunctionCallOrNull() ?: return@inputProvider null
if (!resolvedCall.symbol.hasStableParameterNames) {
return@inputProvider null
}
val argumentsExcludingPrevious =
callElement.valueArgumentList?.arguments?.dropWhile { it != element } ?: return@inputProvider null
AddArgumentNamesApplicators.MultipleArgumentsInput(argumentsExcludingPrevious.associateWith {
getArgumentNameIfCanBeUsedForCalls(it, resolvedCall) ?: return@inputProvider null
})
}
} | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddNamesToFollowingArgumentsIntention.kt | 796836109 |
package com.github.florent37.assets_audio_player
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
class UriResolver(private val context: Context) {
companion object {
const val PREFIX_CONTENT = "content://media"
}
private fun contentPath(uri: Uri, columnName: String): String? {
return context.contentResolver?.query(
uri,
arrayOf(
columnName
),
null,
null,
null)
?.use { cursor ->
cursor.takeIf { it.count == 1 }?.let {
it.moveToFirst()
it.getString(cursor.getColumnIndex(columnName))
}
}
}
fun audioPath(uri: String?): String? {
if(uri != null) {
try {
if (uri.startsWith(PREFIX_CONTENT)) {
val uriParsed = Uri.parse(uri)
return contentPath(uriParsed, MediaStore.Audio.Media.DATA) ?: uri
}
} catch (t: Throwable) {
//print(t)
}
}
return uri
}
fun imagePath(uri: String?): String? {
if(uri != null) {
try {
if (uri.startsWith(PREFIX_CONTENT)) {
val uriParsed = Uri.parse(uri)
return contentPath(uriParsed, MediaStore.Images.Media.DATA) ?: uri
}
} catch (t: Throwable) {
//print(t)
}
}
return uri
}
} | android/src/main/kotlin/com/github/florent37/assets_audio_player/Resolver.kt | 4179463448 |
// 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.actions
import com.intellij.ide.bookmark.BookmarkBundle.messagePointer
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.project.DumbAwareAction
internal open class GotoBookmarkTypeAction(private val type: BookmarkType, private val checkSpeedSearch: Boolean = false)
: DumbAwareAction(messagePointer("goto.bookmark.type.action.text", type.mnemonic)/*, type.icon*/) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
private fun canNavigate(event: AnActionEvent) = event.bookmarksManager?.getBookmark(type)?.canNavigate() ?: false
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible =
(!checkSpeedSearch || event.getData(PlatformDataKeys.SPEED_SEARCH_TEXT) == null) &&
canNavigate(event)
}
override fun actionPerformed(event: AnActionEvent) {
event.bookmarksManager?.getBookmark(type)?.navigate(true)
}
init {
isEnabledInModalContext = true
}
}
internal class GotoBookmark1Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_1)
internal class GotoBookmark2Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_2)
internal class GotoBookmark3Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_3)
internal class GotoBookmark4Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_4)
internal class GotoBookmark5Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_5)
internal class GotoBookmark6Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_6)
internal class GotoBookmark7Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_7)
internal class GotoBookmark8Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_8)
internal class GotoBookmark9Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_9)
internal class GotoBookmark0Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_0)
internal class GotoBookmarkAAction : GotoBookmarkTypeAction(BookmarkType.LETTER_A)
internal class GotoBookmarkBAction : GotoBookmarkTypeAction(BookmarkType.LETTER_B)
internal class GotoBookmarkCAction : GotoBookmarkTypeAction(BookmarkType.LETTER_C)
internal class GotoBookmarkDAction : GotoBookmarkTypeAction(BookmarkType.LETTER_D)
internal class GotoBookmarkEAction : GotoBookmarkTypeAction(BookmarkType.LETTER_E)
internal class GotoBookmarkFAction : GotoBookmarkTypeAction(BookmarkType.LETTER_F)
internal class GotoBookmarkGAction : GotoBookmarkTypeAction(BookmarkType.LETTER_G)
internal class GotoBookmarkHAction : GotoBookmarkTypeAction(BookmarkType.LETTER_H)
internal class GotoBookmarkIAction : GotoBookmarkTypeAction(BookmarkType.LETTER_I)
internal class GotoBookmarkJAction : GotoBookmarkTypeAction(BookmarkType.LETTER_J)
internal class GotoBookmarkKAction : GotoBookmarkTypeAction(BookmarkType.LETTER_K)
internal class GotoBookmarkLAction : GotoBookmarkTypeAction(BookmarkType.LETTER_L)
internal class GotoBookmarkMAction : GotoBookmarkTypeAction(BookmarkType.LETTER_M)
internal class GotoBookmarkNAction : GotoBookmarkTypeAction(BookmarkType.LETTER_N)
internal class GotoBookmarkOAction : GotoBookmarkTypeAction(BookmarkType.LETTER_O)
internal class GotoBookmarkPAction : GotoBookmarkTypeAction(BookmarkType.LETTER_P)
internal class GotoBookmarkQAction : GotoBookmarkTypeAction(BookmarkType.LETTER_Q)
internal class GotoBookmarkRAction : GotoBookmarkTypeAction(BookmarkType.LETTER_R)
internal class GotoBookmarkSAction : GotoBookmarkTypeAction(BookmarkType.LETTER_S)
internal class GotoBookmarkTAction : GotoBookmarkTypeAction(BookmarkType.LETTER_T)
internal class GotoBookmarkUAction : GotoBookmarkTypeAction(BookmarkType.LETTER_U)
internal class GotoBookmarkVAction : GotoBookmarkTypeAction(BookmarkType.LETTER_V)
internal class GotoBookmarkWAction : GotoBookmarkTypeAction(BookmarkType.LETTER_W)
internal class GotoBookmarkXAction : GotoBookmarkTypeAction(BookmarkType.LETTER_X)
internal class GotoBookmarkYAction : GotoBookmarkTypeAction(BookmarkType.LETTER_Y)
internal class GotoBookmarkZAction : GotoBookmarkTypeAction(BookmarkType.LETTER_Z)
| platform/lang-impl/src/com/intellij/ide/bookmark/actions/GotoBookmarkTypeAction.kt | 2643403333 |
// IS_APPLICABLE: false
val foo = "\u0003\u0001\u0004\u0001\u0005" <caret>+
"\u0003\u0001\u0004\u0001\u0005" | plugins/kotlin/idea/tests/testData/intentions/convertToRawStringTemplate/octalEscape.kt | 469921019 |
package six.ca.droiddailyproject.lint
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
/**
* @author hellenxu
* @date 2020-09-02
* Copyright 2020 Six. All rights reserved.
*/
class CustomLintActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val textView = TextView(this)
textView.text = "12345678"
println("xxl-id: 098765432")
println("xxl-phone: 2304568907")
}
} | DroidDailyProject/app/src/main/java/six/ca/droiddailyproject/lint/CustomLintActivity.kt | 4213692342 |
package by.bkug.data
import by.bkug.data.model.Calendar
import by.bkug.data.model.CalendarEvent
import by.bkug.data.model.minskDateTime
import java.time.ZonedDateTime
val calendar = Calendar(
name = "Belarus Kotlin User Group Events",
url = "https://bkug.by/",
events = listOf(
CalendarEvent(
id = "02b3710f-f3ce-43e9-8134-60d6f3a64726",
name = "Belarus Kotlin User Group Meetup #7",
start = minskDateTime("2017-12-19", "19:00"),
end = minskDateTime("2017-12-19", "21:00"),
description = "https://bkug.by/2017/12/17/anons-bkug-7/",
location = "Event Space, Вход через ул. Октябрьскую, 10б, vulica Kastryčnickaja 16А, Minsk, Belarus"
),
CalendarEvent(
id = "a39b0fa6-0add-4745-98c2-157878c24305",
name = "Belarus Kotlin User Group Meetup #8",
start = minskDateTime("2017-02-21", "19:00"),
end = minskDateTime("2017-02-21", "21:00"),
description = "https://bkug.by/2018/02/08/anons-bkug-8/",
location = "Event Space, Вход через ул. Октябрьскую, 10б, vulica Kastryčnickaja 16А, Minsk, Belarus"
),
)
)
val internalCalendar = Calendar(
name = "Internal BKUG Events",
url = "https://bkug.by/",
events = listOf()
)
| data/src/main/kotlin/by/bkug/data/Calendar.kt | 1104951883 |
// Copyright (c) 2016, Miquel Martí <[email protected]>
// See LICENSE for licensing information
package cat.mvmike.minimalcalendarwidget.domain.configuration.item
import cat.mvmike.minimalcalendarwidget.BaseTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.EnumSource
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream
internal class SymbolSetTest : BaseTest() {
@ParameterizedTest
@EnumSource(value = SymbolSet::class)
fun get_shouldReturnEmptyCharacter_whenNoInstances(symbolSet: SymbolSet) {
assertThat(symbolSet.get(0)).isEqualTo(' ')
}
@ParameterizedTest
@MethodSource("getSymbolSetAndExpectedCharacter")
fun get_shouldReturnExpectedCharacter(symbolSet: SymbolSet, numberOfInstances: Int, expectedCharacter: Char) {
assertThat(symbolSet.get(numberOfInstances)).isEqualTo(expectedCharacter)
}
@Suppress("UnusedPrivateMember")
private fun getSymbolSetAndExpectedCharacter(): Stream<Arguments> = Stream.of(
Arguments.of(SymbolSet.MINIMAL, 1, '·'),
Arguments.of(SymbolSet.MINIMAL, 6, '◈'),
Arguments.of(SymbolSet.MINIMAL, 7, '◈'),
Arguments.of(SymbolSet.VERTICAL, 4, '⁞'),
Arguments.of(SymbolSet.VERTICAL, 5, '|'),
Arguments.of(SymbolSet.CIRCLES, 1, '◔'),
Arguments.of(SymbolSet.CIRCLES, 4, '●'),
Arguments.of(SymbolSet.CIRCLES, 5, '๑'),
Arguments.of(SymbolSet.NUMBERS, 5, '5'),
Arguments.of(SymbolSet.NUMBERS, 9, '9'),
Arguments.of(SymbolSet.NUMBERS, 10, '+'),
Arguments.of(SymbolSet.NUMBERS, 11, '+'),
Arguments.of(SymbolSet.ROMAN, 2, 'Ⅱ'),
Arguments.of(SymbolSet.ROMAN, 10, 'Ⅹ'),
Arguments.of(SymbolSet.ROMAN, 11, '∾'),
Arguments.of(SymbolSet.ROMAN, 100, '∾'),
Arguments.of(SymbolSet.BINARY, 1, '☱'),
Arguments.of(SymbolSet.BINARY, 8, '※'),
Arguments.of(SymbolSet.BINARY, 9, '※')
)
}
| app/src/test/kotlin/cat/mvmike/minimalcalendarwidget/domain/configuration/item/SymbolSetTest.kt | 531862283 |
package quanti.com.kotlinlog
import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import quanti.com.kotlinlog.base.LogLevel
import quanti.com.kotlinlog.file.FileLogger
import quanti.com.kotlinlog.file.bundle.DayLogBundle
import quanti.com.kotlinlog.utils.getFormattedFileNameForDayTemp
import quanti.com.kotlinlog.utils.getRandomString
import quanti.com.kotlinlog.utils.logFilesDir
import java.io.File
@RunWith(RobolectricTestRunner::class)
class FileLoggerTest {
private lateinit var appCtx: Context
private val flb = DayLogBundle(LogLevel.VERBOSE, maxDaysSaved = 2)
private lateinit var logger: FileLogger
private lateinit var file: File
@Suppress("DEPRECATION")
@Before
fun init() {
RuntimeEnvironment.application.applicationInfo.nonLocalizedLabel = "FAKE APP NAME"
appCtx = RuntimeEnvironment.application.applicationContext
logger = FileLogger(appCtx, flb)
Log.addLogger(logger)
val fileName = "${getFormattedFileNameForDayTemp()}_dayLog.log"
file = File(appCtx.logFilesDir, fileName)
}
/**
* Checks if daylog is created
* Sync version
*/
@Test
fun daylogIsCreated() {
//force some logs
Log.iSync("Ahoj")
//check if file exists
Assert.assertEquals(true, file.exists())
}
/**
* Checks if given information is written into daylog
* Sync version
*/
@Test
fun daylogIsCreatedAndProperlyWrittenOneLine() {
val str = "Hello world xd"
Log.iSync(str)
//check if file contains
val lines = file.readLines()
Assert.assertEquals(1, lines.size)
Assert.assertEquals(true, lines[0].contains(str))
}
/**
* Checks if more strings are written into daylog
* Sync version
*/
@Test
fun daylogIsCreatedAndProperlyWrittenHundredLines() {
//create random string
val list = (1..100)
.map { getRandomString() }
.onEach { Log.iSync(it) }
.toList()
//check if file contains
val lines = file.readLines()
Assert.assertEquals(list.size, lines.size)
val result = lines
.zip(list)
.all {
val strFromFile = it.first
val strFromList = it.second
strFromFile.contains(strFromList)
}
Assert.assertEquals(true, result)
}
/**
* Checks if daylog is created
* Async version
*/
@Test
fun daylogIsCreatedAsync() {
//force some logs
Log.i("Ahoj")
//wait 6 seconds, beacuse thread executor writes every 5 seconds
Thread.sleep(6000)
//check if file exists
Assert.assertEquals(true, file.exists())
}
/**
* Checks if more strings are written into daylog
* Async version
*/
@Test
fun daylogIsCreatedAndProperlyWrittenHundredLinesAsync() {
//create random string
val list = (1..100)
.map { getRandomString() }
.onEach { Log.i(it) }
.toList()
Thread.sleep(6000)
//check if file contains
val lines = file.readLines()
Assert.assertEquals(list.size, lines.size)
val result = lines
.zip(list)
.all {
val strFromFile = it.first
val strFromList = it.second
strFromFile.contains(strFromList)
}
Assert.assertEquals(true, result)
}
/**
* Checks if daylog is created if lot of threads are writting at once
* Check if everything is properly written
* Async version
*/
@Test
fun daylogIsCreatedAndLotOfThreadAreWrittingAsync() {
//force some logs
val threads = 85
val strings = 999
runBlocking {
(1..threads).forEach { threadNum ->
launch {
(1..strings)
.map { getRandomString() }
.onEach { Log.i("$threadNum $it") }
.toList()
}
}
}
//wait 6 seconds, beacuse thread executor writes every 5 seconds
Thread.sleep(6000L)
//check if file contains
val count = file.readLines().count()
println(count)
Assert.assertEquals(threads * strings, count)
}
/**
* Checks if daylog is created if two threads are writting sync at once
* Check if everything is properly written
* Async version
*/
@Test
fun daylogIsCreatedAnTwoThreadsAreWrittingSync() {
//force some logs
val threads = 2
val strings = 100000
runBlocking {
repeat(threads) { thread ->
launch(Dispatchers.Default) {
repeat(strings) {
Log.iSync("$thread TAG", getRandomString())
}
}
}
}
println("XDDDD")
//wait 6 seconds, beacuse thread executor writes every 5 seconds
Thread.sleep(6000L)
//check if file contains
val count = file.readLines().onEach { println(it) }.count()
println(count)
Assert.assertEquals(threads * strings, count)
}
} | kotlinlog/src/test/java/quanti/com/kotlinlog/FileLoggerTest.kt | 2320273521 |
/*
* SampleTrip.kt
*
* This file is part of FareBot.
* Learn more at: https://codebutler.github.io/farebot/
*
* Copyright (C) 2017 Eric Butler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.farebot.app.core.sample
import android.content.res.Resources
import com.codebutler.farebot.transit.Station
import com.codebutler.farebot.transit.Trip
import java.util.Date
class SampleTrip(private val date: Date) : Trip() {
override fun getTimestamp(): Long = date.time / 1000
override fun getExitTimestamp(): Long = date.time / 1000
override fun getRouteName(resources: Resources): String? = "Route Name"
override fun getAgencyName(resources: Resources): String? = "Agency"
override fun getShortAgencyName(resources: Resources): String? = "Agency"
override fun getBalanceString(): String? = "$42.000"
override fun getStartStationName(resources: Resources): String? = "Start Station"
override fun getStartStation(): Station? = Station.create("Name", "Name", "", "")
override fun hasFare(): Boolean = true
override fun getFareString(resources: Resources): String? = "$4.20"
override fun getEndStationName(resources: Resources): String? = "End Station"
override fun getEndStation(): Station? = Station.create("Name", "Name", "", "")
override fun getMode(): Mode? = Mode.METRO
override fun hasTime(): Boolean = true
}
| farebot-app/src/main/java/com/codebutler/farebot/app/core/sample/SampleTrip.kt | 2276501143 |
package eu.kanade.tachiyomi.data.preference
/**
* This class stores the keys for the preferences in the application.
*/
object PreferenceKeys {
const val confirmExit = "pref_confirm_exit"
const val showReadingMode = "pref_show_reading_mode"
const val defaultReadingMode = "pref_default_reading_mode_key"
const val defaultOrientationType = "pref_default_orientation_type_key"
const val jumpToChapters = "jump_to_chapters"
const val autoUpdateTrack = "pref_auto_update_manga_sync_key"
const val downloadOnlyOverWifi = "pref_download_only_over_wifi_key"
const val folderPerManga = "create_folder_per_manga"
const val removeAfterReadSlots = "remove_after_read_slots"
const val removeAfterMarkedAsRead = "pref_remove_after_marked_as_read_key"
const val removeBookmarkedChapters = "pref_remove_bookmarked"
const val filterDownloaded = "pref_filter_library_downloaded"
const val filterUnread = "pref_filter_library_unread"
const val filterStarted = "pref_filter_library_started"
const val filterCompleted = "pref_filter_library_completed"
const val filterTracked = "pref_filter_library_tracked"
const val librarySortingMode = "library_sorting_mode"
const val librarySortingDirection = "library_sorting_ascending"
const val migrationSortingMode = "pref_migration_sorting"
const val migrationSortingDirection = "pref_migration_direction"
const val startScreen = "start_screen"
const val hideNotificationContent = "hide_notification_content"
const val autoUpdateMetadata = "auto_update_metadata"
const val autoUpdateTrackers = "auto_update_trackers"
const val dateFormat = "app_date_format"
const val defaultCategory = "default_category"
const val skipRead = "skip_read"
const val skipFiltered = "skip_filtered"
const val searchPinnedSourcesOnly = "search_pinned_sources_only"
const val dohProvider = "doh_provider"
const val defaultChapterFilterByRead = "default_chapter_filter_by_read"
const val defaultChapterFilterByDownloaded = "default_chapter_filter_by_downloaded"
const val defaultChapterFilterByBookmarked = "default_chapter_filter_by_bookmarked"
const val defaultChapterSortBySourceOrNumber = "default_chapter_sort_by_source_or_number" // and upload date
const val defaultChapterSortByAscendingOrDescending = "default_chapter_sort_by_ascending_or_descending"
const val defaultChapterDisplayByNameOrNumber = "default_chapter_display_by_name_or_number"
const val verboseLogging = "verbose_logging"
const val autoClearChapterCache = "auto_clear_chapter_cache"
fun trackUsername(syncId: Int) = "pref_mangasync_username_$syncId"
fun trackPassword(syncId: Int) = "pref_mangasync_password_$syncId"
fun trackToken(syncId: Int) = "track_token_$syncId"
}
| app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt | 4226964188 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val GL40C = "GL40C".nativeClassGL("GL40C") {
extends = GL33C
documentation =
"""
The OpenGL functionality up to version 4.0. Includes only Core Profile symbols.
OpenGL 4.0 implementations support revision 4.00 of the OpenGL Shading Language.
Extensions promoted to core in this release:
${ul(
registryLinkTo("ARB", "texture_query_lod"),
registryLinkTo("ARB", "draw_buffers_blend"),
registryLinkTo("ARB", "draw_indirect"),
registryLinkTo("ARB", "gpu_shader5"),
registryLinkTo("ARB", "gpu_shader_fp64"),
registryLinkTo("ARB", "sample_shading"),
registryLinkTo("ARB", "shader_subroutine"),
registryLinkTo("ARB", "tessellation_shader"),
registryLinkTo("ARB", "texture_buffer_object_rgb32"),
registryLinkTo("ARB", "texture_cube_map_array"),
registryLinkTo("ARB", "texture_gather"),
registryLinkTo("ARB", "transform_feedback2"),
registryLinkTo("ARB", "transform_feedback3")
)}
"""
// ARB_draw_buffers_blend
val blendEquations = "#FUNC_ADD #FUNC_SUBTRACT #FUNC_REVERSE_SUBTRACT #MIN #MAX"
void(
"BlendEquationi",
"Specifies the equation used for both the RGB blend equation and the Alpha blend equation for the specified draw buffer.",
GLuint("buf", "the index of the draw buffer for which to set the blend equation"),
GLenum("mode", "how source and destination colors are combined", blendEquations)
)
void(
"BlendEquationSeparatei",
"Sets the RGB blend equation and the alpha blend equation separately for the specified draw buffer.",
GLuint("buf", "the index of the draw buffer for which to set the blend equations"),
GLenum("modeRGB", "the RGB blend equation, how the red, green, and blue components of the source and destination colors are combined", blendEquations),
GLenum("modeAlpha", "the alpha blend equation, how the alpha component of the source and destination colors are combined", blendEquations)
)
void(
"BlendFunci",
"Specifies pixel arithmetic for the specified draw buffer.",
GLuint("buf", "the index of the draw buffer for which to set the blend function"),
GLenum("sfactor", "how the red, green, blue, and alpha source blending factors are computed"),
GLenum("dfactor", "how the red, green, blue, and alpha destination blending factors are computed")
)
void(
"BlendFuncSeparatei",
"Specifies pixel arithmetic for RGB and alpha components separately for the specified draw buffer.",
GLuint("buf", "the index of the draw buffer for which to set the blend functions"),
GLenum("srcRGB", "how the red, green, and blue blending factors are computed"),
GLenum("dstRGB", "how the red, green, and blue destination blending factors are computed"),
GLenum("srcAlpha", "how the alpha source blending factor is computed"),
GLenum("dstAlpha", "how the alpha destination blending factor is computed")
)
// ARB_draw_indirect
IntConstant(
"""
Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, GetBufferPointerv,
MapBufferRange, FlushMappedBufferRange, GetBufferParameteriv, and CopyBufferSubData.
""",
"DRAW_INDIRECT_BUFFER"..0x8F3F
)
IntConstant(
"Accepted by the {@code value} parameter of GetIntegerv, GetBooleanv, GetFloatv, and GetDoublev.",
"DRAW_INDIRECT_BUFFER_BINDING"..0x8F43
)
void(
"DrawArraysIndirect",
"""
Renders primitives from array data, taking parameters from memory.
{@code glDrawArraysIndirect} behaves similarly to #DrawArraysInstancedBaseInstance(), except that the parameters to
glDrawArraysInstancedBaseInstance are stored in memory at the address given by {@code indirect}.
The parameters addressed by {@code indirect} are packed into a structure that takes the form (in C):
${codeBlock("""
typedef struct {
uint count;
uint primCount;
uint first;
uint baseInstance; // must be 0 unless OpenGL 4.2 is supported
} DrawArraysIndirectCommand;
const DrawArraysIndirectCommand *cmd = (const DrawArraysIndirectCommand *)indirect;
glDrawArraysInstancedBaseInstance(mode, cmd->first, cmd->count, cmd->primCount, cmd->baseInstance);
""")}
""",
GLenum("mode", "what kind of primitives to render", PRIMITIVE_TYPES),
Check("4 * 4")..MultiType(
PointerMapping.DATA_INT
)..RawPointer..void.const.p("indirect", "a structure containing the draw parameters")
)
void(
"DrawElementsIndirect",
"""
Renders indexed primitives from array data, taking parameters from memory.
{@code glDrawElementsIndirect} behaves similarly to #DrawElementsInstancedBaseVertexBaseInstance(), execpt that the parameters to
glDrawElementsInstancedBaseVertexBaseInstance are stored in memory at the address given by {@code indirect}.
The parameters addressed by {@code indirect} are packed into a structure that takes the form (in C):
${codeBlock("""
typedef struct {
uint count;
uint primCount;
uint firstIndex;
uint baseVertex;
uint baseInstance;
} DrawElementsIndirectCommand;
""")}
{@code glDrawElementsIndirect} is equivalent to:
${codeBlock("""
void glDrawElementsIndirect(GLenum mode, GLenum type, const void *indirect) {
const DrawElementsIndirectCommand *cmd = (const DrawElementsIndirectCommand *)indirect;
glDrawElementsInstancedBaseVertexBaseInstance(
mode,
cmd->count,
type,
cmd->firstIndex + size-of-type,
cmd->primCount,
cmd->baseVertex,
cmd->baseInstance
);
}
""")}
""",
GLenum("mode", "what kind of primitives to render", PRIMITIVE_TYPES),
GLenum(
"type",
"the type of data in the buffer bound to the #ELEMENT_ARRAY_BUFFER binding",
"#UNSIGNED_BYTE #UNSIGNED_SHORT #UNSIGNED_INT"
),
Check("5 * 4")..MultiType(
PointerMapping.DATA_INT
)..RawPointer..void.const.p("indirect", "the address of a structure containing the draw parameters")
)
// ARB_gpu_shader5
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramiv.",
"GEOMETRY_SHADER_INVOCATIONS"..0x887F
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, GetDoublev, and GetInteger64v.",
"MAX_GEOMETRY_SHADER_INVOCATIONS"..0x8E5A,
"MIN_FRAGMENT_INTERPOLATION_OFFSET"..0x8E5B,
"MAX_FRAGMENT_INTERPOLATION_OFFSET"..0x8E5C,
"FRAGMENT_INTERPOLATION_OFFSET_BITS"..0x8E5D
)
// ARB_gpu_shader_fp64
IntConstant(
"Returned in the {@code type} parameter of GetActiveUniform, and GetTransformFeedbackVarying.",
"DOUBLE_VEC2"..0x8FFC,
"DOUBLE_VEC3"..0x8FFD,
"DOUBLE_VEC4"..0x8FFE,
"DOUBLE_MAT2"..0x8F46,
"DOUBLE_MAT3"..0x8F47,
"DOUBLE_MAT4"..0x8F48,
"DOUBLE_MAT2x3"..0x8F49,
"DOUBLE_MAT2x4"..0x8F4A,
"DOUBLE_MAT3x2"..0x8F4B,
"DOUBLE_MAT3x4"..0x8F4C,
"DOUBLE_MAT4x2"..0x8F4D,
"DOUBLE_MAT4x3"..0x8F4E
)
// Uniform functions javadoc
val uniformLocation = "the location of the uniform variable to be modified"
val uniformX = "the uniform x value"
val uniformY = "the uniform y value"
val uniformZ = "the uniform z value"
val uniformW = "the uniform w value"
val uniformArrayCount = "the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array."
val uniformArrayValue = "a pointer to an array of {@code count} values that will be used to update the specified uniform variable"
val uniformMatrixCount = "the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices."
val uniformMatrixTranspose = "whether to transpose the matrix as the values are loaded into the uniform variable"
val uniformMatrixValue = "a pointer to an array of {@code count} values that will be used to update the specified uniform matrix variable"
void(
"Uniform1d",
"Specifies the value of a double uniform variable for the current program object.",
GLint("location", uniformLocation),
GLdouble("x", uniformX)
)
void(
"Uniform2d",
"Specifies the value of a dvec2 uniform variable for the current program object.",
GLint("location", uniformLocation),
GLdouble("x", uniformX),
GLdouble("y", uniformY)
)
void(
"Uniform3d",
"Specifies the value of a dvec3 uniform variable for the current program object.",
GLint("location", uniformLocation),
GLdouble("x", uniformX),
GLdouble("y", uniformY),
GLdouble("z", uniformZ)
)
void(
"Uniform4d",
"Specifies the value of a dvec4 uniform variable for the current program object.",
GLint("location", uniformLocation),
GLdouble("x", uniformX),
GLdouble("y", uniformY),
GLdouble("z", uniformZ),
GLdouble("w", uniformW)
)
void(
"Uniform1dv",
"Specifies the value of a single double uniform variable or a double uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize("value")..GLsizei("count", uniformArrayCount),
GLdouble.const.p("value", uniformArrayValue)
)
void(
"Uniform2dv",
"Specifies the value of a single dvec2 uniform variable or a dvec2 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(2, "value")..GLsizei("count", uniformArrayCount),
GLdouble.const.p("value", uniformArrayValue)
)
void(
"Uniform3dv",
"Specifies the value of a single dvec3 uniform variable or a dvec3 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(3, "value")..GLsizei("count", uniformArrayCount),
GLdouble.const.p("value", uniformArrayValue)
)
void(
"Uniform4dv",
"Specifies the value of a single dvec4 uniform variable or a dvec4 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(4, "value")..GLsizei("count", uniformArrayCount),
GLdouble.const.p("value", uniformArrayValue)
)
void(
"UniformMatrix2dv",
"Specifies the value of a single dmat2 uniform variable or a dmat2 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(2 x 2, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix3dv",
"Specifies the value of a single dmat3 uniform variable or a dmat3 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(3 x 3, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix4dv",
"Specifies the value of a single dmat4 uniform variable or a dmat4 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(4 x 4, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix2x3dv",
"Specifies the value of a single dmat2x3 uniform variable or a dmat2x3 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(2 x 3, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix2x4dv",
"Specifies the value of a single dmat2x4 uniform variable or a dmat2x4 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(2 x 4, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix3x2dv",
"Specifies the value of a single dmat3x2 uniform variable or a dmat3x2 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(3 x 2, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix3x4dv",
"Specifies the value of a single dmat3x4 uniform variable or a dmat3x4 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(3 x 4, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix4x2dv",
"Specifies the value of a single dmat4x2 uniform variable or a dmat4x2 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(4 x 2, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix4x3dv",
"Specifies the value of a single dmat4x3 uniform variable or a dmat4x3 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(4 x 3, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"GetUniformdv",
"Returns the double value(s) of a uniform variable.",
GLuint("program", "the program object to be queried"),
GLint("location", "the location of the uniform variable to be queried"),
Check(1)..ReturnParam..GLdouble.p("params", "the value of the specified uniform variable")
)
// ARB_sample_shading
IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev.
""",
"SAMPLE_SHADING"..0x8C36
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv.",
"MIN_SAMPLE_SHADING_VALUE"..0x8C37
)
void(
"MinSampleShading",
"Specifies the minimum rate at which sample shading takes place.",
GLfloat("value", "the rate at which samples are shaded within each covered pixel")
)
// ARB_shader_subroutine
val ProgramStageProperties = IntConstant(
"Accepted by the {@code pname} parameter of GetProgramStageiv.",
"ACTIVE_SUBROUTINES"..0x8DE5,
"ACTIVE_SUBROUTINE_UNIFORMS"..0x8DE6,
"ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS"..0x8E47,
"ACTIVE_SUBROUTINE_MAX_LENGTH"..0x8E48,
"ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH"..0x8E49
).javaDocLinks
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, GetDoublev, and GetInteger64v.",
"MAX_SUBROUTINES"..0x8DE7,
"MAX_SUBROUTINE_UNIFORM_LOCATIONS"..0x8DE8
)
IntConstant(
"Accepted by the {@code pname} parameter of GetActiveSubroutineUniformiv.",
"NUM_COMPATIBLE_SUBROUTINES"..0x8E4A,
"COMPATIBLE_SUBROUTINES"..0x8E4B
)
GLint(
"GetSubroutineUniformLocation",
"Retrieves the location of a subroutine uniform of a given shader stage within a program.",
GLuint("program", "the name of the program containing shader stage"),
GLenum("shadertype", "the shader stage from which to query for subroutine uniform index", SHADER_TYPES),
GLcharASCII.const.p("name", "the name of the subroutine uniform whose index to query.")
)
GLuint(
"GetSubroutineIndex",
"Retrieves the index of a subroutine function of a given shader stage within a program.",
GLuint("program", "the name of the program containing shader stage"),
GLenum("shadertype", "the shader stage from which to query for subroutine function index", SHADER_TYPES),
GLcharASCII.const.p("name", "the name of the subroutine function whose index to query")
)
void(
"GetActiveSubroutineUniformiv",
"Queries a property of an active shader subroutine uniform.",
GLuint("program", "the name of the program containing the subroutine"),
GLenum("shadertype", "the shader stage from which to query for the subroutine parameter", SHADER_TYPES),
GLuint("index", "the index of the shader subroutine uniform"),
GLenum(
"pname",
"the parameter of the shader subroutine uniform to query",
"#NUM_COMPATIBLE_SUBROUTINES #COMPATIBLE_SUBROUTINES #UNIFORM_SIZE #UNIFORM_NAME_LENGTH"
),
Check(1)..ReturnParam..GLint.p("values", "the address of a buffer into which the queried value or values will be placed")
)
void(
"GetActiveSubroutineUniformName",
"Queries the name of an active shader subroutine uniform.",
GLuint("program", "the name of the program containing the subroutine"),
GLenum("shadertype", "the shader stage from which to query for the subroutine parameter", SHADER_TYPES),
GLuint("index", "the index of the shader subroutine uniform"),
AutoSize("name")..GLsizei("bufsize", "the size of the buffer whose address is given in {@code name}"),
Check(1)..nullable..GLsizei.p("length", "the address of a variable into which is written the number of characters copied into {@code name}"),
Return(
"length", "glGetActiveSubroutineUniformi(program, shadertype, index, GL31.GL_UNIFORM_NAME_LENGTH)"
)..GLcharASCII.p("name", "the address of a buffer that will receive the name of the specified shader subroutine uniform")
)
void(
"GetActiveSubroutineName",
"Queries the name of an active shader subroutine.",
GLuint("program", "the name of the program containing the subroutine"),
GLenum("shadertype", "the shader stage from which to query the subroutine name", SHADER_TYPES),
GLuint("index", "the index of the shader subroutine uniform"),
AutoSize("name")..GLsizei("bufsize", "the size of the buffer whose address is given in {@code name}"),
Check(1)..nullable..GLsizei.p("length", "a variable which is to receive the length of the shader subroutine uniform name"),
Return(
"length", "glGetProgramStagei(program, shadertype, GL_ACTIVE_SUBROUTINE_MAX_LENGTH)"
)..GLcharASCII.p("name", "an array into which the name of the shader subroutine uniform will be written")
)
void(
"UniformSubroutinesuiv",
"Loads active subroutine uniforms.",
GLenum("shadertype", "the shader stage to update", SHADER_TYPES),
AutoSize("indices")..GLsizei("count", "the number of uniform indices stored in {@code indices}"),
SingleValue("index")..GLuint.const.p("indices", "an array holding the indices to load into the shader subroutine variables")
)
void(
"GetUniformSubroutineuiv",
"Retrieves the value of a subroutine uniform of a given shader stage of the current program.",
GLenum("shadertype", "the shader stage from which to query for subroutine uniform index", SHADER_TYPES),
GLint("location", "the location of the subroutine uniform"),
Check(1)..ReturnParam..GLuint.p("params", "a variable to receive the value or values of the subroutine uniform")
)
void(
"GetProgramStageiv",
"Retrieves properties of a program object corresponding to a specified shader stage.",
GLuint("program", "the name of the program containing shader stage"),
GLenum("shadertype", "the shader stage from which to query for the subroutine parameter", SHADER_TYPES),
GLenum("pname", "the parameter of the shader to query", ProgramStageProperties),
Check(1)..ReturnParam..GLint.p("values", "a variable into which the queried value or values will be placed")
)
// ARB_tesselation_shader
IntConstant(
"Accepted by the {@code mode} parameter of Begin and all vertex array functions that implicitly call Begin.",
"PATCHES"..0xE
)
IntConstant(
"Accepted by the {@code pname} parameter of PatchParameteri, GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, and GetInteger64v.",
"PATCH_VERTICES"..0x8E72
)
IntConstant(
"Accepted by the {@code pname} parameter of PatchParameterfv, GetBooleanv, GetDoublev, GetFloatv, and GetIntegerv, and GetInteger64v.",
"PATCH_DEFAULT_INNER_LEVEL"..0x8E73,
"PATCH_DEFAULT_OUTER_LEVEL"..0x8E74
)
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramiv.",
"TESS_CONTROL_OUTPUT_VERTICES"..0x8E75,
"TESS_GEN_MODE"..0x8E76,
"TESS_GEN_SPACING"..0x8E77,
"TESS_GEN_VERTEX_ORDER"..0x8E78,
"TESS_GEN_POINT_MODE"..0x8E79
)
IntConstant(
"Returned by GetProgramiv when {@code pname} is TESS_GEN_MODE.",
"ISOLINES"..0x8E7A
)
IntConstant(
"Returned by GetProgramiv when {@code pname} is TESS_GEN_SPACING.",
"FRACTIONAL_ODD"..0x8E7B,
"FRACTIONAL_EVEN"..0x8E7C
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, and GetInteger64v.",
"MAX_PATCH_VERTICES"..0x8E7D,
"MAX_TESS_GEN_LEVEL"..0x8E7E,
"MAX_TESS_CONTROL_UNIFORM_COMPONENTS"..0x8E7F,
"MAX_TESS_EVALUATION_UNIFORM_COMPONENTS"..0x8E80,
"MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS"..0x8E81,
"MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS"..0x8E82,
"MAX_TESS_CONTROL_OUTPUT_COMPONENTS"..0x8E83,
"MAX_TESS_PATCH_COMPONENTS"..0x8E84,
"MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS"..0x8E85,
"MAX_TESS_EVALUATION_OUTPUT_COMPONENTS"..0x8E86,
"MAX_TESS_CONTROL_UNIFORM_BLOCKS"..0x8E89,
"MAX_TESS_EVALUATION_UNIFORM_BLOCKS"..0x8E8A,
"MAX_TESS_CONTROL_INPUT_COMPONENTS"..0x886C,
"MAX_TESS_EVALUATION_INPUT_COMPONENTS"..0x886D,
"MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS"..0x8E1E,
"MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS"..0x8E1F
)
IntConstant(
"Accepted by the {@code pname} parameter of GetActiveUniformBlockiv.",
"UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER"..0x84F0,
"UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER"..0x84F1
)
IntConstant(
"Accepted by the {@code type} parameter of CreateShader and returned by the {@code params} parameter of GetShaderiv.",
"TESS_EVALUATION_SHADER"..0x8E87,
"TESS_CONTROL_SHADER"..0x8E88
)
void(
"PatchParameteri",
"Specifies the integer value of the specified parameter for patch primitives.",
GLenum("pname", "the name of the parameter to set", "#PATCH_VERTICES"),
GLint("value", "the new value for the parameter given by {@code pname}")
)
void(
"PatchParameterfv",
"Specifies an array of float values for the specified parameter for patch primitives.",
GLenum("pname", "the name of the parameter to set", "#PATCH_DEFAULT_OUTER_LEVEL #PATCH_DEFAULT_INNER_LEVEL"),
Check(
expression = "GL11.glGetInteger(GL_PATCH_VERTICES)", debug = true
)..GLfloat.const.p("values", "an array containing the new values for the parameter given by {@code pname}")
)
// ARB_texture_cube_map_array
IntConstant(
"Accepted by the {@code target} parameter of TexParameteri, TexParameteriv, TexParameterf, TexParameterfv, BindTexture, and GenerateMipmap.",
"TEXTURE_CUBE_MAP_ARRAY"..0x9009
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv and GetFloatv.",
"TEXTURE_BINDING_CUBE_MAP_ARRAY"..0x900A
)
IntConstant(
"Accepted by the {@code target} parameter of TexImage3D, TexSubImage3D, CompressedTeximage3D, CompressedTexSubImage3D and CopyTexSubImage3D.",
"PROXY_TEXTURE_CUBE_MAP_ARRAY"..0x900B
)
IntConstant(
"Returned by the {@code type} parameter of GetActiveUniform.",
"SAMPLER_CUBE_MAP_ARRAY"..0x900C,
"SAMPLER_CUBE_MAP_ARRAY_SHADOW"..0x900D,
"INT_SAMPLER_CUBE_MAP_ARRAY"..0x900E,
"UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY"..0x900F
)
// ARB_texture_gather
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"MIN_PROGRAM_TEXTURE_GATHER_OFFSET"..0x8E5E,
"MAX_PROGRAM_TEXTURE_GATHER_OFFSET"..0x8E5F
)
// ARB_transform_feedback2
IntConstant(
"Accepted by the {@code target} parameter of BindTransformFeedback.",
"TRANSFORM_FEEDBACK"..0x8E22
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv.",
"TRANSFORM_FEEDBACK_BUFFER_PAUSED"..0x8E23,
"TRANSFORM_FEEDBACK_BUFFER_ACTIVE"..0x8E24,
"TRANSFORM_FEEDBACK_BINDING"..0x8E25
)
void(
"BindTransformFeedback",
"Binds a transform feedback object.",
GLenum("target", "the target to which to bind the transform feedback object {@code id}", "#TRANSFORM_FEEDBACK"),
GLuint("id", "the name of a transform feedback object")
)
void(
"DeleteTransformFeedbacks",
"Deletes transform feedback objects.",
AutoSize("ids")..GLsizei("n", "the number of transform feedback objects to delete"),
SingleValue("id")..GLuint.const.p("ids", "an array of names of transform feedback objects to delete")
)
void(
"GenTransformFeedbacks",
"Reserves transform feedback object names.",
AutoSize("ids")..GLsizei("n", "the number of transform feedback object names to reserve"),
ReturnParam..GLuint.p("ids", "an array of into which the reserved names will be written")
)
GLboolean(
"IsTransformFeedback",
"Determines if a name corresponds to a transform feedback object.",
GLuint("id", "a value that may be the name of a transform feedback object")
)
void(
"PauseTransformFeedback",
"""
Pauses transform feedback operations for the currently bound transform feedback object.
When transform feedback operations are paused, transform feedback is still considered active and changing most transform feedback state related to the
object results in an error. However, a new transform feedback object may be bound while transform feedback is paused. The error #INVALID_OPERATION
is generated by PauseTransformFeedback if the currently bound transform feedback is not active or is paused.
When transform feedback is active and not paused, all geometric primitives generated must be compatible with the value of {@code primitiveMode} passed
to #BeginTransformFeedback(). The error #INVALID_OPERATION is generated by #Begin() or any operation that implicitly calls #Begin()
(such as #DrawElements()) if {@code mode} is not one of the allowed modes. If a geometry shader is active, its output primitive type is used instead
of the {@code mode} parameter passed to #Begin() for the purposes of this error check. Any primitive type may be used while transform feedback is
paused.
"""
)
void(
"ResumeTransformFeedback",
"""
Resumes transform feedback operations for the currently bound transform feedback object.
The error #INVALID_OPERATION is generated by #ResumeTransformFeedback() if the currently bound transform feedback is not active or is not paused.
"""
)
void(
"DrawTransformFeedback",
"Render primitives using a count derived from a transform feedback object.",
GLenum("mode", "what kind of primitives to render", PRIMITIVE_TYPES),
GLuint("id", "the name of a transform feedback object from which to retrieve a primitive count")
)
// ARB_transform_feedback3
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv.",
"MAX_TRANSFORM_FEEDBACK_BUFFERS"..0x8E70,
"MAX_VERTEX_STREAMS"..0x8E71
)
void(
"DrawTransformFeedbackStream",
"Renders primitives using a count derived from a specifed stream of a transform feedback object.",
GLenum("mode", "what kind of primitives to render", PRIMITIVE_TYPES),
GLuint("id", "the name of a transform feedback object from which to retrieve a primitive count"),
GLuint("stream", "the index of the transform feedback stream from which to retrieve a primitive count")
)
void(
"BeginQueryIndexed",
"Begins a query object on an indexed target",
GLenum(
"target",
"the target type of query object established between {@code glBeginQueryIndexed} and the subsequent #EndQueryIndexed()",
QUERY_TARGETS
),
GLuint("index", "the index of the query target upon which to begin the query"),
GLuint("id", "the name of a query object")
)
void(
"EndQueryIndexed",
"Ends a query object on an indexed target",
GLenum("target", "the target type of query object to be concluded", QUERY_TARGETS),
GLuint("index", "the index of the query target upon which to end the query")
)
void(
"GetQueryIndexediv",
"Returns parameters of an indexed query object target.",
GLenum("target", "a query object target", QUERY_TARGETS),
GLuint("index", "the index of the query object target"),
GLenum("pname", "the symbolic name of a query object target parameter"),
Check(1)..ReturnParam..GLint.p("params", "the requested data")
)
} | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/GL40Core.kt | 1173259802 |
package com.talentica.androidkotlin.customcamera.model.camera
import android.app.Activity
import android.view.SurfaceHolder
import com.talentica.androidkotlin.customcamera.callbacks.PhotoClickedCallback
import com.talentica.androidkotlin.customcamera.presenter.camera.CameraActivityPresenterImpl
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.subscriptions.Subscriptions
class CameraActivityModel constructor(val cameraAdapter: CameraAdapter) {
protected var cameraFrameSubscription = Subscriptions.unsubscribed()
private lateinit var cameraActivityPresenter: CameraActivityPresenterImpl
fun startProcessingPreview(cameraActivityPresenter: CameraActivityPresenterImpl) {
this.cameraActivityPresenter = cameraActivityPresenter
observeFrames(cameraAdapter.start())
}
fun stopProcessingPreview() {
stopPreviewing()
}
private fun observeFrames(cameraFrameObservable: Observable<ByteArray>) {
cameraFrameSubscription.unsubscribe()
cameraFrameSubscription = cameraFrameObservable
.onBackpressureLatest()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { extractedDocument ->
}
}
private fun stopPreviewing() {
cameraFrameSubscription.unsubscribe()
cameraAdapter.stop()
}
fun cameraSurfaceReady(holder: SurfaceHolder) {
cameraAdapter.setupSurface(holder)
cameraAdapter.autoFocusOnTargetAndRepeat()
}
fun cameraSurfaceRefresh() {
observeFrames(cameraAdapter.start())
}
fun toggleFlash() {
cameraAdapter.toggleFlash()
}
fun clickPhoto(photoCallback:PhotoClickedCallback) {
cameraAdapter.takePicture(photoCallback)
}
}
| customcamera/src/main/java/com/talentica/androidkotlin/customcamera/model/camera/CameraActivityModel.kt | 1508527910 |
package org.livingdoc.converters.time
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.livingdoc.converters.DefaultTypeConverterContract
import java.time.ZonedDateTime
import java.time.ZonedDateTime.parse
internal class ZonedDateTimeConverterTest : TemporalConverterContract<ZonedDateTime>(), DefaultTypeConverterContract {
override val cut = ZonedDateTimeConverter()
override val validInputVariations = mapOf(
"2017-05-12T12:34+01:00[Europe/Berlin]" to parse("2017-05-12T12:34+01:00[Europe/Berlin]"),
"2017-05-12T12:34:56+01:00[Europe/Paris]" to parse("2017-05-12T12:34:56+01:00[Europe/Paris]"),
"2017-05-12T12:34:56.123+01:00[Europe/London]" to parse("2017-05-12T12:34:56.123+01:00[Europe/London]")
)
override val defaultFormatValue =
"2017-05-12T12:34+01:00[Europe/Berlin]" to parse("2017-05-12T12:34+01:00[Europe/Berlin]")
override val customFormat = "dd.MM.uuuu HH:mm 'Uhr' X VV"
override val customFormatValue =
"12.05.2017 12:34 Uhr +01 Europe/Berlin" to parse("2017-05-12T12:34+01:00[Europe/Berlin]")
override val malformedCustomFormat = "dd.MM.uuuu HH:mm X V"
@Test fun `converter can converted to ZonedDateTime`() {
assertThat(cut.canConvertTo(ZonedDateTime::class.java)).isTrue()
}
}
| livingdoc-converters/src/test/kotlin/org/livingdoc/converters/time/ZonedDateTimeConverterTest.kt | 3909234416 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.arch.handlers.internal
internal interface HandlerWithTransformer<O> : Handler<O> {
fun handle(o: O?, transformer: (O) -> O)
@JvmSuppressWildcards
fun handleMany(oCollection: Collection<O>?, transformer: (O) -> O)
}
| core/src/main/java/org/hisp/dhis/android/core/arch/handlers/internal/HandlerWithTransformer.kt | 3988150957 |
/*
* wac-core
* Copyright (C) 2016 Martijn Heil
*
* 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 tk.martijn_heil.wac_core.general
import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.ClickType
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.InventoryDragEvent
import org.bukkit.event.player.PlayerPickupItemEvent
import org.bukkit.inventory.Inventory
import tk.martijn_heil.wac_core.WacCore
import tk.martijn_heil.wac_core.getStringWithArgs
class MaxOfItemListener() : Listener {
private val maxPerPlayerInventory: Map<Material, Int> = mapOf(
Pair(Material.TNT, 1)
)
/**
* Prevent a player from having more than 1 TNT block in their inventory.
*/
@EventHandler(ignoreCancelled = true)
fun onDragAndDrop(e: InventoryClickEvent) {
// All drag & drop actions.
// If the player tries to drag and drop a single item into their inventory, or if they drag and drop an entire stack into their inventory.
// So, if the player has no TNT in his inventory yet, but tries to put an entire stack in at once, that is also prevented.
if(e.inventory == e.whoClicked.inventory && !e.whoClicked.hasPermission(WacCore.Permission.BYPASS__ITEM_LIMIT.str)) {
maxPerPlayerInventory.forEach {
val m = it.key
val maxAmount = it.value
if (
((e.cursor.type == m && (e.cursor.amount + countItemsOfTypeInInventory(m, e.whoClicked.inventory) > maxAmount)) && (e.click == ClickType.LEFT))
|| (e.cursor.type == m && e.click == ClickType.RIGHT && countItemsOfTypeInInventory(m, e.whoClicked.inventory) >= maxAmount)
|| (e.click == ClickType.LEFT && e.cursor.amount > maxAmount && e.cursor.type == m)
) {
e.isCancelled = true
e.whoClicked.sendMessage(ChatColor.RED.toString() + getStringWithArgs(WacCore.messages,
arrayOf(maxAmount.toString(), m.toString()), "error.event.cancelled.inventory.moreOfItemThanAllowed"))
}
}
}
}
@EventHandler(ignoreCancelled = true)
fun onInventoryDrag(e: InventoryDragEvent) {
// Drag/distribution actions.
maxPerPlayerInventory.forEach {
val m = it.key
val maxAmount = it.value
if(itemsPlacedByInventoryDragContain(m, e) && (e.whoClicked.inventory.contains(m, maxAmount) ||
(countItemsPlacedByInventoryDrag(e) + countItemsOfTypeInInventory(m, e.whoClicked.inventory)) > maxAmount)) {
e.isCancelled = true
e.whoClicked.sendMessage(ChatColor.RED.toString() + getStringWithArgs(WacCore.messages,
arrayOf(maxAmount.toString(), m.toString()), "error.event.cancelled.inventory.moreOfItemThanAllowed"))
}
}
}
/**
* Prevent a player from having more than 1 TNT block in their inventory.
*/
@EventHandler(ignoreCancelled = true)
fun onPlayerShiftClickItemIntoPlayerInventory(e: InventoryClickEvent) {
maxPerPlayerInventory.forEach {
val m = it.key
val maxAmount = it.value
// If the player is trying to shift click TNT into their inventory.
if(e.inventory != e.whoClicked.inventory && (e.click == ClickType.SHIFT_LEFT || e.click == ClickType.SHIFT_RIGHT)
&& e.currentItem.type == m && (e.whoClicked.inventory.contains(m, maxAmount) || (e.currentItem.amount + e.currentItem.amount) > maxAmount)
&& !e.whoClicked.hasPermission(WacCore.Permission.BYPASS__ITEM_LIMIT.str)) {
e.isCancelled = true
e.whoClicked.sendMessage(ChatColor.RED.toString() + getStringWithArgs(WacCore.messages,
arrayOf(maxAmount.toString(), m.toString()), "error.event.cancelled.inventory.moreOfItemThanAllowed"))
}
}
}
/**
* Prevent a player from having more than 1 TNT block in their inventory.
*/
@EventHandler(ignoreCancelled = true)
fun onPlayerPickupItem(e: PlayerPickupItemEvent) {
maxPerPlayerInventory.forEach {
val m = it.key
val maxAmount = it.value
// If the player tries to pick up this item type from the ground.
if(!e.player.hasPermission(WacCore.Permission.BYPASS__ITEM_LIMIT.str) && e.item.itemStack.type == m) {
// If the player already has the max amount of this item type in his inventory, cancel the event.
if(e.player.inventory.contains(m, maxAmount)) {
e.isCancelled = true
} else if(e.item.itemStack.amount > maxAmount && !e.player.inventory.contains(m, maxAmount)) {
// if it is maxAmount, just allow the player to pick it up normally.
// If the player does not yet have this item type in his inventory,
// let him pick up maxAmount of this item type from the stack, but leave the rest lying on the ground
e.isCancelled = true // If we don't cancel it, the player will pick up the whole item stack.
val i = e.item.itemStack.clone()
i.amount = maxAmount
val result = e.player.inventory.addItem(i)
if(result.isEmpty()) { // successfully added maxAmount of this item type to the player's inventory.
// remove the maxAmount items we just added to the player's inventory from the ground.
// Decrementing the amount directly via chunkPropagateSkylightOcclusion.item.itemStack.amount-- does apperantly not work..
val i2 = e.item.itemStack.clone()
i2.amount -= maxAmount
e.item.itemStack = i2
}
}
}
}
}
fun countItemsPlacedByInventoryDrag(e: InventoryDragEvent): Int {
var count: Int = 0
e.newItems.forEach {
count += it.value.amount
}
return count
}
fun itemsPlacedByInventoryDragContain(m: Material, e: InventoryDragEvent): Boolean {
e.newItems.forEach {
if(it.value.type == m) return true
}
return false;
}
fun countItemsOfTypeInInventory(m: Material, i: Inventory): Int {
var count = 0
i.contents.forEach {
if(it != null && it.type == m) {
count += it.amount
}
}
return count
}
} | src/main/kotlin/tk/martijn_heil/wac_core/general/MaxOfItemListener.kt | 908732854 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.dsl.builder.impl
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.dsl.builder.CellBase
import com.intellij.ui.dsl.builder.SpacingConfiguration
import com.intellij.ui.dsl.gridLayout.Constraints
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
@ApiStatus.Internal
internal abstract class PlaceholderBaseImpl<T : CellBase<T>>(private val parent: RowImpl) : CellBaseImpl<T>() {
protected var placeholderCellData: PlaceholderCellData? = null
private set
private var visible = true
private var enabled = true
var component: JComponent? = null
set(value) {
reinstallComponent(field, value)
field = value
}
override fun enabledFromParent(parentEnabled: Boolean) {
doEnabled(parentEnabled && enabled)
}
override fun enabled(isEnabled: Boolean): CellBase<T> {
enabled = isEnabled
if (parent.isEnabled()) {
doEnabled(enabled)
}
return this
}
override fun visibleFromParent(parentVisible: Boolean) {
doVisible(parentVisible && visible)
}
override fun visible(isVisible: Boolean): CellBase<T> {
visible = isVisible
if (parent.isVisible()) {
doVisible(visible)
}
component?.isVisible = isVisible
return this
}
open fun init(panel: DialogPanel, constraints: Constraints, spacing: SpacingConfiguration) {
placeholderCellData = PlaceholderCellData(panel, constraints, spacing)
if (component != null) {
reinstallComponent(null, component)
}
}
private fun reinstallComponent(oldComponent: JComponent?, newComponent: JComponent?) {
var invalidate = false
if (oldComponent != null) {
placeholderCellData?.let {
if (oldComponent is DialogPanel) {
it.panel.unregisterIntegratedPanel(oldComponent)
}
it.panel.remove(oldComponent)
invalidate = true
}
}
if (newComponent != null) {
newComponent.isVisible = visible && parent.isVisible()
newComponent.isEnabled = enabled && parent.isEnabled()
placeholderCellData?.let {
val gaps = customGaps ?: getComponentGaps(it.constraints.gaps.left, it.constraints.gaps.right, newComponent, it.spacing)
it.constraints = it.constraints.copy(
gaps = gaps,
visualPaddings = prepareVisualPaddings(newComponent.origin)
)
it.panel.add(newComponent, it.constraints)
if (newComponent is DialogPanel) {
it.panel.registerIntegratedPanel(newComponent)
}
invalidate = true
}
}
if (invalidate) {
invalidate()
}
}
private fun doVisible(isVisible: Boolean) {
component?.let {
if (it.isVisible != isVisible) {
it.isVisible = isVisible
invalidate()
}
}
}
private fun doEnabled(isEnabled: Boolean) {
component?.let {
it.isEnabled = isEnabled
}
}
private fun invalidate() {
placeholderCellData?.let {
// Force parent to re-layout
it.panel.revalidate()
it.panel.repaint()
}
}
}
@ApiStatus.Internal
internal data class PlaceholderCellData(val panel: DialogPanel, var constraints: Constraints, val spacing: SpacingConfiguration)
| platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/PlaceholderBaseImpl.kt | 2250603140 |
package klay.jvm
import klay.core.Exec
import klay.core.Net
import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft_17
import org.java_websocket.handshake.ServerHandshake
import java.net.URI
import java.net.URISyntaxException
import java.nio.ByteBuffer
class JavaWebSocket(exec: Exec, uri: String, listener: Net.WebSocket.Listener) : Net.WebSocket {
private val socket: WebSocketClient
init {
val juri: URI?
try {
juri = URI(uri)
} catch (e: URISyntaxException) {
throw RuntimeException(e)
}
socket = object : WebSocketClient(juri, Draft_17()) {
override fun onMessage(buffer: ByteBuffer) {
exec.invokeLater({ listener.onDataMessage(JvmByteBuffer(buffer)) })
}
override fun onMessage(msg: String) {
exec.invokeLater({ listener.onTextMessage(msg) })
}
override fun onError(e: Exception) {
exec.invokeLater({ listener.onError(e.message!!) })
}
override fun onClose(code: Int, reason: String, remote: Boolean) {
exec.invokeLater({ listener.onClose() })
}
override fun onOpen(handshake: ServerHandshake) {
exec.invokeLater({ listener.onOpen() })
}
}
socket.connect()
}
override fun close() {
socket.close()
}
override fun send(data: String) {
try {
socket.connection.send(data)
} catch (e: Throwable) {
throw RuntimeException(e)
}
}
override fun send(data: klay.core.buffers.ByteBuffer) {
try {
socket.connection.send((data as JvmByteBuffer).nioBuffer)
} catch (e: Throwable) {
throw RuntimeException(e)
}
}
}
| klay-jvm/src/main/kotlin/klay/jvm/JavaWebSocket.kt | 2675319510 |
// "Convert to anonymous object" "true"
interface I {
fun bar(): Unit
}
fun foo() {
}
fun test() {
<caret>I {
foo()
}
} | plugins/kotlin/idea/tests/testData/quickfix/convertToAnonymousObject/unit.kt | 1974379924 |
/*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.spotify.heroic.aggregation.simple
import com.google.common.collect.ImmutableSet
import com.spotify.heroic.ObjectHasher
import com.spotify.heroic.aggregation.BucketAggregationInstance
import com.spotify.heroic.metric.Metric
import com.spotify.heroic.metric.MetricType
import com.spotify.heroic.metric.Point
data class QuantileInstance(
override val size: Long,
override val extent: Long,
val q: Double,
val error: Double
) : BucketAggregationInstance<QuantileBucket>(size, extent, ImmutableSet.of(MetricType.POINT), MetricType.POINT) {
override fun buildBucket(timestamp: Long): QuantileBucket {
return QuantileBucket(timestamp, q, error)
}
override fun build(bucket: QuantileBucket): Metric {
val value = bucket.value()
return if (java.lang.Double.isNaN(value)) {
Metric.invalid
} else Point(bucket.timestamp, value)
}
override fun bucketHashTo(hasher: ObjectHasher) {
hasher.putField("q", q, hasher.doubleValue())
hasher.putField("error", error, hasher.doubleValue())
}
}
| aggregation/simple/src/main/java/com/spotify/heroic/aggregation/simple/QuantileInstance.kt | 3629907369 |
/*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores.base
import com.github.jonathanxd.kores.Instruction
import com.github.jonathanxd.kores.common.KoresNothing
import java.lang.reflect.Type
/**
* Declares a variable of type [variableType] and name [name] with default value [value] (null does not
* mean that you declared a variable with null value, it means that you declared a variable without a default value,
* for null values use `Literals.NULL`).
*/
data class VariableDeclaration(
override val modifiers: Set<KoresModifier>,
override val variableType: Type,
override val name: String,
override val value: Instruction
) : VariableBase, ValueHolder, TypedInstruction, ModifiersHolder {
override fun builder(): Builder = Builder(this)
class Builder() :
VariableBase.Builder<VariableDeclaration, Builder>,
ValueHolder.Builder<VariableDeclaration, Builder>,
ModifiersHolder.Builder<VariableDeclaration, Builder> {
lateinit var name: String
lateinit var variableType: Type
var value: Instruction = KoresNothing
var modifiers: Set<KoresModifier> = emptySet()
constructor(defaults: VariableDeclaration) : this() {
this.name = defaults.name
this.variableType = defaults.variableType
this.value = defaults.value
this.modifiers = defaults.modifiers
}
override fun name(value: String): Builder {
this.name = value
return this
}
override fun variableType(value: Type): Builder {
this.variableType = value
return this
}
override fun value(value: Instruction): Builder {
this.value = value
return this
}
override fun modifiers(value: Set<KoresModifier>): Builder {
this.modifiers = value
return this
}
/**
* Removes value definition.
*/
fun withoutValue(): Builder = this.value(KoresNothing)
override fun build(): VariableDeclaration =
VariableDeclaration(this.modifiers, this.variableType, this.name, this.value)
companion object {
@JvmStatic
fun builder(): Builder = Builder()
@JvmStatic
fun builder(defaults: VariableDeclaration): Builder = Builder(defaults)
}
}
}
| src/main/kotlin/com/github/jonathanxd/kores/base/VariableDeclaration.kt | 2313841261 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.tree.visitors
import org.jetbrains.kotlin.nj2k.tree.*
abstract class JKVisitorWithCommentsPrinting : JKVisitor() {
abstract fun printLeftNonCodeElements(element: JKFormattingOwner)
abstract fun printRightNonCodeElements(element: JKFormattingOwner)
override fun visitTreeElement(treeElement: JKElement) {
if (treeElement is JKFormattingOwner) {
printLeftNonCodeElements(treeElement)
}
visitTreeElementRaw(treeElement)
if (treeElement is JKFormattingOwner) {
printRightNonCodeElements(treeElement)
}
}
abstract fun visitTreeElementRaw(treeElement: JKElement)
override fun visitDeclaration(declaration: JKDeclaration) {
printLeftNonCodeElements(declaration)
visitDeclarationRaw(declaration)
printRightNonCodeElements(declaration)
}
open fun visitDeclarationRaw(declaration: JKDeclaration) = visitTreeElementRaw(declaration)
override fun visitClass(klass: JKClass) {
printLeftNonCodeElements(klass)
visitClassRaw(klass)
printRightNonCodeElements(klass)
}
open fun visitClassRaw(klass: JKClass) = visitDeclarationRaw(klass)
override fun visitVariable(variable: JKVariable) {
printLeftNonCodeElements(variable)
visitVariableRaw(variable)
printRightNonCodeElements(variable)
}
open fun visitVariableRaw(variable: JKVariable) = visitDeclarationRaw(variable)
override fun visitLocalVariable(localVariable: JKLocalVariable) {
printLeftNonCodeElements(localVariable)
visitLocalVariableRaw(localVariable)
printRightNonCodeElements(localVariable)
}
open fun visitLocalVariableRaw(localVariable: JKLocalVariable) = visitVariableRaw(localVariable)
override fun visitForLoopVariable(forLoopVariable: JKForLoopVariable) {
printLeftNonCodeElements(forLoopVariable)
visitForLoopVariableRaw(forLoopVariable)
printRightNonCodeElements(forLoopVariable)
}
open fun visitForLoopVariableRaw(forLoopVariable: JKForLoopVariable) = visitVariableRaw(forLoopVariable)
override fun visitParameter(parameter: JKParameter) {
printLeftNonCodeElements(parameter)
visitParameterRaw(parameter)
printRightNonCodeElements(parameter)
}
open fun visitParameterRaw(parameter: JKParameter) = visitVariableRaw(parameter)
override fun visitEnumConstant(enumConstant: JKEnumConstant) {
printLeftNonCodeElements(enumConstant)
visitEnumConstantRaw(enumConstant)
printRightNonCodeElements(enumConstant)
}
open fun visitEnumConstantRaw(enumConstant: JKEnumConstant) = visitVariableRaw(enumConstant)
override fun visitTypeParameter(typeParameter: JKTypeParameter) {
printLeftNonCodeElements(typeParameter)
visitTypeParameterRaw(typeParameter)
printRightNonCodeElements(typeParameter)
}
open fun visitTypeParameterRaw(typeParameter: JKTypeParameter) = visitDeclarationRaw(typeParameter)
override fun visitMethod(method: JKMethod) {
printLeftNonCodeElements(method)
visitMethodRaw(method)
printRightNonCodeElements(method)
}
open fun visitMethodRaw(method: JKMethod) = visitDeclarationRaw(method)
override fun visitMethodImpl(methodImpl: JKMethodImpl) {
printLeftNonCodeElements(methodImpl)
visitMethodImplRaw(methodImpl)
printRightNonCodeElements(methodImpl)
}
open fun visitMethodImplRaw(methodImpl: JKMethodImpl) = visitMethodRaw(methodImpl)
override fun visitConstructor(constructor: JKConstructor) {
printLeftNonCodeElements(constructor)
visitConstructorRaw(constructor)
printRightNonCodeElements(constructor)
}
open fun visitConstructorRaw(constructor: JKConstructor) = visitMethodRaw(constructor)
override fun visitConstructorImpl(constructorImpl: JKConstructorImpl) {
printLeftNonCodeElements(constructorImpl)
visitConstructorImplRaw(constructorImpl)
printRightNonCodeElements(constructorImpl)
}
open fun visitConstructorImplRaw(constructorImpl: JKConstructorImpl) = visitConstructorRaw(constructorImpl)
override fun visitKtPrimaryConstructor(ktPrimaryConstructor: JKKtPrimaryConstructor) {
printLeftNonCodeElements(ktPrimaryConstructor)
visitKtPrimaryConstructorRaw(ktPrimaryConstructor)
printRightNonCodeElements(ktPrimaryConstructor)
}
open fun visitKtPrimaryConstructorRaw(ktPrimaryConstructor: JKKtPrimaryConstructor) = visitConstructorRaw(ktPrimaryConstructor)
override fun visitField(field: JKField) {
printLeftNonCodeElements(field)
visitFieldRaw(field)
printRightNonCodeElements(field)
}
open fun visitFieldRaw(field: JKField) = visitVariableRaw(field)
override fun visitKtInitDeclaration(ktInitDeclaration: JKKtInitDeclaration) {
printLeftNonCodeElements(ktInitDeclaration)
visitKtInitDeclarationRaw(ktInitDeclaration)
printRightNonCodeElements(ktInitDeclaration)
}
open fun visitKtInitDeclarationRaw(ktInitDeclaration: JKKtInitDeclaration) = visitDeclarationRaw(ktInitDeclaration)
override fun visitJavaStaticInitDeclaration(javaStaticInitDeclaration: JKJavaStaticInitDeclaration) {
printLeftNonCodeElements(javaStaticInitDeclaration)
visitJavaStaticInitDeclarationRaw(javaStaticInitDeclaration)
printRightNonCodeElements(javaStaticInitDeclaration)
}
open fun visitJavaStaticInitDeclarationRaw(javaStaticInitDeclaration: JKJavaStaticInitDeclaration) =
visitDeclarationRaw(javaStaticInitDeclaration)
override fun visitTreeRoot(treeRoot: JKTreeRoot) {
printLeftNonCodeElements(treeRoot)
visitTreeRootRaw(treeRoot)
printRightNonCodeElements(treeRoot)
}
open fun visitTreeRootRaw(treeRoot: JKTreeRoot) = visitTreeElementRaw(treeRoot)
override fun visitFile(file: JKFile) {
printLeftNonCodeElements(file)
visitFileRaw(file)
printRightNonCodeElements(file)
}
open fun visitFileRaw(file: JKFile) = visitTreeElementRaw(file)
override fun visitTypeElement(typeElement: JKTypeElement) {
printLeftNonCodeElements(typeElement)
visitTypeElementRaw(typeElement)
printRightNonCodeElements(typeElement)
}
open fun visitTypeElementRaw(typeElement: JKTypeElement) = visitTreeElementRaw(typeElement)
override fun visitBlock(block: JKBlock) {
printLeftNonCodeElements(block)
visitBlockRaw(block)
printRightNonCodeElements(block)
}
open fun visitBlockRaw(block: JKBlock) = visitTreeElementRaw(block)
override fun visitInheritanceInfo(inheritanceInfo: JKInheritanceInfo) {
printLeftNonCodeElements(inheritanceInfo)
visitInheritanceInfoRaw(inheritanceInfo)
printRightNonCodeElements(inheritanceInfo)
}
open fun visitInheritanceInfoRaw(inheritanceInfo: JKInheritanceInfo) = visitTreeElementRaw(inheritanceInfo)
override fun visitPackageDeclaration(packageDeclaration: JKPackageDeclaration) {
printLeftNonCodeElements(packageDeclaration)
visitPackageDeclarationRaw(packageDeclaration)
printRightNonCodeElements(packageDeclaration)
}
open fun visitPackageDeclarationRaw(packageDeclaration: JKPackageDeclaration) = visitTreeElementRaw(packageDeclaration)
override fun visitLabel(label: JKLabel) {
printLeftNonCodeElements(label)
visitLabelRaw(label)
printRightNonCodeElements(label)
}
open fun visitLabelRaw(label: JKLabel) = visitTreeElementRaw(label)
override fun visitLabelEmpty(labelEmpty: JKLabelEmpty) {
printLeftNonCodeElements(labelEmpty)
visitLabelEmptyRaw(labelEmpty)
printRightNonCodeElements(labelEmpty)
}
open fun visitLabelEmptyRaw(labelEmpty: JKLabelEmpty) = visitLabelRaw(labelEmpty)
override fun visitLabelText(labelText: JKLabelText) {
printLeftNonCodeElements(labelText)
visitLabelTextRaw(labelText)
printRightNonCodeElements(labelText)
}
open fun visitLabelTextRaw(labelText: JKLabelText) = visitLabelRaw(labelText)
override fun visitImportStatement(importStatement: JKImportStatement) {
printLeftNonCodeElements(importStatement)
visitImportStatementRaw(importStatement)
printRightNonCodeElements(importStatement)
}
open fun visitImportStatementRaw(importStatement: JKImportStatement) = visitTreeElementRaw(importStatement)
override fun visitImportList(importList: JKImportList) {
printLeftNonCodeElements(importList)
visitImportListRaw(importList)
printRightNonCodeElements(importList)
}
open fun visitImportListRaw(importList: JKImportList) = visitTreeElementRaw(importList)
override fun visitAnnotationParameter(annotationParameter: JKAnnotationParameter) {
printLeftNonCodeElements(annotationParameter)
visitAnnotationParameterRaw(annotationParameter)
printRightNonCodeElements(annotationParameter)
}
open fun visitAnnotationParameterRaw(annotationParameter: JKAnnotationParameter) = visitTreeElementRaw(annotationParameter)
override fun visitAnnotationParameterImpl(annotationParameterImpl: JKAnnotationParameterImpl) {
printLeftNonCodeElements(annotationParameterImpl)
visitAnnotationParameterImplRaw(annotationParameterImpl)
printRightNonCodeElements(annotationParameterImpl)
}
open fun visitAnnotationParameterImplRaw(annotationParameterImpl: JKAnnotationParameterImpl) =
visitAnnotationParameterRaw(annotationParameterImpl)
override fun visitAnnotationNameParameter(annotationNameParameter: JKAnnotationNameParameter) {
printLeftNonCodeElements(annotationNameParameter)
visitAnnotationNameParameterRaw(annotationNameParameter)
printRightNonCodeElements(annotationNameParameter)
}
open fun visitAnnotationNameParameterRaw(annotationNameParameter: JKAnnotationNameParameter) =
visitAnnotationParameterRaw(annotationNameParameter)
override fun visitArgument(argument: JKArgument) {
printLeftNonCodeElements(argument)
visitArgumentRaw(argument)
printRightNonCodeElements(argument)
}
open fun visitArgumentRaw(argument: JKArgument) = visitTreeElementRaw(argument)
override fun visitNamedArgument(namedArgument: JKNamedArgument) {
printLeftNonCodeElements(namedArgument)
visitNamedArgumentRaw(namedArgument)
printRightNonCodeElements(namedArgument)
}
open fun visitNamedArgumentRaw(namedArgument: JKNamedArgument) = visitArgumentRaw(namedArgument)
override fun visitArgumentImpl(argumentImpl: JKArgumentImpl) {
printLeftNonCodeElements(argumentImpl)
visitArgumentImplRaw(argumentImpl)
printRightNonCodeElements(argumentImpl)
}
open fun visitArgumentImplRaw(argumentImpl: JKArgumentImpl) = visitArgumentRaw(argumentImpl)
override fun visitArgumentList(argumentList: JKArgumentList) {
printLeftNonCodeElements(argumentList)
visitArgumentListRaw(argumentList)
printRightNonCodeElements(argumentList)
}
open fun visitArgumentListRaw(argumentList: JKArgumentList) = visitTreeElementRaw(argumentList)
override fun visitTypeParameterList(typeParameterList: JKTypeParameterList) {
printLeftNonCodeElements(typeParameterList)
visitTypeParameterListRaw(typeParameterList)
printRightNonCodeElements(typeParameterList)
}
open fun visitTypeParameterListRaw(typeParameterList: JKTypeParameterList) = visitTreeElementRaw(typeParameterList)
override fun visitAnnotationList(annotationList: JKAnnotationList) {
printLeftNonCodeElements(annotationList)
visitAnnotationListRaw(annotationList)
printRightNonCodeElements(annotationList)
}
open fun visitAnnotationListRaw(annotationList: JKAnnotationList) = visitTreeElementRaw(annotationList)
override fun visitAnnotation(annotation: JKAnnotation) {
printLeftNonCodeElements(annotation)
visitAnnotationRaw(annotation)
printRightNonCodeElements(annotation)
}
open fun visitAnnotationRaw(annotation: JKAnnotation) = visitTreeElementRaw(annotation)
override fun visitTypeArgumentList(typeArgumentList: JKTypeArgumentList) {
printLeftNonCodeElements(typeArgumentList)
visitTypeArgumentListRaw(typeArgumentList)
printRightNonCodeElements(typeArgumentList)
}
open fun visitTypeArgumentListRaw(typeArgumentList: JKTypeArgumentList) = visitTreeElementRaw(typeArgumentList)
override fun visitNameIdentifier(nameIdentifier: JKNameIdentifier) {
printLeftNonCodeElements(nameIdentifier)
visitNameIdentifierRaw(nameIdentifier)
printRightNonCodeElements(nameIdentifier)
}
open fun visitNameIdentifierRaw(nameIdentifier: JKNameIdentifier) = visitTreeElementRaw(nameIdentifier)
override fun visitBlockImpl(blockImpl: JKBlockImpl) {
printLeftNonCodeElements(blockImpl)
visitBlockImplRaw(blockImpl)
printRightNonCodeElements(blockImpl)
}
open fun visitBlockImplRaw(blockImpl: JKBlockImpl) = visitBlockRaw(blockImpl)
override fun visitKtWhenCase(ktWhenCase: JKKtWhenCase) {
printLeftNonCodeElements(ktWhenCase)
visitKtWhenCaseRaw(ktWhenCase)
printRightNonCodeElements(ktWhenCase)
}
open fun visitKtWhenCaseRaw(ktWhenCase: JKKtWhenCase) = visitTreeElementRaw(ktWhenCase)
override fun visitKtWhenLabel(ktWhenLabel: JKKtWhenLabel) {
printLeftNonCodeElements(ktWhenLabel)
visitKtWhenLabelRaw(ktWhenLabel)
printRightNonCodeElements(ktWhenLabel)
}
open fun visitKtWhenLabelRaw(ktWhenLabel: JKKtWhenLabel) = visitTreeElementRaw(ktWhenLabel)
override fun visitKtElseWhenLabel(ktElseWhenLabel: JKKtElseWhenLabel) {
printLeftNonCodeElements(ktElseWhenLabel)
visitKtElseWhenLabelRaw(ktElseWhenLabel)
printRightNonCodeElements(ktElseWhenLabel)
}
open fun visitKtElseWhenLabelRaw(ktElseWhenLabel: JKKtElseWhenLabel) = visitKtWhenLabelRaw(ktElseWhenLabel)
override fun visitKtValueWhenLabel(ktValueWhenLabel: JKKtValueWhenLabel) {
printLeftNonCodeElements(ktValueWhenLabel)
visitKtValueWhenLabelRaw(ktValueWhenLabel)
printRightNonCodeElements(ktValueWhenLabel)
}
open fun visitKtValueWhenLabelRaw(ktValueWhenLabel: JKKtValueWhenLabel) = visitKtWhenLabelRaw(ktValueWhenLabel)
override fun visitClassBody(classBody: JKClassBody) {
printLeftNonCodeElements(classBody)
visitClassBodyRaw(classBody)
printRightNonCodeElements(classBody)
}
open fun visitClassBodyRaw(classBody: JKClassBody) = visitTreeElementRaw(classBody)
override fun visitJavaTryCatchSection(javaTryCatchSection: JKJavaTryCatchSection) {
printLeftNonCodeElements(javaTryCatchSection)
visitJavaTryCatchSectionRaw(javaTryCatchSection)
printRightNonCodeElements(javaTryCatchSection)
}
open fun visitJavaTryCatchSectionRaw(javaTryCatchSection: JKJavaTryCatchSection) = visitStatementRaw(javaTryCatchSection)
override fun visitJavaSwitchCase(javaSwitchCase: JKJavaSwitchCase) {
printLeftNonCodeElements(javaSwitchCase)
visitJavaSwitchCaseRaw(javaSwitchCase)
printRightNonCodeElements(javaSwitchCase)
}
open fun visitJavaSwitchCaseRaw(javaSwitchCase: JKJavaSwitchCase) = visitTreeElementRaw(javaSwitchCase)
override fun visitJavaDefaultSwitchCase(javaDefaultSwitchCase: JKJavaDefaultSwitchCase) {
printLeftNonCodeElements(javaDefaultSwitchCase)
visitJavaDefaultSwitchCaseRaw(javaDefaultSwitchCase)
printRightNonCodeElements(javaDefaultSwitchCase)
}
open fun visitJavaDefaultSwitchCaseRaw(javaDefaultSwitchCase: JKJavaDefaultSwitchCase) = visitJavaSwitchCaseRaw(javaDefaultSwitchCase)
override fun visitJavaLabelSwitchCase(javaLabelSwitchCase: JKJavaLabelSwitchCase) {
printLeftNonCodeElements(javaLabelSwitchCase)
visitJavaLabelSwitchCaseRaw(javaLabelSwitchCase)
printRightNonCodeElements(javaLabelSwitchCase)
}
open fun visitJavaLabelSwitchCaseRaw(javaLabelSwitchCase: JKJavaLabelSwitchCase) = visitJavaSwitchCaseRaw(javaLabelSwitchCase)
override fun visitExpression(expression: JKExpression) {
printLeftNonCodeElements(expression)
visitExpressionRaw(expression)
printRightNonCodeElements(expression)
}
open fun visitExpressionRaw(expression: JKExpression) = visitTreeElementRaw(expression)
override fun visitOperatorExpression(operatorExpression: JKOperatorExpression) {
printLeftNonCodeElements(operatorExpression)
visitOperatorExpressionRaw(operatorExpression)
printRightNonCodeElements(operatorExpression)
}
open fun visitOperatorExpressionRaw(operatorExpression: JKOperatorExpression) = visitExpressionRaw(operatorExpression)
override fun visitBinaryExpression(binaryExpression: JKBinaryExpression) {
printLeftNonCodeElements(binaryExpression)
visitBinaryExpressionRaw(binaryExpression)
printRightNonCodeElements(binaryExpression)
}
open fun visitBinaryExpressionRaw(binaryExpression: JKBinaryExpression) = visitOperatorExpressionRaw(binaryExpression)
override fun visitUnaryExpression(unaryExpression: JKUnaryExpression) {
printLeftNonCodeElements(unaryExpression)
visitUnaryExpressionRaw(unaryExpression)
printRightNonCodeElements(unaryExpression)
}
open fun visitUnaryExpressionRaw(unaryExpression: JKUnaryExpression) = visitOperatorExpressionRaw(unaryExpression)
override fun visitPrefixExpression(prefixExpression: JKPrefixExpression) {
printLeftNonCodeElements(prefixExpression)
visitPrefixExpressionRaw(prefixExpression)
printRightNonCodeElements(prefixExpression)
}
open fun visitPrefixExpressionRaw(prefixExpression: JKPrefixExpression) = visitUnaryExpressionRaw(prefixExpression)
override fun visitPostfixExpression(postfixExpression: JKPostfixExpression) {
printLeftNonCodeElements(postfixExpression)
visitPostfixExpressionRaw(postfixExpression)
printRightNonCodeElements(postfixExpression)
}
open fun visitPostfixExpressionRaw(postfixExpression: JKPostfixExpression) = visitUnaryExpressionRaw(postfixExpression)
override fun visitQualifiedExpression(qualifiedExpression: JKQualifiedExpression) {
printLeftNonCodeElements(qualifiedExpression)
visitQualifiedExpressionRaw(qualifiedExpression)
printRightNonCodeElements(qualifiedExpression)
}
open fun visitQualifiedExpressionRaw(qualifiedExpression: JKQualifiedExpression) = visitExpressionRaw(qualifiedExpression)
override fun visitParenthesizedExpression(parenthesizedExpression: JKParenthesizedExpression) {
printLeftNonCodeElements(parenthesizedExpression)
visitParenthesizedExpressionRaw(parenthesizedExpression)
printRightNonCodeElements(parenthesizedExpression)
}
open fun visitParenthesizedExpressionRaw(parenthesizedExpression: JKParenthesizedExpression) = visitExpressionRaw(parenthesizedExpression)
override fun visitTypeCastExpression(typeCastExpression: JKTypeCastExpression) {
printLeftNonCodeElements(typeCastExpression)
visitTypeCastExpressionRaw(typeCastExpression)
printRightNonCodeElements(typeCastExpression)
}
open fun visitTypeCastExpressionRaw(typeCastExpression: JKTypeCastExpression) = visitExpressionRaw(typeCastExpression)
override fun visitLiteralExpression(literalExpression: JKLiteralExpression) {
printLeftNonCodeElements(literalExpression)
visitLiteralExpressionRaw(literalExpression)
printRightNonCodeElements(literalExpression)
}
open fun visitLiteralExpressionRaw(literalExpression: JKLiteralExpression) = visitExpressionRaw(literalExpression)
override fun visitStubExpression(stubExpression: JKStubExpression) {
printLeftNonCodeElements(stubExpression)
visitStubExpressionRaw(stubExpression)
printRightNonCodeElements(stubExpression)
}
open fun visitStubExpressionRaw(stubExpression: JKStubExpression) = visitExpressionRaw(stubExpression)
override fun visitThisExpression(thisExpression: JKThisExpression) {
printLeftNonCodeElements(thisExpression)
visitThisExpressionRaw(thisExpression)
printRightNonCodeElements(thisExpression)
}
open fun visitThisExpressionRaw(thisExpression: JKThisExpression) = visitExpressionRaw(thisExpression)
override fun visitSuperExpression(superExpression: JKSuperExpression) {
printLeftNonCodeElements(superExpression)
visitSuperExpressionRaw(superExpression)
printRightNonCodeElements(superExpression)
}
open fun visitSuperExpressionRaw(superExpression: JKSuperExpression) = visitExpressionRaw(superExpression)
override fun visitIfElseExpression(ifElseExpression: JKIfElseExpression) {
printLeftNonCodeElements(ifElseExpression)
visitIfElseExpressionRaw(ifElseExpression)
printRightNonCodeElements(ifElseExpression)
}
open fun visitIfElseExpressionRaw(ifElseExpression: JKIfElseExpression) = visitExpressionRaw(ifElseExpression)
override fun visitLambdaExpression(lambdaExpression: JKLambdaExpression) {
printLeftNonCodeElements(lambdaExpression)
visitLambdaExpressionRaw(lambdaExpression)
printRightNonCodeElements(lambdaExpression)
}
open fun visitLambdaExpressionRaw(lambdaExpression: JKLambdaExpression) = visitExpressionRaw(lambdaExpression)
override fun visitCallExpression(callExpression: JKCallExpression) {
printLeftNonCodeElements(callExpression)
visitCallExpressionRaw(callExpression)
printRightNonCodeElements(callExpression)
}
open fun visitCallExpressionRaw(callExpression: JKCallExpression) = visitExpressionRaw(callExpression)
override fun visitDelegationConstructorCall(delegationConstructorCall: JKDelegationConstructorCall) {
printLeftNonCodeElements(delegationConstructorCall)
visitDelegationConstructorCallRaw(delegationConstructorCall)
printRightNonCodeElements(delegationConstructorCall)
}
open fun visitDelegationConstructorCallRaw(delegationConstructorCall: JKDelegationConstructorCall) =
visitCallExpressionRaw(delegationConstructorCall)
override fun visitCallExpressionImpl(callExpressionImpl: JKCallExpressionImpl) {
printLeftNonCodeElements(callExpressionImpl)
visitCallExpressionImplRaw(callExpressionImpl)
printRightNonCodeElements(callExpressionImpl)
}
open fun visitCallExpressionImplRaw(callExpressionImpl: JKCallExpressionImpl) = visitCallExpressionRaw(callExpressionImpl)
override fun visitNewExpression(newExpression: JKNewExpression) {
printLeftNonCodeElements(newExpression)
visitNewExpressionRaw(newExpression)
printRightNonCodeElements(newExpression)
}
open fun visitNewExpressionRaw(newExpression: JKNewExpression) = visitExpressionRaw(newExpression)
override fun visitFieldAccessExpression(fieldAccessExpression: JKFieldAccessExpression) {
printLeftNonCodeElements(fieldAccessExpression)
visitFieldAccessExpressionRaw(fieldAccessExpression)
printRightNonCodeElements(fieldAccessExpression)
}
open fun visitFieldAccessExpressionRaw(fieldAccessExpression: JKFieldAccessExpression) = visitExpressionRaw(fieldAccessExpression)
override fun visitPackageAccessExpression(packageAccessExpression: JKPackageAccessExpression) {
printLeftNonCodeElements(packageAccessExpression)
visitPackageAccessExpressionRaw(packageAccessExpression)
printRightNonCodeElements(packageAccessExpression)
}
open fun visitPackageAccessExpressionRaw(packageAccessExpression: JKPackageAccessExpression) =
visitExpressionRaw(packageAccessExpression)
override fun visitMethodAccessExpression(methodAccessExpression: JKMethodAccessExpression) {
printLeftNonCodeElements(methodAccessExpression)
visitMethodAccessExpressionRaw(methodAccessExpression)
printRightNonCodeElements(methodAccessExpression)
}
open fun visitMethodAccessExpressionRaw(methodAccessExpression: JKMethodAccessExpression) = visitExpressionRaw(methodAccessExpression)
override fun visitClassAccessExpression(classAccessExpression: JKClassAccessExpression) {
printLeftNonCodeElements(classAccessExpression)
visitClassAccessExpressionRaw(classAccessExpression)
printRightNonCodeElements(classAccessExpression)
}
open fun visitClassAccessExpressionRaw(classAccessExpression: JKClassAccessExpression) = visitExpressionRaw(classAccessExpression)
override fun visitMethodReferenceExpression(methodReferenceExpression: JKMethodReferenceExpression) {
printLeftNonCodeElements(methodReferenceExpression)
visitMethodReferenceExpressionRaw(methodReferenceExpression)
printRightNonCodeElements(methodReferenceExpression)
}
open fun visitMethodReferenceExpressionRaw(methodReferenceExpression: JKMethodReferenceExpression) =
visitExpressionRaw(methodReferenceExpression)
override fun visitLabeledExpression(labeledExpression: JKLabeledExpression) {
printLeftNonCodeElements(labeledExpression)
visitLabeledExpressionRaw(labeledExpression)
printRightNonCodeElements(labeledExpression)
}
open fun visitLabeledExpressionRaw(labeledExpression: JKLabeledExpression) = visitExpressionRaw(labeledExpression)
override fun visitClassLiteralExpression(classLiteralExpression: JKClassLiteralExpression) {
printLeftNonCodeElements(classLiteralExpression)
visitClassLiteralExpressionRaw(classLiteralExpression)
printRightNonCodeElements(classLiteralExpression)
}
open fun visitClassLiteralExpressionRaw(classLiteralExpression: JKClassLiteralExpression) = visitExpressionRaw(classLiteralExpression)
override fun visitKtAssignmentChainLink(ktAssignmentChainLink: JKKtAssignmentChainLink) {
printLeftNonCodeElements(ktAssignmentChainLink)
visitKtAssignmentChainLinkRaw(ktAssignmentChainLink)
printRightNonCodeElements(ktAssignmentChainLink)
}
open fun visitKtAssignmentChainLinkRaw(ktAssignmentChainLink: JKKtAssignmentChainLink) = visitExpressionRaw(ktAssignmentChainLink)
override fun visitAssignmentChainAlsoLink(assignmentChainAlsoLink: JKAssignmentChainAlsoLink) {
printLeftNonCodeElements(assignmentChainAlsoLink)
visitAssignmentChainAlsoLinkRaw(assignmentChainAlsoLink)
printRightNonCodeElements(assignmentChainAlsoLink)
}
open fun visitAssignmentChainAlsoLinkRaw(assignmentChainAlsoLink: JKAssignmentChainAlsoLink) =
visitKtAssignmentChainLinkRaw(assignmentChainAlsoLink)
override fun visitAssignmentChainLetLink(assignmentChainLetLink: JKAssignmentChainLetLink) {
printLeftNonCodeElements(assignmentChainLetLink)
visitAssignmentChainLetLinkRaw(assignmentChainLetLink)
printRightNonCodeElements(assignmentChainLetLink)
}
open fun visitAssignmentChainLetLinkRaw(assignmentChainLetLink: JKAssignmentChainLetLink) =
visitKtAssignmentChainLinkRaw(assignmentChainLetLink)
override fun visitIsExpression(isExpression: JKIsExpression) {
printLeftNonCodeElements(isExpression)
visitIsExpressionRaw(isExpression)
printRightNonCodeElements(isExpression)
}
open fun visitIsExpressionRaw(isExpression: JKIsExpression) = visitExpressionRaw(isExpression)
override fun visitKtThrowExpression(ktThrowExpression: JKKtThrowExpression) {
printLeftNonCodeElements(ktThrowExpression)
visitKtThrowExpressionRaw(ktThrowExpression)
printRightNonCodeElements(ktThrowExpression)
}
open fun visitKtThrowExpressionRaw(ktThrowExpression: JKKtThrowExpression) = visitExpressionRaw(ktThrowExpression)
override fun visitKtItExpression(ktItExpression: JKKtItExpression) {
printLeftNonCodeElements(ktItExpression)
visitKtItExpressionRaw(ktItExpression)
printRightNonCodeElements(ktItExpression)
}
open fun visitKtItExpressionRaw(ktItExpression: JKKtItExpression) = visitExpressionRaw(ktItExpression)
override fun visitKtAnnotationArrayInitializerExpression(ktAnnotationArrayInitializerExpression: JKKtAnnotationArrayInitializerExpression) {
printLeftNonCodeElements(ktAnnotationArrayInitializerExpression)
visitKtAnnotationArrayInitializerExpressionRaw(ktAnnotationArrayInitializerExpression)
printRightNonCodeElements(ktAnnotationArrayInitializerExpression)
}
open fun visitKtAnnotationArrayInitializerExpressionRaw(ktAnnotationArrayInitializerExpression: JKKtAnnotationArrayInitializerExpression) =
visitExpressionRaw(ktAnnotationArrayInitializerExpression)
override fun visitKtTryExpression(ktTryExpression: JKKtTryExpression) {
printLeftNonCodeElements(ktTryExpression)
visitKtTryExpressionRaw(ktTryExpression)
printRightNonCodeElements(ktTryExpression)
}
open fun visitKtTryExpressionRaw(ktTryExpression: JKKtTryExpression) = visitExpressionRaw(ktTryExpression)
override fun visitKtTryCatchSection(ktTryCatchSection: JKKtTryCatchSection) {
printLeftNonCodeElements(ktTryCatchSection)
visitKtTryCatchSectionRaw(ktTryCatchSection)
printRightNonCodeElements(ktTryCatchSection)
}
open fun visitKtTryCatchSectionRaw(ktTryCatchSection: JKKtTryCatchSection) = visitTreeElementRaw(ktTryCatchSection)
override fun visitJavaNewEmptyArray(javaNewEmptyArray: JKJavaNewEmptyArray) {
printLeftNonCodeElements(javaNewEmptyArray)
visitJavaNewEmptyArrayRaw(javaNewEmptyArray)
printRightNonCodeElements(javaNewEmptyArray)
}
open fun visitJavaNewEmptyArrayRaw(javaNewEmptyArray: JKJavaNewEmptyArray) = visitExpressionRaw(javaNewEmptyArray)
override fun visitJavaNewArray(javaNewArray: JKJavaNewArray) {
printLeftNonCodeElements(javaNewArray)
visitJavaNewArrayRaw(javaNewArray)
printRightNonCodeElements(javaNewArray)
}
open fun visitJavaNewArrayRaw(javaNewArray: JKJavaNewArray) = visitExpressionRaw(javaNewArray)
override fun visitJavaAssignmentExpression(javaAssignmentExpression: JKJavaAssignmentExpression) {
printLeftNonCodeElements(javaAssignmentExpression)
visitJavaAssignmentExpressionRaw(javaAssignmentExpression)
printRightNonCodeElements(javaAssignmentExpression)
}
open fun visitJavaAssignmentExpressionRaw(javaAssignmentExpression: JKJavaAssignmentExpression) = visitExpressionRaw(javaAssignmentExpression)
override fun visitModifierElement(modifierElement: JKModifierElement) {
printLeftNonCodeElements(modifierElement)
visitModifierElementRaw(modifierElement)
printRightNonCodeElements(modifierElement)
}
open fun visitModifierElementRaw(modifierElement: JKModifierElement) = visitTreeElementRaw(modifierElement)
override fun visitMutabilityModifierElement(mutabilityModifierElement: JKMutabilityModifierElement) {
printLeftNonCodeElements(mutabilityModifierElement)
visitMutabilityModifierElementRaw(mutabilityModifierElement)
printRightNonCodeElements(mutabilityModifierElement)
}
open fun visitMutabilityModifierElementRaw(mutabilityModifierElement: JKMutabilityModifierElement) =
visitModifierElementRaw(mutabilityModifierElement)
override fun visitModalityModifierElement(modalityModifierElement: JKModalityModifierElement) {
printLeftNonCodeElements(modalityModifierElement)
visitModalityModifierElementRaw(modalityModifierElement)
printRightNonCodeElements(modalityModifierElement)
}
open fun visitModalityModifierElementRaw(modalityModifierElement: JKModalityModifierElement) =
visitModifierElementRaw(modalityModifierElement)
override fun visitVisibilityModifierElement(visibilityModifierElement: JKVisibilityModifierElement) {
printLeftNonCodeElements(visibilityModifierElement)
visitVisibilityModifierElementRaw(visibilityModifierElement)
printRightNonCodeElements(visibilityModifierElement)
}
open fun visitVisibilityModifierElementRaw(visibilityModifierElement: JKVisibilityModifierElement) =
visitModifierElementRaw(visibilityModifierElement)
override fun visitOtherModifierElement(otherModifierElement: JKOtherModifierElement) {
printLeftNonCodeElements(otherModifierElement)
visitOtherModifierElementRaw(otherModifierElement)
printRightNonCodeElements(otherModifierElement)
}
open fun visitOtherModifierElementRaw(otherModifierElement: JKOtherModifierElement) = visitModifierElementRaw(otherModifierElement)
override fun visitStatement(statement: JKStatement) {
printLeftNonCodeElements(statement)
visitStatementRaw(statement)
printRightNonCodeElements(statement)
}
open fun visitStatementRaw(statement: JKStatement) = visitTreeElementRaw(statement)
override fun visitEmptyStatement(emptyStatement: JKEmptyStatement) {
printLeftNonCodeElements(emptyStatement)
visitEmptyStatementRaw(emptyStatement)
printRightNonCodeElements(emptyStatement)
}
open fun visitEmptyStatementRaw(emptyStatement: JKEmptyStatement) = visitStatementRaw(emptyStatement)
override fun visitLoopStatement(loopStatement: JKLoopStatement) {
printLeftNonCodeElements(loopStatement)
visitLoopStatementRaw(loopStatement)
printRightNonCodeElements(loopStatement)
}
open fun visitLoopStatementRaw(loopStatement: JKLoopStatement) = visitStatementRaw(loopStatement)
override fun visitWhileStatement(whileStatement: JKWhileStatement) {
printLeftNonCodeElements(whileStatement)
visitWhileStatementRaw(whileStatement)
printRightNonCodeElements(whileStatement)
}
open fun visitWhileStatementRaw(whileStatement: JKWhileStatement) = visitLoopStatementRaw(whileStatement)
override fun visitDoWhileStatement(doWhileStatement: JKDoWhileStatement) {
printLeftNonCodeElements(doWhileStatement)
visitDoWhileStatementRaw(doWhileStatement)
printRightNonCodeElements(doWhileStatement)
}
open fun visitDoWhileStatementRaw(doWhileStatement: JKDoWhileStatement) = visitLoopStatementRaw(doWhileStatement)
override fun visitForInStatement(forInStatement: JKForInStatement) {
printLeftNonCodeElements(forInStatement)
visitForInStatementRaw(forInStatement)
printRightNonCodeElements(forInStatement)
}
open fun visitForInStatementRaw(forInStatement: JKForInStatement) = visitStatementRaw(forInStatement)
override fun visitIfElseStatement(ifElseStatement: JKIfElseStatement) {
printLeftNonCodeElements(ifElseStatement)
visitIfElseStatementRaw(ifElseStatement)
printRightNonCodeElements(ifElseStatement)
}
open fun visitIfElseStatementRaw(ifElseStatement: JKIfElseStatement) = visitStatementRaw(ifElseStatement)
override fun visitBreakStatement(breakStatement: JKBreakStatement) {
printLeftNonCodeElements(breakStatement)
visitBreakStatementRaw(breakStatement)
printRightNonCodeElements(breakStatement)
}
open fun visitBreakStatementRaw(breakStatement: JKBreakStatement) = visitStatementRaw(breakStatement)
override fun visitContinueStatement(continueStatement: JKContinueStatement) {
printLeftNonCodeElements(continueStatement)
visitContinueStatementRaw(continueStatement)
printRightNonCodeElements(continueStatement)
}
open fun visitContinueStatementRaw(continueStatement: JKContinueStatement) = visitStatementRaw(continueStatement)
override fun visitBlockStatement(blockStatement: JKBlockStatement) {
printLeftNonCodeElements(blockStatement)
visitBlockStatementRaw(blockStatement)
printRightNonCodeElements(blockStatement)
}
open fun visitBlockStatementRaw(blockStatement: JKBlockStatement) = visitStatementRaw(blockStatement)
override fun visitBlockStatementWithoutBrackets(blockStatementWithoutBrackets: JKBlockStatementWithoutBrackets) {
printLeftNonCodeElements(blockStatementWithoutBrackets)
visitBlockStatementWithoutBracketsRaw(blockStatementWithoutBrackets)
printRightNonCodeElements(blockStatementWithoutBrackets)
}
open fun visitBlockStatementWithoutBracketsRaw(blockStatementWithoutBrackets: JKBlockStatementWithoutBrackets) =
visitStatementRaw(blockStatementWithoutBrackets)
override fun visitExpressionStatement(expressionStatement: JKExpressionStatement) {
printLeftNonCodeElements(expressionStatement)
visitExpressionStatementRaw(expressionStatement)
printRightNonCodeElements(expressionStatement)
}
open fun visitExpressionStatementRaw(expressionStatement: JKExpressionStatement) = visitStatementRaw(expressionStatement)
override fun visitDeclarationStatement(declarationStatement: JKDeclarationStatement) {
printLeftNonCodeElements(declarationStatement)
visitDeclarationStatementRaw(declarationStatement)
printRightNonCodeElements(declarationStatement)
}
open fun visitDeclarationStatementRaw(declarationStatement: JKDeclarationStatement) = visitStatementRaw(declarationStatement)
override fun visitKtWhenStatement(ktWhenStatement: JKKtWhenStatement) {
printLeftNonCodeElements(ktWhenStatement)
visitKtWhenStatementRaw(ktWhenStatement)
printRightNonCodeElements(ktWhenStatement)
}
open fun visitKtWhenStatementRaw(ktWhenStatement: JKKtWhenStatement) = visitStatementRaw(ktWhenStatement)
override fun visitKtWhenExpression(ktWhenExpression: JKKtWhenExpression) {
printLeftNonCodeElements(ktWhenExpression)
visitKtWhenExpressionRaw(ktWhenExpression)
printRightNonCodeElements(ktWhenExpression)
}
open fun visitKtWhenExpressionRaw(ktWhenExpression: JKKtWhenExpression) = visitExpressionRaw(ktWhenExpression)
override fun visitKtWhenBlock(ktWhenBlock: JKKtWhenBlock) {
printLeftNonCodeElements(ktWhenBlock)
visitKtWhenBlockRaw(ktWhenBlock)
printRightNonCodeElements(ktWhenBlock)
}
open fun visitKtWhenBlockRaw(ktWhenBlock: JKKtWhenBlock) = visitTreeElementRaw(ktWhenBlock)
override fun visitKtConvertedFromForLoopSyntheticWhileStatement(ktConvertedFromForLoopSyntheticWhileStatement: JKKtConvertedFromForLoopSyntheticWhileStatement) {
printLeftNonCodeElements(ktConvertedFromForLoopSyntheticWhileStatement)
visitKtConvertedFromForLoopSyntheticWhileStatementRaw(ktConvertedFromForLoopSyntheticWhileStatement)
printRightNonCodeElements(ktConvertedFromForLoopSyntheticWhileStatement)
}
open fun visitKtConvertedFromForLoopSyntheticWhileStatementRaw(ktConvertedFromForLoopSyntheticWhileStatement: JKKtConvertedFromForLoopSyntheticWhileStatement) =
visitStatementRaw(ktConvertedFromForLoopSyntheticWhileStatement)
override fun visitKtAssignmentStatement(ktAssignmentStatement: JKKtAssignmentStatement) {
printLeftNonCodeElements(ktAssignmentStatement)
visitKtAssignmentStatementRaw(ktAssignmentStatement)
printRightNonCodeElements(ktAssignmentStatement)
}
open fun visitKtAssignmentStatementRaw(ktAssignmentStatement: JKKtAssignmentStatement) = visitStatementRaw(ktAssignmentStatement)
override fun visitReturnStatement(returnStatement: JKReturnStatement) {
printLeftNonCodeElements(returnStatement)
visitReturnStatementRaw(returnStatement)
printRightNonCodeElements(returnStatement)
}
open fun visitReturnStatementRaw(returnStatement: JKReturnStatement) = visitStatementRaw(returnStatement)
override fun visitJavaSwitchStatement(javaSwitchStatement: JKJavaSwitchStatement) {
printLeftNonCodeElements(javaSwitchStatement)
visitJavaSwitchStatementRaw(javaSwitchStatement)
printRightNonCodeElements(javaSwitchStatement)
}
open fun visitJavaSwitchStatementRaw(javaSwitchStatement: JKJavaSwitchStatement) = visitStatementRaw(javaSwitchStatement)
override fun visitJavaThrowStatement(javaThrowStatement: JKJavaThrowStatement) {
printLeftNonCodeElements(javaThrowStatement)
visitJavaThrowStatementRaw(javaThrowStatement)
printRightNonCodeElements(javaThrowStatement)
}
open fun visitJavaThrowStatementRaw(javaThrowStatement: JKJavaThrowStatement) = visitStatementRaw(javaThrowStatement)
override fun visitJavaTryStatement(javaTryStatement: JKJavaTryStatement) {
printLeftNonCodeElements(javaTryStatement)
visitJavaTryStatementRaw(javaTryStatement)
printRightNonCodeElements(javaTryStatement)
}
open fun visitJavaTryStatementRaw(javaTryStatement: JKJavaTryStatement) = visitStatementRaw(javaTryStatement)
override fun visitJavaSynchronizedStatement(javaSynchronizedStatement: JKJavaSynchronizedStatement) {
printLeftNonCodeElements(javaSynchronizedStatement)
visitJavaSynchronizedStatementRaw(javaSynchronizedStatement)
printRightNonCodeElements(javaSynchronizedStatement)
}
open fun visitJavaSynchronizedStatementRaw(javaSynchronizedStatement: JKJavaSynchronizedStatement) = visitStatementRaw(javaSynchronizedStatement)
override fun visitJavaAssertStatement(javaAssertStatement: JKJavaAssertStatement) {
printLeftNonCodeElements(javaAssertStatement)
visitJavaAssertStatementRaw(javaAssertStatement)
printRightNonCodeElements(javaAssertStatement)
}
open fun visitJavaAssertStatementRaw(javaAssertStatement: JKJavaAssertStatement) = visitStatementRaw(javaAssertStatement)
override fun visitJavaForLoopStatement(javaForLoopStatement: JKJavaForLoopStatement) {
printLeftNonCodeElements(javaForLoopStatement)
visitJavaForLoopStatementRaw(javaForLoopStatement)
printRightNonCodeElements(javaForLoopStatement)
}
open fun visitJavaForLoopStatementRaw(javaForLoopStatement: JKJavaForLoopStatement) = visitLoopStatementRaw(javaForLoopStatement)
override fun visitJavaAnnotationMethod(javaAnnotationMethod: JKJavaAnnotationMethod) {
printLeftNonCodeElements(javaAnnotationMethod)
visitJavaAnnotationMethodRaw(javaAnnotationMethod)
printRightNonCodeElements(javaAnnotationMethod)
}
open fun visitJavaAnnotationMethodRaw(javaAnnotationMethod: JKJavaAnnotationMethod) = visitMethodRaw(javaAnnotationMethod)
}
| plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/visitors/JKVisitorWithCommentsPrinting.kt | 14240477 |
package org.moire.ultrasonic.api.subsonic.response
import org.moire.ultrasonic.api.subsonic.SubsonicAPIVersions
import org.moire.ultrasonic.api.subsonic.SubsonicError
import org.moire.ultrasonic.api.subsonic.models.Playlist
class GetPlaylistResponse(
status: Status,
version: SubsonicAPIVersions,
error: SubsonicError?,
val playlist: Playlist = Playlist()
) : SubsonicResponse(status, version, error)
| core/subsonic-api/src/main/kotlin/org/moire/ultrasonic/api/subsonic/response/GetPlaylistResponse.kt | 2107430925 |
package klay.core
import euklid.f.AffineTransform
import euklid.f.Points
import react.RFuture
/**
* Represents a square region of a texture. This makes it easy to render tiles from texture
* atlases.
*/
abstract class Tile : TileSource {
/** The texture which contains this tile. */
abstract val texture: Texture
/** The width of this tile (in display units). */
abstract val width: Float
/** The height of this tile (in display units). */
abstract val height: Float
/** Returns the `s` texture coordinate for the x-axis. */
abstract val sx: Float
/** Returns the `s` texture coordinate for the y-axis. */
abstract val sy: Float
/** Returns the `t` texture coordinate for the x-axis. */
abstract val tx: Float
/** Returns the `t` texture coordinate for the y-axis. */
abstract val ty: Float
override val isLoaded: Boolean
get() = true
/** Adds this tile to the supplied quad batch. */
abstract fun addToBatch(batch: QuadBatch, tint: Int, tx: AffineTransform,
x: Float, y: Float, width: Float, height: Float)
/** Adds this tile to the supplied quad batch. */
abstract fun addToBatch(batch: QuadBatch, tint: Int, tx: AffineTransform,
dx: Float, dy: Float, dw: Float, dh: Float,
sx: Float, sy: Float, sw: Float, sh: Float)
override fun tile(): Tile {
return this
}
override fun tileAsync(): RFuture<Tile> {
return RFuture.success(this)
}
override fun toString(): String {
return "Tile[" + width + "x" + height +
"/" + Points.pointToString(sx, sy) + "/" + Points.pointToString(tx, ty) +
"] <- " + texture
}
}
| src/main/kotlin/klay/core/Tile.kt | 1556769982 |
package mapzen.com.sdksampleapp.models
import mapzen.com.sdksampleapp.fragments.BasicMapFragment
/**
* List of [Sample]s for the map section to display.
*/
class MapSampleList {
companion object {
private val basicMap = Sample("basic map", BasicMapFragment::class)
@JvmStatic val MAP_SAMPLES = arrayOf(basicMap)
}
}
| samples/mapzen-sample/src/main/java/mapzen/com/sdksampleapp/models/MapSampleList.kt | 2212782965 |
/*
* Copyright (C) 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.location.sample.foregroundlocation
import android.app.Application
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStoreFile
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.location.LocationServices
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.HiltAndroidApp
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@HiltAndroidApp
class ForegroundLocationApp : Application()
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideGoogleApiAvailability() = GoogleApiAvailability.getInstance()
@Provides
@Singleton
fun provideFusedLocationProviderClient(
application: Application
) = LocationServices.getFusedLocationProviderClient(application)
@Provides
@Singleton
fun provideDataStore(application: Application): DataStore<Preferences> {
return PreferenceDataStoreFactory.create {
application.preferencesDataStoreFile("prefs")
}
}
}
| ForegroundLocationUpdates/app/src/main/java/com/google/android/gms/location/sample/foregroundlocation/ForegroundLocationApp.kt | 3599008111 |
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.views.selector
import android.Manifest.permission.ACCESS_COARSE_LOCATION
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import androidx.annotation.RequiresPermission
import androidx.fragment.app.Fragment
import androidx.core.content.ContextCompat
import android.util.AttributeSet
import android.view.View
import de.dreier.mytargets.R
import de.dreier.mytargets.databinding.SelectorItemImageDetailsBinding
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.features.training.environment.CurrentWeather
import de.dreier.mytargets.features.training.environment.Locator
import de.dreier.mytargets.features.training.environment.WeatherService
import de.dreier.mytargets.shared.models.Environment
import de.dreier.mytargets.utils.Utils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.IOException
class EnvironmentSelector @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : SelectorBase<Environment, SelectorItemImageDetailsBinding>(
context,
attrs,
R.layout.selector_item_image_details,
ENVIRONMENT_REQUEST_CODE
) {
override var selectedItem: Environment?
get() = if (super.selectedItem == null) {
Environment.getDefault(SettingsManager.indoor)
} else super.selectedItem
set(value) {
super.selectedItem = value
}
override fun bindView(item: Environment) {
if (item.indoor) {
view.name.setText(de.dreier.mytargets.shared.R.string.indoor)
view.image.setImageResource(R.drawable.ic_house_24dp)
} else {
view.name.text = item.weather.getName()
view.image.setImageResource(item.weather.drawable)
}
view.details.visibility = View.VISIBLE
view.details.text = getDetails(context, item)
view.title.visibility = View.VISIBLE
view.title.setText(R.string.environment)
}
private fun getDetails(context: Context, item: Environment): String {
var description: String
if (item.indoor) {
description = ""
if (!item.location.isEmpty()) {
description += "${context.getString(de.dreier.mytargets.shared.R.string.location)}: ${item.location}"
}
} else {
description =
"${context.getString(de.dreier.mytargets.shared.R.string.wind)}: ${item.getWindSpeed(
context
)}"
if (!item.location.isEmpty()) {
description += "\n${context.getString(de.dreier.mytargets.shared.R.string.location)}: ${item.location}"
}
}
return description
}
fun queryWeather(fragment: Fragment, requestCode: Int) {
if (isTestMode) {
setDefaultWeather()
return
}
if (ContextCompat.checkSelfPermission(
fragment.context!!,
ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
setDefaultWeather()
fragment.requestPermissions(arrayOf(ACCESS_FINE_LOCATION), requestCode)
} else {
queryWeatherInfo(fragment.context!!)
}
}
@SuppressLint("MissingPermission")
fun onPermissionResult(activity: Activity, grantResult: IntArray) {
if (grantResult.isNotEmpty() && grantResult[0] == PackageManager.PERMISSION_GRANTED) {
queryWeatherInfo(activity)
} else {
setDefaultWeather()
}
}
// Start getting weather for current location
@SuppressLint("MissingPermission", "SupportAnnotationUsage")
@RequiresPermission(anyOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION])
private fun queryWeatherInfo(context: Context) {
setItem(null)
Locator(context).getLocation(Locator.Method.NETWORK_THEN_GPS, object : Locator.Listener {
override fun onLocationFound(location: Location) {
val locationStr = getAddressFromLocation(location.latitude, location.longitude)
val weatherService = WeatherService()
val weatherCall = weatherService
.fetchCurrentWeather(location.longitude, location.latitude)
weatherCall.enqueue(object : Callback<CurrentWeather> {
override fun onResponse(
call: Call<CurrentWeather>,
response: Response<CurrentWeather>
) {
if (response.isSuccessful && response.body()!!.httpCode == 200) {
val toEnvironment = response.body()!!.toEnvironment()
setItem(
toEnvironment.copy(
location = locationStr
?: toEnvironment.location
)
)
} else {
setDefaultWeather()
}
}
override fun onFailure(call: Call<CurrentWeather>, t: Throwable) {
setDefaultWeather()
}
})
}
override fun onLocationNotFound() {
setDefaultWeather()
}
})
}
private fun getAddressFromLocation(latitude: Double, longitude: Double): String? {
val geoCoder = Geocoder(context, Utils.getCurrentLocale(context))
return try {
val addresses = geoCoder.getFromLocation(latitude, longitude, 1)
if (addresses.size > 0) {
val fetchedAddress = addresses[0]
var address = fetchedAddress.locality
if (fetchedAddress.subLocality != null) {
address += ", ${fetchedAddress.subLocality}"
}
address
} else {
null
}
} catch (e: IOException) {
e.printStackTrace()
null
}
}
private fun setDefaultWeather() {
setItem(Environment.getDefault(SettingsManager.indoor))
}
companion object {
const val ENVIRONMENT_REQUEST_CODE = 9
private val isTestMode: Boolean
get() {
return try {
Class.forName("de.dreier.mytargets.test.base.InstrumentedTestBase")
true
} catch (e: Exception) {
false
}
}
}
}
| app/src/main/java/de/dreier/mytargets/views/selector/EnvironmentSelector.kt | 1236152226 |
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.base.viewmodel
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import de.dreier.mytargets.features.arrows.ArrowListViewModel
import de.dreier.mytargets.features.arrows.EditArrowViewModel
import de.dreier.mytargets.features.distance.DistancesViewModel
import de.dreier.mytargets.features.training.details.TrainingViewModel
import de.dreier.mytargets.features.training.overview.TrainingsViewModel
internal class ViewModelFactory(private val applicationInstance: Application) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return when (modelClass) {
EditArrowViewModel::class.java -> EditArrowViewModel(applicationInstance) as T
TrainingViewModel::class.java -> TrainingViewModel(applicationInstance) as T
TrainingsViewModel::class.java -> TrainingsViewModel(applicationInstance) as T
ArrowListViewModel::class.java -> ArrowListViewModel(applicationInstance) as T
DistancesViewModel::class.java -> DistancesViewModel(applicationInstance) as T
else -> throw Exception("No implementation for $modelClass provided")
}
}
}
| app/src/main/java/de/dreier/mytargets/base/viewmodel/ViewModelFactory.kt | 2882475725 |
package top.zbeboy.isy.service.graduate.design
import org.jooq.Record
import org.jooq.Result
import top.zbeboy.isy.domain.tables.pojos.GraduationDesignDatumGroup
import top.zbeboy.isy.web.bean.graduate.design.proposal.GraduationDesignDatumGroupBean
import top.zbeboy.isy.web.util.DataTablesUtils
/**
* Created by zbeboy 2018-01-29 .
**/
interface GraduationDesignDatumGroupService {
/**
* 通过主键查询
*
* @param id 主键
* @return 组内资料
*/
fun findById(id: String): GraduationDesignDatumGroup
/**
* 保存
*
* @param graduationDesignDatumGroup 数据
*/
fun save(graduationDesignDatumGroup: GraduationDesignDatumGroup)
/**
* 删除
*
* @param graduationDesignDatumGroup 数据
*/
fun delete(graduationDesignDatumGroup: GraduationDesignDatumGroup)
/**
* 分页查询
*
* @param dataTablesUtils datatables工具类
* @return 分页数据
*/
fun findAllByPage(dataTablesUtils: DataTablesUtils<GraduationDesignDatumGroupBean>, graduationDesignDatumGroupBean: GraduationDesignDatumGroupBean): Result<Record>
/**
* 总数
*
* @return 总数
*/
fun countAll(graduationDesignDatumGroupBean: GraduationDesignDatumGroupBean): Int
/**
* 根据条件查询总数
*
* @return 条件查询总数
*/
fun countByCondition(dataTablesUtils: DataTablesUtils<GraduationDesignDatumGroupBean>, graduationDesignDatumGroupBean: GraduationDesignDatumGroupBean): Int
} | src/main/java/top/zbeboy/isy/service/graduate/design/GraduationDesignDatumGroupService.kt | 1166581357 |
package com.elpassion.mainframerplugin.common.console
import org.assertj.core.api.Assertions
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class RemoteToLocalInputConverterTest {
private val PROJECT_NAME = "testProject"
private val localBasePath = "/base/path/$PROJECT_NAME"
private val converter = RemoteToLocalInputConverter(PROJECT_NAME, localBasePath)
@Test
fun `Should catch file path from remote machine`() {
assertRegexMatches(
regexString = converter.FILE_PATH_REGEX,
input = "/mainframer/$PROJECT_NAME")
}
@Test
fun `Should not catch file path if it is not from remote machine`() {
assertRegexNotMatches(
regexString = converter.FILE_PATH_REGEX,
input = "/$PROJECT_NAME")
}
@Test
fun `Should catch file path if it starts with longer path`() {
assertRegexMatches(
regexString = converter.FILE_PATH_REGEX,
input = "/longer/path/mainframer/$PROJECT_NAME"
)
}
@Test
fun `Should catch file path if it ends with kotlin class name`() {
assertRegexMatches(
regexString = converter.FILE_PATH_REGEX,
input = "/longer/path/mainframer/$PROJECT_NAME/Example.kt"
)
}
@Test
fun `Should catch file path if it ends with java class name`() {
assertRegexMatches(
regexString = converter.FILE_PATH_REGEX,
input = "/longer/path/mainframer/$PROJECT_NAME/Example.java"
)
}
@Test
fun `Should not catch file path if it ends with undefined class name`() {
assertRegexNotMatches(
regexString = converter.FILE_PATH_REGEX,
input = "/longer/path/mainframer/$PROJECT_NAME/Example."
)
}
@Test
fun `Should catch path`() {
assertRegexMatches(
regexString = converter.PATH,
input = "/test/test2"
)
}
@Test
fun `Should catch line number`() {
assertRegexMatches(
regexString = converter.LINE_NUMBER_REGEX,
input = ":100"
)
}
@Test
fun `Should not catch wrong line number`() {
assertRegexNotMatches(
regexString = converter.LINE_NUMBER_REGEX,
input = ":wrongLineNumber"
)
}
@Test
fun `Should catch line number when there is also given column number`() {
assertRegexMatches(
regexString = converter.LINE_NUMBER_REGEX,
input = ": (9, 10)"
)
}
@Test
fun `Should catch colon and space signs in first fragment of line`() {
assertRegexMatches(
regexString = converter.FIRST_FRAGMENT_REGEX,
input = ": "
)
}
@Test
fun `Should catch whole first fragment of line`() {
assertRegexMatches(
regexString = converter.FIRST_FRAGMENT_REGEX,
input = "Very complicated exception: "
)
}
@Test
fun `Should check only one line if it matches first fragment regex`() {
assertRegexNotMatches(
regexString = converter.FIRST_FRAGMENT_REGEX,
input = "Very complicated exception\n: "
)
}
@Test
fun `Should replace first fragment only`() {
val replacedPath = "Error: /longer/path/mainframer/$PROJECT_NAME/com/elpassion/mainframer/Example.kt: (19, 10): error".replaceFirst(converter.FIRST_FRAGMENT_REGEX.toRegex(), "<>")
Assertions.assertThat(replacedPath).isEqualTo("<>/longer/path/mainframer/$PROJECT_NAME/com/elpassion/mainframer/Example.kt: (19, 10): error")
}
@Test
fun `Should replace remote base path with given local path`() {
val replacedPath = "Error: /longer/path/mainframer/$PROJECT_NAME/com/elpassion/mainframer/Example.kt: (19, 10): error".replace(converter.FILE_PATH_REGEX.toRegex(), "$localBasePath<$1>")
Assertions.assertThat(replacedPath).isEqualTo("Error: $localBasePath</com/elpassion/mainframer/Example.kt>: (19, 10): error")
}
@Test
fun `Should replace remote base path with given local path when inside path is package with dots`() {
val replacedPath = "Error: /longer/path/mainframer/$PROJECT_NAME/src/main/com.elpassion.mainframer/Example.java: (19, 10): error".replace(converter.LINE_WITH_REMOTE_EXCEPTION, "$localBasePath<$1>:$2")
Assertions.assertThat(replacedPath).isEqualTo("$localBasePath</src/main/com.elpassion.mainframer/Example.java>:19: error")
}
@Test
fun `Should replace remote base path with given local path and have first fragment`() {
val replacedPath = "Complicated error: /longer/path/mainframer/$PROJECT_NAME/com/elpassion/mainframer/Example.kt: (19, 10): error: Errors everywhere!".replace(converter.LINE_WITH_REMOTE_EXCEPTION, "$localBasePath$1:$2")
Assertions.assertThat(replacedPath).isEqualTo("$localBasePath/com/elpassion/mainframer/Example.kt:19: error: Errors everywhere!")
}
@Test
fun `Should replace remote base path with given local path also when line number is simply given`() {
val replacedPath = "Complicated error: /longer/path/mainframer/$PROJECT_NAME/com/elpassion/mainframer/Example.kt:19: error: Errors everywhere!".replace(converter.LINE_WITH_REMOTE_EXCEPTION, "$localBasePath$1:$2")
Assertions.assertThat(replacedPath).isEqualTo("$localBasePath/com/elpassion/mainframer/Example.kt:19: error: Errors everywhere!")
}
@Test
fun `Should replace remote base path with given local path also when first fragment is missing`() {
val replacedPath = "/longer/path/mainframer/$PROJECT_NAME/com/elpassion/mainframer/Example.kt:19: error: Errors everywhere!".replace(converter.LINE_WITH_REMOTE_EXCEPTION, "$localBasePath$1:$2")
Assertions.assertThat(replacedPath).isEqualTo("$localBasePath/com/elpassion/mainframer/Example.kt:19: error: Errors everywhere!")
}
@Test
fun `Should replace remote base path and change line number when method convertInput is being used`() {
val input = "Error: /longer/path/mainframer/$PROJECT_NAME/com/elpassion/mainframer/Example.kt: (1, 20): error: Errors everywhere!"
val expectedConvertedInput = "$localBasePath/com/elpassion/mainframer/Example.kt:1: error: Errors everywhere!"
val convertedInput = converter.convertInput(input)
Assertions.assertThat(convertedInput).isEqualTo(expectedConvertedInput)
}
@Test(timeout = 1000)
fun `Should not freeze on several long paths`() {
val input = "-Dretrolambda.includedFiles=/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/storage/BasePropertyDelegate\$observePropertyUpdateStatus\$2.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/storage/BasePropertyDelegate\$PropertyUpdateStatus\$Failed.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/storage/BasePropertyDelegate\$WithDefaultAndSetPrecondition.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/storage/BasePropertyDelegate\$observePropertyUpdateStatus\$1.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/storage/BasePropertyDelegate\$WithDefaultAndSetPrecondition\$1.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/screen/licenses/LicensesScreenActivity.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/screen/licenses/LicensesScreenPresenter.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/storage/BasePropertyDelegate.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/storage/BasePropertyDelegate\$default\$1.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/storage/BasePropertyDelegate\$defaultWithSetPrecondition\$1.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/activity/ActivityStateSaver.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/debug/DebugSettings.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/screen/home/HomeScreenActivity.class:/Users/alexey/Projects/tc-android-app-template/app/build/intermediates/classes/dev/debug/com/omnigon/template/storage/BasePropertyDelegate\$PropertyUpdateStatus\$Success.class\n"
val convertedInput = converter.convertInput(input)
Assertions.assertThat(convertedInput).isEqualTo(input)
}
@Test
fun `Should replace remote path even if remote path contains dashes`() {
val input = "/home/kasper-work/mainframer/$PROJECT_NAME/src/main/java/A.java:1"
val expectedConvertedInput = "$localBasePath/src/main/java/A.java:1"
val convertedInput = converter.convertInput(input)
Assertions.assertThat(convertedInput).isEqualTo(expectedConvertedInput)
}
@Test
fun `Should replace remote path even if package contains dashes`() {
val input = "/home/mainframer/$PROJECT_NAME/src/main/com.elpassion-with-dashes/Example.java:1"
val expectedConvertedInput = "$localBasePath/src/main/com.elpassion-with-dashes/Example.java:1"
val convertedInput = converter.convertInput(input)
Assertions.assertThat(convertedInput).isEqualTo(expectedConvertedInput)
}
@Test
fun `Should format correctly simple path line number value`() {
val replacedPathSimple = ":321".replace(converter.LINE_NUMBER_REGEX.toRegex(), ":$1")
Assertions.assertThat(replacedPathSimple).isEqualTo(":321")
}
@Test
fun `Should format correctly complex path line number value`() {
val replacedPathComplex = ": (90, 100)".replace(converter.LINE_NUMBER_REGEX.toRegex(), ":$1")
Assertions.assertThat(replacedPathComplex).isEqualTo(":90")
}
private fun assertRegexMatches(regexString: String, input: String) {
assertTrue(regexString.toRegex().matches(input))
}
private fun assertRegexNotMatches(regexString: String, input: String) {
assertFalse(regexString.toRegex().matches(input))
}
} | src/test/kotlin/com/elpassion/mainframerplugin/common/console/RemoteToLocalInputConverterTest.kt | 262479317 |
/*
* Copyright 2017, Red Hat, Inc. and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.zanata.action
import org.codehaus.jackson.annotate.JsonIgnoreProperties
import org.codehaus.jackson.annotate.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
data class FrontendManifest(
@JsonProperty("editor.css") val editorCss: String,
@JsonProperty("editor.js") val editorJs: String,
@JsonProperty("frontend.css") val frontendCss: String,
@JsonProperty("frontend.js") val frontendJs: String,
@JsonProperty("frontend.legacy.js") val legacyJs: String,
// This js module is referenced in zanata-frontend/src/frontend/app/editor/index.js
// as npm module 'intl-polyfill'.
// It appears to work properly despite the hashed name.
@JsonProperty("intl-polyfill.js") val intlPolyFillJs: String,
@JsonProperty("runtime.js") val runtime: String
)
| server/services/src/main/java/org/zanata/action/FrontendManifest.kt | 1369861988 |
package demo
@Anno2
class Closed2 | libraries/kotlinlibrary/src/main/java/demo/Closed2.kt | 4120150665 |
package com.swmansion.gesturehandler
import android.view.MotionEvent
interface OnTouchEventListener {
fun <T : GestureHandler<T>> onHandlerUpdate(handler: T, event: MotionEvent)
fun <T : GestureHandler<T>> onStateChange(handler: T, newState: Int, oldState: Int)
fun <T : GestureHandler<T>> onTouchEvent(handler: T)
}
| android/lib/src/main/java/com/swmansion/gesturehandler/OnTouchEventListener.kt | 3004371948 |
package com.virtlink.editorservices.intellij.resources
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.virtlink.editorservices.resources.IContent
import com.virtlink.editorservices.resources.IResourceManager
import java.net.URI
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.testFramework.LightVirtualFile
import com.virtlink.editorservices.Offset
import com.virtlink.editorservices.Position
import com.virtlink.editorservices.content.StringContent
import com.virtlink.editorservices.resources.IAesiContent
/**
* IntelliJ resource manager.
*/
@Suppress("PrivatePropertyName", "unused")
class IntellijResourceManager: IResourceManager {
private val INTELLIJ_SCHEME = "intellij"
private val MEM_SCHEME = "mem"
// An IntelliJ URI is:
// intellij:///project/module!/filepath
// An in-memory URI is:
// mem:///myfile
// An absolute URI is, for example:
// file:///myfolder/myfile
fun getUri(document: Document, project: Project): URI {
val psiFile = getPsiFile(document, project)
if (psiFile != null) {
return getUri(psiFile)
} else {
TODO()
}
}
fun getUri(file: PsiFile): URI {
val module = getModule(file)
if (module != null) {
return getUri(file.originalFile.virtualFile, module)
} else {
TODO()
}
}
fun getUri(file: VirtualFile, project: Project): URI {
val module = getModule(file, project)
if (module != null) {
return getUri(file, module)
} else {
TODO()
}
}
fun getUri(module: Module): URI {
val projectName = module.project.name
val moduleName = module.name
return URI("$INTELLIJ_SCHEME:///$projectName/$moduleName")
}
fun getUri(file: VirtualFile, module: Module): URI {
val modulePath = ModuleUtil.getModuleDirPath(module)
val moduleVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(modulePath)!!
val relativeFilePath = VfsUtil.getRelativePath(file, moduleVirtualFile)
return if (relativeFilePath != null) {
// Path relative to the module.
URI(getUri(module).toString() + "!/$relativeFilePath")
} else {
// Absolute path.
URI(file.url)
}
}
/**
* Gets the PSI file for the specified document in the specified project.
*
* @param document The document.
* @param project The project.
* @return The PSI file; or null when it could not be determined.
*/
fun getPsiFile(document: Document, project: Project): PsiFile? {
return PsiDocumentManager.getInstance(project).getPsiFile(document)
}
/**
* Gets the PSI file for the specified URI.
*
* @param uri The URI.
* @return The PSI file; or null when it could not be determined.
*/
fun getPsiFile(uri: URI): PsiFile? {
val result = parseUri(uri)
if (result.module == null || result.file == null) {
return null
}
return PsiManager.getInstance(result.module.project).findFile(result.file)
}
/**
* Gets the virtual file for the specified URI.
*
* @param uri The URI.
* @return The virtual file; or null when it could not be determined.
*/
fun getFile(uri: URI): VirtualFile? {
val result = parseUri(uri)
return result.file
}
/**
* Gets the module for the specified virtual file in the specified project.
*
* @param file The virtual file.
* @param project The project.
* @return The module; or null when it could not be determined.
*/
fun getModule(file: VirtualFile, project: Project): Module? {
var module = ModuleUtil.findModuleForFile(file, project)
if (module == null && file is LightVirtualFile && file.originalFile != null) {
module = ModuleUtil.findModuleForFile(file.originalFile, project)
}
return module
}
/**
* Gets the module for the specified PSI file.
*
* @param psiFile The PSI file.
* @return The module; or null when it could not be determined.
*/
fun getModule(psiFile: PsiFile): Module? {
return ModuleUtilCore.findModuleForPsiElement(psiFile)
// From > IDEA 2017.2.5:
// return ModuleUtilCore.findModuleForFile(psiFile)
}
/**
* Gets the module for the specified PSI element.
*
* @param element The PSI element.
* @return The module; or null when it could not be determined.
*/
fun getModule(element: PsiElement): Module? {
return ModuleUtil.findModuleForPsiElement(element)
}
/**
* Gets the module that contains (or is) the specified URI.
*
* @param uri The URI.
* @return The module; or null when it could not be determined.
*/
fun getModule(uri: URI): Module? {
val result = parseUri(uri)
return result.module
}
/**
* Gets the content roots of the specified module.
*
* Content roots won't overlap.
*
* @param module The module.
* @return A list of virtual files representing the content roots of the module.
*/
fun getContentRoots(module: Module): List<VirtualFile> {
return ModuleRootManager.getInstance(module).contentRoots.toList()
}
/**
* Parses the specified URI.
*
* @param uri The URI to parse.
* @return The resulting components.
*/
private fun parseUri(uri: URI): ParsedUrl {
val module: Module?
val file: VirtualFile?
if (uri.scheme == INTELLIJ_SCHEME) {
// intellij:///project/module/!/filepath
val path = uri.path
val modulePathSeparator = path.indexOf('!')
val projectModulePart: String
val filePart: String?
if (modulePathSeparator >= 0) {
// /project/module/!/filepath
// A file or folder in a module.
projectModulePart = path.substring(0, modulePathSeparator)
filePart = path.substring(modulePathSeparator + 1).trimStart('/')
} else {
// /project/module/
// A module a project
projectModulePart = path
filePart = null
}
module = parseModule(projectModulePart)
file = getFileInModule(filePart, module)
} else if (uri.scheme == MEM_SCHEME) {
TODO()
} else {
module = null
file = getFileInModule(uri.toString(), null)
}
return ParsedUrl(module, file)
}
/**
* Parses the Project/Module combination.
*
* @param path The path, in the form `/projectname/modulename/`.
*/
private fun parseModule(path: String): Module? {
val trimmedPath = path.trim('/')
val projectModuleSeparator = trimmedPath.indexOf('/')
val projectName: String
val moduleName: String?
if (projectModuleSeparator > 0) {
projectName = trimmedPath.substring(0, projectModuleSeparator)
moduleName = trimmedPath.substring(projectModuleSeparator + 1)
} else {
projectName = trimmedPath
moduleName = null
}
val project = getProjectByName(projectName)
val module = if (project != null) getModuleByName(moduleName, project) else null
return module
}
/**
* Parses the file path.
*
* @param uri The relative path or absolute URI, in the form `/myfolder/myfile`.
* @param module The module.
* @return The virtual file; or null when not found.
*/
private fun getFileInModule(uri: String?, module: Module?): VirtualFile? {
if (uri == null) return null
val moduleVirtualFile: VirtualFile?
if (module != null) {
val modulePath = ModuleUtil.getModuleDirPath(module)
moduleVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(modulePath)
} else {
moduleVirtualFile = null
}
return VfsUtil.findRelativeFile(uri, moduleVirtualFile)
}
/**
* Gets a project by name.
*
* @param name The project name.
* @return The project; or null when not found.
*/
private fun getProjectByName(name: String?): Project? {
if (name == null) return null
return ProjectManager.getInstance().openProjects.singleOrNull { p -> p.name == name }
}
/**
* Gets a module by name.
*
* @param name The name to look for.
* @param project The project that contains the module.
* @return The module; or null when not found.
*/
private fun getModuleByName(name: String?, project: Project): Module? {
if (name == null) return null
return ModuleManager.getInstance(project).findModuleByName(name)
}
override fun getProjectOf(uri: URI): URI? {
val module = getModule(uri)
return if (module != null) getUri(module) else module
}
override fun isProject(uri: URI): Boolean {
val (module, file) = parseUri(uri)
return module != null && file == null
}
override fun isFolder(uri: URI): Boolean {
val virtualFile = getFile(uri)
return virtualFile != null && virtualFile.isDirectory
}
override fun isFile(uri: URI): Boolean {
val virtualFile = getFile(uri)
return virtualFile != null && !virtualFile.isDirectory
}
override fun exists(uri: URI): Boolean {
val virtualFile = getFile(uri)
return virtualFile != null && virtualFile.exists()
}
override fun getChildren(uri: URI): Iterable<URI>? {
val (module, file) = parseUri(uri)
if (module == null || file == null) return null
return file.children.map { f -> getUri(f, module) }
}
override fun getParent(uri: URI): URI? {
// This is probably not correct in all situations.
return if (uri.path.endsWith("/")) uri.resolve("..") else uri.resolve(".")
}
override fun getContent(uri: URI): IContent? {
val psiFile = getPsiFile(uri)
val document: Document?
if (psiFile != null) {
document = PsiDocumentManager.getInstance(psiFile.project).getDocument(psiFile)
} else {
val virtualFile = getFile(uri) ?: return null
document = if (virtualFile != null) FileDocumentManager.getInstance().getDocument(virtualFile) else null
}
return if (document != null) StringContent(document.text, document.modificationStamp) else null
}
override fun getOffset(content: IContent, position: Position): Offset? {
return (content as? IAesiContent)?.getOffset(position)
}
override fun getPosition(content: IContent, offset: Offset): Position? {
return (content as? IAesiContent)?.getPosition(offset)
}
private data class ParsedUrl(
val module: Module?,
val file: VirtualFile?
)
} | aesi-intellij/src/main/kotlin/com/virtlink/editorservices/intellij/resources/IntellijResourceManager.kt | 3114789152 |
package mp
actual class ClassWithMultiPlatformFunctionality {
actual fun commonFunctionality() {
println("This is multi-platform functionality implemented in JavaScript")
}
fun javascriptFunctionality() {
println("This is JavaScript-specific functionality")
}
override fun toString(): String {
return "A JavaScript class implementing common and providing JavaScript-specific functionality"
}
}
| js/src/main/kotlin/mp/ClassWithMultiPlatformFunctionality.kt | 217925994 |
/*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.data.nosql.cassandra.connecting
import org.springframework.data.cassandra.core.CassandraTemplate
import org.springframework.stereotype.Component
@Component
class MyBean(private val template: CassandraTemplate) {
// @fold:on // ...
fun someMethod(): Long {
return template.count(User::class.java)
}
// @fold:off
} | spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/data/nosql/cassandra/connecting/MyBean.kt | 3962934389 |
//new comment
package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
interface SimpleEntity : WorkspaceEntity {
val version: Int
val name: String
val isSimple: Boolean
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SimpleEntity, ModifiableWorkspaceEntity<SimpleEntity>, ObjBuilder<SimpleEntity> {
override var entitySource: EntitySource
override var version: Int
override var name: String
override var isSimple: Boolean
}
companion object : Type<SimpleEntity, Builder>() {
operator fun invoke(version: Int,
name: String,
isSimple: Boolean,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): SimpleEntity {
val builder = builder()
builder.version = version
builder.name = name
builder.isSimple = isSimple
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SimpleEntity, modification: SimpleEntity.Builder.() -> Unit) = modifyEntity(
SimpleEntity.Builder::class.java, entity, modification)
//endregion
| plugins/devkit/intellij.devkit.workspaceModel/tests/testData/updateOldCode/after/entity.kt | 1084961319 |
package org.runestar.client.plugins.dev
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.game.live.Game
import org.runestar.client.api.game.live.Players
import org.runestar.client.raw.access.XPlayer
import org.runestar.client.raw.CLIENT
import org.runestar.client.api.plugins.PluginSettings
class Transmog : DisposablePlugin<Transmog.Settings>() {
override val defaultSettings = Settings()
override fun onStart() {
add(Game.ticks.subscribe {
Players.local?.accessor?.let { transmog(it, settings.npcId) }
})
}
override fun onStop() {
Players.local?.appearance?.accessor?.npcTransformId = -1
}
private fun transmog(player: XPlayer, npcId: Int) {
val appearance = player.appearance ?: return
val def = CLIENT.getNPCType(npcId) ?: return
appearance.npcTransformId = npcId
player.walkSequence = def.walkanim
player.walkBackSequence = def.walkbackanim
player.walkLeftSequence = def.walkleftanim
player.walkRightSequence = def.walkrightanim
player.readySequence = def.readyanim
player.turnLeftSequence = def.turnleftanim
player.turnRightSequence = def.turnrightanim
// npcs can't run
player.runSequence = def.walkanim
}
class Settings(
val npcId: Int = 7530
) : PluginSettings()
} | plugins-dev/src/main/java/org/runestar/client/plugins/dev/Transmog.kt | 2312472011 |
package net.tvidal.skillsmatter.ex1
import java.util.*
class MyStack<T> {
private val items = ArrayList<T>()
fun pop(): T {
if (items.isEmpty()) {
throw EmptyStackException()
}
return items.removeAt(items.size - 1)
}
fun push(obj: T) {
items.add(obj)
}
}
| src/main/kotlin/net/tvidal/skillsmatter/ex1/MyStack.kt | 3853745198 |
// "Change parameter 'z' type of function 'foo' to '(Int) -> String'" "false"
// ACTION: Convert to 'buildString' call
// ACTION: Introduce local variable
// ACTION: To raw string literal
fun foo(y: Int = 0, z: (Int) -> String = {""}) {
foo {
""<caret> as Int
""
}
} | plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/parameterTypeMismatch/changeFunctionParameterType4.kt | 1723660789 |
enum class E {
A,
B {
override fun bar() {}
};
open fun bar() {}
}
| plugins/kotlin/j2k/new/tests/testData/newJ2k/enum/constantsWithBody1.kt | 1518892699 |
// 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.util
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.*
import java.util.*
import kotlin.properties.Delegates
class CommentSaver(originalElements: PsiChildRange, private val saveLineBreaks: Boolean = false/*TODO?*/) {
constructor(originalElement: PsiElement, saveLineBreaks: Boolean = false/*TODO?*/) : this(
PsiChildRange.singleElement(originalElement),
saveLineBreaks
)
private val SAVED_TREE_KEY = Key<TreeElement>("SAVED_TREE")
private val psiFactory = KtPsiFactory(originalElements.first!!.project)
private abstract class TreeElement {
companion object {
fun create(element: PsiElement): TreeElement? {
val tokenType = element.tokenType
return when {
element is PsiWhiteSpace -> if (element.textContains('\n')) LineBreakTreeElement() else null
element is PsiComment -> CommentTreeElement.create(element)
tokenType != null -> TokenTreeElement(tokenType)
else -> if (element.textLength > 0) StandardTreeElement() else null // don't save empty elements
}
}
}
var parent: TreeElement? = null
var prev: TreeElement? = null
var next: TreeElement? = null
var firstChild: TreeElement? = null
var lastChild: TreeElement? = null
val children: Sequence<TreeElement>
get() = generateSequence({ firstChild }, { it.next })
val reverseChildren: Sequence<TreeElement>
get() = generateSequence({ lastChild }, { it.prev })
val prevSiblings: Sequence<TreeElement>
get() = generateSequence({ prev }, { it.prev })
val nextSiblings: Sequence<TreeElement>
get() = generateSequence({ next }, { it.next })
val parents: Sequence<TreeElement>
get() = generateSequence({ parent }, { it.parent })
val parentsWithSelf: Sequence<TreeElement>
get() = generateSequence(this) { it.parent }
val firstLeafInside: TreeElement
get() {
var result = this
while (true) {
result = result.firstChild ?: break
}
return result
}
val lastLeafInside: TreeElement
get() {
var result = this
while (true) {
result = result.lastChild ?: break
}
return result
}
val prevLeaf: TreeElement?
get() {
return (prev ?: return parent?.prevLeaf).lastLeafInside
}
val nextLeaf: TreeElement?
get() {
return (next ?: return parent?.nextLeaf).firstLeafInside
}
val prevLeafs: Sequence<TreeElement>
get() = generateSequence({ prevLeaf }, { it.prevLeaf })
val nextLeafs: Sequence<TreeElement>
get() = generateSequence({ nextLeaf }, { it.nextLeaf })
fun withDescendants(leftToRight: Boolean): Sequence<TreeElement> {
val children = if (leftToRight) children else reverseChildren
return sequenceOf(this) + children.flatMap { it.withDescendants(leftToRight) }
}
val prevElements: Sequence<TreeElement>
get() = prevSiblings.flatMap { it.withDescendants(leftToRight = false) }
val nextElements: Sequence<TreeElement>
get() = nextSiblings.flatMap { it.withDescendants(leftToRight = true) }
// var debugText: String? = null
}
private class StandardTreeElement() : TreeElement()
private class TokenTreeElement(val tokenType: KtToken) : TreeElement()
private class LineBreakTreeElement() : TreeElement()
private class CommentTreeElement(
val commentText: String,
val spaceBefore: String,
val spaceAfter: String
) : TreeElement() {
companion object {
fun create(comment: PsiComment): CommentTreeElement {
val spaceBefore = (comment.prevLeaf(skipEmptyElements = true) as? PsiWhiteSpace)?.text ?: ""
val spaceAfter = (comment.nextLeaf(skipEmptyElements = true) as? PsiWhiteSpace)?.text ?: ""
return CommentTreeElement(comment.text, spaceBefore, spaceAfter)
}
}
}
private val commentsToRestore = ArrayList<CommentTreeElement>()
private val lineBreaksToRestore = ArrayList<LineBreakTreeElement>()
private var toNewPsiElementMap by Delegates.notNull<MutableMap<TreeElement, MutableCollection<PsiElement>>>()
private var needAdjustIndentAfterRestore = false
init {
if (saveLineBreaks || originalElements.any { it.anyDescendantOfType<PsiComment>() }) {
originalElements.save(null)
}
}
private fun PsiChildRange.save(parentTreeElement: TreeElement?) {
var first: TreeElement? = null
var last: TreeElement? = null
for (child in this) {
assert(child.savedTreeElement == null)
val savedChild = TreeElement.create(child) ?: continue
savedChild.parent = parentTreeElement
savedChild.prev = last
if (child !is PsiWhiteSpace) { // we don't try to anchor comments to whitespaces
child.savedTreeElement = savedChild
}
last?.next = savedChild
last = savedChild
if (first == null) {
first = savedChild
}
when (savedChild) {
is CommentTreeElement -> commentsToRestore.add(savedChild)
is LineBreakTreeElement -> if (saveLineBreaks) lineBreaksToRestore.add(savedChild)
}
child.allChildren.save(savedChild)
}
parentTreeElement?.firstChild = first
parentTreeElement?.lastChild = last
}
private var PsiElement.savedTreeElement: TreeElement?
get() = getCopyableUserData(SAVED_TREE_KEY)
set(value) = putCopyableUserData(SAVED_TREE_KEY, value)
private var isFinished = false
private set
private fun deleteCommentsInside(element: PsiElement) {
assert(!isFinished)
element.accept(object : PsiRecursiveElementVisitor() {
override fun visitComment(comment: PsiComment) {
val treeElement = comment.savedTreeElement
if (treeElement != null) {
commentsToRestore.remove(treeElement)
}
}
})
}
fun elementCreatedByText(createdElement: PsiElement, original: PsiElement, rangeInOriginal: TextRange) {
assert(!isFinished)
assert(createdElement.textLength == rangeInOriginal.length)
assert(createdElement.text == original.text.substring(rangeInOriginal.startOffset, rangeInOriginal.endOffset))
createdElement.accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element is PsiWhiteSpace) return
val token = original.findElementAt(element.getStartOffsetIn(createdElement) + rangeInOriginal.startOffset)
if (token != null) {
val elementLength = element.textLength
for (originalElement in token.parentsWithSelf) {
val length = originalElement.textLength
if (length < elementLength) continue
if (length == elementLength) {
element.savedTreeElement = originalElement.savedTreeElement
}
break
}
}
super.visitElement(element)
}
})
}
private fun putNewElementIntoMap(psiElement: PsiElement, treeElement: TreeElement) {
toNewPsiElementMap.getOrPut(treeElement) { ArrayList(1) }.add(psiElement)
}
private fun bindNewElement(newPsiElement: PsiElement, treeElement: TreeElement) {
newPsiElement.savedTreeElement = treeElement
putNewElementIntoMap(newPsiElement, treeElement)
}
fun restore(
resultElement: PsiElement,
isCommentBeneathSingleLine: Boolean,
isCommentInside: Boolean,
forceAdjustIndent: Boolean
) {
restore(PsiChildRange.singleElement(resultElement), forceAdjustIndent, isCommentBeneathSingleLine, isCommentInside)
}
fun restore(resultElement: PsiElement, forceAdjustIndent: Boolean = false) {
restore(PsiChildRange.singleElement(resultElement), forceAdjustIndent)
}
fun restore(
resultElements: PsiChildRange,
forceAdjustIndent: Boolean = false,
isCommentBeneathSingleLine: Boolean = false,
isCommentInside: Boolean = false
) {
assert(!isFinished)
assert(!resultElements.isEmpty)
if (commentsToRestore.isNotEmpty() || lineBreaksToRestore.isNotEmpty()) {
// remove comments that present inside resultElements from commentsToRestore
resultElements.forEach { deleteCommentsInside(it) }
if (commentsToRestore.isNotEmpty() || lineBreaksToRestore.isNotEmpty()) {
toNewPsiElementMap = HashMap<TreeElement, MutableCollection<PsiElement>>()
for (element in resultElements) {
element.accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
val treeElement = element.savedTreeElement
if (treeElement != null) {
putNewElementIntoMap(element, treeElement)
}
super.visitElement(element)
}
})
}
restoreComments(resultElements, isCommentBeneathSingleLine, isCommentInside)
restoreLineBreaks()
// clear user data
resultElements.forEach {
it.accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
element.savedTreeElement = null
super.visitElement(element)
}
})
}
}
}
if (needAdjustIndentAfterRestore || forceAdjustIndent) {
val file = resultElements.first().containingFile
val project = file.project
val psiDocumentManager = PsiDocumentManager.getInstance(project)
val document = psiDocumentManager.getDocument(file)
if (document != null) {
psiDocumentManager.doPostponedOperationsAndUnblockDocument(document)
psiDocumentManager.commitDocument(document)
}
CodeStyleManager.getInstance(project).adjustLineIndent(file, resultElements.textRange)
}
isFinished = true
}
private fun restoreComments(
resultElements: PsiChildRange,
isCommentBeneathSingleLine: Boolean = false,
isCommentInside: Boolean = false
) {
var putAbandonedCommentsAfter = resultElements.last!!
for (commentTreeElement in commentsToRestore) {
val comment = psiFactory.createComment(commentTreeElement.commentText)
val anchorBefore = findAnchor(commentTreeElement, before = true)
val anchorAfter = findAnchor(commentTreeElement, before = false)
val anchor = chooseAnchor(anchorBefore, anchorAfter)
val restored: PsiComment
if (anchor != null) {
val anchorElement = findFinalAnchorElement(anchor, comment)
val parent = anchorElement.parent
if (anchor.before) {
restored = parent.addAfter(comment, anchorElement) as PsiComment
if (commentTreeElement.spaceBefore.isNotEmpty()) {
parent.addAfter(psiFactory.createWhiteSpace(commentTreeElement.spaceBefore), anchorElement)
}
// make sure that there is a line break after EOL_COMMENT
if (restored.tokenType == KtTokens.EOL_COMMENT) {
val whiteSpace = restored.nextLeaf(skipEmptyElements = true) as? PsiWhiteSpace
if (whiteSpace == null) {
parent.addAfter(psiFactory.createWhiteSpace("\n"), restored)
} else if (!whiteSpace.textContains('\n')) {
val newWhiteSpace = psiFactory.createWhiteSpace("\n" + whiteSpace.text)
whiteSpace.replace(newWhiteSpace)
}
}
} else {
restored = parent.addBefore(comment, anchorElement) as PsiComment
if (commentTreeElement.spaceAfter.isNotEmpty()) {
parent.addBefore(psiFactory.createWhiteSpace(commentTreeElement.spaceAfter), anchorElement)
}
val functionLiteral = restored.parent as? KtFunctionLiteral
if (functionLiteral != null && commentTreeElement.spaceBefore.isNotEmpty()) {
functionLiteral.addBefore(psiFactory.createWhiteSpace(commentTreeElement.spaceBefore), restored)
}
}
} else {
restored = putAbandonedCommentsAfter.parent.addBefore(comment, putAbandonedCommentsAfter) as PsiComment
if (isCommentInside) {
val element = resultElements.first
val innerExpression = element?.lastChild?.getPrevSiblingIgnoringWhitespace()
innerExpression?.add(psiFactory.createWhiteSpace())
innerExpression?.add(restored)
restored.delete()
}
putAbandonedCommentsAfter = restored
}
// shift (possible contained) comment in expression underneath braces
if (isCommentBeneathSingleLine && resultElements.count() == 1) {
val element = resultElements.first
element?.add(psiFactory.createWhiteSpace("\n"))
element?.add(restored)
restored.delete()
}
bindNewElement(restored, commentTreeElement) // will be used when restoring line breaks
if (restored.tokenType == KtTokens.EOL_COMMENT) {
needAdjustIndentAfterRestore = true // TODO: do we really need it?
}
}
}
private fun restoreLineBreaks() {
for (lineBreakElement in lineBreaksToRestore) {
if (toNewPsiElementMap[lineBreakElement] != null) continue
val lineBreakParent = lineBreakElement.parent
fun findRestored(leaf: TreeElement): PsiElement? {
if (leaf is LineBreakTreeElement) return null
return leaf.parentsWithSelf
.takeWhile { it != lineBreakParent }
.mapNotNull { toNewPsiElementMap[it]?.first() } //TODO: what about multiple?
.firstOrNull()
}
val tokensToMatch = arrayListOf<KtToken>()
for (leaf in lineBreakElement.prevLeafs) {
var psiElement = findRestored(leaf)
if (psiElement != null) {
psiElement = skipTokensForward(psiElement, tokensToMatch.asReversed())
psiElement?.restoreLineBreakAfter()
break
} else {
if (leaf !is TokenTreeElement) break
tokensToMatch.add(leaf.tokenType)
}
}
}
}
private fun skipTokensForward(psiElement: PsiElement, tokensToMatch: List<KtToken>): PsiElement? {
var currentPsiElement = psiElement
for (token in tokensToMatch) {
currentPsiElement = currentPsiElement.nextLeaf(nonSpaceAndNonEmptyFilter) ?: return null
if (currentPsiElement.tokenType != token) return null
}
return currentPsiElement
}
private fun PsiElement.restoreLineBreakAfter() {
val addAfter = shiftNewLineAnchor(this).anchorToAddCommentOrSpace(before = false)
var whitespace = addAfter.nextSibling as? PsiWhiteSpace
//TODO: restore blank lines
if (whitespace != null && whitespace.text.contains('\n')) return // line break is already there
if (whitespace == null) {
addAfter.parent.addAfter(psiFactory.createNewLine(), addAfter)
} else {
whitespace.replace(psiFactory.createWhiteSpace("\n" + whitespace.text))
}
needAdjustIndentAfterRestore = true
}
private class Anchor(val element: PsiElement, val treeElementsBetween: Collection<TreeElement>, val before: Boolean)
private fun findAnchor(commentTreeElement: CommentTreeElement, before: Boolean): Anchor? {
val treeElementsBetween = ArrayList<TreeElement>()
val sequence = if (before) commentTreeElement.prevElements else commentTreeElement.nextElements
for (treeElement in sequence) {
val newPsiElements = toNewPsiElementMap[treeElement]
if (newPsiElements != null) {
val psiElement = newPsiElements.first().anchorToAddCommentOrSpace(!before) //TODO: should we restore multiple?
return Anchor(psiElement, treeElementsBetween, before)
}
if (treeElement.firstChild == null) { // we put only leafs into treeElementsBetween
treeElementsBetween.add(treeElement)
}
}
return null
}
private fun PsiElement.anchorToAddCommentOrSpace(before: Boolean): PsiElement {
return parentsWithSelf
.dropWhile { it.parent !is PsiFile && (if (before) it.prevSibling else it.nextSibling) == null }
.first()
}
private fun chooseAnchor(anchorBefore: Anchor?, anchorAfter: Anchor?): Anchor? {
if (anchorBefore == null) return anchorAfter
if (anchorAfter == null) return anchorBefore
val elementsBefore = anchorBefore.treeElementsBetween
val elementsAfter = anchorAfter.treeElementsBetween
val lineBreakBefore = elementsBefore.any { it is LineBreakTreeElement }
val lineBreakAfter = elementsAfter.any { it is LineBreakTreeElement }
if (lineBreakBefore && !lineBreakAfter) return anchorAfter
if (elementsBefore.isNotEmpty() && elementsAfter.isEmpty()) return anchorAfter
return anchorBefore //TODO: more analysis?
}
private fun findFinalAnchorElement(anchor: Anchor, comment: PsiComment): PsiElement {
val tokensBetween = anchor.treeElementsBetween.filterIsInstance<TokenTreeElement>()
fun PsiElement.next(): PsiElement? {
return if (anchor.before) nextLeaf(nonSpaceAndNonEmptyFilter) else prevLeaf(nonSpaceAndNonEmptyFilter)
}
var psiElement = anchor.element
for (token in tokensBetween.asReversed()) {
val next = psiElement.next() ?: break
if (next.tokenType != token.tokenType) break
psiElement = next
}
// don't put end of line comment right before comma
if (anchor.before && comment.tokenType == KtTokens.EOL_COMMENT) {
psiElement = shiftNewLineAnchor(psiElement)
}
return psiElement
}
// don't put line break right before comma
private fun shiftNewLineAnchor(putAfter: PsiElement): PsiElement {
val next = putAfter.nextLeaf(nonSpaceAndNonEmptyFilter)
return if (next?.tokenType == KtTokens.COMMA) next!! else putAfter
}
private val nonSpaceAndNonEmptyFilter = { element: PsiElement -> element !is PsiWhiteSpace && element.textLength > 0 }
companion object {
//TODO: making it private causes error on runtime (KT-7874?)
val PsiElement.tokenType: KtToken?
get() = node.elementType as? KtToken
}
} | plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/util/CommentSaver.kt | 292722964 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.