content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package info.nightscout.androidaps.plugins.general.tidepool.elements
import com.google.gson.annotations.Expose
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.database.entities.TemporaryBasal
import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.utils.DateUtil
import java.util.*
class BasalElement(tbr: TemporaryBasal, private val profile: Profile, dateUtil: DateUtil)
: BaseElement(tbr.timestamp, UUID.nameUUIDFromBytes(("AAPS-basal" + tbr.timestamp).toByteArray()).toString(), dateUtil) {
internal var timestamp: Long = 0 // not exposed
@Expose
internal var deliveryType = "automated"
@Expose
internal var duration: Long = 0
@Expose
internal var rate = -1.0
@Expose
internal var scheduleName = "AAPS"
@Expose
internal var clockDriftOffset: Long = 0
@Expose
internal var conversionOffset: Long = 0
init {
type = "basal"
timestamp = tbr.timestamp
rate = tbr.convertedToAbsolute(tbr.timestamp, profile)
duration = tbr.duration
}
} | app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BasalElement.kt | 2172909430 |
package info.nightscout.androidaps.di
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.widget.WidgetConfigureActivity
import info.nightscout.androidaps.skins.SkinListPreference
import info.nightscout.androidaps.widget.Widget
@Module
@Suppress("unused")
abstract class UIModule {
@ContributesAndroidInjector abstract fun skinListPreferenceInjector(): SkinListPreference
@ContributesAndroidInjector abstract fun aapsWidgetInjector(): Widget
@ContributesAndroidInjector abstract fun contributesWidgetConfigureActivity(): WidgetConfigureActivity
} | app/src/main/java/info/nightscout/androidaps/di/UIModule.kt | 916388470 |
/*
* Copyright (c) 2021. Adventech <[email protected]>
*
* 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 app.ss.media.playback
import android.content.ComponentName
import android.content.Context
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.core.os.bundleOf
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import app.ss.media.playback.extensions.NONE_PLAYBACK_STATE
import app.ss.media.playback.extensions.NONE_PLAYING
import app.ss.media.playback.extensions.duration
import app.ss.media.playback.extensions.isBuffering
import app.ss.media.playback.extensions.isPlaying
import app.ss.media.playback.model.MEDIA_TYPE_AUDIO
import app.ss.media.playback.model.MediaId
import app.ss.media.playback.model.PlaybackModeState
import app.ss.media.playback.model.PlaybackProgressState
import app.ss.media.playback.model.PlaybackQueue
import app.ss.media.playback.model.PlaybackSpeed
import app.ss.media.playback.players.AudioPlayer
import app.ss.media.playback.players.QUEUE_LIST_KEY
import app.ss.models.media.AudioFile
import com.cryart.sabbathschool.core.extensions.coroutines.flow.flowInterval
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
const val PLAYBACK_PROGRESS_INTERVAL = 1000L
interface PlaybackConnection {
val isConnected: StateFlow<Boolean>
val playbackState: StateFlow<PlaybackStateCompat>
val nowPlaying: StateFlow<MediaMetadataCompat>
val playbackQueue: StateFlow<PlaybackQueue>
val playbackProgress: StateFlow<PlaybackProgressState>
val playbackMode: StateFlow<PlaybackModeState>
val playbackSpeed: StateFlow<PlaybackSpeed>
var mediaController: MediaControllerCompat?
val transportControls: MediaControllerCompat.TransportControls?
fun playAudio(audio: AudioFile)
fun playAudios(audios: List<AudioFile>, index: Int = 0)
fun toggleSpeed(playbackSpeed: PlaybackSpeed)
fun setQueue(audios: List<AudioFile>, index: Int = 0)
}
internal class PlaybackConnectionImpl(
context: Context,
serviceComponent: ComponentName,
private val audioPlayer: AudioPlayer,
coroutineScope: CoroutineScope = ProcessLifecycleOwner.get().lifecycleScope
) : PlaybackConnection, CoroutineScope by coroutineScope {
override val isConnected = MutableStateFlow(false)
override val playbackState = MutableStateFlow(NONE_PLAYBACK_STATE)
override val nowPlaying = MutableStateFlow(NONE_PLAYING)
private val playbackQueueState = MutableStateFlow(PlaybackQueue())
override val playbackQueue = playbackQueueState
private var playbackProgressInterval: Job = Job()
override val playbackProgress = MutableStateFlow(PlaybackProgressState())
override val playbackMode = MutableStateFlow(PlaybackModeState())
override val playbackSpeed = MutableStateFlow(PlaybackSpeed.NORMAL)
override var mediaController: MediaControllerCompat? = null
override val transportControls get() = mediaController?.transportControls
private val mediaBrowserConnectionCallback = MediaBrowserConnectionCallback(context)
private val mediaBrowser = MediaBrowserCompat(
context,
serviceComponent,
mediaBrowserConnectionCallback,
null
).apply { connect() }
private var currentProgressInterval: Long = PLAYBACK_PROGRESS_INTERVAL
init {
startPlaybackProgress()
}
override fun playAudio(audio: AudioFile) = playAudios(audios = listOf(audio), index = 0)
override fun playAudios(audios: List<AudioFile>, index: Int) {
val audiosIds = audios.map { it.id }.toTypedArray()
val audio = audios[index]
transportControls?.playFromMediaId(
MediaId(MEDIA_TYPE_AUDIO, audio.id).toString(),
Bundle().apply {
putStringArray(QUEUE_LIST_KEY, audiosIds)
}
)
transportControls?.sendCustomAction(UPDATE_QUEUE, bundleOf())
}
override fun toggleSpeed(playbackSpeed: PlaybackSpeed) {
val nextSpeed = when (playbackSpeed) {
PlaybackSpeed.SLOW -> PlaybackSpeed.NORMAL
PlaybackSpeed.NORMAL -> PlaybackSpeed.FAST
PlaybackSpeed.FAST -> PlaybackSpeed.FASTEST
PlaybackSpeed.FASTEST -> PlaybackSpeed.SLOW
}
audioPlayer.setPlaybackSpeed(nextSpeed.speed)
this.playbackSpeed.value = nextSpeed
resetPlaybackProgressInterval()
}
override fun setQueue(audios: List<AudioFile>, index: Int) {
val audiosIds = audios.map { it.id }
val initialId = audios.getOrNull(index)?.id ?: ""
val playbackQueue = PlaybackQueue(
list = audiosIds,
audiosList = audios,
initialMediaId = initialId,
currentIndex = index
)
this.playbackQueueState.value = playbackQueue
}
private fun startPlaybackProgress() = launch {
combine(playbackState, nowPlaying, ::Pair).collect { (state, current) ->
playbackProgressInterval.cancel()
val duration = current.duration
val position = state.position
if (state == NONE_PLAYBACK_STATE || current == NONE_PLAYING || duration < 1) {
return@collect
}
val initial = PlaybackProgressState(duration, position, buffered = audioPlayer.bufferedPosition())
playbackProgress.value = initial
if (state.isPlaying && !state.isBuffering) {
startPlaybackProgressInterval(initial)
}
}
}
private fun startPlaybackProgressInterval(initial: PlaybackProgressState) {
playbackProgressInterval = launch {
flowInterval(currentProgressInterval).collect {
val current = playbackProgress.value.elapsed
val elapsed = current + PLAYBACK_PROGRESS_INTERVAL
playbackProgress.value = initial.copy(elapsed = elapsed, buffered = audioPlayer.bufferedPosition())
}
}
}
private fun resetPlaybackProgressInterval() {
val speed = playbackSpeed.value.speed
currentProgressInterval = (PLAYBACK_PROGRESS_INTERVAL.toDouble() / speed).toLong()
playbackProgressInterval.cancel()
startPlaybackProgressInterval(playbackProgress.value)
}
private inner class MediaBrowserConnectionCallback(private val context: Context) :
MediaBrowserCompat.ConnectionCallback() {
override fun onConnected() {
mediaController = MediaControllerCompat(context, mediaBrowser.sessionToken).apply {
registerCallback(MediaControllerCallback())
}
isConnected.value = true
}
override fun onConnectionSuspended() {
isConnected.value = false
}
override fun onConnectionFailed() {
isConnected.value = false
}
}
private inner class MediaControllerCallback : MediaControllerCompat.Callback() {
override fun onPlaybackStateChanged(state: PlaybackStateCompat?) {
playbackState.value = state ?: return
}
override fun onMetadataChanged(metadata: MediaMetadataCompat?) {
nowPlaying.value = metadata ?: return
}
override fun onRepeatModeChanged(repeatMode: Int) {
playbackMode.value = playbackMode.value.copy(repeatMode = repeatMode)
}
override fun onShuffleModeChanged(shuffleMode: Int) {
playbackMode.value = playbackMode.value.copy(shuffleMode = shuffleMode)
}
override fun onSessionDestroyed() {
mediaBrowserConnectionCallback.onConnectionSuspended()
}
}
}
| features/media/src/main/kotlin/app/ss/media/playback/PlaybackConnection.kt | 3526911242 |
/*
* Copyright (c) 2022. Adventech <[email protected]>
*
* 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 app.ss.lessons.data.model.api
import androidx.annotation.Keep
import com.squareup.moshi.JsonClass
@Keep
@JsonClass(generateAdapter = true)
internal data class SSLanguage(
val code: String,
val name: String
)
| common/lessons-data/src/main/java/app/ss/lessons/data/model/api/SSLanguage.kt | 118772270 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.platform.js.isJs
import org.jetbrains.kotlin.psi.KtBinaryExpressionWithTypeRHS
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.TypeUtils
class ConvertUnsafeCastToUnsafeCastCallIntention : SelfTargetingIntention<KtBinaryExpressionWithTypeRHS>(
KtBinaryExpressionWithTypeRHS::class.java,
KotlinBundle.lazyMessage("convert.to.unsafecast.call"),
) {
override fun isApplicableTo(element: KtBinaryExpressionWithTypeRHS, caretOffset: Int): Boolean {
if (!element.platform.isJs()) return false
if (element.operationReference.getReferencedNameElementType() != KtTokens.AS_KEYWORD) return false
val right = element.right ?: return false
val context = right.analyze(BodyResolveMode.PARTIAL)
val type = context[BindingContext.TYPE, right] ?: return false
if (TypeUtils.isNullableType(type)) return false
setTextGetter(KotlinBundle.lazyMessage("convert.to.0.unsafecast.1", element.left.text, right.text))
return true
}
override fun applyTo(element: KtBinaryExpressionWithTypeRHS, editor: Editor?) {
val right = element.right ?: return
val newExpression = KtPsiFactory(element).createExpressionByPattern("$0.unsafeCast<$1>()", element.left, right)
element.replace(newExpression)
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertUnsafeCastToUnsafeCastCallIntention.kt | 3312625879 |
package bz.stew.bracken.ui.common.bill.status
import bz.stew.bracken.ui.extension.html.emptyDate
import bz.stew.bracken.ui.common.bill.MajorAction
import bz.stew.bracken.ui.common.bill.emptyMajorAction
import bz.stewart.bracken.shared.data.FixedStatus
import bz.stewart.bracken.shared.data.MajorStatus
import kotlin.js.Date
/**
* Created by stew on 3/4/17.
*/
class BillStatusData(private val fixedStatus: FixedStatus = FixedStatus.NONE,
private val date: Date = emptyDate(),
private val description: String = "",
private val label: String = "",
private val majorActions: Collection<MajorAction> = emptyList()) : BillStatus {
private val lastMajorActionCached: MajorAction =
this.majorActions.maxBy {
val dt = it.date()
dt.getTime()
} ?: emptyMajorAction()
override fun lastMajorAction(): MajorAction {
return this.lastMajorActionCached
}
override fun lastMajorStatus(): MajorStatus {
return this.fixedStatus.lastMajorCompletedStatus
}
override fun fixedStatus(): FixedStatus {
return this.fixedStatus
}
override fun date(): Date {
return this.date
}
override fun description(): String {
return this.description
}
override fun label(): String {
return this.label
}
override fun majorActions(): Collection<MajorAction> {
return this.majorActions
}
}
private val emptyBillStatusData: BillStatus = BillStatusData(
majorActions = listOf(emptyMajorAction()))
fun emptyBillStatus(): BillStatus {
return emptyBillStatusData
}
| ui/src/main/kotlin/bz/stew/bracken/ui/common/bill/status/BillStatusData.kt | 1528247786 |
package com.bajdcc.util.lexer.regex
/**
* 正则表达式部件接口(父类)
*
* @author bajdcc
*/
interface IRegexComponent {
/**
* 设定扩展自身结点的方式
*
* @param visitor 递归遍历算法
*/
fun visit(visitor: IRegexComponentVisitor)
}
| src/main/kotlin/com/bajdcc/util/lexer/regex/IRegexComponent.kt | 1543210769 |
package com.fsck.k9.preferences.migrations
import android.database.sqlite.SQLiteDatabase
/**
* Rewrite frequencies lower than LOWEST_FREQUENCY_SUPPORTED
*/
class StorageMigrationTo5(
private val db: SQLiteDatabase,
private val migrationsHelper: StorageMigrationsHelper
) {
fun fixMailCheckFrequencies() {
val accountUuidsListValue = migrationsHelper.readValue(db, "accountUuids")
if (accountUuidsListValue == null || accountUuidsListValue.isEmpty()) {
return
}
val accountUuids = accountUuidsListValue.split(",")
for (accountUuid in accountUuids) {
fixFrequencyForAccount(accountUuid)
}
}
private fun fixFrequencyForAccount(accountUuid: String) {
val key = "$accountUuid.automaticCheckIntervalMinutes"
val frequencyValue = migrationsHelper.readValue(db, key)?.toIntOrNull()
if (frequencyValue != null && frequencyValue > -1 && frequencyValue < LOWEST_FREQUENCY_SUPPORTED) {
migrationsHelper.writeValue(db, key, LOWEST_FREQUENCY_SUPPORTED.toString())
}
}
companion object {
// see: https://github.com/evernote/android-job/wiki/FAQ#why-cant-an-interval-be-smaller-than-15-minutes-for-periodic-jobs
private const val LOWEST_FREQUENCY_SUPPORTED = 15
}
}
| app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo5.kt | 785713691 |
package com.johnny.gank.model.ui
import com.johnny.gank.model.entity.Gank
import java.util.*
/*
* Copyright (C) 2015 Johnny Shieh 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.
*/
/**
* Unified data model for all sorts of gank items
* @author Johnny Shieh
* *
* @version 1.0
*/
interface GankItem
data class GankHeaderItem(var name: String = "") : GankItem
data class GankNormalItem(
var page: Int = -1,
var gank: Gank = Gank()
) : GankItem {
companion object {
fun newGankList(gankList: List<Gank>?): List<GankNormalItem> {
if (null == gankList || gankList.isEmpty()) {
return arrayListOf()
}
return gankList.map { GankNormalItem(gank = it) }
}
fun newGankList(gankList: List<Gank>?, pageIndex: Int): List<GankNormalItem> {
if (null == gankList || gankList.isEmpty()) {
return arrayListOf()
}
return gankList.map { GankNormalItem(page = pageIndex, gank = it) }
}
}
}
data class GankGirlImageItem(
var imgUrl: String = "",
var publishedAt: Date = Date()
) : GankItem {
companion object {
fun newImageItem(gank: Gank): GankGirlImageItem {
return GankGirlImageItem(gank.url, gank.publishedAt)
}
}
}
| app/src/main/kotlin/com/johnny/gank/model/ui/GankItem.kt | 2279253972 |
/**
* 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.apihook;
data class Column(val name: String, val location: String, val status: String, val color: Int)
| src/main/java/io/lavagna/model/apihook/Column.kt | 260594632 |
package org.wordpress.android.ui.posts.prepublishing.home.usecases
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.post.PostStatus
import org.wordpress.android.fluxc.model.post.PostStatus.SCHEDULED
import org.wordpress.android.ui.posts.EditPostRepository
import org.wordpress.android.util.DateTimeUtilsWrapper
import javax.inject.Inject
class PublishPostImmediatelyUseCase @Inject constructor(private val dateTimeUtilsWrapper: DateTimeUtilsWrapper) {
fun updatePostToPublishImmediately(
editPostRepository: EditPostRepository,
isNewPost: Boolean
) {
editPostRepository.updateAsync({ postModel: PostModel ->
if (postModel.status == SCHEDULED.toString()) {
postModel.setDateCreated(dateTimeUtilsWrapper.currentTimeInIso8601())
}
// when the post is a Draft, Publish Now is shown as the Primary Action but if it's already Published then
// Update Now is shown.
if (isNewPost) {
postModel.setStatus(PostStatus.DRAFT.toString())
} else {
postModel.setStatus(PostStatus.PUBLISHED.toString())
}
true
})
}
}
| WordPress/src/main/java/org/wordpress/android/ui/posts/prepublishing/home/usecases/PublishPostImmediatelyUseCase.kt | 3333544166 |
package com.msa.reduxed.presentation.di
import javax.inject.Named
@Named
annotation class AndroidScheduler
| reduxed/src/main/java/com/msa/reduxed/presentation/di/AndroidScheduler.kt | 1156562266 |
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* 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 com.kotlinnlp.simplednn.core.optimizer
import com.kotlinnlp.simplednn.core.functionalities.gradientclipping.GradientClipping
import com.kotlinnlp.simplednn.core.functionalities.updatemethods.UpdateMethod
import com.kotlinnlp.simplednn.utils.scheduling.BatchScheduling
import com.kotlinnlp.simplednn.utils.scheduling.EpochScheduling
import com.kotlinnlp.simplednn.utils.scheduling.ExampleScheduling
/**
* The optimizer of neural parameters.
*
* @param updateMethod the update method helper (Learning Rate, ADAM, AdaGrad, ...)
* @param gradientClipping the gradient clipper (default null)
*/
class ParamsOptimizer(
private val updateMethod: UpdateMethod<*>,
private val gradientClipping: GradientClipping? = null
) : ParamsErrorsAccumulator(), ScheduledUpdater {
/**
* Calculate the errors average, update the parameters.
*/
override fun update() {
if (this.isNotEmpty) {
this.clipGradients()
this.updateParams()
this.clear()
}
}
/**
* Method to call every new epoch.
* In turn it calls the same method into the `updateMethod`
*/
override fun newEpoch() {
if (this.updateMethod is EpochScheduling) {
this.updateMethod.newEpoch()
}
}
/**
* Method to call every new batch.
* In turn it calls the same method into the `updateMethod`
*/
override fun newBatch() {
if (this.updateMethod is BatchScheduling) {
this.updateMethod.newBatch()
}
}
/**
* Method to call every new example.
* In turn it calls the same method into the `updateMethod`
*/
override fun newExample() {
if (this.updateMethod is ExampleScheduling) {
this.updateMethod.newExample()
}
}
/**
* Update the parameters in respect of the errors using the update method helper (Learning Rate, ADAM, AdaGrad, ...).
*/
private fun updateParams() {
this.getParamsErrors(copy = false).forEach { errors ->
this.updateMethod.update(array = errors.refParams, errors = errors.values)
}
}
/**
* Perform the gradient clipping.
*/
private fun clipGradients() {
this.gradientClipping?.clip(this.getParamsErrors(copy = false))
}
}
| src/main/kotlin/com/kotlinnlp/simplednn/core/optimizer/ParamsOptimizer.kt | 3204208243 |
fun foo(bar: Int) {
0 <= bar && bar < 10<caret>
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/lteqlt.kt | 769488090 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.hints.codeVision
import com.intellij.codeInsight.codeVision.*
import com.intellij.codeInsight.codeVision.ui.model.ClickableTextCodeVisionEntry
import com.intellij.codeInsight.hints.InlayHintsUtils
import com.intellij.codeInsight.hints.settings.language.isInlaySettingsEditor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.SyntaxTraverser
import java.awt.event.MouseEvent
abstract class CodeVisionProviderBase : DaemonBoundCodeVisionProvider {
/**
* WARNING! This method is executed also before the file is open. It must be fast! During it users see no editor.
* @return true iff this provider may provide lenses for this file.
*/
abstract fun acceptsFile(file: PsiFile): Boolean
/**
* WARNING! This method is executed also before the file is open. It must be fast! During it users see no editor.
* @return true iff this provider may provide lenses for this element.
*/
abstract fun acceptsElement(element: PsiElement): Boolean
/**
* @return text that user sees for a given element as a code lens
*/
abstract fun getHint(element: PsiElement, file: PsiFile): String?
open fun logClickToFUS(element: PsiElement) {}
override fun computeForEditor(editor: Editor, file: PsiFile): List<Pair<TextRange, CodeVisionEntry>> {
if (!acceptsFile(file)) return emptyList()
// we want to let this provider work only in tests dedicated for code vision, otherwise they harm performance
if (ApplicationManager.getApplication().isUnitTestMode && !CodeVisionHost.isCodeLensTest(editor)) return emptyList()
val lenses = ArrayList<Pair<TextRange, CodeVisionEntry>>()
val traverser = SyntaxTraverser.psiTraverser(file)
for (element in traverser) {
if (!acceptsElement(element)) continue
if (!InlayHintsUtils.isFirstInLine(element)) continue
val hint = getHint(element, file)
if (hint == null) continue
val handler = ClickHandler(element)
val range = InlayHintsUtils.getTextRangeWithoutLeadingCommentsAndWhitespaces(element)
lenses.add(range to ClickableTextCodeVisionEntry(hint, id, handler))
}
return lenses
}
private inner class ClickHandler(
element: PsiElement
) : (MouseEvent?, Editor) -> Unit {
private val elementPointer = SmartPointerManager.createPointer(element)
override fun invoke(event: MouseEvent?, editor: Editor) {
if (isInlaySettingsEditor(editor)) return
val element = elementPointer.element ?: return
logClickToFUS(element)
handleClick(editor, element, event)
}
}
abstract fun handleClick(editor: Editor, element: PsiElement, event: MouseEvent?)
override fun getPlaceholderCollector(editor: Editor, psiFile: PsiFile?): CodeVisionPlaceholderCollector? {
if (psiFile == null || !acceptsFile(psiFile)) return null
return object: BypassBasedPlaceholderCollector {
override fun collectPlaceholders(element: PsiElement, editor: Editor): List<TextRange> {
if (!acceptsElement(element)) return emptyList()
val range = InlayHintsUtils.getTextRangeWithoutLeadingCommentsAndWhitespaces(element)
return listOf(range)
}
}
}
override val defaultAnchor: CodeVisionAnchorKind
get() = CodeVisionAnchorKind.Default
} | platform/lang-impl/src/com/intellij/codeInsight/hints/codeVision/CodeVisionProviderBase.kt | 1863181535 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.fir.analysisApiProviders
import com.intellij.lang.ASTNode
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.Disposable
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.pom.PomManager
import com.intellij.pom.PomModelAspect
import com.intellij.pom.event.PomModelEvent
import com.intellij.pom.event.PomModelListener
import com.intellij.pom.tree.TreeAspect
import com.intellij.pom.tree.events.TreeChangeEvent
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.FileElement
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.analysis.low.level.api.fir.element.builder.getNonLocalContainingInBodyDeclarationWith
import org.jetbrains.kotlin.analysis.low.level.api.fir.file.structure.isReanalyzableContainer
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.util.module
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
internal class FirIdeModificationTrackerService(project: Project) : Disposable {
init {
PomManager.getModel(project).addModelListener(Listener())
}
private val _projectGlobalOutOfBlockInKotlinFilesModificationCount = AtomicLong()
val projectGlobalOutOfBlockInKotlinFilesModificationCount: Long
get() = _projectGlobalOutOfBlockInKotlinFilesModificationCount.get()
fun getOutOfBlockModificationCountForModules(module: Module): Long =
moduleModificationsState.getModificationsCountForModule(module)
private val moduleModificationsState = ModuleModificationsState()
private val treeAspect = TreeAspect.getInstance(project)
override fun dispose() {}
fun increaseModificationCountForAllModules() {
_projectGlobalOutOfBlockInKotlinFilesModificationCount.incrementAndGet()
moduleModificationsState.increaseModificationCountForAllModules()
}
@TestOnly
fun increaseModificationCountForModule(module: Module) {
moduleModificationsState.increaseModificationCountForModule(module)
}
private inner class Listener : PomModelListener {
override fun isAspectChangeInteresting(aspect: PomModelAspect): Boolean =
treeAspect == aspect
override fun modelChanged(event: PomModelEvent) {
val changeSet = event.getChangeSet(treeAspect) as TreeChangeEvent? ?: return
val psi = changeSet.rootElement.psi
val changedElements = changeSet.changedElements
handleChangedElementsInAllModules(changedElements, changeSet, psi)
}
private fun handleChangedElementsInAllModules(
changedElements: Array<out ASTNode>,
changeSet: TreeChangeEvent,
changeSetRootElementPsi: PsiElement
) {
if (!changeSetRootElementPsi.isPhysical) {
/**
* Element which do not belong to a project should not cause OOBM
*/
return
}
if (changedElements.isEmpty()) {
incrementModificationCountForFileChange(changeSet)
} else {
incrementModificationCountForSpecificElements(changedElements, changeSet, changeSetRootElementPsi)
}
}
private fun incrementModificationCountForSpecificElements(
changedElements: Array<out ASTNode>,
changeSet: TreeChangeEvent,
changeSetRootElementPsi: PsiElement
) {
require(changedElements.isNotEmpty())
var isOutOfBlockChangeInAnyModule = false
changedElements.forEach { element ->
val isOutOfBlock = element.isOutOfBlockChange(changeSet, changeSetRootElementPsi)
isOutOfBlockChangeInAnyModule = isOutOfBlockChangeInAnyModule || isOutOfBlock
if (isOutOfBlock) {
incrementModificationTrackerForContainingModule(element)
}
}
if (isOutOfBlockChangeInAnyModule) {
_projectGlobalOutOfBlockInKotlinFilesModificationCount.incrementAndGet()
}
}
private fun incrementModificationCountForFileChange(changeSet: TreeChangeEvent) {
val fileElement = changeSet.rootElement as FileElement ?: return
incrementModificationTrackerForContainingModule(fileElement)
_projectGlobalOutOfBlockInKotlinFilesModificationCount.incrementAndGet()
}
private fun incrementModificationTrackerForContainingModule(element: ASTNode) {
element.psi.module?.let { module ->
moduleModificationsState.increaseModificationCountForModule(module)
}
}
private fun ASTNode.isOutOfBlockChange(changeSet: TreeChangeEvent, changeSetRootElementPsi: PsiElement): Boolean {
return when (changeSetRootElementPsi.language) {
KotlinLanguage.INSTANCE -> {
val nodes = changeSet.getChangesByElement(this).affectedChildren
nodes.any(::isOutOfBlockChange)
}
JavaLanguage.INSTANCE -> {
true // TODO improve for Java KTIJ-21684
}
else -> {
// Any other language may cause OOBM in Kotlin too
true
}
}
}
private fun isOutOfBlockChange(node: ASTNode): Boolean {
val psi = node.psi ?: return true
if (!psi.isValid) {
/**
* If PSI is not valid, well something bad happened, OOBM won't hurt
*/
return true
}
val container = psi.getNonLocalContainingInBodyDeclarationWith() ?: return true
return !isReanalyzableContainer(container)
}
}
}
private class ModuleModificationsState {
private val modificationCountForModule = ConcurrentHashMap<Module, ModuleModifications>()
private val state = AtomicLong()
fun getModificationsCountForModule(module: Module) = modificationCountForModule.compute(module) { _, modifications ->
val currentState = state.get()
when {
modifications == null -> ModuleModifications(0, currentState)
modifications.state == currentState -> modifications
else -> ModuleModifications(modificationsCount = modifications.modificationsCount + 1, state = currentState)
}
}!!.modificationsCount
fun increaseModificationCountForAllModules() {
state.incrementAndGet()
}
fun increaseModificationCountForModule(module: Module) {
modificationCountForModule.compute(module) { _, modifications ->
val currentState = state.get()
when (modifications) {
null -> ModuleModifications(0, currentState)
else -> ModuleModifications(modifications.modificationsCount + 1, currentState)
}
}
}
private data class ModuleModifications(val modificationsCount: Long, val state: Long)
} | plugins/kotlin/base/fir/analysis-api-providers/src/org/jetbrains/kotlin/idea/base/fir/analysisApiProviders/FirIdeModificationTrackerService.kt | 2506980984 |
// Copyright (c) 2017 Alexander Håkansson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package se.creotec.chscardbalance2.controller
import android.support.design.widget.AppBarLayout
abstract class AppBarStateChangeListener : AppBarLayout.OnOffsetChangedListener {
enum class State {
EXPANDED,
COLLAPSED,
IDLE
}
private var currentState = State.IDLE
override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
appBarLayout?.let {
if (verticalOffset == 0) {
if (currentState != State.EXPANDED) {
onStateChanged(it, State.EXPANDED)
}
currentState = State.EXPANDED;
} else if (Math.abs(verticalOffset) >= it.totalScrollRange) {
if (currentState != State.COLLAPSED) {
onStateChanged(it, State.COLLAPSED)
}
currentState = State.COLLAPSED
} else {
if (currentState != State.IDLE) {
onStateChanged(it, State.IDLE)
}
}
}
}
abstract fun onStateChanged(appBarLayout: AppBarLayout, state: State)
} | app/src/main/java/se/creotec/chscardbalance2/controller/AppBarStateChangeListener.kt | 1692444458 |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.data.model
import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity
import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic
fun NetworkTopic.asEntity() = TopicEntity(
id = id,
name = name,
shortDescription = shortDescription,
longDescription = longDescription,
url = url,
imageUrl = imageUrl
)
| core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/model/Topic.kt | 2785890193 |
@file:Suppress("MemberVisibilityCanBePrivate")
package instep.dao.sql
import com.alibaba.druid.pool.DruidDataSource
import instep.Instep
import instep.InstepLogger
import instep.InstepLoggerFactory
import instep.dao.sql.dialect.HSQLDialect
import instep.dao.sql.dialect.MySQLDialect
import instep.dao.sql.dialect.SQLServerDialect
import instep.dao.sql.impl.DefaultConnectionProvider
import net.moznion.random.string.RandomStringGenerator
import org.testng.Assert
import org.testng.annotations.AfterClass
import org.testng.annotations.BeforeClass
import org.testng.annotations.Test
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
object InstepSQLTest {
val stringGenerator = RandomStringGenerator()
val datasourceUrl: String = System.getenv("instep.test.jdbc_url")
val dialect = Dialect.of(datasourceUrl)
val datasource = DruidDataSource()
object TransactionTable : Table("transaction_" + stringGenerator.generateByRegex("[a-z]{8}"), "transaction test", dialect) {
val id = autoIncrementLong("id").primary()
val name = varchar("name", 256).notnull()
}
init {
datasource.url = datasourceUrl
datasource.initialSize = 1
datasource.minIdle = 1
datasource.maxActive = 2
datasource.timeBetweenEvictionRunsMillis = 60000
datasource.minEvictableIdleTimeMillis = 300000
datasource.isTestWhileIdle = true
datasource.maxPoolPreparedStatementPerConnectionSize = 16
Instep.bind(ConnectionProvider::class.java, DefaultConnectionProvider(datasource, dialect))
val factory = object : InstepLoggerFactory {
override fun getLogger(cls: Class<*>): InstepLogger {
return object : InstepLogger {
var msg = ""
var context = mutableMapOf<String, Any>()
var t: Throwable? = null
override fun message(message: String): InstepLogger {
msg = message
return this
}
override fun exception(e: Throwable): InstepLogger {
t = e
return this
}
override fun context(key: String, value: Any): InstepLogger {
context[key] = value
return this
}
override fun context(key: String, lazy: () -> String): InstepLogger {
context[key] = lazy.invoke()
return this
}
override fun trace() {
println(msg)
println(context)
}
override fun debug() {
println(msg)
println(context)
}
override fun info() {
println(msg)
println(context)
}
override fun warn() {
System.err.println(msg)
System.err.println(context)
}
override fun error() {
System.err.println(msg)
System.err.println(context)
}
}
}
}
Instep.bind(InstepLoggerFactory::class.java, factory)
InstepLogger.factory = factory
}
@BeforeClass
fun init() {
TransactionTable.create().debug().execute()
}
@AfterClass
fun cleanUp() {
TransactionTable.drop().execute()
}
@Test
fun executeScalar() {
val scalar = when (dialect) {
is HSQLDialect -> InstepSQL.plan("""VALUES(to_char(current_timestamp, 'YYYY-MM-DD HH24\:MI\:SS'))""").executeString()
is MySQLDialect -> InstepSQL.plan("""SELECT date_format(current_timestamp, '%Y-%m-%d %k\:%i\:%S')""").executeString()
is SQLServerDialect -> InstepSQL.plan("""SELECT format(current_timestamp, 'yyyy-MM-dd HH:mm:ss')""").executeString()
else -> InstepSQL.plan("""SELECT to_char(current_timestamp, 'YYYY-MM-DD HH24:MI:SS')""").executeString()
}
LocalDateTime.parse(scalar, DateTimeFormatter.ofPattern("""yyyy-MM-dd HH:mm:ss"""))
Assert.assertEquals(InstepSQL.plan("""SELECT NULL""").executeLong(), 0)
}
@Test
fun transaction() {
InstepSQL.transaction().committed {
val row = TableRow()
row[TransactionTable.name] = stringGenerator.generateByRegex("\\w{8,64}")
TransactionTable[1] = row
}
assert(TransactionTable[1] != null)
InstepSQL.transaction().serializable {
val row = TableRow()
row[TransactionTable.name] = stringGenerator.generateByRegex("\\w{8,64}")
TransactionTable[2] = row
abort()
}
assert(TransactionTable[2] == null)
Assert.assertEquals(TransactionTable.selectExpression(TransactionTable.id.count()).distinct().executeLong(), 1)
}
} | dao/src/test/kotlin/instep/dao/sql/InstepSQLTest.kt | 2160546490 |
import TemplateLintUtil.Companion.isTemplateLintConfigFile
import com.intellij.lang.javascript.linter.JSLinterConfigChangeTracker
import com.intellij.lang.javascript.linter.JSLinterConfiguration
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
class TemplateLintConfigFileChangeTracker(project: Project) : JSLinterConfigChangeTracker(project, ::isTemplateLintConfigFile) {
override fun isAnalyzerRestartNeeded(project: Project, file: VirtualFile): Boolean {
return TemplateLintConfiguration.getInstance(project).extendedState.isEnabled
}
}
| src/main/kotlin/com/emberjs/hbs/linter/ember-template-lint/config/TemplateLintConfigFileChangeTracker.kt | 2540936575 |
package com.eden.orchid.kotlindoc.menu
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.theme.menus.MenuItem
import com.eden.orchid.api.theme.menus.OrchidMenuFactory
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.kotlindoc.model.KotlindocModel
@Description("All Kotlindoc class pages.", name = "Kotlindoc Classes")
class AllClassesMenuItemType : OrchidMenuFactory("kotlindocClasses") {
@Option
@StringDefault("All Classes")
lateinit var title: String
override fun getMenuItems(
context: OrchidContext,
page: OrchidPage
): List<MenuItem> {
val model = context.resolve(KotlindocModel::class.java)
val items = ArrayList<MenuItem>()
val pages = ArrayList<OrchidPage>(model.allClasses)
pages.sortBy { it.title }
items.add(MenuItem.Builder(context)
.title(title)
.pages(pages)
.build()
)
return items
}
}
| plugins/OrchidKotlindoc/src/main/kotlin/com/eden/orchid/kotlindoc/menu/AllClassesMenuItemType.kt | 4220031006 |
/*
* Copyright (C) 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 com.intellij.diagnostic.hprof.visitors
import com.intellij.diagnostic.hprof.classstore.ClassDefinition
import com.intellij.diagnostic.hprof.classstore.ClassStore
import com.intellij.diagnostic.hprof.parser.*
import com.intellij.diagnostic.hprof.util.FileChannelBackedWriteBuffer
import com.intellij.openapi.diagnostic.Logger
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
internal class CreateAuxiliaryFilesVisitor(
private val auxOffsetsChannel: FileChannel,
private val auxChannel: FileChannel,
private val classStore: ClassStore,
private val parser: HProfEventBasedParser
) : HProfVisitor() {
private lateinit var offsets: FileChannelBackedWriteBuffer
private lateinit var aux: FileChannelBackedWriteBuffer
private var directByteBufferClass: ClassDefinition? = null
private var directByteBufferCapacityOffset: Int = 0
private var directByteBufferFdOffset: Int = 0
private var stringClass: ClassDefinition? = null
private var stringCoderOffset: Int = -1
companion object {
private val LOG = Logger.getInstance(CreateAuxiliaryFilesVisitor::class.java)
}
override fun preVisit() {
disableAll()
enable(HeapDumpRecordType.ClassDump)
enable(HeapDumpRecordType.InstanceDump)
enable(HeapDumpRecordType.ObjectArrayDump)
enable(HeapDumpRecordType.PrimitiveArrayDump)
offsets = FileChannelBackedWriteBuffer(auxOffsetsChannel)
aux = FileChannelBackedWriteBuffer(auxChannel)
directByteBufferClass = null
val dbbClass = classStore.getClassIfExists("java.nio.DirectByteBuffer")
if (dbbClass != null) {
directByteBufferClass = dbbClass
directByteBufferCapacityOffset = dbbClass.computeOffsetOfField("capacity", classStore)
directByteBufferFdOffset = dbbClass.computeOffsetOfField("fd", classStore)
if (directByteBufferCapacityOffset == -1 || directByteBufferFdOffset == -1) {
LOG.error("DirectByteBuffer.capacity and/or .fd field is missing.")
}
}
stringClass = classStore.getClassIfExists("java.lang.String")
stringClass?.let {
stringCoderOffset = it.computeOffsetOfField("coder", classStore)
}
// Map id=0 to 0
offsets.writeInt(0)
}
override fun postVisit() {
aux.close()
offsets.close()
}
override fun visitPrimitiveArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, numberOfElements: Long, elementType: Type, primitiveArrayData: ByteBuffer) {
assert(arrayObjectId <= Int.MAX_VALUE)
assert(offsets.position() / 4 == arrayObjectId.toInt())
offsets.writeInt(aux.position())
aux.writeId(classStore.getClassForPrimitiveArray(elementType)!!.id.toInt())
assert(numberOfElements <= Int.MAX_VALUE) // arrays in java don't support more than Int.MAX_VALUE elements
aux.writeNonNegativeLEB128Int(numberOfElements.toInt())
primitiveArrayData.mark()
aux.writeBytes(primitiveArrayData)
primitiveArrayData.reset()
}
override fun visitClassDump(classId: Long,
stackTraceSerialNumber: Long,
superClassId: Long,
classloaderClassId: Long,
instanceSize: Long,
constants: Array<ConstantPoolEntry>,
staticFields: Array<StaticFieldEntry>,
instanceFields: Array<InstanceFieldEntry>) {
assert(classId <= Int.MAX_VALUE)
assert(offsets.position() / 4 == classId.toInt())
offsets.writeInt(aux.position())
aux.writeId(0) // Special value for class definitions, to differentiate from regular java.lang.Class instances
}
override fun visitObjectArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, arrayClassObjectId: Long, objects: LongArray) {
assert(arrayObjectId <= Int.MAX_VALUE)
assert(arrayClassObjectId <= Int.MAX_VALUE)
assert(offsets.position() / 4 == arrayObjectId.toInt())
offsets.writeInt(aux.position())
aux.writeId(arrayClassObjectId.toInt())
val nonNullElementsCount = objects.count { it != 0L }
val nullElementsCount = objects.count() - nonNullElementsCount
// To minimize serialized size, store (nullElementsCount, nonNullElementsCount) pair instead of
// (objects.count, nonNullElementsCount) pair.
aux.writeNonNegativeLEB128Int(nullElementsCount)
aux.writeNonNegativeLEB128Int(nonNullElementsCount)
objects.forEach {
if (it == 0L) return@forEach
assert(it <= Int.MAX_VALUE)
aux.writeId(it.toInt())
}
}
override fun visitInstanceDump(objectId: Long, stackTraceSerialNumber: Long, classObjectId: Long, bytes: ByteBuffer) {
assert(objectId <= Int.MAX_VALUE)
assert(classObjectId <= Int.MAX_VALUE)
assert(offsets.position() / 4 == objectId.toInt())
offsets.writeInt(aux.position())
aux.writeId(classObjectId.toInt())
var classOffset = 0
val objectClass = classStore[classObjectId]
run {
var classDef: ClassDefinition = objectClass
do {
classDef.refInstanceFields.forEach {
val offset = classOffset + it.offset
val value = bytes.getLong(offset)
if (value == 0L) {
aux.writeId(0)
}
else {
// bytes are just raw data. IDs have to be mapped manually.
val reference = parser.remap(value)
assert(reference != 0L)
aux.writeId(reference.toInt())
}
}
classOffset += classDef.superClassOffset
if (classDef.superClassId == 0L) {
break
}
classDef = classStore[classDef.superClassId]
}
while (true)
}
// DirectByteBuffer class contains additional field with buffer capacity.
if (objectClass == directByteBufferClass) {
if (directByteBufferCapacityOffset == -1 || directByteBufferFdOffset == -1) {
aux.writeNonNegativeLEB128Int(1)
}
else {
val directByteBufferCapacity = bytes.getInt(directByteBufferCapacityOffset)
val directByteBufferFd = bytes.getLong(directByteBufferFdOffset)
if (directByteBufferFd == 0L) {
// When fd == 0, the buffer is directly allocated in memory.
aux.writeNonNegativeLEB128Int(directByteBufferCapacity)
}
else {
// File-mapped buffer
aux.writeNonNegativeLEB128Int(1)
}
}
}
else if (objectClass == stringClass) {
if (stringCoderOffset == -1) {
aux.writeByte(-1)
}
else {
aux.writeByte(bytes.get(stringCoderOffset))
}
}
}
private fun FileChannelBackedWriteBuffer.writeId(id: Int) {
// Use variable-length Int for IDs to save space
this.writeNonNegativeLEB128Int(id)
}
}
| platform/platform-impl/src/com/intellij/diagnostic/hprof/visitors/CreateAuxiliaryFilesVisitor.kt | 90112186 |
fun foo(minus : String.(String) -> Unit) {
"A" <selection>-</selection> "B"
} | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/basic/convertBinaryExpression.kt | 470921001 |
object Test {
@JvmStatic
fun main(args: Array<String>) {
for (i in 0 until 1 + 1) {
}
}
}
| plugins/kotlin/j2k/new/tests/testData/newJ2k/for/withInfixCallCondition.kt | 3322584505 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.nj2k.conversions
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase
import org.jetbrains.kotlin.nj2k.psi
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.tree.JKClass.ClassKind.*
import org.jetbrains.kotlin.nj2k.tree.Modality.*
import org.jetbrains.kotlin.nj2k.tree.Visibility.PRIVATE
class ModalityConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
when (element) {
is JKClass -> element.process()
is JKMethod -> element.process()
is JKField -> element.process()
}
return recurse(element)
}
private fun JKClass.process() {
modality = when {
classKind == ENUM || classKind == RECORD -> FINAL
classKind == INTERFACE -> OPEN
modality == OPEN && context.converter.settings.openByDefault -> OPEN
modality == OPEN && !hasInheritors(psi as PsiClass) -> FINAL
else -> modality
}
}
private fun hasInheritors(psiClass: PsiClass): Boolean =
context.converter.converterServices.oldServices.referenceSearcher.hasInheritors(psiClass)
private fun JKMethod.process() {
val psiMethod = psi<PsiMethod>() ?: return
val containingClass = parentOfType<JKClass>() ?: return
when {
visibility == PRIVATE -> modality = FINAL
modality != ABSTRACT && psiMethod.findSuperMethods().isNotEmpty() -> {
modality = FINAL
if (!hasOtherModifier(OtherModifier.OVERRIDE)) {
otherModifierElements += JKOtherModifierElement(OtherModifier.OVERRIDE)
}
}
modality == OPEN
&& context.converter.settings.openByDefault
&& containingClass.modality == OPEN
&& visibility != PRIVATE -> {
modality = OPEN
}
modality == OPEN
&& containingClass.classKind != INTERFACE
&& !hasOverrides(psiMethod) -> {
modality = FINAL
}
else -> modality = modality
}
}
private fun hasOverrides(psiMethod: PsiMethod): Boolean =
context.converter.converterServices.oldServices.referenceSearcher.hasOverrides(psiMethod)
private fun JKField.process() {
val containingClass = parentOfType<JKClass>() ?: return
if (containingClass.classKind == INTERFACE) modality = FINAL
}
} | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/ModalityConversion.kt | 1608971562 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vfs.encoding
import com.intellij.ide.IdeBundle
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.vfs.encoding.EncodingProjectManagerImpl.BOMForNewUTF8Files
import com.intellij.ui.EnumComboBoxModel
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.dsl.builder.*
import java.awt.event.ItemListener
import javax.swing.JComponent
class FileEncodingConfigurableUI {
lateinit var transparentNativeToAsciiCheckBox: JBCheckBox
lateinit var bomForUTF8Combo: ComboBox<BOMForNewUTF8Files>
private lateinit var bomForUTF8ComboCell: Cell<ComboBox<BOMForNewUTF8Files>>
fun createContent(tablePanel: JComponent, filesEncodingCombo: JComponent): DialogPanel {
return panel {
row {
cell(tablePanel).align(Align.FILL)
}.resizableRow()
.bottomGap(BottomGap.SMALL)
row(IdeBundle.message("editbox.default.encoding.for.properties.files")) {
cell(filesEncodingCombo)
}
indent {
row {
transparentNativeToAsciiCheckBox = checkBox(IdeBundle.message("checkbox.transparent.native.to.ascii.conversion")).component
}.bottomGap(BottomGap.SMALL)
}
row(IdeBundle.message("file.encoding.option.create.utf8.files")) {
bomForUTF8ComboCell = comboBox(EnumComboBoxModel(BOMForNewUTF8Files::class.java)).applyToComponent {
addItemListener(ItemListener { updateExplanationLabelText() })
}.comment("")
bomForUTF8Combo = bomForUTF8ComboCell.component
}.layout(RowLayout.INDEPENDENT)
}
}
private fun updateExplanationLabelText() {
val item = bomForUTF8ComboCell.component.selectedItem as BOMForNewUTF8Files
val productName = ApplicationNamesInfo.getInstance().productName
val comment = when (item) {
BOMForNewUTF8Files.ALWAYS -> IdeBundle.message("file.encoding.option.warning.always", productName)
BOMForNewUTF8Files.NEVER -> IdeBundle.message("file.encoding.option.warning.never", productName)
BOMForNewUTF8Files.WINDOWS_ONLY -> IdeBundle.message("file.encoding.option.warning.windows.only", productName)
}
bomForUTF8ComboCell.comment?.text = comment
}
} | platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurableUI.kt | 3602969630 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.completion
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.pom.PomManager
import com.intellij.pom.core.impl.PomModelImpl
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.source.tree.FileElement
import java.util.function.Supplier
class OffsetsInFile(val file: PsiFile, val offsets: OffsetMap) {
constructor(file: PsiFile) : this(file, OffsetMap(file.viewProvider.document!!))
fun toTopLevelFile(): OffsetsInFile {
val manager = InjectedLanguageManager.getInstance(file.project)
val hostFile = manager.getTopLevelFile(file)
if (hostFile == file) return this
return OffsetsInFile(hostFile, offsets.mapOffsets(hostFile.viewProvider.document!!) { manager.injectedToHost(file, it) })
}
fun toInjectedIfAny(offset: Int): OffsetsInFile {
val manager = InjectedLanguageManager.getInstance(file.project)
val injected = manager.findInjectedElementAt(file, offset)?.containingFile ?: return this
val virtualFile = injected.virtualFile
if (virtualFile is VirtualFileWindow) {
val documentWindow = virtualFile.documentWindow
return OffsetsInFile(injected, offsets.mapOffsets(
documentWindow) { documentWindow.hostToInjected(it) })
}
else {
return this
}
}
fun copyWithReplacement(startOffset: Int, endOffset: Int, replacement: String): OffsetsInFile {
return replaceInCopy(file.copy() as PsiFile, startOffset, endOffset, replacement).get()
}
fun replaceInCopy(fileCopy: PsiFile, startOffset: Int, endOffset: Int, replacement: String): Supplier<OffsetsInFile> {
val originalText = offsets.document.immutableCharSequence
val tempDocument = DocumentImpl(originalText, originalText.contains('\r') || replacement.contains('\r'), true)
val tempMap = offsets.copyOffsets(tempDocument)
tempDocument.replaceString(startOffset, endOffset, replacement)
val copyDocument = fileCopy.viewProvider.document!!
val node = fileCopy.node as? FileElement
?: throw IllegalStateException("Node is not a FileElement ${fileCopy.javaClass.name} / ${fileCopy.fileType} / ${fileCopy.node}")
val applyPsiChange = (PomManager.getModel(file.project) as PomModelImpl).reparseFile(fileCopy,
node,
tempDocument.immutableCharSequence)
return Supplier {
applyPsiChange?.run()
OffsetsInFile(fileCopy, tempMap.copyOffsets(copyDocument))
}
}
}
| platform/analysis-impl/src/com/intellij/codeInsight/completion/OffsetsInFile.kt | 2114444090 |
// 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.console
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.KotlinIdeaReplBundle
import org.jetbrains.kotlin.cli.common.repl.replNormalizeLineBreaks
import org.jetbrains.kotlin.cli.common.repl.replUnescapeLineBreaks
import org.jetbrains.kotlin.console.actions.logError
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.utils.repl.ReplEscapeType
import org.jetbrains.kotlin.utils.repl.ReplEscapeType.*
import org.w3c.dom.Element
import org.xml.sax.InputSource
import java.io.ByteArrayInputStream
import java.nio.charset.Charset
import javax.xml.parsers.DocumentBuilderFactory
data class SeverityDetails(val severity: Severity, val description: String, val range: TextRange)
class ReplOutputHandler(
private val runner: KotlinConsoleRunner,
process: Process,
commandLine: String
) : OSProcessHandler(process, commandLine) {
private var isBuildInfoChecked = false
private val factory = DocumentBuilderFactory.newInstance()
private val outputProcessor = ReplOutputProcessor(runner)
private val inputBuffer = StringBuilder()
override fun isSilentlyDestroyOnClose() = true
override fun notifyTextAvailable(text: String, key: Key<*>) {
// hide warning about adding test folder to classpath
if (text.startsWith("warning: classpath entry points to a non-existent location")) return
if (key == ProcessOutputTypes.STDOUT) {
inputBuffer.append(text)
val resultingText = inputBuffer.toString()
if (resultingText.endsWith("\n")) {
handleReplMessage(resultingText)
inputBuffer.setLength(0)
}
} else {
super.notifyTextAvailable(text, key)
}
}
private fun handleReplMessage(text: String) {
if (text.isBlank()) return
val output = try {
factory.newDocumentBuilder().parse(strToSource(text))
} catch (e: Exception) {
logError(ReplOutputHandler::class.java, "Couldn't parse REPL output: $text", e)
return
}
val root = output.firstChild as Element
val outputType = ReplEscapeType.valueOfOrNull(root.getAttribute("type"))
val content = root.textContent.replUnescapeLineBreaks().replNormalizeLineBreaks()
when (outputType) {
INITIAL_PROMPT -> buildWarningIfNeededBeforeInit(content)
HELP_PROMPT -> outputProcessor.printHelp(content)
USER_OUTPUT -> outputProcessor.printUserOutput(content)
REPL_RESULT -> outputProcessor.printResultWithGutterIcon(content)
READLINE_START -> runner.isReadLineMode = true
READLINE_END -> runner.isReadLineMode = false
REPL_INCOMPLETE -> outputProcessor.highlightCompilerErrors(createCompilerMessages(content))
COMPILE_ERROR,
RUNTIME_ERROR -> outputProcessor.printRuntimeError("${content.trim()}\n")
INTERNAL_ERROR -> outputProcessor.printInternalErrorMessage(content)
ERRORS_REPORTED -> {}
SUCCESS -> runner.commandHistory.lastUnprocessedEntry()?.entryText?.let { runner.successfulLine(it) }
else -> logError(ReplOutputHandler::class.java, "Unexpected output type:\n$outputType")
}
if (outputType in setOf(SUCCESS, ERRORS_REPORTED, READLINE_END)) {
runner.commandHistory.entryProcessed()
}
}
private fun buildWarningIfNeededBeforeInit(content: String) {
if (!isBuildInfoChecked) {
outputProcessor.printBuildInfoWarningIfNeeded()
isBuildInfoChecked = true
}
// there are several INITIAL_PROMPT messages, the 1st starts with `Welcome to Kotlin version ...`
if (content.startsWith("Welcome")) {
outputProcessor.printUserOutput(KotlinIdeaReplBundle.message("repl.is.in.experimental.stage") + "\n")
}
outputProcessor.printInitialPrompt(content)
}
private fun strToSource(s: String, encoding: Charset = Charsets.UTF_8) = InputSource(ByteArrayInputStream(s.toByteArray(encoding)))
private fun createCompilerMessages(runtimeErrorsReport: String): List<SeverityDetails> {
val compilerMessages = arrayListOf<SeverityDetails>()
val report = factory.newDocumentBuilder().parse(strToSource(runtimeErrorsReport, Charsets.UTF_16))
val entries = report.getElementsByTagName("reportEntry")
for (i in 0 until entries.length) {
val reportEntry = entries.item(i) as Element
val severityLevel = reportEntry.getAttribute("severity").toSeverity()
val rangeStart = reportEntry.getAttribute("rangeStart").toInt()
val rangeEnd = reportEntry.getAttribute("rangeEnd").toInt()
val description = reportEntry.textContent
compilerMessages.add(SeverityDetails(severityLevel, description, TextRange(rangeStart, rangeEnd)))
}
return compilerMessages
}
private fun String.toSeverity() = when (this) {
"ERROR" -> Severity.ERROR
"WARNING" -> Severity.WARNING
"INFO" -> Severity.INFO
else -> throw IllegalArgumentException("Unsupported Severity: '$this'") // this case shouldn't occur
}
} | plugins/kotlin/repl/src/org/jetbrains/kotlin/console/ReplOutputHandler.kt | 607125357 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.tests.community.toolWindow
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.testGuiFramework.fixtures.IdeFrameFixture
import com.intellij.testGuiFramework.impl.GuiTestCase
import com.intellij.testGuiFramework.impl.actionButton
import com.intellij.testGuiFramework.tests.community.CommunityProjectCreator
import org.fest.swing.timing.Pause
import org.junit.After
import org.junit.Assert
import org.junit.Test
class DockedModeGuiTest : GuiTestCase() {
enum class ToolWindowModes(val mode: String) {
PINNED_MODE("Pinned Mode"),
DOCKED_MODE("Docked Mode")
}
@Test
fun testDockedMode() {
CommunityProjectCreator.importCommandLineAppAndOpenMain()
ideFrame {
if (!projectView.isVisible) projectView.activate()
setProjectViewMode(ToolWindowModes.PINNED_MODE, true)
editor.clickCenter()
setProjectViewMode(ToolWindowModes.DOCKED_MODE, false)
editor.clickCenter()
Pause.pause(2000) // pause to wait when project view is closed
val projectViewWasVisible = projectView.isVisible
Assert.assertFalse("Project tool window should be hidden in 'pinned' and not 'docked' mode", projectViewWasVisible)
}
}
@After
fun tearDown() {
ideFrame { setProjectViewMode(ToolWindowModes.DOCKED_MODE, true) }
}
private fun IdeFrameFixture.setProjectViewMode(toolWindowMode: ToolWindowModes, flag: Boolean) {
if (!projectView.isVisible) {
projectView.activate()
Pause.pause(2000) // pause to wait when project view is appeared
}
actionButton("Show Options Menu").click()
val pinnedModeItem = menu(toolWindowMode.mode)
val selected = (pinnedModeItem.target() as ActionMenuItem).isSelected
if (selected != flag) pinnedModeItem.click()
}
} | community-guitests/testSrc/com/intellij/testGuiFramework/tests/community/toolWindow/DockedModeGuiTest.kt | 4026088075 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.intellij.application.options.PathMacrosImpl
import com.intellij.openapi.components.impl.BasePathMacroManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.SystemProperties
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.jps.model.serialization.PathMacroUtil
import org.junit.Test
class LightPathMacroManagerTest {
@Test
fun systemOverridesUser() {
val macros = PathMacrosImpl()
val userHome = FileUtil.toSystemIndependentName(SystemProperties.getUserHome())
macros.setMacro("foo", userHome)
val manager = BasePathMacroManager(macros)
assertThat(manager.collapsePath(userHome)).isEqualTo("$${PathMacroUtil.USER_HOME_NAME}$")
}
} | platform/platform-tests/testSrc/com/intellij/openapi/components/impl/pathMacroManagerTest.kt | 1078854236 |
package org.thoughtcrime.securesms.search
data class MessageSearchResult(val results: List<MessageResult>, val query: String)
| app/src/main/java/org/thoughtcrime/securesms/search/MessageSearchResult.kt | 1766296521 |
package rustyice.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.scenes.scene2d.Stage
import rustyengine.RustyEngine
import rustyice.graphics.PerformanceTracker
import java.util.*
/**
* Manages which screens are currently active and displays them.
*/
class ScreenManager(val tracker: PerformanceTracker? = null){
val stage: Stage
private val screens: HashMap<String, LazyScreen>
private val screenHistory: Stack<Screen>
private var currentScreen: Screen?
init {
stage = Stage(RustyEngine.viewport, RustyEngine.batch)
currentScreen = null
screens = HashMap()
screenHistory = Stack()
}
/**
* adds a screen with a given name
*
* @param name the name the screen will be referenced to by
* @param screen a screen object
*/
fun addScreen(name: String, screen: () -> Screen) {
screens.put(name, LazyScreen(screen))
}
/**
* displays a screen, the last screen will be added to a stack.
*
* @param name see add screen
*/
fun showScreen(name: String) {
val screen = screens[name]
var currentScreen = currentScreen
if(screen != null) {
if(currentScreen != null) {
currentScreen.hide()
screenHistory.push(currentScreen)
}
currentScreen = screen.get()
currentScreen.show()
currentScreen.resize(Gdx.graphics.width, Gdx.graphics.height)
this.currentScreen = currentScreen
showTracker()
} else {
throw IllegalArgumentException("No screen is registered with the name")
}
}
private fun showTracker() {
if (tracker != null) {
stage.actors.removeValue(tracker, true)
stage.addActor(tracker)
tracker.setFillParent(true)
tracker.validate()
}
}
/**
* sets a screen to the screen before the last activation
*/
fun popScreen() {
val popScreen: Screen?
currentScreen?.hide()
popScreen = screenHistory.pop()
currentScreen = popScreen
if(popScreen != null) {
popScreen.show()
showTracker()
}
}
/**
* NEEDS to be called whenever the window resizes for screens to behave properly.
*
* @param width in pixels
* @param height in pixels
*/
fun resize(width: Int, height: Int) {
stage.viewport.update(width, height, true)
currentScreen?.resize(width, height)
tracker?.validate()
}
/**
* NEEDS to be called every frame
*
* @param delta in seconds
*/
fun render(batch: Batch, delta: Float) {
currentScreen?.render(batch, delta)
stage.act(delta)
stage.draw()
}
fun dispose() {
stage.dispose()
}
private inner class LazyScreen(private val builder: () -> Screen){
private var screen: Screen? = null
fun get(): Screen {
val screen = screen
if(screen == null){
val out = builder()
out.screenManager = this@ScreenManager
this.screen = out
return out
} else {
return screen
}
}
}
}
| core/src/rustyice/screens/ScreenManager.kt | 1020699411 |
package lt.markmerkk.utils
import lt.markmerkk.ConfigPathProvider
import org.slf4j.LoggerFactory
import java.io.File
import java.util.*
class ConfigSetSettingsImpl(
private val configPathProvider: ConfigPathProvider
) : BaseSettings(), ConfigSetSettings {
private var configSetName: String = ""
set(value) {
field = sanitizeConfigName(value)
}
private var configs: List<String> = emptyList()
override fun changeActiveConfig(configSelection: String) {
configSetName = configSelection
}
override fun configs(): List<String> {
return configs
.plus(DEFAULT_ROOT_CONFIG_NAME)
}
override fun currentConfig(): String {
return configSetName
}
override fun currentConfigOrDefault(): String {
if (configSetName.isEmpty()) {
return DEFAULT_ROOT_CONFIG_NAME
}
return configSetName
}
override fun propertyPath(): String {
return File(configPathProvider.fullAppDir, "${File.separator}${PROPERTIES_FILENAME}")
.absolutePath
}
override fun onLoad(properties: Properties) {
configs = configsFromProperty(properties.getOrDefault(KEY_CONFIGS, "").toString())
configSetName = properties.getOrDefault(KEY_CONFIG_NAME, "").toString()
}
override fun onSave(properties: Properties) {
properties.put(KEY_CONFIG_NAME, configSetName)
properties.put(KEY_CONFIGS, configsToProperty(configs))
}
//region Convenience
/**
* Sanitizes input value to be valid for a validation name
* If no such config exist, will create a new one in the [configs]
*
* Note: "default" value will be reserved and interpreted as an empty string.
*/
fun sanitizeConfigName(inputValue: String): String {
if (inputValue.isEmpty()) return ""
if (inputValue == DEFAULT_ROOT_CONFIG_NAME) return ""
if (!configs.contains(inputValue)) {
configs += inputValue
}
return inputValue.replace(",", "").trim()
}
/**
* Transforms a list of configs from property
*/
fun configsFromProperty(property: String): List<String> {
if (property.isEmpty()) return emptyList()
return property.split(",")
.filter { it != "\n" }
.filter { it != "\r\n" }
.map(String::trim)
.filter { !it.isEmpty() }
.toList()
}
/**
* Transforms list of configs to property to be saved.
* Will take care of invalid items.
*/
fun configsToProperty(configs: List<String>): String {
val sb = StringBuilder()
for (config in configs) {
if (config.isNullOrEmpty()) continue
sb.append(
config.toString()
.trim()
.replace(",", "")
)
sb.append(",")
}
if (sb.length > 0) {
sb.deleteCharAt(sb.length - 1)
}
return sb.toString()
}
//endregion
companion object {
const val KEY_CONFIG_NAME = "config_set_name"
const val KEY_CONFIGS = "configs"
const val DEFAULT_ROOT_CONFIG_NAME = "default"
const val PROPERTIES_FILENAME = "config_set.properties"
val logger = LoggerFactory.getLogger(ConfigSetSettingsImpl::class.java)!!
}
} | components/src/main/java/lt/markmerkk/utils/ConfigSetSettingsImpl.kt | 3210135490 |
package com.beust.kobalt.misc
import com.beust.kobalt.Glob
import com.beust.kobalt.IFileSpec
import com.google.common.io.CharStreams
import java.io.*
import java.nio.file.Paths
import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.jar.JarInputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipException
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream
public class JarUtils {
companion object {
val DEFAULT_HANDLER: (Exception) -> Unit = { ex: Exception ->
// Ignore duplicate entry exceptions
if (! ex.message?.contains("duplicate")!!) {
throw ex
}
}
fun addFiles(directory: String, files: List<IncludedFile>, target: ZipOutputStream,
expandJarFiles: Boolean,
onError: (Exception) -> Unit = DEFAULT_HANDLER) {
files.forEach {
addSingleFile(directory, it, target, expandJarFiles, onError)
}
}
private val DEFAULT_JAR_EXCLUDES =
Glob("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA")
fun addSingleFile(directory: String, file: IncludedFile, outputStream: ZipOutputStream,
expandJarFiles: Boolean, onError: (Exception) -> Unit = DEFAULT_HANDLER) {
val foundFiles = file.allFromFiles(directory)
foundFiles.forEach { foundFile ->
// Turn the found file into the local physical file that will be put in the jar file
val fromFile = file.from(foundFile.path)
val localFile = if (fromFile.isAbsolute) fromFile
else File(directory, fromFile.path)
if (!localFile.exists()) {
throw AssertionError("File should exist: $localFile")
}
if (foundFile.isDirectory) {
log(2, "Writing contents of directory $foundFile")
// Directory
var name = foundFile.name
if (!name.isEmpty()) {
if (!name.endsWith("/")) name += "/"
val entry = JarEntry(name)
entry.time = localFile.lastModified()
try {
outputStream.putNextEntry(entry)
} catch(ex: ZipException) {
log(2, "Can't add $name: ${ex.message}")
} finally {
outputStream.closeEntry()
}
}
val includedFile = IncludedFile(From(foundFile.path), To(""), listOf(IFileSpec.GlobSpec("**")))
addSingleFile(".", includedFile, outputStream, expandJarFiles)
} else {
if (file.expandJarFiles && foundFile.name.endsWith(".jar") && ! file.from.contains("resources")) {
log(2, "Writing contents of jar file $foundFile")
val stream = JarInputStream(FileInputStream(localFile))
var entry = stream.nextEntry
while (entry != null) {
if (!entry.isDirectory && !KFiles.isExcluded(entry.name, DEFAULT_JAR_EXCLUDES)) {
val ins = JarFile(localFile).getInputStream(entry)
addEntry(ins, JarEntry(entry), outputStream, onError)
}
entry = stream.nextEntry
}
} else {
val entryFileName = file.to(foundFile.path).path.replace("\\", "/")
val entry = JarEntry(entryFileName)
entry.time = localFile.lastModified()
addEntry(FileInputStream(localFile), entry, outputStream, onError)
}
}
}
}
private fun addEntry(inputStream: InputStream, entry: ZipEntry, outputStream: ZipOutputStream,
onError: (Exception) -> Unit = DEFAULT_HANDLER) {
var bis: BufferedInputStream? = null
try {
outputStream.putNextEntry(entry)
bis = BufferedInputStream(inputStream)
val buffer = ByteArray(50 * 1024)
while (true) {
val count = bis.read(buffer)
if (count == -1) break
outputStream.write(buffer, 0, count)
}
outputStream.closeEntry()
} catch(ex: Exception) {
onError(ex)
} finally {
bis?.close()
}
}
fun extractTextFile(zip : ZipFile, fileName: String) : String? {
val enumEntries = zip.entries()
while (enumEntries.hasMoreElements()) {
val file = enumEntries.nextElement()
if (file.name == fileName) {
log(2, "Found $fileName in ${zip.name}")
zip.getInputStream(file).use { ins ->
return CharStreams.toString(InputStreamReader(ins, "UTF-8"))
}
}
}
return null
}
fun extractJarFile(file: File, destDir: File) = extractZipFile(JarFile(file), destDir)
fun extractZipFile(zipFile: ZipFile, destDir: File) {
val enumEntries = zipFile.entries()
while (enumEntries.hasMoreElements()) {
val file = enumEntries.nextElement()
val f = File(destDir.path + File.separator + file.name)
if (file.isDirectory) {
f.mkdir()
continue
}
zipFile.getInputStream(file).use { ins ->
f.parentFile.mkdirs()
FileOutputStream(f).use { fos ->
while (ins.available() > 0) {
fos.write(ins.read())
}
}
}
}
}
}
}
open class Direction(open val p: String) {
override fun toString() = path
fun isCurrentDir() = path == "./"
val path: String get() =
if (p.isEmpty()) "./"
else if (p.startsWith("/") || p.endsWith("/")) p
else p + "/"
}
class IncludedFile(val fromOriginal: From, val toOriginal: To, val specs: List<IFileSpec>,
val expandJarFiles: Boolean = false) {
constructor(specs: List<IFileSpec>, expandJarFiles: Boolean = false) : this(From(""), To(""), specs, expandJarFiles)
fun from(s: String) = File(if (fromOriginal.isCurrentDir()) s else KFiles.joinDir(from, s))
val from: String get() = fromOriginal.path.replace("\\", "/")
fun to(s: String) = File(if (toOriginal.isCurrentDir()) s else KFiles.joinDir(to, s))
val to: String get() = toOriginal.path.replace("\\", "/")
override public fun toString() = toString("IncludedFile",
"files - ", specs.map { it.toString() },
"from", from,
"to", to)
fun allFromFiles(directory: String? = null): List<File> {
val result = arrayListOf<File>()
specs.forEach { spec ->
// val fullDir = if (directory == null) from else KFiles.joinDir(directory, from)
spec.toFiles(directory, from).forEach { source ->
result.add(if (source.isAbsolute) source else File(source.path))
}
}
return result.map { Paths.get(it.path).normalize().toFile()}
}
}
class From(override val p: String) : Direction(p)
class To(override val p: String) : Direction(p)
| modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/JarUtils.kt | 2217226316 |
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.plugins.partialcontent
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.util.pipeline.*
internal object BodyTransformedHook :
Hook<suspend BodyTransformedHook.Context.(call: ApplicationCall, message: Any) -> Unit> {
class Context(private val context: PipelineContext<Any, ApplicationCall>) {
val call: ApplicationCall = context.call
fun transformBodyTo(newValue: Any) {
context.subject = newValue
}
}
override fun install(
pipeline: ApplicationCallPipeline,
handler: suspend Context.(call: ApplicationCall, message: Any) -> Unit
) {
val partialContentPhase = PipelinePhase("PartialContent")
pipeline.sendPipeline.insertPhaseAfter(ApplicationSendPipeline.ContentEncoding, partialContentPhase)
pipeline.sendPipeline.intercept(partialContentPhase) { message ->
Context(this).handler(call, message)
}
}
}
internal suspend fun BodyTransformedHook.Context.tryProcessRange(
content: OutgoingContent.ReadChannelContent,
call: ApplicationCall,
rangesSpecifier: RangesSpecifier,
length: Long,
maxRangeCount: Int
) {
if (checkIfRangeHeader(content, call)) {
processRange(content, rangesSpecifier, length, maxRangeCount)
} else {
transformBodyTo(PartialOutgoingContent.Bypass(content))
}
}
| ktor-server/ktor-server-plugins/ktor-server-partial-content/jvmAndNix/src/io/ktor/server/plugins/partialcontent/BodyTransformedHook.kt | 751893635 |
package org.roylance.yaclib.core.plugins.server
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel.Dependency
import org.roylance.yaclib.core.enums.CommonTokens
import org.roylance.yaclib.core.utilities.GradleUtilities
import org.roylance.yaclib.core.utilities.InitUtilities
import java.nio.file.Paths
class JavaServerBuilder(private val location: String,
private val mainDependency: Dependency) : IBuilder<Boolean> {
override fun build(): Boolean {
val javaServerDirectory = Paths.get(location, "${mainDependency.name}${CommonTokens.ServerSuffix}").toFile()
println(InitUtilities.buildPhaseMessage("java server begin"))
// todo: just sticking with jetty
val cleanReport = GradleUtilities.clean(javaServerDirectory.toString())
println(cleanReport.normalOutput)
println(cleanReport.errorOutput)
println(InitUtilities.buildPhaseMessage("compiling"))
val compileReport = GradleUtilities.build(javaServerDirectory.toString())
println(compileReport.normalOutput)
println(compileReport.errorOutput)
println(InitUtilities.buildPhaseMessage("java server end"))
return true
}
} | core/src/main/java/org/roylance/yaclib/core/plugins/server/JavaServerBuilder.kt | 2843824375 |
/*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.reactivex.subjects
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.mockito.kotlin.*
import java.io.IOException
class AsyncInitialValueBehaviorSubjectTest {
private val wrapped: BehaviorSubject<Int> = mock()
private val initialValueSupplier = { 666 }
private val underTest = AsyncInitialValueBehaviorSubject(initialValueSupplier, wrapped)
@Test
fun forwardsOnCompleteToWrapped() {
underTest.onComplete()
verify(wrapped).onComplete()
}
@Test
fun forwardsOnErrorToWrapped() {
val throwable = IOException()
underTest.onError(throwable)
verify(wrapped).onError(throwable)
}
@Test
fun forwardsOnNextToWrapped() {
underTest.onNext(1)
verify(wrapped).onNext(1)
}
@Test
fun forwardsOnSubscribeToWrapped() {
val disposable: Disposable = mock()
underTest.onSubscribe(disposable)
verify(wrapped).onSubscribe(disposable)
}
@Test
fun forwardsSubscribeActualToWrapped() {
val observer: Observer<Int> = mock()
invokeSubscribeActual(underTest, observer)
verify(wrapped).subscribeActual(observer)
}
@Test
fun returnsHasCompleteFromWrapped() {
whenever(wrapped.hasComplete()).thenReturn(true)
assertTrue(underTest.hasComplete())
verify(wrapped).hasComplete()
}
@Test
fun returnsHasObserversFromWrapped() {
whenever(wrapped.hasObservers()).thenReturn(true)
assertTrue(underTest.hasObservers())
verify(wrapped).hasObservers()
}
@Test
fun returnsHasThrowableFromWrapped() {
whenever(wrapped.hasThrowable()).thenReturn(true)
assertTrue(underTest.hasThrowable())
verify(wrapped).hasThrowable()
}
@Test
fun returnsThrowableFromWrapped() {
val throwable = IOException()
whenever(wrapped.throwable).thenReturn(throwable)
assertEquals(throwable, underTest.throwable)
verify(wrapped).throwable
}
@Test
fun suppliesInitialValueOnSubscribeActualWhenNoInitialValue() {
invokeSubscribeActual(underTest, mock())
verify(wrapped).onNext(initialValueSupplier.invoke())
}
@Test
fun doesNotSupplyInitialValueOnSubscribeActualWhenHasInitialValue() {
whenever(wrapped.hasValue()).thenReturn(true)
invokeSubscribeActual(underTest, mock())
verify(wrapped, never()).onNext(any())
}
private fun <T> invokeSubscribeActual(
receiver: AsyncInitialValueBehaviorSubject<T>,
argument: Observer<T>
) {
underTest.javaClass.getDeclaredMethod("subscribeActual", Observer::class.java).apply {
isAccessible = true
invoke(receiver, argument)
}
}
}
| app/src/test/java/io/reactivex/subjects/AsyncInitialValueBehaviorSubjectTest.kt | 242967617 |
package eu.kanade.tachiyomi.ui.browse.extension
import android.app.Dialog
import android.os.Bundle
import androidx.core.os.bundleOf
import com.bluelinelabs.conductor.Controller
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.ui.base.controller.DialogController
class ExtensionTrustDialog<T>(bundle: Bundle? = null) : DialogController(bundle)
where T : Controller, T : ExtensionTrustDialog.Listener {
constructor(target: T, signatureHash: String, pkgName: String) : this(
bundleOf(
SIGNATURE_KEY to signatureHash,
PKGNAME_KEY to pkgName
)
) {
targetController = target
}
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
return MaterialAlertDialogBuilder(activity!!)
.setTitle(R.string.untrusted_extension)
.setMessage(R.string.untrusted_extension_message)
.setPositiveButton(R.string.ext_trust) { _, _ ->
(targetController as? Listener)?.trustSignature(args.getString(SIGNATURE_KEY)!!)
}
.setNegativeButton(R.string.ext_uninstall) { _, _ ->
(targetController as? Listener)?.uninstallExtension(args.getString(PKGNAME_KEY)!!)
}
.create()
}
interface Listener {
fun trustSignature(signatureHash: String)
fun uninstallExtension(pkgName: String)
}
}
private const val SIGNATURE_KEY = "signature_key"
private const val PKGNAME_KEY = "pkgname_key"
| app/src/main/java/eu/kanade/tachiyomi/ui/browse/extension/ExtensionTrustDialog.kt | 1319852744 |
package com.atslangplugin
import com.intellij.lang.Language
/**
* Created by brandon on 12/16/14.
*/
public class ATSLanguage private() : Language("ATS") {
companion object {
public val INSTANCE: ATSLanguage = ATSLanguage()
}
}
| src/com/atslangplugin/ATSLanguage.kt | 1564636109 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.i18n.lang.colors
import com.demonwav.mcdev.i18n.lang.gen.psi.I18nTypes
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
class I18nSyntaxHighlighter(private val lexer: Lexer) : SyntaxHighlighterBase() {
override fun getHighlightingLexer() = lexer
override fun getTokenHighlights(tokenType: IElementType?) =
when (tokenType) {
I18nTypes.KEY, I18nTypes.DUMMY -> KEY_KEYS
I18nTypes.EQUALS -> EQUALS_KEYS
I18nTypes.VALUE -> VALUE_KEYS
I18nTypes.COMMENT -> COMMENT_KEYS
else -> EMPTY_KEYS
}
companion object {
val KEY = TextAttributesKey.createTextAttributesKey("I18N_KEY", DefaultLanguageHighlighterColors.KEYWORD)
val EQUALS = TextAttributesKey.createTextAttributesKey("I18N_EQUALS", DefaultLanguageHighlighterColors.OPERATION_SIGN)
val VALUE = TextAttributesKey.createTextAttributesKey("I18N_VALUE", DefaultLanguageHighlighterColors.STRING)
val COMMENT = TextAttributesKey.createTextAttributesKey("I18N_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT)
val KEY_KEYS = arrayOf(KEY)
val EQUALS_KEYS = arrayOf(EQUALS)
val VALUE_KEYS = arrayOf(VALUE)
val COMMENT_KEYS = arrayOf(COMMENT)
val EMPTY_KEYS = emptyArray<TextAttributesKey>()
}
}
| src/main/kotlin/com/demonwav/mcdev/i18n/lang/colors/I18nSyntaxHighlighter.kt | 3288746588 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package openxr.templates
import org.lwjgl.generator.*
import openxr.*
val VARJO_marker_tracking = "VARJOMarkerTracking".nativeClassXR("VARJO_marker_tracking", type = "instance", postfix = "VARJO") {
documentation =
"""
The <a href="https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html\#XR_VARJO_marker_tracking">XR_VARJO_marker_tracking</a> extension.
Varjo Markers are physical markers tracked by the video cameras of the HMD. Different types of markers <b>can</b> be used for different purposes. As an example, Varjo Markers <b>can</b> be used as cheap replacements for electronic trackers. The cost per printed tracker is significantly lower and the markers require no power to function.
This extension provides the tracking interface to a set of marker types and sizes. Markers <b>can</b> be printed out from the PDF documents and instructions freely available at <a target="_blank" href="https://developer.varjo.com/docs/get-started/varjo-markers\#printing-varjo-markers">https://developer.varjo.com/docs/get-started/varjo-markers\#printing-varjo-markers</a>. Note that the printed marker <b>must</b> have the exact physical size for its ID.
Object markers are used to track static or dynamic objects in the user environment. You <b>may</b> use object markers in both XR and VR applications. Each marker has a unique ID, and you <b>must</b> not use the same physical marker more than once in any given environment. For added precision, an application <b>may</b> use multiple markers to track a single object. For example, you could track a monitor by placing a marker in each corner.
There is a set of marker IDs recognized by runtime and if the application uses ID which is not in the set then runtime <b>must</b> return #ERROR_MARKER_ID_INVALID_VARJO.
"""
IntConstant(
"The extension specification version.",
"VARJO_marker_tracking_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"VARJO_MARKER_TRACKING_EXTENSION_NAME".."XR_VARJO_marker_tracking"
)
EnumConstant(
"Extends {@code XrStructureType}.",
"TYPE_SYSTEM_MARKER_TRACKING_PROPERTIES_VARJO".."1000124000",
"TYPE_EVENT_DATA_MARKER_TRACKING_UPDATE_VARJO".."1000124001",
"TYPE_MARKER_SPACE_CREATE_INFO_VARJO".."1000124002"
)
EnumConstant(
"Extends {@code XrResult}.",
"ERROR_MARKER_NOT_TRACKED_VARJO".."-1000124000",
"ERROR_MARKER_ID_INVALID_VARJO".."-1000124001"
)
XrResult(
"SetMarkerTrackingVARJO",
"""
Enables marker tracking.
<h5>C Specification</h5>
The #SetMarkerTrackingVARJO() function is defined as:
<pre><code>
XrResult xrSetMarkerTrackingVARJO(
XrSession session,
XrBool32 enabled);</code></pre>
<h5>Description</h5>
The #SetMarkerTrackingVARJO() function enables or disables marker tracking functionality. As soon as feature is become disabled all trackable markers become inactive and corresponding events will be generated. An application <b>may</b> call any of the functions in this extension regardless if the marker tracking functionality is enabled or disabled.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>The {@link VARJOMarkerTracking XR_VARJO_marker_tracking} extension <b>must</b> be enabled prior to calling #SetMarkerTrackingVARJO()</li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
<li>#SESSION_LOSS_PENDING</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_FUNCTION_UNSUPPORTED</li>
<li>#ERROR_RUNTIME_FAILURE</li>
<li>#ERROR_HANDLE_INVALID</li>
<li>#ERROR_INSTANCE_LOST</li>
<li>#ERROR_SESSION_LOST</li>
<li>#ERROR_FEATURE_UNSUPPORTED</li>
</ul></dd>
</dl>
""",
XrSession("session", "an {@code XrSession} handle previously created with #CreateSession()."),
XrBool32("enabled", "the flag to enable or disable marker tracking.")
)
XrResult(
"SetMarkerTrackingTimeoutVARJO",
"""
Sets marker lifetime duration.
<h5>C Specification</h5>
The #SetMarkerTrackingTimeoutVARJO() function is defined as:
<pre><code>
XrResult xrSetMarkerTrackingTimeoutVARJO(
XrSession session,
uint64_t markerId,
XrDuration timeout);</code></pre>
<h5>Description</h5>
The #SetMarkerTrackingTimeoutVARJO() function sets a desired lifetime duration for a specified marker. The default value is #NO_DURATION. Negative value will be clamped to #NO_DURATION. It defines the time period during which the runtime <b>must</b> keep returning poses of previously tracked markers. The tracking may be lost if the marker went outside of the trackable field of view. In this case the runtime still will try to predict marker’s pose for the timeout period. The runtime <b>must</b> return #ERROR_MARKER_ID_INVALID_VARJO if the supplied {@code markerId} is invalid.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>The {@link VARJOMarkerTracking XR_VARJO_marker_tracking} extension <b>must</b> be enabled prior to calling #SetMarkerTrackingTimeoutVARJO()</li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
<li>#SESSION_LOSS_PENDING</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_FUNCTION_UNSUPPORTED</li>
<li>#ERROR_RUNTIME_FAILURE</li>
<li>#ERROR_HANDLE_INVALID</li>
<li>#ERROR_INSTANCE_LOST</li>
<li>#ERROR_SESSION_LOST</li>
<li>#ERROR_MARKER_ID_INVALID_VARJO</li>
<li>#ERROR_FEATURE_UNSUPPORTED</li>
</ul></dd>
</dl>
""",
XrSession("session", "an {@code XrSession} handle previously created with #CreateSession()."),
uint64_t("markerId", "the unique identifier of the marker for which the timeout will be updated."),
XrDuration("timeout", "the desired lifetime duration for a specified marker.")
)
XrResult(
"SetMarkerTrackingPredictionVARJO",
"""
Sets marker tracking with prediction.
<h5>C Specification</h5>
The #SetMarkerTrackingPredictionVARJO() function is defined as:
<pre><code>
XrResult xrSetMarkerTrackingPredictionVARJO(
XrSession session,
uint64_t markerId,
XrBool32 enabled);</code></pre>
<h5>Description</h5>
The #SetMarkerTrackingPredictionVARJO() function enables or disables the prediction feature for a specified marker. By default, markers are created with disabled prediction. This works well for markers that are supposed to be stationary. The prediction <b>can</b> be used to improve tracking of movable markers. The runtime <b>must</b> return #ERROR_MARKER_ID_INVALID_VARJO if the supplied {@code markerId} is invalid.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>The {@link VARJOMarkerTracking XR_VARJO_marker_tracking} extension <b>must</b> be enabled prior to calling #SetMarkerTrackingPredictionVARJO()</li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
<li>#SESSION_LOSS_PENDING</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_FUNCTION_UNSUPPORTED</li>
<li>#ERROR_RUNTIME_FAILURE</li>
<li>#ERROR_HANDLE_INVALID</li>
<li>#ERROR_INSTANCE_LOST</li>
<li>#ERROR_SESSION_LOST</li>
<li>#ERROR_MARKER_ID_INVALID_VARJO</li>
<li>#ERROR_FEATURE_UNSUPPORTED</li>
</ul></dd>
</dl>
""",
XrSession("session", "an {@code XrSession} handle previously created with #CreateSession()."),
uint64_t("markerId", "the unique identifier of the marker which should be tracked with prediction."),
XrBool32("enabled", "")
)
XrResult(
"GetMarkerSizeVARJO",
"""
Gets physical size of marker.
<h5>C Specification</h5>
The #GetMarkerSizeVARJO() function is defined as:
<pre><code>
XrResult xrGetMarkerSizeVARJO(
XrSession session,
uint64_t markerId,
XrExtent2Df* size);</code></pre>
<h5>Description</h5>
The #GetMarkerSizeVARJO() function retrieves the height and width of an active marker. The runtime <b>must</b> return #ERROR_MARKER_NOT_TRACKED_VARJO if marker tracking functionality is disabled or the marker with given {@code markerId} is inactive. The runtime <b>must</b> return #ERROR_MARKER_ID_INVALID_VARJO if the supplied {@code markerId} is invalid.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>The {@link VARJOMarkerTracking XR_VARJO_marker_tracking} extension <b>must</b> be enabled prior to calling #GetMarkerSizeVARJO()</li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
<li>{@code size} <b>must</b> be a pointer to an ##XrExtent2Df structure</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
<li>#SESSION_LOSS_PENDING</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_FUNCTION_UNSUPPORTED</li>
<li>#ERROR_RUNTIME_FAILURE</li>
<li>#ERROR_HANDLE_INVALID</li>
<li>#ERROR_INSTANCE_LOST</li>
<li>#ERROR_SESSION_LOST</li>
<li>#ERROR_MARKER_NOT_TRACKED_VARJO</li>
<li>#ERROR_MARKER_ID_INVALID_VARJO</li>
<li>#ERROR_FEATURE_UNSUPPORTED</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##XrExtent2Df
""",
XrSession("session", "an {@code XrSession} handle previously created with #CreateSession()."),
uint64_t("markerId", "the unique identifier of the marker for which size is requested."),
XrExtent2Df.p("size", "pointer to the size to populate by the runtime with the physical size of plane marker in meters.")
)
XrResult(
"CreateMarkerSpaceVARJO",
"""
Creates marker space.
<h5>C Specification</h5>
The #CreateMarkerSpaceVARJO() function is defined as:
<pre><code>
XrResult xrCreateMarkerSpaceVARJO(
XrSession session,
const XrMarkerSpaceCreateInfoVARJO* createInfo,
XrSpace* space);</code></pre>
<h5>Description</h5>
The #CreateMarkerSpaceVARJO() function creates marker {@code XrSpace} for pose relative to the marker specified in ##XrMarkerSpaceCreateInfoVARJO. The runtime <b>must</b> return #ERROR_MARKER_ID_INVALID_VARJO if the supplied {@code markerId} is invalid.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>The {@link VARJOMarkerTracking XR_VARJO_marker_tracking} extension <b>must</b> be enabled prior to calling #CreateMarkerSpaceVARJO()</li>
<li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li>
<li>{@code createInfo} <b>must</b> be a pointer to a valid ##XrMarkerSpaceCreateInfoVARJO structure</li>
<li>{@code space} <b>must</b> be a pointer to an {@code XrSpace} handle</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
<li>#SESSION_LOSS_PENDING</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_FUNCTION_UNSUPPORTED</li>
<li>#ERROR_VALIDATION_FAILURE</li>
<li>#ERROR_HANDLE_INVALID</li>
<li>#ERROR_INSTANCE_LOST</li>
<li>#ERROR_SESSION_LOST</li>
<li>#ERROR_OUT_OF_MEMORY</li>
<li>#ERROR_LIMIT_REACHED</li>
<li>#ERROR_POSE_INVALID</li>
<li>#ERROR_MARKER_ID_INVALID_VARJO</li>
<li>#ERROR_FEATURE_UNSUPPORTED</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##XrMarkerSpaceCreateInfoVARJO
""",
XrSession("session", "an {@code XrSession} handle previously created with #CreateSession()."),
XrMarkerSpaceCreateInfoVARJO.const.p("createInfo", "the structure containing information about how to create the space based on marker."),
Check(1)..XrSpace.p("space", "a pointer to a handle in which the created {@code XrSpace} is returned.")
)
} | modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/VARJO_marker_tracking.kt | 559729125 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package cuda.templates
import cuda.*
import org.lwjgl.generator.*
val NVRTC = "NVRTC".nativeClass(Module.CUDA, prefix = "NVRTC", binding = NVRTC_BINDING) {
documentation =
"Contains bindings to <a href=\"https://docs.nvidia.com/cuda/nvrtc/index.html\">NVRTC</a>, a runtime compilation library for CUDA C++."
EnumConstant(
"""
The enumerated type {@code nvrtcResult} defines API call result codes.
NVRTC API functions return {@code nvrtcResult} to indicate the call result.
""",
"SUCCESS".enum("", "0"),
"ERROR_OUT_OF_MEMORY".enum,
"ERROR_PROGRAM_CREATION_FAILURE".enum,
"ERROR_INVALID_INPUT".enum,
"ERROR_INVALID_PROGRAM".enum,
"ERROR_INVALID_OPTION".enum,
"ERROR_COMPILATION".enum,
"ERROR_BUILTIN_OPERATION_FAILURE".enum,
"ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION".enum,
"ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION".enum,
"ERROR_NAME_EXPRESSION_NOT_VALID".enum,
"ERROR_INTERNAL_ERROR".enum
)
charASCII.const.p(
"GetErrorString",
"""
A helper function that returns a string describing the given {@code nvrtcResult} code, e.g., #SUCCESS to {@code "NVRTC_SUCCESS"}.
For unrecognized enumeration values, it returns {@code "NVRTC_ERROR unknown"}.
""",
nvrtcResult("result", "CUDA Runtime Compilation API result code"),
returnDoc = "message string for the given {@code nvrtcResult} code"
)
nvrtcResult(
"Version",
"Sets the output parameters {@code major} and {@code minor} with the CUDA Runtime Compilation version number.",
Check(1)..int.p("major", "CUDA Runtime Compilation major version number"),
Check(1)..int.p("minor", "CUDA Runtime Compilation minor version number")
)
IgnoreMissing..nvrtcResult(
"GetNumSupportedArchs",
"""
Sets the output parameter {@code numArchs} with the number of architectures supported by NVRTC.
This can then be used to pass an array to #GetSupportedArchs() to get the supported architectures.
""",
Check(1)..int.p("numArchs", "number of supported architectures")
)
IgnoreMissing..nvrtcResult(
"GetSupportedArchs",
"""
Populates the array passed via the output parameter {@code supportedArchs} with the architectures supported by NVRTC.
The array is sorted in the ascending order. The size of the array to be passed can be determined using #GetNumSupportedArchs().
""",
Unsafe..int.p("supportedArchs", "sorted array of supported architectures")
)
nvrtcResult(
"CreateProgram",
"Creates an instance of {@code nvrtcProgram} with the given input parameters, and sets the output parameter {@code prog} with it.",
Check(1)..nvrtcProgram.p("prog", "CUDA Runtime Compilation program"),
charUTF8.const.p("src", "CUDA program source"),
nullable..charUTF8.const.p("name", "CUDA program name. {@code name} can be #NULL; {@code \"default_program\"} is used when {@code name} is #NULL or \"\"."),
AutoSize("headers", "includeNames")..int("numHeaders", "number of headers used. {@code numHeaders} must be greater than or equal to 0."),
nullable..charUTF8.const.p.const.p("headers", "sources of the headers. {@code headers} can be #NULL when {@code numHeaders} is 0."),
nullable..char.const.p.const.p(
"includeNames",
"name of each header by which they can be included in the CUDA program source. {@code includeNames} can be #NULL when {@code numHeaders} is 0."
)
)
nvrtcResult(
"DestroyProgram",
"Destroys the given program.",
Check(1)..nvrtcProgram.p("prog", "CUDA Runtime Compilation program")
)
nvrtcResult(
"CompileProgram",
"""
Compiles the given program.
It supports compile options listed in {@code options}.
""",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
AutoSize("options")..int("numOptions", "number of compiler options passed"),
nullable..charASCII.const.p.const.p("options", "compiler options in the form of C string array. {@code options} can be #NULL when {@code numOptions} is 0.")
)
nvrtcResult(
"GetPTXSize",
"Sets {@code ptxSizeRet} with the size of the PTX generated by the previous compilation of {@code prog} (including the trailing #NULL).",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
Check(1)..size_t.p("ptxSizeRet", "size of the generated PTX (including the trailing #NULL)")
)
nvrtcResult(
"GetPTX",
"Stores the PTX generated by the previous compilation of {@code prog} in the memory pointed by {@code ptx}.",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
Unsafe..char.p("ptx", "compiled result")
)
IgnoreMissing..nvrtcResult(
"GetCUBINSize",
"""
Sets {@code cubinSizeRet} with the size of the {@code cubin} generated by the previous compilation of {@code prog}.
The value of {@code cubinSizeRet} is set to 0 if the value specified to {@code -arch} is a virtual architecture instead of an actual architecture.
""",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
Check(1)..size_t.p("cubinSizeRet", "size of the generated cubin")
)
IgnoreMissing..nvrtcResult(
"GetCUBIN",
"""
Stores the {@code cubin} generated by the previous compilation of {@code prog} in the memory pointed by {@code cubin}.
No {@code cubin} is available if the value specified to {@code -arch} is a virtual architecture instead of an actual architecture.
""",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
Unsafe..char.p("cubin", "compiled and assembled result")
)
IgnoreMissing..nvrtcResult(
"GetNVVMSize",
"""
Sets {@code nvvmSizeRet} with the size of the NVVM generated by the previous compilation of {@code prog}.
The value of {@code nvvmSizeRet} is set to 0 if the program was not compiled with {@code -dlto}.
""",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
Check(1)..size_t.p("nvvmSizeRet", "size of the generated NVVM"),
returnDoc = ""
)
IgnoreMissing..nvrtcResult(
"GetNVVM",
"""
Stores the NVVM generated by the previous compilation of {@code prog} in the memory pointed by {@code nvvm}.
The program must have been compiled with {@code -dlto}, otherwise will return an error.
""",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
Unsafe..char.p("nvvm", "compiled result")
)
nvrtcResult(
"GetProgramLogSize",
"""
Sets {@code logSizeRet} with the size of the log generated by the previous compilation of {@code prog} (including the trailing #NULL).
Note that compilation log may be generated with warnings and informative messages, even when the compilation of {@code prog} succeeds.
""",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
Check(1)..size_t.p("logSizeRet", "size of the compilation log (including the trailing #NULL)")
)
nvrtcResult(
"GetProgramLog",
"Stores the log generated by the previous compilation of {@code prog} in the memory pointed by {@code log}.",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
Unsafe..char.p("log", "compilation log")
)
nvrtcResult(
"AddNameExpression",
"""
Notes the given name expression denoting the address of a {@code __global__} function or {@code __device__}/{@code __constant__} variable.
The identical name expression string must be provided on a subsequent call to #GetLoweredName() to extract the lowered name.
""",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
charUTF8.const.p.const(
"name_expression",
"constant expression denoting the address of a {@code __global__} function or {@code __device__}/{@code __constant__} variable"
),
returnDoc = ""
)
nvrtcResult(
"GetLoweredName",
"""
Extracts the lowered (mangled) name for a {@code __global__} function or {@code __device__}/{@code __constant__} variable, and updates
{@code *lowered_name} to point to it.
The memory containing the name is released when the NVRTC program is destroyed by #DestroyProgram(). The identical name expression must have been
previously provided to #AddNameExpression().
""",
nvrtcProgram("prog", "CUDA Runtime Compilation program"),
charUTF8.const.p.const(
"name_expression",
"constant expression denoting the address of a {@code __global__} function or {@code __device__}/{@code __constant__} variable"),
Check(1)..charUTF8.const.p.p(
"lowered_name",
"initialized by the function to point to a C string containing the lowered (mangled) name corresponding to the provided name expression"
)
)
} | modules/lwjgl/cuda/src/templates/kotlin/cuda/templates/NVRTC.kt | 4270992585 |
package fredboat.sentinel
class SentinelException(message: String, cause: Throwable? = null) : RuntimeException(message, cause) | FredBoat/src/main/java/fredboat/sentinel/SentinelException.kt | 2392100376 |
/* Telegram_Backup
* Copyright (C) 2016 Fabian Schlenz
*
* 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 de.fabianonline.telegram_backup
import de.fabianonline.telegram_backup.CommandLineController
import de.fabianonline.telegram_backup.Utils
import de.fabianonline.telegram_backup.Version
import java.util.concurrent.TimeUnit
import org.slf4j.LoggerFactory
import ch.qos.logback.classic.Logger
import ch.qos.logback.classic.LoggerContext
import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.classic.Level
fun main(args: Array<String>) {
val clr = CommandLineRunner(args)
clr.setupLogging()
clr.checkVersion()
clr.run()
}
class CommandLineRunner(args: Array<String>) {
val logger = LoggerFactory.getLogger(CommandLineRunner::class.java) as Logger
val options = CommandLineOptions(args)
fun run() {
// Always use the console for now.
try {
CommandLineController(options)
} catch (e: Throwable) {
println("An error occured!")
e.printStackTrace()
logger.error("Exception caught!", e)
System.exit(1)
}
}
fun setupLogging() {
if (options.isSet("anonymize")) {
Utils.anonymize = true
}
logger.trace("Setting up Loggers...")
val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger
val rootContext = rootLogger.getLoggerContext()
rootContext.reset()
val encoder = PatternLayoutEncoder()
encoder.setContext(rootContext)
encoder.setPattern("%d{HH:mm:ss.SSS} %-5level %-35.-35(%logger{0}.%method): %message%n")
encoder.start()
val appender = ConsoleAppender<ILoggingEvent>()
appender.setContext(rootContext)
appender.setEncoder(encoder)
appender.start()
rootLogger.addAppender(appender)
rootLogger.setLevel(Level.OFF)
if (options.isSet("trace")) {
(LoggerFactory.getLogger("de.fabianonline.telegram_backup") as Logger).setLevel(Level.TRACE)
} else if (options.isSet("debug")) {
(LoggerFactory.getLogger("de.fabianonline.telegram_backup") as Logger).setLevel(Level.DEBUG)
}
if (options.isSet("trace_telegram")) {
(LoggerFactory.getLogger("com.github.badoualy") as Logger).setLevel(Level.TRACE)
}
}
fun checkVersion() {
if (Config.APP_APPVER.contains("-")) {
println("Your version ${Config.APP_APPVER} seems to be a development version. Version check is disabled.")
return
}
val v = Utils.getNewestVersion()
if (v != null && v.isNewer) {
println()
println()
println()
println("A newer version is vailable!")
println("You are using: " + Config.APP_APPVER)
println("Available: " + v.version)
println("Get it here: " + v.url)
println()
println()
println("Changes in this version:")
println(v.body)
println()
println()
println()
TimeUnit.SECONDS.sleep(5)
}
}
}
| src/main/kotlin/de/fabianonline/telegram_backup/CommandLineRunner.kt | 1797299788 |
package com.github.programmerr47.ganalytics.core
open class DummyClass(val id: Int, val name: String) {
override fun toString() = "DummyClass(id=$id, name=$name)"
}
data class DummyDataClass(val id: Int, val name: String)
class DummyReversedClass(id: Int, name: String) : DummyClass(id, name.reversed()) {
override fun toString() = "DummyReversedClass(id=$id, name=$name)"
}
enum class DummyEnum { ONE, TWO, THREE }
| ganalytics-core/src/test/java/com/github/programmerr47/ganalytics/core/test_classes.kt | 1513421803 |
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.converter
/**
* ## Converter (转换器)
*
* @author lgou2w
* @since 2.0
*/
interface Converter {
}
| API/src/main/kotlin/com/mcmoonlake/api/converter/Converter.kt | 2894087527 |
fun test(): Int {
<selection>val j = 1
fun local() = 1
return local()</selection>
} | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/basic/localFunctionInTheMiddleUnusedVar.kt | 3907613631 |
// PROBLEM: none
class My {
fun <caret>foo() = null
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/implicitNullableNothingType/final.kt | 2024247591 |
package com.kennyc.dashweather
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.preference.ListPreference
import androidx.preference.MultiSelectListPreference
import androidx.preference.PreferenceFragmentCompat
import com.kennyc.dashweather.data.Logger
import com.kennyc.dashweather.data.WeatherRepository
import com.kennyc.dashweather.data.model.LocalPreferences
import javax.inject.Inject
/**
* Created by kcampagna on 10/6/17.
*/
class SettingsFragment : PreferenceFragmentCompat() {
companion object {
const val UPDATE_FREQUENCY_NO_LIMIT = "0"
const val UPDATE_FREQUENCY_1_HOUR = "1"
const val UPDATE_FREQUENCY_3_HOURS = "2"
const val UPDATE_FREQUENCY_4_HOURS = "3"
const val WEATHER_DETAILS_HIGH_LOW = "0"
const val WEATHER_DETAILS_HUMIDITY = "1"
const val WEATHER_DETAILS_LOCATION = "2"
}
@Inject
lateinit var preferences: LocalPreferences
@Inject
lateinit var logger: Logger
@Inject
lateinit var repo: WeatherRepository
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
(context!!.applicationContext as WeatherApp).component.inject(this)
addPreferencesFromResource(R.xml.settings)
val frequencyKey = SettingsActivity.KEY_UPDATE_FREQUENCY
val listPreference: ListPreference = findPreference(frequencyKey) as ListPreference
listPreference.summary = listPreference.entries[preferences.getString(frequencyKey, UPDATE_FREQUENCY_1_HOUR)!!.toInt()]
listPreference.setOnPreferenceChangeListener { preference, newValue ->
val listPreference: ListPreference = preference as ListPreference
listPreference.summary = listPreference.entries[newValue.toString().toInt()]
true
}
val detailsKey = SettingsActivity.KEY_SHOW_WEATHER_DETAILS
val weatherDetails: MultiSelectListPreference = findPreference(detailsKey) as MultiSelectListPreference
preferences.getStringSet(detailsKey,
setOf(SettingsFragment.WEATHER_DETAILS_HIGH_LOW, SettingsFragment.WEATHER_DETAILS_LOCATION))?.let {
setWeatherDetails(weatherDetails, it)
}
weatherDetails.setOnPreferenceChangeListener { preference, newValue ->
setWeatherDetails(preference as MultiSelectListPreference, newValue as Set<String>)
true
}
val version = findPreference(getString(R.string.pref_key_version))
try {
val act = activity as Activity
val pInfo = act.packageManager.getPackageInfo(act.packageName, 0)
version.summary = pInfo.versionName
} catch (e: PackageManager.NameNotFoundException) {
logger.e("Settings", "Unable to get version number")
}
checkPermissions()
findPreference(getString(R.string.pref_key_powered_by)).summary = repo.getWeatherProviderName()
}
private fun checkPermissions() {
val context = activity as Context
val coarsePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
val finePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
val hasPermission = coarsePermission || finePermission
if (!hasPermission) {
findPreference(getString(R.string.pref_key_permission)).setOnPreferenceClickListener {
ActivityCompat.requestPermissions(context as Activity,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION),
SettingsActivity.PERMISSION_REQUEST_CODE)
true
}
}
onPermissionUpdated(hasPermission)
}
private fun setWeatherDetails(weatherDetails: MultiSelectListPreference, uiPreferences: Set<String>) {
val summary = StringBuilder()
val size = uiPreferences.size
uiPreferences.withIndex().forEach {
summary.append(weatherDetails.entries[weatherDetails.findIndexOfValue(it.value)])
if (it.index < size - 1) summary.append("\n")
}
weatherDetails.summary = summary.toString()
}
fun onPermissionUpdated(available: Boolean) {
val stringRes = if (available) R.string.preference_permission_granted else R.string.preference_permission_declined
findPreference(getString(R.string.pref_key_permission)).setSummary(stringRes)
}
} | app/src/main/java/com/kennyc/dashweather/SettingsFragment.kt | 2562777782 |
// WITH_STDLIB
// MIN_JAVA_VERSION: 9
// FIX: Replace with 'mutableSetOf' function
fun test() {
val a = java.util.Set.of<caret><String>()
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/collections/mutableSetOf.kt | 1702304623 |
package cy.github
import cy.rfc6570.*
import org.json.simple.*
import java.io.*
import java.net.*
import javax.net.ssl.*
data class Repo(val serverEndpoint: String, val user: String, val repoName: String)
data class Release(val tagName: String, val releaseId: Long, val releasesFormat: String, val uploadFormat: String, val htmlPage: String)
fun endpointOf(protoSpec: String?, hostSpec: String) = "${protoSpec ?: "https://"}api.$hostSpec"
fun connectionOf(url: String, method: String = "GET", token: String? = null): HttpURLConnection {
val connection = URL(url).openConnection() as HttpURLConnection
connection.setRequestProperty("User-Agent", "Kotlin")
connection.setRequestProperty("Accept", "application/vnd.github.v3+json")
connection.instanceFollowRedirects = false
connection.allowUserInteraction = false
connection.defaultUseCaches = false
connection.useCaches = false
connection.doInput = true
connection.requestMethod = method
connection.connectTimeout = 15000
connection.readTimeout = 30000
if (token != null) {
connection.setRequestProperty("Authorization", "token " + token)
}
if (connection is HttpsURLConnection) {
// connection.setHostnameVerifier { host, sslsession ->
// if (host in unsafeHosts) {
// } else DefaultHostVerifier...
// }
}
return connection
}
fun jsonOf(url: String, method: String = "GET", token: String? = null, body: JSONObject? = null): JSONObject? {
val connection = connectionOf(url, method, token)
try {
if (body != null) {
connection.setRequestProperty("Content-Type", "application/json")
connection.doOutput = true
connection.outputStream.bufferedWriter(Charsets.UTF_8).use { writer ->
body.writeJSONString(writer)
}
}
return connection.withReader {
JSONValue.parse(it) as JSONObject
}
} catch (ffn: FileNotFoundException) {
return null
} catch (e: IOException) {
throw IOException("Failed due to ${connection.errorStream?.bufferedReader()?.readText()}", e)
} finally {
connection.disconnect()
}
}
fun createRelease(token: String, releasesFormat: String, tagName: String, releaseTitle: String, description: String, preRelease: Boolean): Release? {
val request = JSONObject()
request["tag_name"] = tagName
request["name"] = releaseTitle
request["body"] = description
request["draft"] = false
request["prerelease"] = preRelease
return jsonOf(releasesFormat.expandURLFormat(emptyMap<String, String>()), "POST", token, body = request)?.parseRelease(releasesFormat)
}
fun findRelease(releasesFormat: String, tagName: String, token: String? = null): Release? =
jsonOf("${releasesFormat.expandURLFormat(emptyMap<String, String>())}/tags/${tagName.encodeURLComponent()}", token = token).parseRelease(releasesFormat)
fun JSONObject?.parseRelease(releasesFormat: String): Release? {
val id = this?.getAsLong("id")
return if (this == null || id == null) {
null
} else {
Release(this["tag_name"]!!.toString(), this.getAsLong("id")!!, releasesFormat, this["upload_url"]!!.toString(), this["html_url"]!!.toString())
}
}
fun upload(token: String, uploadFormat: String, source: File, name: String = source.name) {
val connection = connectionOf(uploadFormat.expandURLFormat(mapOf("name" to name)), "POST", token)
connection.setRequestProperty("Content-Type", when (source.extension.toLowerCase()) {
"txt" -> "text/plain"
"html", "htm", "xhtml" -> "text/html"
"md" -> "text/x-markdown"
"adoc", "asciidoc" -> "text/x-asciidoc"
"zip", "war" -> "application/x-zip"
"rar" -> "application/x-rar-compressed"
"js" -> "application/javascript"
"gzip", "gz", "tgz" -> "application/x-gzip"
"bzip2", "bz2", "tbz", "tbz2" -> "application/bzip2"
"xz", "txz" -> "application/x-xz"
"jar", "ear", "aar" -> "application/java-archive"
"tar" -> "application/x-tar"
"svg", "pom", "xml" -> "text/xml"
"jpg", "jpeg" -> "image/jpeg"
"png" -> "image/png"
"gif" -> "image/gif"
"md5", "sha", "sha1", "sha256", "asc" -> "text/plain"
else -> "binary/octet-stream"
})
connection.doOutput = true
connection.outputStream.use { out ->
source.inputStream().use { ins ->
ins.copyTo(out)
}
}
connection.errorStream?.let { error ->
error.use {
it.copyTo(System.out)
}
throw IOException("${connection.responseCode} ${connection.responseMessage}")
}
connection.withReader {
it.toJSONObject()
}
}
fun probeGitHubRepositoryFormat(base: String = "https://api.github.com", token: String? = null): String =
connectionOf(base, token = token).withReader {
it.toJSONObject()?.get("repository_url")?.toString() ?: throw IllegalArgumentException("No repository_url endpoint found for $base")
}
data class RepositoryUrlFormats(val releasesFormat: String, val tagsFormat: String)
fun probeGitHubReleasesFormat(repositoryFormat: String, repo: Repo, token: String? = null): RepositoryUrlFormats =
connectionOf(repositoryFormat.expandURLFormat(mapOf("owner" to repo.user, "repo" to repo.repoName)), token = token).withReader {
it.toJSONObject()?.let { json ->
RepositoryUrlFormats(
releasesFormat = json.required("releases_url"),
tagsFormat = json.required("tags_url")
)
} ?: throw IllegalArgumentException("No response found")
}
fun JSONObject.required(name: String) = get(name)?.toString() ?: throw IllegalArgumentException("No $name found") | github-release-shared/src/main/kotlin/github-api.kt | 1291683848 |
package uk.tldcode.math.tldmaths
import java.math.BigInteger
import uk.tldcode.math.tldmaths.biginteger.*
object Phi {
operator fun invoke(n: BigInteger):BigInteger{
return (BigInteger.ONE..n).bigCount{Coprime(it,n)}
}
} | TLDMaths/src/main/kotlin/uk/tldcode/math/tldmaths/Phi.kt | 3458307525 |
package soutvoid.com.DsrWeatherApp.interactor.common.network
object ServerConstants {
const val API_KEY_PARAMETER = "appid"
const val API_KEY = "c0c7d349be8cec8728ea408d0e6acfe7"
const val UNITS_PARAMETER = "units"
const val QUERY_PARAMETER = "q"
const val CITY_ID_PARAMETER = "id"
const val LATITUDE_PARAMETER = "lat"
const val LONGITUDE_PARAMETER = "lon"
const val ZIP_CODE_PARAMETER = "zip"
const val ACCURACY_PARAMETER = "type"
const val LANG_PARAMETER = "lang"
} | app/src/main/java/soutvoid/com/DsrWeatherApp/interactor/common/network/ServerConstants.kt | 3398422585 |
package me.serce.solidity.ide.colors
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import me.serce.solidity.ide.SolHighlighter
import me.serce.solidity.ide.SolidityIcons
import me.serce.solidity.lang.SolidityLanguage
import me.serce.solidity.loadCodeSampleResource
class SolColorSettingsPage : ColorSettingsPage {
private val ATTRIBUTES: Array<AttributesDescriptor> = SolColor.values().map { it.attributesDescriptor }.toTypedArray()
private val ANNOTATOR_TAGS = SolColor.values().associateBy({ it.name }, { it.textAttributesKey })
private val DEMO_TEXT by lazy {
loadCodeSampleResource(this, "me/serce/solidity/ide/colors/highlighter_example.sol")
}
override fun getDisplayName() = SolidityLanguage.displayName
override fun getIcon() = SolidityIcons.FILE_ICON
override fun getAttributeDescriptors() = ATTRIBUTES
override fun getColorDescriptors(): Array<ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getHighlighter() = SolHighlighter
override fun getAdditionalHighlightingTagToDescriptorMap() = ANNOTATOR_TAGS
override fun getDemoText() = DEMO_TEXT
}
| src/main/kotlin/me/serce/solidity/ide/colors/SolColorSettingsPage.kt | 3780657906 |
package test.j2k
class Converter
| plugins/kotlin/j2k/old/tests/testData/fileOrElement/importStatement/simpleImport.kt | 414098835 |
/*
* 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.locationaddress.data
import android.location.Geocoder
import android.location.Location
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import javax.inject.Inject
data class FormattedAddress(val display: String)
/** Provides an API to search for addresses from a [Location]. */
class GeocodingApi @Inject constructor(
private val geocoder: Geocoder
) {
// Geocoder specifically says that this call can use network and that it must not be called
// from the main thread, so move it to the IO dispatcher.
suspend fun getFromLocation(
location: Location,
maxResults: Int = 1
): List<FormattedAddress> = withContext(Dispatchers.IO) {
try {
val addresses = geocoder.getFromLocation(
location.latitude,
location.longitude,
maxResults
) ?: emptyList()
addresses.map { address ->
FormattedAddress(
(0..address.maxAddressLineIndex)
.joinToString("\n") { address.getAddressLine(it) }
)
}
} catch (e: IOException) {
Log.w("GeocodingApi", "Error trying to get address from location.", e)
emptyList()
}
}
}
| LocationAddress/app/src/main/java/com/google/android/gms/location/sample/locationaddress/data/GeocodingApi.kt | 3283817482 |
/*
* 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.dao
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import de.dreier.mytargets.shared.models.augmented.AugmentedEnd
import de.dreier.mytargets.shared.models.db.End
import de.dreier.mytargets.shared.models.db.EndImage
import de.dreier.mytargets.shared.models.db.Round
import de.dreier.mytargets.shared.models.db.Shot
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.threeten.bp.LocalTime
@RunWith(AndroidJUnit4::class)
open class EndDAOTest : DAOTestBase() {
@Before
fun initRound() {
appDatabase.roundDAO().insertRound(Round(id = 1))
}
@Test
fun saveCompleteEndSavesData() {
val endToInsert = EndFactory.makeSimpleEnd(1)
appDatabase.endDAO().insertCompleteEnd(endToInsert.end, endToInsert.images, endToInsert.shots)
assertThat(endToInsert.id).isGreaterThan(0)
val ends = appDatabase.endDAO().loadEnds(1)
assertThat(ends.size).isEqualTo(1)
assertThat(ends[0].id).isEqualTo(endToInsert.id)
assertThat(ends[0].exact)
assertThat(ends[0].saveTime).isEqualTo(LocalTime.of(12, 42))
assertThat(ends[0].index).isEqualTo(0)
val images = appDatabase.endDAO().loadEndImages(ends[0].id)
assertThat(images).isEmpty()
val shots = appDatabase.endDAO().loadShots(ends[0].id)
assertThat(shots.size).isEqualTo(2)
assertThat(shots[0].index).isEqualTo(0)
assertThat(shots[1].index).isEqualTo(1)
assertThat(shots[0].x).isEqualTo(0.5f)
assertThat(shots[0].scoringRing).isEqualTo(4)
assertThat(shots[1].y).isEqualTo(0.4f)
assertThat(shots[1].scoringRing).isEqualTo(5)
}
@Test
fun insertEndUpdatesIndicesWhenInsertedAtFront() {
val firstEnd = EndFactory.makeSimpleEnd(1)
appDatabase.endDAO().insertCompleteEnd(firstEnd.end, firstEnd.images, firstEnd.shots)
val insertedEnd = EndFactory.makeSimpleEnd(1)
appDatabase.endDAO().insertEnd(insertedEnd.end, insertedEnd.images, insertedEnd.shots)
val ends = appDatabase.endDAO().loadEnds(1)
assertThat(ends.size).isEqualTo(2)
assertThat(ends[0].index).isEqualTo(0)
assertThat(ends[1].index).isEqualTo(1)
}
@Test
fun insertEndUpdatesIndicesWhenInsertedAtBack() {
val firstEnd = EndFactory.makeSimpleEnd(1)
appDatabase.endDAO().insertCompleteEnd(firstEnd.end, firstEnd.images, firstEnd.shots)
val insertedEnd = EndFactory.makeSimpleEnd(1)
insertedEnd.end.comment = "second"
insertedEnd.end.index = 1
appDatabase.endDAO().insertEnd(insertedEnd.end, insertedEnd.images, insertedEnd.shots)
val ends = appDatabase.endDAO().loadEnds(1)
assertThat(ends.size).isEqualTo(2)
assertThat(ends[0].index).isEqualTo(0)
assertThat(ends[1].index).isEqualTo(1)
assertThat(ends[0].comment).isEqualTo("")
assertThat(ends[1].comment).isEqualTo("second")
}
@Test
fun deleteEndUpdatesIndices() {
val firstEnd = EndFactory.makeSimpleEnd(1)
appDatabase.endDAO().insertCompleteEnd(firstEnd.end, firstEnd.images, firstEnd.shots)
val insertedEnd = EndFactory.makeSimpleEnd(1)
insertedEnd.end.comment = "second"
insertedEnd.end.index = 1
appDatabase.endDAO().insertCompleteEnd(insertedEnd.end, insertedEnd.images, insertedEnd.shots)
appDatabase.endDAO().deleteEnd(firstEnd.end)
val ends = appDatabase.endDAO().loadEnds(1)
assertThat(ends.size).isEqualTo(1)
assertThat(ends[0].index).isEqualTo(0)
assertThat(ends[0].comment).isEqualTo("second")
}
}
class EndFactory {
companion object {
fun makeSimpleEnd(roundId: Long): AugmentedEnd {
val end =
End(roundId = roundId, exact = true, index = 0, saveTime = LocalTime.of(12, 42))
val images = mutableListOf<EndImage>()
val shots = mutableListOf<Shot>()
shots.add(Shot(index = 0, x = 0.5f, y = 0.4f, scoringRing = 4))
shots.add(Shot(index = 1, x = 0.5f, y = 0.4f, scoringRing = 5))
return AugmentedEnd(end = end, images = images, shots = shots)
}
}
}
| app/src/androidTest/java/de/dreier/mytargets/dao/EndDAOTest.kt | 2070914643 |
package org.pixelndice.table.pixelserver.connection.ping
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelprotocol.Protobuf
private val logger = LogManager.getLogger(StateStop::class.java)
class StateStop : StatePing {
override fun process(ctx: ContextPing) {
val packet: Protobuf.Packet? = ctx.channel.packet
if (packet != null) {
if (packet.payloadCase != Protobuf.Packet.PayloadCase.END &&
packet.payloadCase != Protobuf.Packet.PayloadCase.ENDWITHERROR) {
logger.error("Expecting Protobuf.Packet.PayloadCase.END || ENDWITHERROR instead received ${packet.payloadCase}. IP:${ctx.channel.address}")
}
}
}
}
| src/main/kotlin/org/pixelndice/table/pixelserver/connection/ping/StateStop.kt | 3809462923 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val EXT_robustness2 = "EXTRobustness2".nativeClassVK("EXT_robustness2", type = "device", postfix = "EXT") {
documentation =
"""
This extension adds stricter requirements for how out of bounds reads and writes are handled. Most accesses <b>must</b> be tightly bounds-checked, out of bounds writes <b>must</b> be discarded, out of bound reads <b>must</b> return zero. Rather than allowing multiple possible <code>(0,0,0,x)</code> vectors, the out of bounds values are treated as zero, and then missing components are inserted based on the format as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#textures-conversion-to-rgba">Conversion to RGBA</a> and <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#fxvertex-input-extraction">vertex input attribute extraction</a>.
These additional requirements <b>may</b> be expensive on some implementations, and should only be enabled when truly necessary.
This extension also adds support for “{@code null descriptors}”, where #NULL_HANDLE <b>can</b> be used instead of a valid handle. Accesses to null descriptors have well-defined behavior, and do not rely on robustness.
<h5>Examples</h5>
None.
<h5>VK_EXT_robustness2</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_EXT_robustness2}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>287</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Liam Middlebrook <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_robustness2]%20@liam-middlebrook%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_robustness2%20extension%3E%3E">liam-middlebrook</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2020-01-29</dd>
<dt><b>IP Status</b></dt>
<dd>No known IP claims.</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Liam Middlebrook, NVIDIA</li>
<li>Jeff Bolz, NVIDIA</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"EXT_ROBUSTNESS_2_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"EXT_ROBUSTNESS_2_EXTENSION_NAME".."VK_EXT_robustness2"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT".."1000286000",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_PROPERTIES_EXT".."1000286001"
)
} | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_robustness2.kt | 1519679744 |
package top.zbeboy.isy.service.data
import org.jooq.Result
import top.zbeboy.isy.domain.tables.pojos.CollegeApplication
import top.zbeboy.isy.domain.tables.records.CollegeApplicationRecord
/**
* Created by zbeboy 2017-12-02 .
**/
interface CollegeApplicationService {
/**
* 通过应用id删除
*
* @param applicationId 应用id
*/
fun deleteByApplicationId(applicationId: String)
/**
* 通过院id查询
*
* @param collegeId 院id
* @return 数据
*/
fun findByCollegeId(collegeId: Int): Result<CollegeApplicationRecord>
/**
* 保存
*
* @param collegeApplication 表数据
*/
fun save(collegeApplication: CollegeApplication)
/**
* 通过院id删除
*
* @param collegeId 院id
*/
fun deleteByCollegeId(collegeId: Int)
} | src/main/java/top/zbeboy/isy/service/data/CollegeApplicationService.kt | 3874865763 |
package co.smartreceipts.android.search
import co.smartreceipts.android.widget.viper.BaseViperPresenter
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class SearchPresenter(view: SearchView, interactor: SearchInteractor, private val debounceScheduler: Scheduler) :
BaseViperPresenter<SearchView, SearchInteractor>(view, interactor) {
@Inject
constructor(view: SearchView, interactor: SearchInteractor) : this(view, interactor, Schedulers.computation())
override fun subscribe() {
compositeDisposable.add(
view.inputChanges
.filter { it.isNotBlank() }
.debounce(250, TimeUnit.MILLISECONDS, debounceScheduler)
.map { it.trim() }
.observeOn(AndroidSchedulers.mainThread())
.flatMapSingle { input: CharSequence -> interactor.getSearchResults(input.toString()) }
.subscribe { searchResults -> view.presentSearchResults(searchResults) }
)
}
} | app/src/main/java/co/smartreceipts/android/search/SearchPresenter.kt | 1125055007 |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots.ui.configuration
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import java.util.*
/**
* @author nik
*/
class ObsoleteLibraryFilesRemover(private val project: Project) {
private val oldRoots = LinkedHashSet<VirtualFile>()
fun registerObsoleteLibraryRoots(roots: Collection<VirtualFile>) {
oldRoots += roots
}
fun deleteFiles() {
val index = ProjectFileIndex.getInstance(project)
//do not suggest to delete library files located outside project roots: they may be used in other projects or aren't stored in VCS
val toDelete = oldRoots.filter { it.isValid && !index.isInLibrary(it) && index.isInContent(VfsUtil.getLocalFile(it)) }
oldRoots.clear()
if (toDelete.isNotEmpty()) {
val many = toDelete.size > 1
if (Messages.showYesNoDialog(project, "The following ${if (many) "files aren't" else "file isn't"} used anymore:\n" +
"${toDelete.joinToString("\n") { it.presentableUrl }}\n" +
"Do you want to delete ${if (many) "them" else "it"}?\n" +
"You might not be able to fully undo this operation!",
"Delete Unused Files", null) == Messages.YES) {
runWriteAction {
toDelete.forEach {
VfsUtil.getLocalFile(it).delete(this)
}
}
}
}
}
} | java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ObsoleteLibraryFilesRemover.kt | 1717388165 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.configurationStore.schemeManager.SchemeChangeApplicator
import com.intellij.configurationStore.schemeManager.SchemeChangeEvent
import com.intellij.configurationStore.schemeManager.useSchemeLoader
import com.intellij.ide.impl.ProjectUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectReloadState
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.UserDataHolderEx
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.VirtualFileManagerListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.ui.AppUIUtil
import com.intellij.util.ExceptionUtil
import com.intellij.util.SingleAlarm
import com.intellij.util.containers.MultiMap
import gnu.trove.THashSet
import kotlinx.coroutines.withContext
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
private val CHANGED_FILES_KEY = Key<MultiMap<ComponentStoreImpl, StateStorage>>("CHANGED_FILES_KEY")
private val CHANGED_SCHEMES_KEY = Key<MultiMap<SchemeChangeApplicator, SchemeChangeEvent>>("CHANGED_SCHEMES_KEY")
internal class StoreReloadManagerImpl : StoreReloadManager, Disposable {
private val reloadBlockCount = AtomicInteger()
private val blockStackTrace = AtomicReference<String?>()
private val changedApplicationFiles = LinkedHashSet<StateStorage>()
private val changedFilesAlarm = SingleAlarm(Runnable {
if (!isReloadUnblocked() || !tryToReloadApplication()) {
return@Runnable
}
val projectsToReload = THashSet<Project>()
for (project in ProjectManager.getInstance().openProjects) {
if (project.isDisposed) {
continue
}
val changedSchemes = CHANGED_SCHEMES_KEY.getAndClear(project as UserDataHolderEx)
val changedStorages = CHANGED_FILES_KEY.getAndClear(project as UserDataHolderEx)
if ((changedSchemes == null || changedSchemes.isEmpty) && (changedStorages == null || changedStorages.isEmpty)) {
continue
}
runBatchUpdate(project.messageBus) {
// reload schemes first because project file can refer to scheme (e.g. inspection profile)
if (changedSchemes != null) {
useSchemeLoader { schemeLoaderRef ->
for ((tracker, files) in changedSchemes.entrySet()) {
LOG.runAndLogException {
tracker.reload(files, schemeLoaderRef)
}
}
}
}
if (changedStorages != null) {
for ((store, storages) in changedStorages.entrySet()) {
if ((store.storageManager as? StateStorageManagerImpl)?.componentManager?.isDisposed == true) {
continue
}
@Suppress("UNCHECKED_CAST")
if (reloadStore(storages as Set<StateStorage>, store) == ReloadComponentStoreStatus.RESTART_AGREED) {
projectsToReload.add(project)
}
}
}
}
}
for (project in projectsToReload) {
doReloadProject(project)
}
}, delay = 300, parentDisposable = this)
init {
ApplicationManager.getApplication().messageBus.connect(this).subscribe(STORAGE_TOPIC, object : StorageManagerListener {
override fun storageFileChanged(event: VFileEvent, storage: StateStorage, componentManager: ComponentManager) {
if (event.requestor is StoreReloadManager) {
return
}
registerChangedStorage(storage, componentManager)
}
})
VirtualFileManager.getInstance().addVirtualFileManagerListener(object : VirtualFileManagerListener {
override fun beforeRefreshStart(asynchronous: Boolean) {
blockReloadingProjectOnExternalChanges()
}
override fun afterRefreshFinish(asynchronous: Boolean) {
unblockReloadingProjectOnExternalChanges()
}
})
}
private fun isReloadUnblocked(): Boolean {
val count = reloadBlockCount.get()
LOG.debug { "[RELOAD] myReloadBlockCount = $count" }
return count == 0
}
override fun saveChangedProjectFile(file: VirtualFile, project: Project) {
val storageManager = (project.stateStore as ComponentStoreImpl).storageManager as? StateStorageManagerImpl ?: return
storageManager.getCachedFileStorages(listOf(storageManager.collapseMacros(file.path))).firstOrNull()?.let {
// if empty, so, storage is not yet loaded, so, we don't have to reload
registerChangedStorage(it, project)
}
}
override fun blockReloadingProjectOnExternalChanges() {
if (reloadBlockCount.getAndIncrement() == 0 && !ApplicationInfoImpl.isInStressTest()) {
blockStackTrace.set(ExceptionUtil.currentStackTrace())
}
}
override fun unblockReloadingProjectOnExternalChanges() {
val counter = reloadBlockCount.get()
if (counter <= 0) {
LOG.error("Block counter $counter must be > 0, first block stack trace: ${blockStackTrace.get()}")
}
if (reloadBlockCount.decrementAndGet() != 0) {
return
}
blockStackTrace.set(null)
changedFilesAlarm.request()
}
/**
* Internal use only. Force reload changed project files. Must be called before save otherwise saving maybe not performed (because storage saving is disabled).
*/
override fun flushChangedProjectFileAlarm() {
changedFilesAlarm.drainRequestsInTest()
}
override suspend fun reloadChangedStorageFiles() {
val unfinishedRequest = changedFilesAlarm.getUnfinishedRequest() ?: return
withContext(storeEdtCoroutineContext) {
unfinishedRequest.run()
// just to be sure
changedFilesAlarm.getUnfinishedRequest()?.run()
}
}
override fun reloadProject(project: Project) {
CHANGED_FILES_KEY.set(project, null)
doReloadProject(project)
}
private fun registerChangedStorage(storage: StateStorage, componentManager: ComponentManager) {
if (LOG.isDebugEnabled) {
LOG.debug("[RELOAD] Registering project to reload: $storage", Exception())
}
val project: Project? = when (componentManager) {
is Project -> componentManager
is Module -> componentManager.project
else -> null
}
if (project == null) {
val changes = changedApplicationFiles
synchronized (changes) {
changes.add(storage)
}
}
else {
val changes = CHANGED_FILES_KEY.get(project) ?: (project as UserDataHolderEx).putUserDataIfAbsent(CHANGED_FILES_KEY, MultiMap.createLinkedSet())
synchronized (changes) {
changes.putValue(componentManager.stateStore as ComponentStoreImpl, storage)
}
}
if (storage is StateStorageBase<*>) {
storage.disableSaving()
}
if (isReloadUnblocked()) {
changedFilesAlarm.cancelAndRequest()
}
}
internal fun registerChangedSchemes(events: List<SchemeChangeEvent>, schemeFileTracker: SchemeChangeApplicator, project: Project) {
if (LOG.isDebugEnabled) {
LOG.debug("[RELOAD] Registering scheme to reload: $events", Exception())
}
val changes = CHANGED_SCHEMES_KEY.get(project) ?: (project as UserDataHolderEx).putUserDataIfAbsent(CHANGED_SCHEMES_KEY, MultiMap.createLinkedSet())
synchronized(changes) {
changes.putValues(schemeFileTracker, events)
}
if (isReloadUnblocked()) {
changedFilesAlarm.cancelAndRequest()
}
}
private fun tryToReloadApplication(): Boolean {
if (ApplicationManager.getApplication().isDisposed) {
return false
}
if (changedApplicationFiles.isEmpty()) {
return true
}
val changes = LinkedHashSet<StateStorage>(changedApplicationFiles)
changedApplicationFiles.clear()
return reloadAppStore(changes)
}
override fun dispose() {
}
}
fun reloadAppStore(changes: Set<StateStorage>): Boolean {
val status = reloadStore(changes, ApplicationManager.getApplication().stateStore as ComponentStoreImpl)
if (status == ReloadComponentStoreStatus.RESTART_AGREED) {
ApplicationManagerEx.getApplicationEx().restart(true)
return false
}
else {
return status == ReloadComponentStoreStatus.SUCCESS || status == ReloadComponentStoreStatus.RESTART_CANCELLED
}
}
internal fun reloadStore(changedStorages: Set<StateStorage>, store: ComponentStoreImpl): ReloadComponentStoreStatus {
val notReloadableComponents: Collection<String>?
var willBeReloaded = false
try {
try {
notReloadableComponents = store.reload(changedStorages)
}
catch (e: Throwable) {
LOG.warn(e)
AppUIUtil.invokeOnEdt {
Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.message), ProjectBundle.message("project.reload.failed.title"))
}
return ReloadComponentStoreStatus.ERROR
}
if (notReloadableComponents == null || notReloadableComponents.isEmpty()) {
return ReloadComponentStoreStatus.SUCCESS
}
willBeReloaded = askToRestart(store, notReloadableComponents, changedStorages, store.project == null)
return if (willBeReloaded) ReloadComponentStoreStatus.RESTART_AGREED else ReloadComponentStoreStatus.RESTART_CANCELLED
}
finally {
if (!willBeReloaded) {
for (storage in changedStorages) {
if (storage is StateStorageBase<*>) {
storage.enableSaving()
}
}
}
}
}
// used in settings repository plugin
fun askToRestart(store: IComponentStore, notReloadableComponents: Collection<String>, changedStorages: Set<StateStorage>?, isApp: Boolean): Boolean {
val message = StringBuilder()
val storeName = if (store is IProjectStore) "Project '${store.projectName}'" else "Application"
message.append(storeName).append(' ')
message.append("components were changed externally and cannot be reloaded:\n\n")
var count = 0
for (component in notReloadableComponents) {
if (count == 10) {
message.append('\n').append("and ").append(notReloadableComponents.size - count).append(" more").append('\n')
}
else {
message.append(component).append('\n')
count++
}
}
message.append("\nWould you like to ")
if (isApp) {
message.append(if (ApplicationManager.getApplication().isRestartCapable) "restart" else "shutdown").append(' ')
message.append(ApplicationNamesInfo.getInstance().productName).append('?')
}
else {
message.append("reload project?")
}
if (Messages.showYesNoDialog(message.toString(), "$storeName Files Changed", Messages.getQuestionIcon()) == Messages.YES) {
if (changedStorages != null) {
for (storage in changedStorages) {
if (storage is StateStorageBase<*>) {
storage.disableSaving()
}
}
}
return true
}
return false
}
internal enum class ReloadComponentStoreStatus {
RESTART_AGREED,
RESTART_CANCELLED,
ERROR,
SUCCESS
}
private fun <T : Any> Key<T>.getAndClear(holder: UserDataHolderEx): T? {
val value = holder.getUserData(this) ?: return null
holder.replace(this, value, null)
return value
}
private fun doReloadProject(project: Project) {
val projectRef = Ref.create(project)
ProjectReloadState.getInstance(project).onBeforeAutomaticProjectReload()
ApplicationManager.getApplication().invokeLater({
LOG.debug("Reloading project.")
val project1 = projectRef.get()
// Let it go
projectRef.set(null)
if (project1.isDisposed) {
return@invokeLater
}
// must compute here, before project dispose
val presentableUrl = project1.presentableUrl
if (!ProjectUtil.closeAndDispose(project1)) {
return@invokeLater
}
ProjectUtil.openProject(Objects.requireNonNull<String>(presentableUrl), null, true)
}, ModalityState.NON_MODAL)
} | platform/configuration-store-impl/src/StoreReloadManagerImpl.kt | 294707453 |
// Copyright 2017 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// PdfLayoutMgr is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2.lineWrapping
import com.planbase.pdf.lm2.attributes.DimAndPageNums
import com.planbase.pdf.lm2.contents.WrappedText
import com.planbase.pdf.lm2.pages.RenderTarget
import com.planbase.pdf.lm2.utils.Coord
import com.planbase.pdf.lm2.utils.Dim
import org.organicdesign.indented.IndentedStringable
import org.organicdesign.indented.StringUtils.listToStr
import kotlin.math.nextUp
// TODO: Rename to MultiItemWrappedLine?
/** A mutable data structure to hold a single wrapped line consisting of multiple items. */
class MultiLineWrapped(tempItems: Iterable<LineWrapped>?) : LineWrapped, IndentedStringable {
constructor() : this(null)
var width: Double = 0.0
override var ascent: Double = 0.0
internal var lineHeight: Double = 0.0
internal val items: MutableList<LineWrapped> = mutableListOf()
init {
tempItems?.forEach { append(it) }
}
override val dim: Dim
get() = Dim(width, lineHeight)
override fun items(): List<LineWrapped> = items
private var descentLeading = lineHeight - ascent
fun isEmpty() = items.isEmpty()
fun append(fi: LineWrapped): MultiLineWrapped {
// lineHeight has to be ascent + descentLeading because we align on the baseline
ascent = maxOf(ascent, fi.ascent)
descentLeading = maxOf(descentLeading, fi.dim.height - fi.ascent)
lineHeight = ascent + descentLeading
width += fi.dim.width
items.add(fi)
return this
}
override fun render(lp: RenderTarget, topLeft: Coord, reallyRender: Boolean, justifyWidth: Double): DimAndPageNums {
// println("this=$this")
// println(" MultiLineWrapped.render(${lp.javaClass.simpleName}, $topLeft, reallyRender=$reallyRender, $justifyWidth=justifyWidth)")
// Note that I'm using height.nextUp() so that if there's a rounding error, our whole line gets thrown to
// the next page, not just the line-fragment with the highest ascent.
val adj = lp.pageBreakingTopMargin(topLeft.y - dim.height, dim.height.nextUp(), 0.0)
// println(" adj=$adj")
val y = if (adj == 0.0) {
topLeft.y
} else {
topLeft.y - adj
}
var pageNums: IntRange = DimAndPageNums.INVALID_PAGE_RANGE
var x: Double = topLeft.x
if (reallyRender) {
var tempItems = items
// Text justification calculation 2/2
// Do we need to justify text?
if (justifyWidth > 0.0) {
val contentWidth: Double = dim.width
// Justified text only looks good if the line is long enough.
if (contentWidth > justifyWidth * 0.75) {
val numSpaces: Int = items
.filter { it is WrappedText }
.sumBy { (it as WrappedText).numSpaces }
val wordSpacing = (justifyWidth - contentWidth) / numSpaces
tempItems = items.map {
if (it is WrappedText) {
it.withWordSpacing(wordSpacing)
} else {
it
}
}.toMutableList()
}
}
// Now that we've accounted for anything on the line that could cause a page-break,
// really render each wrapped item in this line
//
// Text rendering calculation spot 2/3
// ascent is the maximum ascent for anything on this line.
// _____
// / | \ \
// | | \ |
// (max) | | | > ascentDiff
// ascent < |_____/ |
// | | \ _ /
// | | \ |_)
// \. .|. . . .\. | \. . . .
// ^item
//
// Subtracting that from the top-y
// yields the baseline, which is what we want to align on.
for (item: LineWrapped in tempItems) {
val ascentDiff = ascent - item.ascent
// println(" item=$item, ascentDiff=$ascentDiff")
val innerUpperLeft = Coord(x, y - ascentDiff)
val dimAndPageNums: DimAndPageNums = item.render(lp, innerUpperLeft, true)
x += item.dim.width
pageNums = dimAndPageNums.maxExtents(pageNums)
}
} else {
pageNums = lp.pageNumFor(y)..lp.pageNumFor(y - dim.height)
x = topLeft.x + dim.width
}
return DimAndPageNums(Dim(x - topLeft.x, (topLeft.y - y) + dim.height), pageNums)
} // end fun render()
override fun indentedStr(indent: Int): String =
"MultiLineWrapped(width=$width, ascent=$ascent, lineHeight=$lineHeight, items=\n" +
"${listToStr(indent + "MultiLineWrapped(".length, items)})"
override fun toString(): String = indentedStr(0)
companion object {
/**
Given a maximum width, turns a list of renderables into a list of fixed-item WrappedMultiLineWrappeds.
This allows each line to contain multiple Renderables. They are baseline-aligned.
If any renderables are not text, their bottom is aligned to the text baseline.
Start a new line.
For each renderable
While renderable is not empty
If our current line is empty
add items.getSomething(blockWidth) to our current line.
Else
If getIfFits(blockWidth - line.widthSoFar)
add it to our current line.
Else
complete our line
Add it to finishedLines
start a new line.
*/
@JvmStatic
fun wrapLines(wrappables: List<LineWrappable>, maxWidth: Double): List<LineWrapped> {
// println("================in wrapLines...")
// println("wrapLines($wrappables, $maxWidth)")
if (maxWidth < 0) {
throw IllegalArgumentException("maxWidth must be >= 0, not $maxWidth")
}
// These are lines consisting of multiple (line-wrapped) items.
val wrappedLines: MutableList<LineWrapped> = mutableListOf()
// This is the current line we're working on.
var wrappedLine = MultiLineWrapped() // Is this right, putting no source here?
// var prevItem:LineWrappable = LineWrappable.ZeroLineWrappable
var unusedWidth = maxWidth
for (item in wrappables) {
// println("Wrappable: $item")
val lineWrapper: LineWrapper = item.lineWrapper()
while (lineWrapper.hasMore()) {
// println(" lineWrapper.hasMore()")
if (wrappedLine.isEmpty()) {
unusedWidth = maxWidth
// println(" wrappedLine.isEmpty()")
val something: ConTerm = lineWrapper.getSomething(maxWidth)
// println("🢂something=$something")
wrappedLine.append(something.item)
unusedWidth -= something.item.dim.width
// println(" unusedWidth1=$unusedWidth")
if (something is Terminal) {
// println("=============== TERMINAL")
// println("something:$something")
addLineCheckBlank(wrappedLine, wrappedLines)
wrappedLine = MultiLineWrapped()
unusedWidth = maxWidth
} else if ((something is Continuing) &&
(something.hasMore)) {
// println(" Continuing and has more. Adding line so far and starting a new one.")
// If we got as much as we could and there's more left, then it has to go on the next line.
addLineCheckBlank(wrappedLine, wrappedLines)
wrappedLine = MultiLineWrapped()
unusedWidth = maxWidth
} else if (lineWrapper.hasMore()) {
throw Exception("This shouldn't happen any more. 1")
// println(" LOOKAHEAD??? lineWrapper.hasMore()")
// We have a line of text which is too long and must be broken up. But if it’s too long by less
// than the width of a single space, it truncates the final space from the text fragment, then
// looks again and sees that the next word now fits, so adds it to the same line *without the space*
// which is wrong. To fix this, we check if the lineWrapper already gave us all it has for this
// line and if so, we store it and start the next line.
// addLineCheckBlank(wrappedLine, wrappedLines)
// wrappedLine = MultiLineWrapped()
// // This should never happen any more and should be deleted.
// if ( (something is Continuing) &&
// (something.item is WrappedText) ) {
// unusedWidth -= (something.item as WrappedText).textStyle.spaceWidth
// }
// println(" unusedWidth2=$unusedWidth")
}
} else {
// println(" wrappedLine is not empty")
val ctn: ConTermNone = lineWrapper.getIfFits(unusedWidth) //maxWidth - wrappedLine.width)
// println("🢂ctn=$ctn")
when (ctn) {
is Continuing -> {
// println(" appending result to current wrapped line")
wrappedLine.append(ctn.item)
if (ctn.hasMore) {
// println(" ctn.hasMore but it has to go on the next line.")
addLineCheckBlank(wrappedLine, wrappedLines)
wrappedLine = MultiLineWrapped()
unusedWidth = maxWidth
} else {
// println(" ctn doesn't have more, so something else might fit on this line.")
unusedWidth -= ctn.item.dim.width
}
// println(" unusedWidth3=$unusedWidth")
if (unusedWidth <= 0) {
throw Exception("This shouldn't happen any more. 2")
// addLineCheckBlank(wrappedLine, wrappedLines)
// wrappedLine = MultiLineWrapped()
// unusedWidth = maxWidth
}
}
is Terminal -> {
// println("=============== TERMINAL 222222222")
// println("ctn:$ctn")
wrappedLine.append(ctn.item)
wrappedLine = MultiLineWrapped()
unusedWidth = maxWidth
}
None -> {
// println("=============== NONE 222222222")
// MultiLineWrappeds.add(wrappedLine)
addLineCheckBlank(wrappedLine, wrappedLines)
wrappedLine = MultiLineWrapped()
unusedWidth = maxWidth
}
}
}
} // end while lineWrapper.hasMore()
} // end for item in wrappables
// println("Line before last item: $wrappedLine")
// Don't forget to add last item.
addLineCheckBlank(wrappedLine, wrappedLines)
return wrappedLines.toList()
}
private fun addLineCheckBlank(currLine: MultiLineWrapped,
wrappedLines: MutableList<LineWrapped>) {
// If this item is a blank line, take the height from the previous item (if there is one).
if (currLine.isEmpty() && wrappedLines.isNotEmpty()) {
val lastRealItem: LineWrapped = wrappedLines.last().items().last()
// println("================================ adding a spacer ===========================")
wrappedLines.add(BlankLineWrapped(Dim(0.0, lastRealItem.dim.height), lastRealItem.ascent))
} else if (currLine.items.size == 1) {
// Don't add a MultilineWrapped if we can just add a single wrapped thing.
// Trim space from final item on completed line.
val lastItem = currLine.items[0]
wrappedLines.add(when (lastItem) {
is WrappedText -> lastItem.withoutTrailingSpace()
else -> lastItem
})
} else {
// Add multiple items.
if (currLine.items.size > 1) {
// Trim space from final item on completed line.
val lastIdx = currLine.items.lastIndex
val lastItem = currLine.items[lastIdx]
if (lastItem is WrappedText) {
currLine.items.removeAt(lastIdx)
currLine.items.add(lastItem.withoutTrailingSpace())
}
}
wrappedLines.add(currLine)
}
}
}
} | src/main/java/com/planbase/pdf/lm2/lineWrapping/MultiLineWrapped.kt | 3792442219 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistics
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.service.fus.collectors.FUStateUsagesLogger
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.util.Version
import org.junit.Assert
import org.junit.Test
class FeatureUsageDataTest {
@Test
fun `test empty data`() {
val build = FeatureUsageData().build()
Assert.assertTrue(build.isEmpty())
}
@Test
fun `test put string data`() {
val build = FeatureUsageData().addData("key", "my-value").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == "my-value")
}
@Test
fun `test put int data`() {
val build = FeatureUsageData().addData("key", 99).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == 99)
}
@Test
fun `test put long data`() {
val value: Long = 99
val build = FeatureUsageData().addData("key", value).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == 99L)
}
@Test
fun `test put boolean data`() {
val build = FeatureUsageData().addData("key", true).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == true)
}
@Test
fun `test put os data`() {
val build = FeatureUsageData().addOS().build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("os"))
}
@Test
fun `test put add null place`() {
val build = FeatureUsageData().addPlace(null).build()
Assert.assertTrue(build.isEmpty())
}
@Test
fun `test put add empty place`() {
val build = FeatureUsageData().addPlace("").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("place"))
Assert.assertTrue(build["place"] == ActionPlaces.UNKNOWN)
}
@Test
fun `test put add common place`() {
val build = FeatureUsageData().addPlace("TestTreeViewToolbar").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("place"))
Assert.assertTrue(build["place"] == "TestTreeViewToolbar")
}
@Test
fun `test put add common popup place`() {
val build = FeatureUsageData().addPlace("FavoritesPopup").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("place"))
Assert.assertTrue(build["place"] == "FavoritesPopup")
}
@Test
fun `test put add custom popup place`() {
val build = FeatureUsageData().addPlace("popup@my-custom-popup").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("place"))
Assert.assertTrue(build["place"] == ActionPlaces.POPUP)
}
@Test
fun `test put add custom place`() {
val build = FeatureUsageData().addPlace("my-custom-popup").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("place"))
Assert.assertTrue(build["place"] == ActionPlaces.UNKNOWN)
}
@Test
fun `test put null obj version`() {
val build = FeatureUsageData().addVersion(null).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "unknown.format")
}
@Test
fun `test put null version`() {
val build = FeatureUsageData().addVersionByString(null).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "unknown")
}
@Test
fun `test put obj version`() {
val build = FeatureUsageData().addVersion(Version(3, 5, 0)).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "3.5")
}
@Test
fun `test put version`() {
val build = FeatureUsageData().addVersionByString("5.11.0").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "5.11")
}
@Test
fun `test put obj version with bugfix`() {
val build = FeatureUsageData().addVersion(Version(3, 5, 9)).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "3.5")
}
@Test
fun `test put version with bugfix`() {
val build = FeatureUsageData().addVersionByString("5.11.98").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "5.11")
}
@Test
fun `test put invalid version`() {
val build = FeatureUsageData().addVersionByString("2018-11").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "2018.0")
}
@Test
fun `test put empty version`() {
val build = FeatureUsageData().addVersionByString("").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "unknown.format")
}
@Test
fun `test put version with snapshot`() {
val build = FeatureUsageData().addVersionByString("1.4-SNAPSHOT").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "1.4")
}
@Test
fun `test put version with suffix`() {
val build = FeatureUsageData().addVersionByString("2.5.0.BUILD-2017091412345").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "2.5")
}
@Test
fun `test put version with letters`() {
val build = FeatureUsageData().addVersionByString("abcd").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "unknown.format")
}
@Test
fun `test copy empty data`() {
val data = FeatureUsageData()
val data2 = data.copy()
Assert.assertTrue(data.build().isEmpty())
Assert.assertEquals(data, data2)
Assert.assertEquals(data.build(), data2.build())
}
@Test
fun `test copy single element data`() {
val data = FeatureUsageData().addData("new-key", "new-value")
val data2 = data.copy()
Assert.assertTrue(data.build().size == 1)
Assert.assertTrue(data.build()["new-key"] == "new-value")
Assert.assertEquals(data, data2)
Assert.assertEquals(data.build(), data2.build())
}
@Test
fun `test copy multi elements data`() {
val data = FeatureUsageData().addData("new-key", "new-value").addData("second", "test")
val data2 = data.copy()
Assert.assertTrue(data.build().size == 2)
Assert.assertTrue(data.build()["new-key"] == "new-value")
Assert.assertTrue(data.build()["second"] == "test")
Assert.assertEquals(data, data2)
Assert.assertEquals(data.build(), data2.build())
}
@Test
fun `test merge empty data`() {
val data = FeatureUsageData()
val data2 = FeatureUsageData()
data.merge(data2, "pr")
Assert.assertTrue(data.build().isEmpty())
}
@Test
fun `test merge empty with not empty data`() {
val data = FeatureUsageData()
val data2 = FeatureUsageData().addData("key", "value")
data.merge(data2, "pr")
val build = data.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == "value")
}
@Test
fun `test merge empty with default not empty data`() {
val data = FeatureUsageData()
val data2 = FeatureUsageData().addData("data_1", "value")
data.merge(data2, "pr_")
val build = data.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["pr_data_1"] == "value")
}
@Test
fun `test merge not empty with empty data`() {
val data = FeatureUsageData().addData("key", "value")
val data2 = FeatureUsageData()
data.merge(data2, "pr")
val build = data.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == "value")
}
@Test
fun `test merge not empty default with empty data`() {
val data = FeatureUsageData().addData("data_2", "value")
val data2 = FeatureUsageData()
data.merge(data2, "pr")
val build = data.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["data_2"] == "value")
}
@Test
fun `test merge not empty data`() {
val data = FeatureUsageData().addData("first", "value-1")
val data2 = FeatureUsageData().addData("second", "value-2").addData("data_99", "default-value")
data.merge(data2, "pr")
Assert.assertTrue(data.build().size == 3)
Assert.assertTrue(data.build()["first"] == "value-1")
Assert.assertTrue(data.build()["second"] == "value-2")
Assert.assertTrue(data.build()["prdata_99"] == "default-value")
}
@Test
fun `test merge null group with null event data`() {
val merged = FUStateUsagesLogger.mergeWithEventData(null, null, 1)
Assert.assertNull(merged)
}
@Test
fun `test merge null group with null event data with not default value`() {
val merged = FUStateUsagesLogger.mergeWithEventData(null, null, 10)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["value"] == 10)
}
@Test
fun `test merge group with null event data`() {
val group = FeatureUsageData().addData("first", "value-1")
val merged = FUStateUsagesLogger.mergeWithEventData(group, null, 1)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["first"] == "value-1")
}
@Test
fun `test merge group with null event data with not default value`() {
val group = FeatureUsageData().addData("first", "value-1")
val merged = FUStateUsagesLogger.mergeWithEventData(group, null, 10)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 2)
Assert.assertTrue(build["first"] == "value-1")
Assert.assertTrue(build["value"] == 10)
}
@Test
fun `test merge null group with event data`() {
val event = FeatureUsageData().addData("first", 99)
val merged = FUStateUsagesLogger.mergeWithEventData(null, event, 1)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["first"] == 99)
}
@Test
fun `test merge null group with default named event data`() {
val event = FeatureUsageData().addData("data_5", 99)
val merged = FUStateUsagesLogger.mergeWithEventData(null, event, 1)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["event_data_5"] == 99)
}
@Test
fun `test merge null group with event data with not default value`() {
val event = FeatureUsageData().addData("first", true)
val merged = FUStateUsagesLogger.mergeWithEventData(null, event, 10)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 2)
Assert.assertTrue(build["first"] == true)
Assert.assertTrue(build["value"] == 10)
}
@Test
fun `test merge null group with default named event data with not default value`() {
val event = FeatureUsageData().addData("data_9", true)
val merged = FUStateUsagesLogger.mergeWithEventData(null, event, 10)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 2)
Assert.assertTrue(build["event_data_9"] == true)
Assert.assertTrue(build["value"] == 10)
}
@Test
fun `test merge group with event data`() {
val group = FeatureUsageData().addData("first", "value-1")
val event = FeatureUsageData().addData("second", "value-2").addData("data_99", "default-value")
val merged = FUStateUsagesLogger.mergeWithEventData(group, event, 1)
val build = merged!!.build()
Assert.assertTrue(build.size == 3)
Assert.assertTrue(build["first"] == "value-1")
Assert.assertTrue(build["second"] == "value-2")
Assert.assertTrue(build["event_data_99"] == "default-value")
}
@Test
fun `test merge group with event data with not default value`() {
val group = FeatureUsageData().addData("first", "value-1")
val event = FeatureUsageData().addData("second", "value-2").addData("data_99", "default-value")
val merged = FUStateUsagesLogger.mergeWithEventData(group, event, 10)
val build = merged!!.build()
Assert.assertTrue(build.size == 4)
Assert.assertTrue(build["first"] == "value-1")
Assert.assertTrue(build["second"] == "value-2")
Assert.assertTrue(build["event_data_99"] == "default-value")
Assert.assertTrue(build["value"] == 10)
}
} | platform/platform-tests/testSrc/com/intellij/internal/statistics/FeatureUsageDataTest.kt | 2576064261 |
/*
* 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.codeInsight.completion
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.ChangedPsiRangeUtil
import com.intellij.psi.impl.source.tree.FileElement
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil
import com.intellij.psi.text.BlockSupport
/**
* @author peter
*/
class OffsetsInFile(val file: PsiFile, val offsets: OffsetMap) {
constructor(file: PsiFile) : this(file, OffsetMap(file.viewProvider.document!!))
fun toTopLevelFile(): OffsetsInFile {
val manager = InjectedLanguageManager.getInstance(file.project)
val hostFile = manager.getTopLevelFile(file)
if (hostFile == file) return this
return OffsetsInFile(hostFile, offsets.mapOffsets(hostFile.viewProvider.document!!) { manager.injectedToHost(file, it) })
}
fun toInjectedIfAny(offset: Int): OffsetsInFile {
val injected = InjectedLanguageUtil.findInjectedPsiNoCommit(file, offset) ?: return this
val documentWindow = InjectedLanguageUtil.getDocumentWindow(injected)!!
return OffsetsInFile(injected, offsets.mapOffsets(documentWindow) { documentWindow.hostToInjected(it) })
}
fun copyWithReplacement(startOffset: Int, endOffset: Int, replacement: String): OffsetsInFile {
return replaceInCopy(file.copy() as PsiFile, startOffset, endOffset, replacement)
}
fun replaceInCopy(fileCopy: PsiFile, startOffset: Int, endOffset: Int, replacement: String): OffsetsInFile {
val tempDocument = DocumentImpl(offsets.document.immutableCharSequence, true)
val tempMap = offsets.copyOffsets(tempDocument)
tempDocument.replaceString(startOffset, endOffset, replacement)
reparseFile(fileCopy, tempDocument.immutableCharSequence)
val copyOffsets = tempMap.copyOffsets(fileCopy.viewProvider.document!!)
return OffsetsInFile(fileCopy, copyOffsets)
}
private fun reparseFile(file: PsiFile, newText: CharSequence) {
val node = file.node as? FileElement ?: throw IllegalStateException("${file.javaClass} ${file.fileType}")
val range = ChangedPsiRangeUtil.getChangedPsiRange(file, node, newText) ?: return
val indicator = ProgressManager.getGlobalProgressIndicator() ?: EmptyProgressIndicator()
val log = BlockSupport.getInstance(file.project).reparseRange(file, node, range, newText, indicator, file.viewProvider.contents)
ProgressManager.getInstance().executeNonCancelableSection { log.doActualPsiChange(file) }
}
}
| platform/lang-impl/src/com/intellij/codeInsight/completion/OffsetsInFile.kt | 2310184449 |
// 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.plugins.groovy.lang.psi.dataFlow.types
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.psi.PsiType
import com.intellij.util.castSafelyTo
import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.VariableDescriptor
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ResolvedVariableDescriptor
import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic
internal class InitialTypeProvider(private val start: GrControlFlowOwner, private val reverseMapping : Array<VariableDescriptor>) {
private val TYPE_INFERENCE_FAILED = Any()
private val cache: MutableMap<Int, Any> = mutableMapOf()
fun initialType(descriptorId: Int): PsiType? {
if (!cache.containsKey(descriptorId)) {
try {
if (isCompileStatic(start)) return null
if (descriptorId >= reverseMapping.size) {
thisLogger().error("Unrecognized variable at index $descriptorId", IllegalStateException(),
Attachment("block.text", start.text),
Attachment("block.flow", start.controlFlow.contentDeepToString()),
Attachment("block.vars", reverseMapping.contentToString()))
} else {
val field = reverseMapping[descriptorId].castSafelyTo<ResolvedVariableDescriptor>()?.variable?.castSafelyTo<GrField>() ?: return null
val fieldType = field.typeGroovy
if (fieldType != null) {
cache[descriptorId] = fieldType
}
}
} finally {
cache.putIfAbsent(descriptorId, TYPE_INFERENCE_FAILED)
}
}
return cache[descriptorId]?.castSafelyTo<PsiType>()
}
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/types/InitialTypeProvider.kt | 1060581683 |
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class OoChildForParentWithPidEntityImpl(val dataSource: OoChildForParentWithPidEntityData) : OoChildForParentWithPidEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentWithPidEntity::class.java,
OoChildForParentWithPidEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val childProperty: String
get() = dataSource.childProperty
override val parentEntity: OoParentWithPidEntity
get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: OoChildForParentWithPidEntityData?) : ModifiableWorkspaceEntityBase<OoChildForParentWithPidEntity>(), OoChildForParentWithPidEntity.Builder {
constructor() : this(OoChildForParentWithPidEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity OoChildForParentWithPidEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isChildPropertyInitialized()) {
error("Field OoChildForParentWithPidEntity#childProperty should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field OoChildForParentWithPidEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field OoChildForParentWithPidEntity#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as OoChildForParentWithPidEntity
this.entitySource = dataSource.entitySource
this.childProperty = dataSource.childProperty
if (parents != null) {
this.parentEntity = parents.filterIsInstance<OoParentWithPidEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var childProperty: String
get() = getEntityData().childProperty
set(value) {
checkModificationAllowed()
getEntityData().childProperty = value
changedProperty.add("childProperty")
}
override var parentEntity: OoParentWithPidEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as OoParentWithPidEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as OoParentWithPidEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): OoChildForParentWithPidEntityData = result ?: super.getEntityData() as OoChildForParentWithPidEntityData
override fun getEntityClass(): Class<OoChildForParentWithPidEntity> = OoChildForParentWithPidEntity::class.java
}
}
class OoChildForParentWithPidEntityData : WorkspaceEntityData<OoChildForParentWithPidEntity>() {
lateinit var childProperty: String
fun isChildPropertyInitialized(): Boolean = ::childProperty.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<OoChildForParentWithPidEntity> {
val modifiable = OoChildForParentWithPidEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): OoChildForParentWithPidEntity {
return getCached(snapshot) {
val entity = OoChildForParentWithPidEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return OoChildForParentWithPidEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return OoChildForParentWithPidEntity(childProperty, entitySource) {
this.parentEntity = parents.filterIsInstance<OoParentWithPidEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(OoParentWithPidEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as OoChildForParentWithPidEntityData
if (this.entitySource != other.entitySource) return false
if (this.childProperty != other.childProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as OoChildForParentWithPidEntityData
if (this.childProperty != other.childProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + childProperty.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + childProperty.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OoChildForParentWithPidEntityImpl.kt | 1728481021 |
package com.virtlink.editorservices.intellij.psi
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.util.IncorrectOperationException
class AesiPsiNamedElement(node: ASTNode) : AesiPsiElement(node), PsiNamedElement {
override fun getName(): String? {
return this.node.text
}
override fun setName(name: String): PsiElement {
throw IncorrectOperationException()
}
} | aesi-intellij/src/main/kotlin/com/virtlink/editorservices/intellij/psi/AesiPsiNamedElement.kt | 745464454 |
package quickbeer.android.network.result
import quickbeer.android.network.CallDelegate
import retrofit2.Call
import retrofit2.Callback
import retrofit2.HttpException
import retrofit2.Response
class ResultDelegate<T>(proxy: Call<T>) : CallDelegate<T, ApiResult<T>>(proxy) {
override fun delegatedEnqueue(callback: Callback<ApiResult<T>>) = proxy.enqueue(
object : Callback<T> {
@Suppress("MagicNumber")
override fun onResponse(call: Call<T>, response: Response<T>) {
val result = when (val code = response.code()) {
in 200 until 300 -> ApiResult.Success(response.body())
else -> ApiResult.HttpError(code, HttpException(response))
}
callback.onResponse(this@ResultDelegate, Response.success(result))
}
override fun onFailure(call: Call<T>, error: Throwable) {
val result = ApiResult.mapError<T>(error)
callback.onResponse(this@ResultDelegate, Response.success(result))
}
}
)
override fun delegatedClone() = ResultDelegate(proxy.clone())
}
| app/src/main/java/quickbeer/android/network/result/ResultDelegate.kt | 1906824078 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.wizard
import com.intellij.ide.IdeBundle
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.util.installNameGenerators
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.externalSystem.util.ui.DataView
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory.createSingleLocalFileDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.observable.properties.transform
import com.intellij.openapi.observable.properties.map
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.getCanonicalPath
import com.intellij.openapi.ui.getPresentablePath
import com.intellij.openapi.util.io.FileUtil.*
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.SortedComboBoxModel
import com.intellij.ui.layout.*
import java.io.File
import java.nio.file.InvalidPathException
import java.nio.file.Paths
import java.util.Comparator.comparing
import java.util.function.Function
import javax.swing.JList
import javax.swing.JTextField
import javax.swing.ListCellRenderer
abstract class MavenizedStructureWizardStep<Data : Any>(val context: WizardContext) : ModuleWizardStep() {
abstract fun createView(data: Data): DataView<Data>
abstract fun findAllParents(): List<Data>
private val propertyGraph = PropertyGraph()
private val entityNameProperty = propertyGraph.graphProperty(::suggestName)
private val locationProperty = propertyGraph.graphProperty { suggestLocationByName() }
private val parentProperty = propertyGraph.graphProperty(::suggestParentByLocation)
private val groupIdProperty = propertyGraph.graphProperty(::suggestGroupIdByParent)
private val artifactIdProperty = propertyGraph.graphProperty(::suggestArtifactIdByName)
private val versionProperty = propertyGraph.graphProperty(::suggestVersionByParent)
var entityName by entityNameProperty.map { it.trim() }
var location by locationProperty
var parent by parentProperty
var groupId by groupIdProperty.map { it.trim() }
var artifactId by artifactIdProperty.map { it.trim() }
var version by versionProperty.map { it.trim() }
val parents by lazy { parentsData.map(::createView) }
val parentsData by lazy { findAllParents() }
var parentData: Data?
get() = DataView.getData(parent)
set(value) {
parent = if (value == null) EMPTY_VIEW else createView(value)
}
init {
entityNameProperty.dependsOn(locationProperty, ::suggestNameByLocation)
entityNameProperty.dependsOn(artifactIdProperty, ::suggestNameByArtifactId)
parentProperty.dependsOn(locationProperty, ::suggestParentByLocation)
locationProperty.dependsOn(parentProperty) { suggestLocationByParentAndName() }
locationProperty.dependsOn(entityNameProperty) { suggestLocationByParentAndName() }
groupIdProperty.dependsOn(parentProperty, ::suggestGroupIdByParent)
artifactIdProperty.dependsOn(entityNameProperty, ::suggestArtifactIdByName)
versionProperty.dependsOn(parentProperty, ::suggestVersionByParent)
}
private val contentPanel by lazy {
panel {
if (!context.isCreatingNewProject) {
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.parent.label")) {
val presentationName = Function<DataView<Data>, String> { it.presentationName }
val parentComboBoxModel = SortedComboBoxModel(comparing(presentationName, String.CASE_INSENSITIVE_ORDER))
parentComboBoxModel.add(EMPTY_VIEW)
parentComboBoxModel.addAll(parents)
comboBox(parentComboBoxModel, parentProperty, renderer = getParentRenderer())
}
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.name.label")) {
textField(entityNameProperty)
.withValidationOnApply { validateName() }
.withValidationOnInput { validateName() }
.constraints(pushX)
.focused()
installNameGenerators(getBuilderId(), entityNameProperty)
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.location.label")) {
val fileChooserDescriptor = createSingleLocalFileDescriptor().withFileFilter { it.isDirectory }
val fileChosen = { file: VirtualFile -> getPresentablePath(file.path) }
val title = IdeBundle.message("title.select.project.file.directory", context.presentationName)
val property = locationProperty.transform(::getPresentablePath, ::getCanonicalPath)
textFieldWithBrowseButton(property, title, context.project, fileChooserDescriptor, fileChosen)
.withValidationOnApply { validateLocation() }
.withValidationOnInput { validateLocation() }
}
hideableRow(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.coordinates.title")) {
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.group.id.label")) {
textField(groupIdProperty)
.withValidationOnApply { validateGroupId() }
.withValidationOnInput { validateGroupId() }
.comment(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.group.id.help"))
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.id.label")) {
textField(artifactIdProperty)
.withValidationOnApply { validateArtifactId() }
.withValidationOnInput { validateArtifactId() }
.comment(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.id.help", context.presentationName))
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.version.label")) {
textField(versionProperty)
.withValidationOnApply { validateVersion() }
.withValidationOnInput { validateVersion() }
}
}
}.apply {
registerValidators(context.disposable)
}
}
protected open fun getBuilderId(): String? = null
override fun getPreferredFocusedComponent() = contentPanel.preferredFocusedComponent
override fun getComponent() = contentPanel
override fun updateStep() = (preferredFocusedComponent as JTextField).selectAll()
private fun getParentRenderer(): ListCellRenderer<DataView<Data>?> {
return object : SimpleListCellRenderer<DataView<Data>?>() {
override fun customize(list: JList<out DataView<Data>?>,
value: DataView<Data>?,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
val view = value ?: EMPTY_VIEW
text = view.presentationName
icon = DataView.getIcon(view)
}
}
}
protected open fun suggestName(): String {
val projectFileDirectory = File(context.projectFileDirectory)
val moduleNames = findAllModules().map { it.name }.toSet()
return createSequentFileName(projectFileDirectory, "untitled", "") {
!it.exists() && it.name !in moduleNames
}
}
protected fun findAllModules(): List<Module> {
val project = context.project ?: return emptyList()
val moduleManager = ModuleManager.getInstance(project)
return moduleManager.modules.toList()
}
protected open fun suggestNameByLocation(): String {
return File(location).name
}
protected open fun suggestNameByArtifactId(): String {
return artifactId
}
protected open fun suggestLocationByParentAndName(): String {
if (!parent.isPresent) return suggestLocationByName()
return join(parent.location, entityName)
}
protected open fun suggestLocationByName(): String {
return join(context.projectFileDirectory, entityName)
}
protected open fun suggestParentByLocation(): DataView<Data> {
val location = location
return parents.find { isAncestor(it.location, location, true) } ?: EMPTY_VIEW
}
protected open fun suggestGroupIdByParent(): String {
return parent.groupId
}
protected open fun suggestArtifactIdByName(): String {
return entityName
}
protected open fun suggestVersionByParent(): String {
return parent.version
}
override fun validate(): Boolean {
return contentPanel.validateCallbacks
.asSequence()
.mapNotNull { it() }
.all { it.okEnabled }
}
protected open fun ValidationInfoBuilder.validateGroupId() = superValidateGroupId()
protected fun ValidationInfoBuilder.superValidateGroupId(): ValidationInfo? {
if (groupId.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.group.id.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateArtifactId() = superValidateArtifactId()
protected fun ValidationInfoBuilder.superValidateArtifactId(): ValidationInfo? {
if (artifactId.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.id.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateVersion() = superValidateVersion()
protected fun ValidationInfoBuilder.superValidateVersion(): ValidationInfo? {
if (version.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.version.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateName() = superValidateName()
protected fun ValidationInfoBuilder.superValidateName(): ValidationInfo? {
if (entityName.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.name.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
val moduleNames = findAllModules().map { it.name }.toSet()
if (entityName in moduleNames) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.entity.name.exists.error",
context.presentationName.capitalize(), entityName)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateLocation() = superValidateLocation()
protected fun ValidationInfoBuilder.superValidateLocation(): ValidationInfo? {
val location = location
if (location.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.location.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
val locationPath = try {
Paths.get(location)
}
catch (ex: InvalidPathException) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.invalid", ex.reason)
return error(message)
}
for (project in ProjectManager.getInstance().openProjects) {
if (ProjectUtil.isSameProject(locationPath, project)) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.already.taken.error", project.name)
return error(message)
}
}
val file = locationPath.toFile()
if (file.exists()) {
if (!file.canWrite()) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.not.writable.error")
return error(message)
}
val children = file.list()
if (children == null) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.file.not.directory.error")
return error(message)
}
if (!ApplicationManager.getApplication().isUnitTestMode) {
if (children.isNotEmpty()) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.not.empty.warning")
return warning(message)
}
}
}
return null
}
override fun updateDataModel() {
val location = location
context.projectName = entityName
context.setProjectFileDirectory(location)
createDirectory(File(location))
updateProjectData()
}
abstract fun updateProjectData()
companion object {
private val EMPTY_VIEW = object : DataView<Nothing>() {
override val data: Nothing get() = throw UnsupportedOperationException()
override val location: String = ""
override val icon: Nothing get() = throw UnsupportedOperationException()
override val presentationName: String = "<None>"
override val groupId: String = "org.example"
override val version: String = "1.0-SNAPSHOT"
override val isPresent: Boolean = false
}
}
}
| platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/MavenizedStructureWizardStep.kt | 1563211419 |
// 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.j2k
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.psi.KtFile
class AfterConversionPass(val project: Project, private val postProcessor: PostProcessor) {
@JvmOverloads
fun run(
kotlinFile: KtFile,
converterContext: ConverterContext?,
range: TextRange?,
onPhaseChanged: ((Int, String) -> Unit)? = null
) {
postProcessor.doAdditionalProcessing(
when {
range != null -> JKPieceOfCodePostProcessingTarget(kotlinFile, range.toRangeMarker(kotlinFile))
else -> JKMultipleFilesPostProcessingTarget(listOf(kotlinFile))
},
converterContext,
onPhaseChanged
)
}
}
fun TextRange.toRangeMarker(file: KtFile): RangeMarker =
runReadAction { file.viewProvider.document!!.createRangeMarker(startOffset, endOffset) }.apply {
isGreedyToLeft = true
isGreedyToRight = true
} | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/AfterConversionPass.kt | 3492841743 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.data.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
/**
* The [Room] database for this app.
*/
@Database(
entities = [
SessionFtsEntity::class,
SpeakerFtsEntity::class,
CodelabFtsEntity::class
],
version = 3,
exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
abstract fun sessionFtsDao(): SessionFtsDao
abstract fun speakerFtsDao(): SpeakerFtsDao
abstract fun codelabFtsDao(): CodelabFtsDao
companion object {
private const val databaseName = "iosched-db"
fun buildDatabase(context: Context): AppDatabase {
// Since Room is only used for FTS, destructive migration is enough because the tables
// are cleared every time the app launches.
// https://medium.com/androiddevelopers/understanding-migrations-with-room-f01e04b07929
return Room.databaseBuilder(context, AppDatabase::class.java, databaseName)
.fallbackToDestructiveMigration()
.build()
}
}
}
| shared/src/main/java/com/google/samples/apps/iosched/shared/data/db/AppDatabase.kt | 1607041199 |
/*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.robotservices.generalinfo
import com.neatorobotics.sdk.android.robotservices.RobotServices
object GeneralInfoServiceFactory {
fun get(serviceVersion: String): GeneralInfoService? {
return when {
RobotServices.VERSION_BASIC_1.equals(serviceVersion, ignoreCase = true) -> GeneralInfoBasic1Service()
RobotServices.VERSION_BASIC_LCD_1.equals(serviceVersion, ignoreCase = true) -> GeneralInfoBasicLCD1Service()
else -> null
}
}
}
| Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/robotservices/generalinfo/GeneralInfoServiceFactory.kt | 3710810415 |
package de.theunknownxy.mcdocs.gui.base
import de.theunknownxy.mcdocs.gui.container.SingleContainer
import de.theunknownxy.mcdocs.gui.event.MouseButton
import net.minecraft.client.gui.GuiScreen
import java.util.HashMap
public class Root(public val gui: GuiScreen) : SingleContainer(null) {
public var mouse_pos: Point = Point(0f, 0f)
public var named_widgets: HashMap<String, Widget> = HashMap()
public var selected_widget: Widget? = null
override fun onMouseClick(pos: Point, button: MouseButton): Widget? {
val new_selected = super.onMouseClick(pos, button)
if (new_selected != selected_widget) {
// Unfocus old one
selected_widget?.onUnfocus()
selected_widget = new_selected
}
return selected_widget
}
override fun onMouseClickMove(pos: Point) {
// Send the move events to the last clicked widget
selected_widget?.onMouseClickMove(pos)
}
override fun onKeyTyped(ch: Char, t: Int) {
selected_widget?.onKeyTyped(ch, t)
}
override fun recalculateChildren() {
child?.rect = rect
}
} | src/main/kotlin/de/theunknownxy/mcdocs/gui/base/Root.kt | 3536454756 |
package com.intellij.tools.launch
import java.io.File
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.SystemProperties
interface PathsProvider {
val productId: String
val ultimateRootFolder: File
val communityRootFolder: File
val outputRootFolder: File
val tempFolder: File
get() = TeamCityHelper.tempDirectory ?: ultimateRootFolder.resolve("out").resolve("tmp")
val launcherFolder: File
get() = tempFolder.resolve("launcher").resolve(productId)
val logFolder: File
get() = launcherFolder.resolve("log")
val configFolder: File
get() = launcherFolder.resolve("config")
val systemFolder: File
get() = launcherFolder.resolve("system")
val javaHomeFolder: File
get() = File(SystemProperties.getJavaHome())
val mavenRepositoryFolder: File
get() = File(System.getProperty("user.home")).resolve(".m2/repository")
val communityBinFolder: File
get() = communityRootFolder.resolve("bin")
val javaExecutable: File
get() = when {
SystemInfo.isWindows -> javaHomeFolder.resolve("bin").resolve("java.exe")
else -> javaHomeFolder.resolve("bin").resolve("java")
}
val dockerVolumesToWritable: Map<File, Boolean>
get() = emptyMap()
} | build/launch/src/com/intellij/tools/launch/PathsProvider.kt | 1152157469 |
package com.thedeadpixelsociety.ld34.scripts
import com.badlogic.ashley.core.Engine
import com.badlogic.ashley.core.Entity
import com.thedeadpixelsociety.ld34.components.Box2DComponent
class WeightScript() : HazardScript() {
override fun act(engine: Engine, entity: Entity) {
val box2d = entity.getComponent(Box2DComponent::class.java)
if (box2d != null && box2d.body != null) {
if (box2d.body!!.linearVelocity.len() > 75f) {
super.act(engine, entity)
}
}
}
}
| core/src/com/thedeadpixelsociety/ld34/scripts/WeightScript.kt | 961408249 |
package examples
import io.fluidsonic.json.*
import java.io.*
fun main() {
// You can write values directly to a stream without having to build the temporary map or list
val output = StringWriter()
JsonWriter.build(output).use { writer ->
writer.writeIntoMap {
writeMapElement("data") {
writeIntoList {
for (value in 0 .. 10) {
writer.writeInt(value)
}
}
}
}
}
println(output.toString())
}
| examples/sources-jvm/0022-SerializingAsStream.kt | 4220635619 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.utils
import com.intellij.internal.statistic.eventLog.EventLogConfiguration
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.getProjectCacheFileName
import java.text.SimpleDateFormat
import java.time.ZoneOffset
import java.util.*
fun addPluginInfoTo(info: PluginInfo, data: MutableMap<String, Any>) {
data["plugin_type"] = info.type.name
if (!info.type.isSafeToReport()) return
val id = info.id
if (!id.isNullOrEmpty()) {
data["plugin"] = id
}
val version = info.version
if (!version.isNullOrEmpty()) {
data["plugin_version"] = version
}
}
object StatisticsUtil {
private const val kilo = 1000
private const val mega = kilo * kilo
@JvmStatic
fun getProjectId(project: Project, recorderId: String): String {
return EventLogConfiguration.getOrCreate(recorderId).anonymize(project.getProjectCacheFileName())
}
/**
* Anonymizes sensitive project properties by rounding it to the next power of two
* See `com.intellij.internal.statistic.collectors.fus.fileTypes.FileTypeUsagesCollector`
*/
@JvmStatic
fun getNextPowerOfTwo(value: Int): Int = if (value <= 1) 1 else Integer.highestOneBit(value - 1) shl 1
/**
* Anonymizes value by finding upper bound in provided bounds.
* Allows more fine tuning then `com.intellij.internal.statistic.utils.StatisticsUtil#getNextPowerOfTwo`
* but requires manual maintaining.
*
* @param bounds is an integer array sorted in ascending order (required, but not checked)
* @return value upper bound or next power of two if no bounds were provided (as fallback)
* */
@JvmStatic
fun getUpperBound(value: Int, bounds: IntArray): Int {
if (bounds.isEmpty()) return getNextPowerOfTwo(value)
for (bound in bounds)
if (value <= bound) return bound
return bounds.last()
}
/**
* Anonymizes sensitive project properties by rounding it to the next value in steps list.
* See `com.intellij.internal.statistic.collectors.fus.fileTypes.FileTypeUsagesCollector`
*/
fun getCountingStepName(value: Int, steps: List<Int>): String {
if (steps.isEmpty()) return value.toString()
if (value < steps[0]) return "<" + steps[0]
var stepIndex = 0
while (stepIndex < steps.size - 1) {
if (value < steps[stepIndex + 1]) break
stepIndex++
}
val step = steps[stepIndex]
val addPlus = stepIndex == steps.size - 1 || steps[stepIndex + 1] != step + 1
return humanize(step) + if (addPlus) "+" else ""
}
/**
* Returns current hour in UTC as "yyMMddHH"
*/
fun getCurrentHourInUTC(calendar: Calendar = Calendar.getInstance(Locale.ENGLISH)): String {
calendar[Calendar.YEAR] = calendar[Calendar.YEAR].coerceIn(2000, 2099)
val format = SimpleDateFormat("yyMMddHH", Locale.ENGLISH)
format.timeZone = TimeZone.getTimeZone(ZoneOffset.UTC)
return format.format(calendar.time)
}
private fun humanize(number: Int): String {
if (number == 0) return "0"
val m = number / mega
val k = (number % mega) / kilo
val r = (number % kilo)
val ms = if (m > 0) "${m}M" else ""
val ks = if (k > 0) "${k}K" else ""
val rs = if (r > 0) "${r}" else ""
return ms + ks + rs
}
} | platform/statistics/src/com/intellij/internal/statistic/utils/StatisticsUtil.kt | 2775896186 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.commit
import com.intellij.openapi.application.ApplicationManager.getApplication
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages.getQuestionIcon
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.VcsShowConfirmationOption
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.actions.MoveChangesToAnotherListAction
import com.intellij.openapi.vcs.changes.ui.ChangelistMoveOfferDialog
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.ConfirmationDialog.requestForConfirmation
import org.jetbrains.annotations.ApiStatus
class ChangeListCommitState(val changeList: LocalChangeList, val changes: List<Change>, val commitMessage: String) {
internal fun copy(commitMessage: String): ChangeListCommitState =
if (this.commitMessage == commitMessage) this else ChangeListCommitState(changeList, changes, commitMessage)
}
open class SingleChangeListCommitter(
project: Project,
private val commitState: ChangeListCommitState,
commitContext: CommitContext,
localHistoryActionName: String,
private val isDefaultChangeListFullyIncluded: Boolean
) : LocalChangesCommitter(project, commitState.changes, commitState.commitMessage, commitContext, localHistoryActionName) {
@Deprecated("Use constructor without `vcsToCommit: AbstractVcs?` parameter")
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
constructor(
project: Project,
commitState: ChangeListCommitState,
commitContext: CommitContext,
@Suppress("UNUSED_PARAMETER") vcsToCommit: AbstractVcs?, // external usages pass `null` here
localHistoryActionName: String,
isDefaultChangeListFullyIncluded: Boolean
) : this(project, commitState, commitContext, localHistoryActionName, isDefaultChangeListFullyIncluded)
private val changeList get() = commitState.changeList
override fun onFailure() {
getApplication().invokeLater(Runnable {
val failedCommitState = ChangeListCommitState(changeList, failedToCommitChanges, commitMessage)
moveToFailedList(project, failedCommitState, message("commit.dialog.failed.commit.template", changeList.name))
}, ModalityState.defaultModalityState(), project.disposed)
}
override fun afterRefreshChanges() {
if (isSuccess) {
updateChangeListAfterRefresh()
}
super.afterRefreshChanges()
}
private fun updateChangeListAfterRefresh() {
val changeListManager = ChangeListManagerImpl.getInstanceImpl(project)
val listName = changeList.name
val localList = changeListManager.findChangeList(listName) ?: return
changeListManager.editChangeListData(listName, null)
if (!localList.isDefault) {
changeListManager.scheduleAutomaticEmptyChangeListDeletion(localList)
}
else {
val changes = localList.changes
if (configuration.OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT && !changes.isEmpty() && isDefaultChangeListFullyIncluded) {
val dialog = ChangelistMoveOfferDialog(configuration)
if (dialog.showAndGet()) {
MoveChangesToAnotherListAction.askAndMove(project, changes, emptyList())
}
}
}
}
companion object {
@JvmStatic
@RequiresEdt
fun moveToFailedList(project: Project, commitState: ChangeListCommitState, newChangeListName: String) {
// No need to move since we'll get exactly the same changelist.
val failedChanges = commitState.changes
if (failedChanges.containsAll(commitState.changeList.changes)) return
val configuration = VcsConfiguration.getInstance(project)
if (configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST != VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY) {
val option = object : VcsShowConfirmationOption {
override fun getValue(): VcsShowConfirmationOption.Value = configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST
override fun setValue(value: VcsShowConfirmationOption.Value) {
configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST = value
}
override fun isPersistent(): Boolean = true
}
val result = requestForConfirmation(option, project, message("commit.failed.confirm.prompt"),
message("commit.failed.confirm.title"), getQuestionIcon())
if (!result) return
}
val changeListManager = ChangeListManager.getInstance(project)
var index = 1
var failedListName = newChangeListName
while (changeListManager.findChangeList(failedListName) != null) {
index++
failedListName = "$newChangeListName ($index)"
}
val failedList = changeListManager.addChangeList(failedListName, commitState.commitMessage)
changeListManager.moveChangesTo(failedList, *failedChanges.toTypedArray())
}
}
} | platform/vcs-impl/src/com/intellij/vcs/commit/SingleChangeListCommitter.kt | 2831503729 |
package com.glodanif.bluetoothchat.data.database
import androidx.room.*
import com.glodanif.bluetoothchat.data.entity.Conversation
import com.glodanif.bluetoothchat.data.entity.ConversationWithMessages
@Dao
interface ConversationsDao {
@Query("SELECT * FROM conversation")
fun getContacts(): List<Conversation>
@Transaction
@Query("SELECT * FROM conversation")
fun getAllConversationsWithMessages(): List<ConversationWithMessages>
@Query("SELECT * FROM conversation WHERE address = :address")
fun getConversationByAddress(address: String): Conversation?
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(conversations: Conversation)
@Query("DELETE FROM conversation WHERE address = :address")
fun delete(address: String)
}
| app/src/main/kotlin/com/glodanif/bluetoothchat/data/database/ConversationsDao.kt | 3603564214 |
package com.aemtools.codeinsight.osgiservice.navigationhandler
import com.aemtools.codeinsight.osgiservice.markerinfo.FelixOSGiPropertyDescriptor
import com.aemtools.common.util.toNavigatable
import com.intellij.codeInsight.daemon.GutterIconNavigationHandler
import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator
import com.intellij.ide.util.PsiElementListCellRenderer
import com.intellij.psi.NavigatablePsiElement
import com.intellij.psi.PsiElement
import java.awt.event.MouseEvent
/**
* Felix OSGi gutter navigation handler.
*
* @author Dmytro Troynikov
*/
class FelixOSGiPropertyNavigationHandler(
val propertyDescriptors: List<FelixOSGiPropertyDescriptor>
) : GutterIconNavigationHandler<PsiElement> {
override fun navigate(e: MouseEvent?, elt: PsiElement?) {
PsiElementListNavigator.openTargets(e,
propertyDescriptors.map {
(it.xmlAttribute?.toNavigatable() ?: it.osgiConfigFIle) as NavigatablePsiElement
}.toTypedArray(),
"OSGi Property", null, createListCellRenderer())
}
private fun createListCellRenderer(): PsiElementListCellRenderer<PsiElement> {
return object : PsiElementListCellRenderer<PsiElement>() {
override fun getIconFlags(): Int = 0
override fun getContainerText(element: PsiElement, name: String): String? {
return propertyDescriptors.find {
it.xmlAttribute?.toNavigatable() == element
|| it.osgiConfigFIle == element
}?.propertyValue ?: ""
}
override fun getElementText(element: PsiElement?): String {
if (element == null) {
return ""
}
return propertyDescriptors.find {
it.xmlAttribute?.toNavigatable() == element
|| it.osgiConfigFIle == element
}?.mods ?: ""
}
}
}
}
| aem-intellij-core/src/main/kotlin/com/aemtools/codeinsight/osgiservice/navigationhandler/FelixOSGiPropertyNavigationHandler.kt | 3922689999 |
package i_introduction._7_Nullable_Types
import org.junit.Test
import junit.framework.Assert
class _05_Nullable_Types {
fun testSendMessageToClient(
client: Client?,
message: String?,
email: String? = null,
shouldBeInvoked: Boolean = false
) {
var invoked = false
sendMessageToClient(client, message, object : Mailer {
public override fun sendMessage(actualEmail: String, actualMessage: String) {
invoked = true
Assert.assertEquals("The message is not as expected:",
message, actualMessage)
Assert.assertEquals("The email is not as expected:",
email, actualEmail)
}
})
Assert.assertEquals("The function 'sendMessage' should${if (shouldBeInvoked) "" else "n't"} be invoked",
shouldBeInvoked, invoked)
}
@Test fun everythingIsOk() {
testSendMessageToClient(Client(PersonalInfo("[email protected]")),
"Hi Bob! We have an awesome proposition for you...",
"[email protected]",
true)
}
@Test fun noMessage() {
testSendMessageToClient(Client(PersonalInfo("[email protected]")), null)
}
@Test fun noEmail() {
testSendMessageToClient(Client(PersonalInfo(null)), "Hi Bob! We have an awesome proposition for you...")
}
@Test fun noPersonalInfo() {
testSendMessageToClient(Client(null), "Hi Bob! We have an awesome proposition for you...")
}
@Test fun noClient() {
testSendMessageToClient(null, "Hi Bob! We have an awesome proposition for you...")
}
} | test/i_introduction/_7_Nullable_Types/_05_Nullable_Types.kt | 367414147 |
package com.github.himaaaatti.spigot.plugin.auto_craft
import org.bukkit.material.Sign
import org.bukkit.Material
import org.bukkit.block.Block
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.plugin.java.JavaPlugin
import org.bukkit.block.BlockFace
import org.bukkit.material.Attachable
import org.bukkit.inventory.ShapedRecipe
import org.bukkit.inventory.Recipe
import org.bukkit.inventory.ItemStack
import org.bukkit.event.block.SignChangeEvent
import org.bukkit.event.block.BlockRedstoneEvent
import org.bukkit.inventory.InventoryHolder
import org.bukkit.Bukkit
import org.bukkit.block.Chest
class AutoCraft: JavaPlugin() {
val AUTO_CRAFT_TEXT = "auto craft"
override fun onEnable() {
getServer().getPluginManager().registerEvents(
object : Listener {
@EventHandler
fun onChange(e: SignChangeEvent)
{
val sign = e.getBlock().getState().getData() as Sign
val holder = e.getBlock().getRelative(sign.getAttachedFace())
if(holder.getType() != Material.WORKBENCH)
{
return
}
if(e.getLine(0) != AUTO_CRAFT_TEXT)
{
return
}
e.setLine(1,"↑ Recipe")
e.setLine(2, "<-Input|Output->");
e.setLine(3, "[ok]");
}
@EventHandler
fun onRedStone(e: BlockRedstoneEvent)
{
if(!(e.getOldCurrent() == 0 && e.getNewCurrent() != 0))
{
return
}
val pumpkin = e.block.getRelative(0, -1, 0)
if(pumpkin.getType() != Material.PUMPKIN)
{
return
}
val w_face = when
{
pumpkin.getRelative(BlockFace.EAST).getType() == Material.WORKBENCH
-> BlockFace.EAST
pumpkin.getRelative(BlockFace.WEST).getType() == Material.WORKBENCH
-> BlockFace.WEST
pumpkin.getRelative(BlockFace.SOUTH).getType() == Material.WORKBENCH
-> BlockFace.SOUTH
pumpkin.getRelative(BlockFace.NORTH).getType() == Material.WORKBENCH
-> BlockFace.NORTH
else -> return@onRedStone
}
val work_bench = pumpkin.getRelative(w_face)
val face: BlockFace? = getSignAttachedFace(work_bench)
if(face == null)
{
getLogger().info("getSignAttachedFace")
return
}
val recipe_block = work_bench.getRelative(0, 1, 0)
if(recipe_block.getType() != Material.CHEST)
{
getLogger().info("above block is not CHEST")
return
}
val chest_faces = when(face) {
BlockFace.NORTH -> Pair(BlockFace.EAST, BlockFace.WEST)
BlockFace.EAST -> Pair(BlockFace.SOUTH, BlockFace.NORTH)
BlockFace.SOUTH -> Pair(BlockFace.WEST, BlockFace.EAST)
BlockFace.WEST -> Pair(BlockFace.NORTH, BlockFace.SOUTH)
else -> return@onRedStone
}
val source_chest = work_bench.getRelative(chest_faces.first)
if(source_chest.getType() != Material.CHEST)
{
getLogger().info("left block is not CHEST")
return
}
val dest_chest = work_bench.getRelative(chest_faces.second)
if(dest_chest.getType() != Material.CHEST)
{
getLogger().info("right block is not CHEST")
return
}
val recipe_invent = (recipe_block.getState() as InventoryHolder).getInventory()
val item = recipe_invent.getItem(0);
if(item == null)
{
getLogger().info("getItem 0 is empty")
return
}
val source_invent =
(source_chest.getState() as Chest).getBlockInventory()
var materials: MutableList<Pair<ItemStack, Int>>? = null
for(recipe: Recipe in Bukkit.getRecipesFor(item))
{
if(recipe is ShapedRecipe)
{
val shapes = recipe.getShape()
val map :Map<Char, ItemStack> = recipe.getIngredientMap()
for(c in shapes[0])
{
val stack = map.get(c)
if(stack == null)
{
continue
}
val type = stack.getType()
val index = source_invent.first(type)
if(index == -1)
{
return
}
val ingred_stack = source_invent.getItem(index)
if(materials == null)
{
materials = mutableListOf(Pair(ingred_stack, index))
}
else {
materials.add(Pair(ingred_stack, index))
}
}
}
}
val reduce_stack = fun(m: MutableList<Pair<ItemStack, Int>>?)
{
if(m == null)
{
return
}
for(p in m.listIterator())
{
if(p.first.getAmount() == 1)
{
source_invent.setItem(p.second, null);
}
else {
p.first.setAmount(p.first.getAmount() - 1)
}
}
}
val dest_invent = (dest_chest.getState() as Chest).getBlockInventory()
for(stack in dest_invent.iterator())
{
if(stack == null)
{
continue
}
if(stack.getType() != item.getType())
{
continue
}
if(stack.getMaxStackSize() == stack.getAmount())
{
continue
}
stack.setAmount(stack.getAmount() + 1)
reduce_stack(materials)
return
}
val empty_index = dest_invent.firstEmpty()
if(empty_index == -1)
{
return
}
item.setAmount(1)
dest_invent.setItem(empty_index, item)
reduce_stack(materials)
}
},
this
)
}
fun getSignAttachedFace(block: Block) : BlockFace?
{
val face = when {
block.getRelative(BlockFace.WEST).getType() == Material.WALL_SIGN
-> BlockFace.WEST
block.getRelative(BlockFace.EAST).getType() == Material.WALL_SIGN
-> BlockFace.EAST
block.getRelative(BlockFace.SOUTH).getType() == Material.WALL_SIGN
-> BlockFace.SOUTH
block.getRelative(BlockFace.NORTH).getType() == Material.WALL_SIGN
-> BlockFace.NORTH
else -> return@getSignAttachedFace null
}
val sign_block = block.getRelative(face)
val sign = sign_block.getState() as org.bukkit.block.Sign
if(sign.getLine(0) != AUTO_CRAFT_TEXT)
{
return null
}
val attached_face = (sign.getData() as Attachable).getAttachedFace()
return when {
(face == BlockFace.EAST) && (attached_face == BlockFace.WEST)
-> BlockFace.EAST
(face == BlockFace.WEST) && (attached_face == BlockFace.EAST)
-> BlockFace.WEST
(face == BlockFace.SOUTH) && (attached_face == BlockFace.NORTH)
-> BlockFace.SOUTH
(face == BlockFace.NORTH) && (attached_face == BlockFace.SOUTH)
-> BlockFace.NORTH
else -> null
}
}
}
| auto_craft/auto_craft.kt | 488467477 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.filePrediction.history
import com.intellij.testFramework.UsefulTestCase
class FilePredictionHistorySerializationTest : UsefulTestCase() {
private fun doTest(state: FilePredictionHistoryState) {
val element = state.serialize()
val newState = FilePredictionHistoryState().deserialize(element)
assertEquals(state, newState)
}
fun `test serializing state with recent files`() {
val state = FilePredictionHistoryState()
state.recentFiles.add(newRecentFile(0, "a"))
state.recentFiles.add(newRecentFile(1, "b"))
state.recentFiles.add(newRecentFile(2, "c"))
doTest(state)
}
fun `test serializing state with recent files with prev file`() {
val state = FilePredictionHistoryState()
state.recentFiles.add(newRecentFile(0, "a"))
state.recentFiles.add(newRecentFile(1, "b"))
state.recentFiles.add(newRecentFile(2, "c"))
state.prevFile = 2
doTest(state)
}
fun `test serializing usages map`() {
val state = FilePredictionHistoryState()
state.root.count = 9
state.root.usages.put(0, newNode(3, 1 to 1, 2 to 2))
state.root.usages.put(1, newNode(4, 0 to 3, 2 to 1))
state.root.usages.put(2, newNode(2, 0 to 2))
doTest(state)
}
fun `test serializing usages map with empty sequence`() {
val state = FilePredictionHistoryState()
state.root.count = 9
state.root.usages.put(0, newNode(3, 1 to 1, 2 to 2))
state.root.usages.put(1, newNode(4, 0 to 3, 2 to 1))
state.root.usages.put(2, NGramListNode())
doTest(state)
}
fun `test serializing complete state object`() {
val state = FilePredictionHistoryState()
state.recentFiles.add(newRecentFile(0, "a"))
state.recentFiles.add(newRecentFile(1, "b"))
state.recentFiles.add(newRecentFile(2, "c"))
state.prevFile = 2
state.root.count = 9
state.root.usages.put(0, newNode(3, 1 to 1, 2 to 2))
state.root.usages.put(1, newNode(4, 0 to 3, 2 to 1))
state.root.usages.put(2, newNode(2, 0 to 2))
doTest(state)
}
private fun newNode(count: Int, vararg usages: Pair<Int, Int>): NGramListNode {
val node = NGramListNode()
node.count = count
for (usage in usages) {
node.usages.put(usage.first, usage.second)
}
return node
}
private fun newRecentFile(code: Int, url: String): RecentFileEntry {
val entry = RecentFileEntry()
entry.code = code
entry.fileUrl = url
return entry
}
} | plugins/filePrediction/test/com/intellij/filePrediction/history/FilePredictionHistorySerializationTest.kt | 3800955731 |
package slatekit.cache
import slatekit.common.Identity
import slatekit.common.log.Logger
import slatekit.results.Outcome
class SimpleSyncCache(private val cache: Cache) : Cache {
override val id: Identity get() = cache.id
override val settings: CacheSettings = cache.settings
override val listener: ((CacheEvent) -> Unit)? get() = cache.listener
override val logger: Logger? get() = cache.logger
@Synchronized
override fun size(): Int = cache.size()
@Synchronized
override fun keys(): List<String> = cache.keys()
@Synchronized
override fun contains(key: String): Boolean = cache.contains(key)
@Synchronized
override fun stats(): List<CacheStats> = cache.stats()
@Synchronized
override fun stats(key:String): CacheStats? = cache.stats(key)
@Synchronized
override fun <T> get(key: String): T? = cache.get(key)
@Synchronized
override fun <T> getOrLoad(key: String): T? = cache.getOrLoad(key)
@Synchronized
override fun <T> getFresh(key: String): T? = cache.getFresh(key)
@Synchronized
override fun <T> put(key: String, desc: String, seconds: Int, fetcher: suspend () -> T?) = cache.put(key, desc, seconds, fetcher)
@Synchronized
override fun <T> set(key: String, value: T?) = cache.set(key, value)
@Synchronized
override fun delete(key: String): Outcome<Boolean> = cache.delete(key)
@Synchronized
override fun deleteAll(): Outcome<Boolean> = cache.deleteAll()
@Synchronized
override fun refresh(key: String):Outcome<Boolean> = cache.refresh(key)
@Synchronized
override fun expire(key: String):Outcome<Boolean> = cache.expire(key)
@Synchronized
override fun expireAll():Outcome<Boolean> = cache.expireAll()
companion object {
/**
* Convenience method to build async cache using Default channel coordinator
*/
fun of(id:Identity, settings: CacheSettings? = null, listener:((CacheEvent) -> Unit)? = null):SimpleSyncCache {
val raw = SimpleCache(id,settings ?: CacheSettings(10), listener )
val syncCache = SimpleSyncCache(raw)
return syncCache
}
}
}
| src/lib/kotlin/slatekit-cache/src/main/kotlin/slatekit/cache/SimpleSyncCache.kt | 421585477 |
package com.sqisland.espresso.repeatedly_until
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.repeatedlyUntil
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.ActivityTestRule
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@get:Rule
val activityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java)
@Test
fun eleven() {
onView(withId(R.id.number))
.check(matches(withText("0")))
onView(withId(R.id.number))
.perform(repeatedlyUntil(click(), withText("11"), 20))
onView(withId(R.id.squared))
.check(matches(withText("121")))
}
} | repeatedly-until/app/src/androidTest/java/com/sqisland/espresso/repeatedly_until/MainActivityTest.kt | 2927424889 |
/*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.channelgraph
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.nhaarman.mockitokotlin2.whenever
import com.vrem.util.EMPTY
import com.vrem.wifianalyzer.MainContextHelper
import com.vrem.wifianalyzer.wifi.band.WiFiBand
import com.vrem.wifianalyzer.wifi.band.WiFiChannels
import com.vrem.wifianalyzer.wifi.graphutils.MAX_Y
import com.vrem.wifianalyzer.wifi.graphutils.MIN_Y
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.*
class ChannelAxisLabelTest {
private val settings = MainContextHelper.INSTANCE.settings
private val fixture = ChannelAxisLabel(WiFiBand.GHZ2, WiFiBand.GHZ2.wiFiChannels.wiFiChannelPairs()[0])
@After
fun tearDown() {
verifyNoMoreInteractions(settings)
MainContextHelper.INSTANCE.restore()
}
@Test
fun testYAxis() {
// execute & verify
assertEquals(String.EMPTY, fixture.formatLabel(MIN_Y.toDouble(), false))
assertEquals("-99", fixture.formatLabel(MIN_Y + 1.toDouble(), false))
assertEquals("0", fixture.formatLabel(MAX_Y.toDouble(), false))
assertEquals(String.EMPTY, fixture.formatLabel(MAX_Y + 1.toDouble(), false))
}
@Test
fun testXAxis() {
// setup
val (channel, frequency) = WiFiBand.GHZ2.wiFiChannels.wiFiChannelFirst()
whenever(settings.countryCode()).thenReturn(Locale.US.country)
// execute
val actual = fixture.formatLabel(frequency.toDouble(), true)
// validate
assertEquals("" + channel, actual)
verify(settings).countryCode()
}
@Test
fun testXAxisWithFrequencyInRange() {
// setup
val (channel, frequency) = WiFiBand.GHZ2.wiFiChannels.wiFiChannelFirst()
whenever(settings.countryCode()).thenReturn(Locale.US.country)
// execute & validate
assertEquals("" + channel, fixture.formatLabel(frequency - 2.toDouble(), true))
assertEquals("" + channel, fixture.formatLabel(frequency + 2.toDouble(), true))
verify(settings, times(2)).countryCode()
}
@Test
fun testXAxisWithFrequencyNotAllowedInLocale() {
// setup
val (_, frequency) = WiFiBand.GHZ2.wiFiChannels.wiFiChannelLast()
// execute
val actual = fixture.formatLabel(frequency.toDouble(), true)
// validate
assertEquals(String.EMPTY, actual)
}
@Test
fun testXAxisWithUnknownFrequencyReturnEmptyString() {
// setup
val wiFiChannels = WiFiBand.GHZ2.wiFiChannels
val (_, frequency) = wiFiChannels.wiFiChannelFirst()
// execute
val actual = fixture.formatLabel(frequency - WiFiChannels.FREQUENCY_OFFSET.toDouble(), true)
// validate
assertEquals(String.EMPTY, actual)
}
} | app/src/test/kotlin/com/vrem/wifianalyzer/wifi/channelgraph/ChannelAxisLabelTest.kt | 1147395932 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
class A(var value: String)
fun box(): String {
val a = A("start")
try {
test(a)
} catch(e: java.lang.RuntimeException) {
}
if (a.value != "start, try, finally1, finally2") return "fail: ${a.value}"
return "OK"
}
fun test(a: A) : String {
while (a.value == "start") {
try {
try {
a.value += ", try"
continue
}
finally {
a.value += ", finally1"
}
}
finally {
a.value += ", finally2"
throw RuntimeException("fail")
}
}
return "fail"
}
| backend.native/tests/external/codegen/box/controlStructures/kt8148_continue.kt | 4199100852 |
import kotlin.test.*
import kotlin.test.assertTrue
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
val p = Pair(1, "a")
val t = Triple(1, "a", 0.07)
fun box() {
val s = hashSetOf(Pair(1, "a"), Pair(1, "b"), Pair(1, "a"))
assertEquals(2, s.size)
assertTrue(s.contains(p))
}
| backend.native/tests/external/stdlib/TuplesTest/pairHashSet.kt | 954839802 |
// FILE: 1.kt
package test
class Test(var result: Int)
class A {
var result = Test(1)
inline var z: Test
get() = result
set(value) {
result = value
}
}
operator fun Test.plus(p: Int): Test {
return Test(result + p)
}
operator fun Test.inc(): Test {
return Test(result + 1)
}
// FILE: 2.kt
import test.*
fun box(): String {
val a = A()
a.z = Test(1)
a.z += 1
if (a.result.result != 2) return "fail 1: ${a.result.result}"
var p = a.z++
if (a.result.result != 3) return "fail 2: ${a.result.result}"
if (p.result != 2) return "fail 3: ${p.result}"
p = ++a.z
if (a.result.result != 4) return "fail 4: ${a.result.result}"
if (p.result != 4) return "fail 5: ${p.result}"
return "OK"
} | backend.native/tests/external/codegen/boxInline/property/augAssignmentAndIncInClassViaConvention.kt | 2538654617 |
/*
* Copyright (c) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.chromeos.videocompositionsample.presentation.media.encoder.surface
import android.view.Surface
class WindowSurface(
eglCore: EglCore,
private var surface: Surface,
private var releaseSurface: Boolean
) : EglSurfaceBase(eglCore) {
init {
createWindowSurface(surface)
}
fun release() {
releaseEglSurface()
if (releaseSurface) {
surface.release()
}
}
fun recreate(newEglCore: EglCore) {
eglCore = newEglCore
createWindowSurface(surface)
}
} | VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/media/encoder/surface/WindowSurface.kt | 597424606 |
package com.peterlaurence.trekme.ui.trackview.components
import android.content.Context
import androidx.constraintlayout.widget.ConstraintLayout
import android.util.AttributeSet
import android.view.View
import com.peterlaurence.trekme.R
import kotlinx.android.synthetic.main.track_view_distance.view.*
class TrackDistanceView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
init {
View.inflate(context, R.layout.track_view_distance, this)
}
fun setDistanceText(dist: String) {
distanceText.text = dist
invalidate()
}
} | app/src/main/java/com/peterlaurence/trekme/ui/trackview/components/TrackDistanceView.kt | 3837864617 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing
import com.intellij.openapi.util.ThrowableComputable
internal object IndexUpToDateCheckIn {
private val upToDateCheckState = ThreadLocal<Int>()
@JvmStatic
fun <T, E : Throwable?> disableUpToDateCheckIn(runnable: ThrowableComputable<T, E>): T {
disableUpToDateCheckForCurrentThread()
return try {
runnable.compute()
}
finally {
enableUpToDateCheckForCurrentThread()
}
}
@JvmStatic
fun isUpToDateCheckEnabled(): Boolean {
val value: Int? = upToDateCheckState.get()
return value == null || value == 0
}
private fun disableUpToDateCheckForCurrentThread() {
val currentValue = upToDateCheckState.get()
upToDateCheckState.set(if (currentValue == null) 1 else currentValue.toInt() + 1)
}
private fun enableUpToDateCheckForCurrentThread() {
val currentValue = upToDateCheckState.get()
if (currentValue != null) {
val newValue = currentValue.toInt() - 1
if (newValue != 0) {
upToDateCheckState.set(newValue)
}
else {
upToDateCheckState.remove()
}
}
}
} | platform/lang-impl/src/com/intellij/util/indexing/IndexUpToDateCheckIn.kt | 960660135 |
package a
var <caret>test: String
get() = ""
set(value: String) {
val aFoo: Foo = Foo()
val bFoo: b.Foo = b.Foo()
val cFoo: c.Foo = c.Foo()
val aBar: Foo.Bar = Foo.Bar()
val bBar: b.Foo.Bar = b.Foo.Bar()
val cBar: c.Foo.Bar = c.Foo.Bar()
fun foo(u: Int) {
class T(val t: Int)
object O {
val t: Int = 1
}
val v = T(u).t + O.t
println(v)
}
foo(1)
}
class Test {
fun foo() {
test
}
}
| plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/movePropertyToPackage/before/a/main.kt | 3260990566 |
// "Make 'a' 'private'" "true"
open class A {
<caret>protected val a = ""
fun foo() {
a
}
} | plugins/kotlin/idea/tests/testData/quickfix/memberVisibilityCanBePrivate/protected.kt | 1816341637 |
package com.intellij.tools.launch
import java.io.File
import java.util.*
object TeamCityHelper {
val systemProperties: Map<String, String> by lazy {
if (!isUnderTeamCity) {
return@lazy mapOf<String, String>()
}
val systemPropertiesEnvName = "TEAMCITY_BUILD_PROPERTIES_FILE"
val systemPropertiesFile = System.getenv(systemPropertiesEnvName)
if (systemPropertiesFile == null || systemPropertiesFile.isEmpty()) {
throw RuntimeException("TeamCity environment variable $systemPropertiesEnvName was not found while running under TeamCity")
}
val file = File(systemPropertiesFile)
if (!file.exists()) {
throw RuntimeException("TeamCity system properties file is not found: $file")
}
return@lazy loadPropertiesFile(file)
}
val isUnderTeamCity: Boolean by lazy {
val version = System.getenv("TEAMCITY_VERSION")
if (version != null) {
println("TeamCityHelper: running under TeamCity $version")
}
else {
println("TeamCityHelper: NOT running under TeamCity")
}
version != null
}
val tempDirectory: File? by lazy {
systemProperties["teamcity.build.tempDir"]?.let { File(it) }
}
private fun loadPropertiesFile(file: File): Map<String, String> {
val result = mutableMapOf<String, String>()
val properties = Properties()
file.reader(Charsets.UTF_8).use { properties.load(it) }
for (entry in properties.entries) {
result[entry.key as String] = entry.value as String
}
return result
}
} | build/launch/src/com/intellij/tools/launch/TeamCityHelper.kt | 1014169603 |
package com.eggheadgames.inapppayments
import com.billing.BillingService
import com.billing.splitMessages
import org.junit.Assert
import org.junit.Test
class AmazonSkuLimitTest {
@Test
fun checkSkuListSize_ShouldSplitIfMoreThen100() {
val iapKeys = mutableListOf<String>()
for (i in 0 until 230) {
iapKeys.add("sku_$i")
}
val splitMessages = iapKeys.splitMessages(BillingService.MAX_SKU_LIMIT)
Assert.assertEquals(3, splitMessages.size)
Assert.assertEquals(100, splitMessages[0].size)
Assert.assertEquals(100, splitMessages[1].size)
Assert.assertEquals(30, splitMessages[2].size)
}
@Test
fun checkSkuListSize_ShouldReturnSizeIfLessThen100() {
val iapKeys = mutableListOf<String>()
for (i in 0 until 40) {
iapKeys.add("sku_$i")
}
val splitMessages = iapKeys.splitMessages(BillingService.MAX_SKU_LIMIT)
Assert.assertEquals(1, splitMessages.size)
Assert.assertEquals(40, splitMessages[0].size)
}
@Test
fun checkSkuListSize_ShouldReturn0() {
val iapKeys = mutableListOf<String>()
val splitMessages = iapKeys.splitMessages(BillingService.MAX_SKU_LIMIT)
Assert.assertEquals(0, splitMessages.size)
}
} | library/src/testAmazon/java/com/eggheadgames/inapppayments/AmazonSkuLimitTest.kt | 1624787550 |
import seal.*
val sealedOutsideClass = SubSealed
class KotlinSealedTest {
val sealedInsideClass = SubSealed
fun testSeal() {
val sealedInsideMethod = SubSealed
SubSealed
}
} | plugins/kotlin/idea/tests/testData/multiFileLocalInspections/convertSealedSubClassToObject/convertInOtherFiles/after/KotlinSealedTest.kt | 3497662571 |
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.frontend.api.fir.symbols
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.fir.containingClass
import org.jetbrains.kotlin.fir.declarations.FirEnumEntry
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.idea.fir.findPsi
import org.jetbrains.kotlin.idea.fir.low.level.api.api.FirModuleResolveState
import org.jetbrains.kotlin.idea.frontend.api.ValidityToken
import org.jetbrains.kotlin.idea.frontend.api.fir.KtSymbolByFirBuilder
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.pointers.KtFirEnumEntrySymbolPointer
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.pointers.createSignature
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.cached
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.firRef
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtEnumEntrySymbol
import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.KtTypeAndAnnotations
import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtPsiBasedSymbolPointer
import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.Name
internal class KtFirEnumEntrySymbol(
fir: FirEnumEntry,
resolveState: FirModuleResolveState,
override val token: ValidityToken,
private val builder: KtSymbolByFirBuilder
) : KtEnumEntrySymbol(), KtFirSymbol<FirEnumEntry> {
override val firRef = firRef(fir, resolveState)
override val psi: PsiElement? by firRef.withFirAndCache { fir -> fir.findPsi(fir.session) }
override val name: Name get() = firRef.withFir { it.name }
override val annotatedType: KtTypeAndAnnotations by cached {
firRef.returnTypeAndAnnotations(FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE, builder)
}
override val containingEnumClassIdIfNonLocal: ClassId?
get() = firRef.withFir { it.containingClass()?.classId?.takeUnless { it.isLocal } }
override fun createPointer(): KtSymbolPointer<KtEnumEntrySymbol> {
KtPsiBasedSymbolPointer.createForSymbolFromSource(this)?.let { return it }
return KtFirEnumEntrySymbolPointer(containingEnumClassIdIfNonLocal!!, firRef.withFir { it.createSignature() })
}
}
| plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/frontend/api/fir/symbols/KtFirEnumEntrySymbol.kt | 3509122175 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.