content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.apollographql.apollo3.gradle.test import com.apollographql.apollo3.gradle.util.TestUtils import com.apollographql.apollo3.gradle.util.TestUtils.withSimpleProject import com.apollographql.apollo3.gradle.util.generatedChild import com.apollographql.apollo3.gradle.util.replaceInText import org.gradle.testkit.runner.TaskOutcome import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.not import org.junit.Assert.assertEquals import org.junit.Assert.assertThat import org.junit.Assert.assertTrue import org.junit.Test import java.io.File class UpToDateTests { @Test fun `complete test`() { withSimpleProject { dir -> `builds successfully and generates expected outputs`(dir) `nothing changed, task up to date`(dir) `adding a custom scalar to the build script re-generates the CustomScalars`(dir) } } private fun `builds successfully and generates expected outputs`(dir: File) { val result = TestUtils.executeTask("generateApolloSources", dir) assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) // Java classes generated successfully assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) assertTrue(dir.generatedChild("service/com/example/FilmsQuery.kt").isFile) assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").isFile) // verify that the custom type generated was Any because no customScalarsMapping was specified TestUtils.assertFileContains(dir, "service/com/example/type/Types.kt", "\"kotlin.Any\"") } fun `nothing changed, task up to date`(dir: File) { val result = TestUtils.executeTask("generateApolloSources", dir) assertEquals(TaskOutcome.UP_TO_DATE, result.task(":generateApolloSources")!!.outcome) // Java classes generated successfully assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) assertTrue(dir.generatedChild("service/com/example/FilmsQuery.kt").isFile) assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").isFile) } fun `adding a custom scalar to the build script re-generates the CustomScalars`(dir: File) { val apolloBlock = """ apollo { customScalarsMapping = ["DateTime": "java.util.Date"] } """.trimIndent() File(dir, "build.gradle").appendText(apolloBlock) val result = TestUtils.executeTask("generateApolloSources", dir) // modifying the customScalarsMapping should cause the task to be out of date // and the task should run again assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) TestUtils.assertFileContains(dir, "service/com/example/type/Types.kt", "\"java.util.Date\"") val text = File(dir, "build.gradle").readText() File(dir, "build.gradle").writeText(text.replace(apolloBlock, "")) } @Test fun `change graphql file rebuilds the sources`() { withSimpleProject { dir -> var result = TestUtils.executeTask("generateApolloSources", dir, "-i") assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) assertThat(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").readText(), containsString("classification")) File(dir, "src/main/graphql/com/example/DroidDetails.graphql").replaceInText("classification", "") result = TestUtils.executeTask("generateApolloSources", dir, "-i") assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) assertThat(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").readText(), not(containsString("classification"))) } } @Test fun `change schema file rebuilds the sources`() { withSimpleProject { dir -> var result = TestUtils.executeTask("generateApolloSources", dir, "-i") assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) val schemaFile = File(dir, "src/main/graphql/com/example/schema.json") schemaFile.replaceInText("The ID of an object", "The ID of an object (modified)") result = TestUtils.executeTask("generateApolloSources", dir, "-i") assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) } } }
apollo-gradle-plugin/src/test/kotlin/com/apollographql/apollo3/gradle/test/UpToDateTests.kt
1185198167
package co.garmax.materialflashlight.ui.main import androidx.lifecycle.ViewModel import co.garmax.materialflashlight.extensions.liveDataOf import co.garmax.materialflashlight.features.LightManager import co.garmax.materialflashlight.features.modes.ModeBase import co.garmax.materialflashlight.features.modes.ModeFactory import co.garmax.materialflashlight.features.modules.ModuleBase import co.garmax.materialflashlight.features.modules.ModuleFactory import co.garmax.materialflashlight.repositories.SettingsRepository import co.garmax.materialflashlight.utils.PostExecutionThread import io.reactivex.disposables.Disposable class MainViewModel( postExecutionThread: PostExecutionThread, private val lightManager: LightManager, private val settingsRepository: SettingsRepository, private val modeFactory: ModeFactory, private val moduleFactory: ModuleFactory ) : ViewModel() { val liveDataLightToggle = liveDataOf<Boolean>() var isAutoTurnedOn: Boolean get() = settingsRepository.isAutoTurnedOn set(value) { settingsRepository.isAutoTurnedOn = value } var isKeepScreenOn: Boolean get() = settingsRepository.isKeepScreenOn set(value) { settingsRepository.isKeepScreenOn = value } val isLightTurnedOn get() = lightManager.isTurnedOn val lightMode get() = settingsRepository.mode val lightModule get() = settingsRepository.module val strobeOnPeriod get() = settingsRepository.strobeOnPeriod val strobeOffPeriod get() = settingsRepository.strobeOffPeriod private var disposableLightToggle: Disposable? = null init { disposableLightToggle = lightManager .toggleStateStream .observeOn(postExecutionThread.scheduler) .subscribe { liveDataLightToggle.value = it } } fun setMode(mode: ModeBase.Mode) { settingsRepository.mode = mode lightManager.setMode(modeFactory.getMode(mode)) } fun setModule(module: ModuleBase.Module) { settingsRepository.module = module lightManager.setModule(moduleFactory.getModule(module)) } fun setStrobePeriod(timeOn: Int, timeOff: Int) { settingsRepository.strobeOnPeriod = timeOn settingsRepository.strobeOffPeriod = timeOff lightManager.setStrobePeriod(timeOn, timeOff) } override fun onCleared() { super.onCleared() disposableLightToggle?.dispose() } }
app/src/main/java/co/garmax/materialflashlight/ui/main/MainViewModel.kt
931652296
package eu.kanade.presentation.more.settings.screen import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.FlipToBack import androidx.compose.material.icons.outlined.SelectAll import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Checkbox import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.model.StateScreenModel import cafe.adriel.voyager.core.model.coroutineScope import cafe.adriel.voyager.core.model.rememberScreenModel import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import eu.kanade.domain.source.interactor.GetSourcesWithNonLibraryManga import eu.kanade.domain.source.model.Source import eu.kanade.domain.source.model.SourceWithCount import eu.kanade.presentation.browse.components.SourceIcon import eu.kanade.presentation.components.AppBar import eu.kanade.presentation.components.AppBarActions import eu.kanade.presentation.components.Divider import eu.kanade.presentation.components.EmptyScreen import eu.kanade.presentation.components.FastScrollLazyColumn import eu.kanade.presentation.components.LoadingScreen import eu.kanade.presentation.components.Scaffold import eu.kanade.presentation.util.selectedBackground import eu.kanade.tachiyomi.Database import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.lang.launchIO import eu.kanade.tachiyomi.util.system.toast import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class ClearDatabaseScreen : Screen { @Composable override fun Content() { val context = LocalContext.current val navigator = LocalNavigator.currentOrThrow val model = rememberScreenModel { ClearDatabaseScreenModel() } val state by model.state.collectAsState() when (val s = state) { is ClearDatabaseScreenModel.State.Loading -> LoadingScreen() is ClearDatabaseScreenModel.State.Ready -> { if (s.showConfirmation) { AlertDialog( onDismissRequest = model::hideConfirmation, confirmButton = { TextButton( onClick = { model.removeMangaBySourceId() model.clearSelection() model.hideConfirmation() context.toast(R.string.clear_database_completed) }, ) { Text(text = stringResource(android.R.string.ok)) } }, dismissButton = { TextButton(onClick = model::hideConfirmation) { Text(text = stringResource(android.R.string.cancel)) } }, text = { Text(text = stringResource(R.string.clear_database_confirmation)) }, ) } Scaffold( topBar = { scrollBehavior -> AppBar( title = stringResource(R.string.pref_clear_database), navigateUp = navigator::pop, actions = { if (s.items.isNotEmpty()) { AppBarActions( actions = listOf( AppBar.Action( title = stringResource(R.string.action_select_all), icon = Icons.Outlined.SelectAll, onClick = model::selectAll, ), AppBar.Action( title = stringResource(R.string.action_select_all), icon = Icons.Outlined.FlipToBack, onClick = model::invertSelection, ), ), ) } }, scrollBehavior = scrollBehavior, ) }, ) { contentPadding -> if (s.items.isEmpty()) { EmptyScreen( message = stringResource(R.string.database_clean), modifier = Modifier.padding(contentPadding), ) } else { Column( modifier = Modifier .padding(contentPadding) .fillMaxSize(), ) { FastScrollLazyColumn( modifier = Modifier.weight(1f), ) { items(s.items) { sourceWithCount -> ClearDatabaseItem( source = sourceWithCount.source, count = sourceWithCount.count, isSelected = s.selection.contains(sourceWithCount.id), onClickSelect = { model.toggleSelection(sourceWithCount.source) }, ) } } Divider() Button( modifier = Modifier .padding(horizontal = 16.dp, vertical = 8.dp) .fillMaxWidth(), onClick = model::showConfirmation, enabled = s.selection.isNotEmpty(), ) { Text( text = stringResource(R.string.action_delete), color = MaterialTheme.colorScheme.onPrimary, ) } } } } } } } @Composable private fun ClearDatabaseItem( source: Source, count: Long, isSelected: Boolean, onClickSelect: () -> Unit, ) { Row( modifier = Modifier .selectedBackground(isSelected) .clickable(onClick = onClickSelect) .padding(horizontal = 8.dp) .height(56.dp), verticalAlignment = Alignment.CenterVertically, ) { SourceIcon(source = source) Column( modifier = Modifier .padding(start = 8.dp) .weight(1f), ) { Text( text = source.visualName, style = MaterialTheme.typography.bodyMedium, ) Text(text = stringResource(R.string.clear_database_source_item_count, count)) } Checkbox( checked = isSelected, onCheckedChange = { onClickSelect() }, ) } } } private class ClearDatabaseScreenModel : StateScreenModel<ClearDatabaseScreenModel.State>(State.Loading) { private val getSourcesWithNonLibraryManga: GetSourcesWithNonLibraryManga = Injekt.get() private val database: Database = Injekt.get() init { coroutineScope.launchIO { getSourcesWithNonLibraryManga.subscribe() .collectLatest { list -> mutableState.update { old -> val items = list.sortedBy { it.name } when (old) { State.Loading -> State.Ready(items) is State.Ready -> old.copy(items = items) } } } } } fun removeMangaBySourceId() { val state = state.value as? State.Ready ?: return database.mangasQueries.deleteMangasNotInLibraryBySourceIds(state.selection) database.historyQueries.removeResettedHistory() } fun toggleSelection(source: Source) = mutableState.update { state -> if (state !is State.Ready) return@update state val mutableList = state.selection.toMutableList() if (mutableList.contains(source.id)) { mutableList.remove(source.id) } else { mutableList.add(source.id) } state.copy(selection = mutableList) } fun clearSelection() = mutableState.update { state -> if (state !is State.Ready) return@update state state.copy(selection = emptyList()) } fun selectAll() = mutableState.update { state -> if (state !is State.Ready) return@update state state.copy(selection = state.items.map { it.id }) } fun invertSelection() = mutableState.update { state -> if (state !is State.Ready) return@update state state.copy( selection = state.items .map { it.id } .filterNot { it in state.selection }, ) } fun showConfirmation() = mutableState.update { state -> if (state !is State.Ready) return@update state state.copy(showConfirmation = true) } fun hideConfirmation() = mutableState.update { state -> if (state !is State.Ready) return@update state state.copy(showConfirmation = false) } sealed class State { object Loading : State() data class Ready( val items: List<SourceWithCount>, val selection: List<Long> = emptyList(), val showConfirmation: Boolean = false, ) : State() } }
app/src/main/java/eu/kanade/presentation/more/settings/screen/ClearDatabaseScreen.kt
892690366
package com.lyc.gank.category import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import com.lyc.data.resp.GankItem import com.lyc.gank.R import com.lyc.gank.OnGankItemClickListener import com.lyc.gank.utils.gankOption import com.lyc.gank.utils.logi import kotlinx.android.synthetic.main.item_girl.view.* import me.drakeet.multitype.ItemViewBinder /** * Created by Liu Yuchuan on 2018/2/24. */ class GirlItemViewBinder( private val onGankItemClickListener: OnGankItemClickListener ) : ItemViewBinder<GankItem, GirlItemViewBinder.ViewHolder>() { override fun onBindViewHolder(holder: ViewHolder, item: GankItem) { holder.itemView.setOnClickListener { onGankItemClickListener.onGirlItemClick(holder.img, item) } Glide.with(holder.img) .load(item.imgUrl) .gankOption() .into(holder.img) } override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder { return ViewHolder(inflater.inflate(R.layout.item_girl, parent, false)) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val img = itemView.iv_girl!! } }
app/src/main/java/com/lyc/gank/category/GirlItemViewBinder.kt
3897114737
package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.R import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification class MsgSetBasalProfile( injector: HasAndroidInjector, index: Byte, values: Array<Double> ) : MessageBase(injector) { // index 0-3 init { setCommand(0x3306) addParamByte(index) for (i in 0..23) { addParamInt((values[i] * 100).toInt()) } aapsLogger.debug(LTag.PUMPCOMM, "Set basal profile: $index") } override fun handleMessage(bytes: ByteArray) { val result = intFromBuff(bytes, 0, 1) if (result != 1) { failed = true aapsLogger.debug(LTag.PUMPCOMM, "Set basal profile result: $result FAILED!!!") val reportFail = Notification(Notification.PROFILE_SET_FAILED, rh.gs(R.string.profile_set_failed), Notification.URGENT) rxBus.send(EventNewNotification(reportFail)) } else { failed = false aapsLogger.debug(LTag.PUMPCOMM, "Set basal profile result: $result") val reportOK = Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60) rxBus.send(EventNewNotification(reportOK)) } } }
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetBasalProfile.kt
783276156
package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.os.SystemClock import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.Constants import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonOverviewButtonsBinding import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonOverviewPodInfoBinding import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandHandleTimeChange import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandResumeDelivery import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandSilenceAlerts import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandSuspendDelivery import info.nightscout.androidaps.plugins.pump.omnipod.dash.EventOmnipodDashPumpValuesChanged import info.nightscout.androidaps.plugins.pump.omnipod.dash.OmnipodDashPumpPlugin import info.nightscout.androidaps.plugins.pump.omnipod.dash.R import info.nightscout.androidaps.plugins.pump.omnipod.dash.databinding.OmnipodDashOverviewBinding import info.nightscout.androidaps.plugins.pump.omnipod.dash.databinding.OmnipodDashOverviewBluetoothStatusBinding import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodConstants import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.events.EventQueueChanged import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.ui.UIRunnable import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import org.apache.commons.lang3.StringUtils import java.time.Duration import java.time.ZonedDateTime import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject // TODO generify; see OmnipodErosOverviewFragment class OmnipodDashOverviewFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var omnipodDashPumpPlugin: OmnipodDashPumpPlugin @Inject lateinit var podStateManager: OmnipodDashPodStateManager @Inject lateinit var sp: SP @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var pumpSync: PumpSync @Inject lateinit var buildHelper: BuildHelper companion object { private const val REFRESH_INTERVAL_MILLIS = 15 * 1000L // 15 seconds private const val PLACEHOLDER = "-" private const val MAX_TIME_DEVIATION_MINUTES = 10L } private var disposables: CompositeDisposable = CompositeDisposable() private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) private lateinit var refreshLoop: Runnable init { refreshLoop = Runnable { activity?.runOnUiThread { updateUi() } handler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) } } private var _binding: OmnipodDashOverviewBinding? = null private var _bluetoothStatusBinding: OmnipodDashOverviewBluetoothStatusBinding? = null private var _podInfoBinding: OmnipodCommonOverviewPodInfoBinding? = null private var _buttonBinding: OmnipodCommonOverviewButtonsBinding? = null // These properties are only valid between onCreateView and onDestroyView. val binding get() = _binding!! private val bluetoothStatusBinding get() = _bluetoothStatusBinding!! private val podInfoBinding get() = _podInfoBinding!! private val buttonBinding get() = _buttonBinding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = OmnipodDashOverviewBinding.inflate(inflater, container, false).also { _buttonBinding = OmnipodCommonOverviewButtonsBinding.bind(it.root) _podInfoBinding = OmnipodCommonOverviewPodInfoBinding.bind(it.root) _bluetoothStatusBinding = OmnipodDashOverviewBluetoothStatusBinding.bind(it.root) _binding = it }.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) buttonBinding.buttonPodManagement.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.PREFERENCES, UIRunnable { startActivity(Intent(context, DashPodManagementActivity::class.java)) } ) } } buttonBinding.buttonResumeDelivery.setOnClickListener { disablePodActionButtons() commandQueue.customCommand( CommandResumeDelivery(), DisplayResultDialogCallback( rh.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true ).messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_delivery_resumed)) ) } buttonBinding.buttonRefreshStatus.setOnClickListener { disablePodActionButtons() commandQueue.readStatus( rh.gs(R.string.requested_by_user), DisplayResultDialogCallback( rh.gs(R.string.omnipod_common_error_failed_to_refresh_status), false ) ) } buttonBinding.buttonSilenceAlerts.setOnClickListener { disablePodActionButtons() commandQueue.customCommand( CommandSilenceAlerts(), DisplayResultDialogCallback( rh.gs(R.string.omnipod_common_error_failed_to_silence_alerts), false ) .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_silenced_alerts)) .actionOnSuccess { rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_ALERTS)) } ) } buttonBinding.buttonSuspendDelivery.setOnClickListener { disablePodActionButtons() commandQueue.customCommand( CommandSuspendDelivery(), DisplayResultDialogCallback( rh.gs(R.string.omnipod_common_error_failed_to_suspend_delivery), true ) .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_suspended_delivery)) ) } buttonBinding.buttonSetTime.setOnClickListener { disablePodActionButtons() commandQueue.customCommand( CommandHandleTimeChange(true), DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_set_time), true) .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_time_on_pod_updated)) ) } if (buildHelper.isEngineeringMode()) { bluetoothStatusBinding.deliveryStatus.visibility = View.VISIBLE bluetoothStatusBinding.connectionQuality.visibility = View.VISIBLE } podInfoBinding.omnipodCommonOverviewLotNumberLayout.visibility = View.GONE podInfoBinding.omnipodCommonOverviewPodUniqueIdLayout.visibility = View.GONE } override fun onResume() { super.onResume() handler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) disposables += rxBus .toObservable(EventOmnipodDashPumpValuesChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe( { updateOmnipodStatus() updatePodActionButtons() }, fabricPrivacy::logException ) disposables += rxBus .toObservable(EventQueueChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe( { updateQueueStatus() updatePodActionButtons() }, fabricPrivacy::logException ) disposables += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.main) .subscribe( { updatePodActionButtons() }, fabricPrivacy::logException ) disposables += rxBus .toObservable(EventPumpStatusChanged::class.java) .observeOn(aapsSchedulers.main) .delay(30, TimeUnit.MILLISECONDS, aapsSchedulers.main) .subscribe( { updateBluetoothConnectionStatus(it) }, fabricPrivacy::logException ) updateUi() } override fun onPause() { super.onPause() disposables.clear() handler.removeCallbacks(refreshLoop) } @Synchronized override fun onDestroyView() { super.onDestroyView() _binding = null _bluetoothStatusBinding = null _buttonBinding = null _podInfoBinding = null } private fun updateUi() { updateBluetoothStatus() updateOmnipodStatus() updatePodActionButtons() updateQueueStatus() } private fun updateBluetoothConnectionStatus(event: EventPumpStatusChanged) { val status = event.getStatus(rh) bluetoothStatusBinding.omnipodDashBluetoothStatus.text = status } private fun updateBluetoothStatus() { bluetoothStatusBinding.omnipodDashBluetoothAddress.text = podStateManager.bluetoothAddress ?: PLACEHOLDER val connectionSuccessPercentage = podStateManager.connectionSuccessRatio() * 100 val connectionAttempts = podStateManager.failedConnectionsAfterRetries + podStateManager.successfulConnectionAttemptsAfterRetries val successPercentageString = String.format("%.2f %%", connectionSuccessPercentage) val quality = "${podStateManager.successfulConnectionAttemptsAfterRetries}/$connectionAttempts :: $successPercentageString" bluetoothStatusBinding.omnipodDashBluetoothConnectionQuality.text = quality val connectionStatsColor = rh.gac( context, when { connectionSuccessPercentage < 70 && podStateManager.successfulConnectionAttemptsAfterRetries > 50 -> R.attr.warningColor connectionSuccessPercentage < 90 && podStateManager.successfulConnectionAttemptsAfterRetries > 50 -> R.attr.omniYellowColor else -> R.attr.defaultTextColor } ) bluetoothStatusBinding.omnipodDashBluetoothConnectionQuality.setTextColor(connectionStatsColor) bluetoothStatusBinding.omnipodDashDeliveryStatus.text = podStateManager.deliveryStatus?.let { podStateManager.deliveryStatus.toString() } ?: PLACEHOLDER } private fun updateOmnipodStatus() { updateLastConnection() updateLastBolus() updateTempBasal() updatePodStatus() val errors = ArrayList<String>() if (podStateManager.activationProgress.isBefore(ActivationProgress.SET_UNIQUE_ID)) { podInfoBinding.uniqueId.text = PLACEHOLDER podInfoBinding.podLot.text = PLACEHOLDER podInfoBinding.podSequenceNumber.text = PLACEHOLDER podInfoBinding.firmwareVersion.text = PLACEHOLDER podInfoBinding.timeOnPod.text = PLACEHOLDER podInfoBinding.podExpiryDate.text = PLACEHOLDER podInfoBinding.podExpiryDate.setTextColor(rh.gac(context, R.attr.defaultTextColor)) podInfoBinding.baseBasalRate.text = PLACEHOLDER podInfoBinding.totalDelivered.text = PLACEHOLDER podInfoBinding.reservoir.text = PLACEHOLDER podInfoBinding.reservoir.setTextColor(rh.gac(context, R.attr.defaultTextColor)) podInfoBinding.podActiveAlerts.text = PLACEHOLDER } else { podInfoBinding.uniqueId.text = podStateManager.uniqueId.toString() podInfoBinding.podLot.text = podStateManager.lotNumber.toString() podInfoBinding.podSequenceNumber.text = podStateManager.podSequenceNumber.toString() podInfoBinding.firmwareVersion.text = rh.gs( R.string.omnipod_dash_overview_firmware_version_value, podStateManager.firmwareVersion.toString(), podStateManager.bluetoothVersion.toString() ) val timeZone = podStateManager.timeZoneId?.let { timeZoneId -> podStateManager.timeZoneUpdated?.let { timeZoneUpdated -> val tz = TimeZone.getTimeZone(timeZoneId) val inDST = tz.inDaylightTime(Date(timeZoneUpdated)) val locale = resources.configuration.locales.get(0) tz.getDisplayName(inDST, TimeZone.SHORT, locale) } ?: PLACEHOLDER } ?: PLACEHOLDER podInfoBinding.timeOnPod.text = podStateManager.time?.let { rh.gs( R.string.omnipod_common_time_with_timezone, dateUtil.dateAndTimeString(it.toEpochSecond() * 1000), timeZone ) } ?: PLACEHOLDER val timeDeviationTooBig = podStateManager.timeDrift?.let { Duration.ofMinutes(MAX_TIME_DEVIATION_MINUTES).minus( it.abs() ).isNegative } ?: false podInfoBinding.timeOnPod.setTextColor( rh.gac( context, when { !podStateManager.sameTimeZone -> R.attr.omniMagentaColor timeDeviationTooBig -> R.attr.omniYellowColor else -> R.attr.defaultTextColor } ) ) // Update Pod expiry time val expiresAt = podStateManager.expiry podInfoBinding.podExpiryDate.text = expiresAt?.let { dateUtil.dateAndTimeString(it.toEpochSecond() * 1000) } ?: PLACEHOLDER podInfoBinding.podExpiryDate.setTextColor( rh.gac( context, when { expiresAt != null && ZonedDateTime.now().isAfter(expiresAt) -> R.attr.warningColor expiresAt != null && ZonedDateTime.now().isAfter(expiresAt.minusHours(4)) -> R.attr.omniYellowColor else -> R.attr.defaultTextColor } ) ) podStateManager.alarmType?.let { errors.add( rh.gs( R.string.omnipod_common_pod_status_pod_fault_description, it.value, it.toString() ) ) } // base basal rate podInfoBinding.baseBasalRate.text = if (podStateManager.basalProgram != null && !podStateManager.isSuspended) { rh.gs( R.string.pump_basebasalrate, omnipodDashPumpPlugin.model() .determineCorrectBasalSize(podStateManager.basalProgram!!.rateAt(System.currentTimeMillis())) ) } else { PLACEHOLDER } // total delivered podInfoBinding.totalDelivered.text = if (podStateManager.isActivationCompleted && podStateManager.pulsesDelivered != null) { rh.gs( R.string.omnipod_common_overview_total_delivered_value, (podStateManager.pulsesDelivered!! * PodConstants.POD_PULSE_BOLUS_UNITS) ) } else { PLACEHOLDER } // reservoir if (podStateManager.pulsesRemaining == null) { podInfoBinding.reservoir.text = rh.gs(R.string.omnipod_common_overview_reservoir_value_over50) podInfoBinding.reservoir.setTextColor(rh.gac(context, R.attr.defaultTextColor)) } else { // TODO // val lowReservoirThreshold = (omnipodAlertUtil.lowReservoirAlertUnits // ?: OmnipodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD).toDouble() val lowReservoirThreshold: Short = PodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD podInfoBinding.reservoir.text = rh.gs( R.string.omnipod_common_overview_reservoir_value, (podStateManager.pulsesRemaining!! * PodConstants.POD_PULSE_BOLUS_UNITS) ) podInfoBinding.reservoir.setTextColor( rh.gac( context, if (podStateManager.pulsesRemaining!! < lowReservoirThreshold) { R.attr.warningColor } else { R.attr.defaultTextColor } ) ) } podInfoBinding.podActiveAlerts.text = podStateManager.activeAlerts?.let { it -> it.joinToString(System.lineSeparator()) { t -> translatedActiveAlert(t) } } ?: PLACEHOLDER } if (errors.size == 0) { podInfoBinding.errors.text = PLACEHOLDER podInfoBinding.errors.setTextColor(rh.gac(context, R.attr.defaultTextColor)) } else { podInfoBinding.errors.text = StringUtils.join(errors, System.lineSeparator()) podInfoBinding.errors.setTextColor(rh.gac(context, R.attr.warningColor)) } } private fun translatedActiveAlert(alert: AlertType): String { val id = when (alert) { AlertType.LOW_RESERVOIR -> R.string.omnipod_common_alert_low_reservoir AlertType.EXPIRATION -> R.string.omnipod_common_alert_expiration_advisory AlertType.EXPIRATION_IMMINENT -> R.string.omnipod_common_alert_expiration AlertType.USER_SET_EXPIRATION -> R.string.omnipod_common_alert_expiration_advisory AlertType.AUTO_OFF -> R.string.omnipod_common_alert_shutdown_imminent AlertType.SUSPEND_IN_PROGRESS -> R.string.omnipod_common_alert_delivery_suspended AlertType.SUSPEND_ENDED -> R.string.omnipod_common_alert_delivery_suspended else -> R.string.omnipod_common_alert_unknown_alert } return rh.gs(id) } private fun updateLastConnection() { if (podStateManager.isUniqueIdSet) { podInfoBinding.lastConnection.text = readableDuration( Duration.ofMillis( System.currentTimeMillis() - podStateManager.lastUpdatedSystem, ) ) val lastConnectionColor = rh.gac( context, if (omnipodDashPumpPlugin.isUnreachableAlertTimeoutExceeded(getPumpUnreachableTimeout().toMillis())) { R.attr.warningColor } else { R.attr.defaultTextColor } ) podInfoBinding.lastConnection.setTextColor(lastConnectionColor) } else { podInfoBinding.lastConnection.setTextColor(rh.gac(context, R.attr.defaultTextColor)) podInfoBinding.lastConnection.text = PLACEHOLDER } } private fun updatePodStatus() { podInfoBinding.podStatus.text = if (podStateManager.activationProgress == ActivationProgress.NOT_STARTED) { rh.gs(R.string.omnipod_common_pod_status_no_active_pod) } else if (!podStateManager.isActivationCompleted) { if (!podStateManager.isUniqueIdSet) { rh.gs(R.string.omnipod_common_pod_status_waiting_for_activation) } else { if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIME_COMPLETED)) { rh.gs(R.string.omnipod_common_pod_status_waiting_for_activation) } else { rh.gs(R.string.omnipod_common_pod_status_waiting_for_cannula_insertion) } } } else { if (podStateManager.podStatus!!.isRunning()) { if (podStateManager.isSuspended) { rh.gs(R.string.omnipod_common_pod_status_suspended) } else { rh.gs(R.string.omnipod_common_pod_status_running) } /* } else if (podStateManager.podStatus == PodProgressStatus.FAULT_EVENT_OCCURRED) { rh.gs(R.string.omnipod_common_pod_status_pod_fault) } else if (podStateManager.podStatus == PodProgressStatus.INACTIVE) { rh.gs(R.string.omnipod_common_pod_status_inactive) */ } else { podStateManager.podStatus.toString() } } val podStatusColor = rh.gac( context, when { !podStateManager.isActivationCompleted || podStateManager.isPodKaput || podStateManager.isSuspended -> R.attr.warningColor podStateManager.activeCommand != null -> R.attr.omniYellowColor else -> R.attr.defaultTextColor } ) podInfoBinding.podStatus.setTextColor(podStatusColor) } private fun updateLastBolus() { var textColorAttr = R.attr.defaultTextColor podStateManager.activeCommand?.let { val requestedBolus = it.requestedBolus if (requestedBolus != null) { var text = rh.gs( R.string.omnipod_common_overview_last_bolus_value, omnipodDashPumpPlugin.model().determineCorrectBolusSize(requestedBolus), rh.gs(R.string.insulin_unit_shortname), readableDuration(Duration.ofMillis(SystemClock.elapsedRealtime() - it.createdRealtime)) ) text += " (uncertain) " textColorAttr = R.attr.warningColor podInfoBinding.lastBolus.text = text podInfoBinding.lastBolus.setTextColor(rh.gac(context, textColorAttr)) return } } podInfoBinding.lastBolus.setTextColor(rh.gac(context, textColorAttr)) podStateManager.lastBolus?.let { // display requested units if delivery is in progress val bolusSize = it.deliveredUnits() ?: it.requestedUnits val text = rh.gs( R.string.omnipod_common_overview_last_bolus_value, omnipodDashPumpPlugin.model().determineCorrectBolusSize(bolusSize), rh.gs(R.string.insulin_unit_shortname), readableDuration(Duration.ofMillis(System.currentTimeMillis() - it.startTime)) ) if (!it.deliveryComplete) { textColorAttr = R.attr.omniYellowColor } podInfoBinding.lastBolus.text = text podInfoBinding.lastBolus.setTextColor(rh.gac(context, textColorAttr)) return } podInfoBinding.lastBolus.text = PLACEHOLDER } private fun updateTempBasal() { val tempBasal = podStateManager.tempBasal if (podStateManager.isActivationCompleted && podStateManager.tempBasalActive && tempBasal != null) { val startTime = tempBasal.startTime val rate = tempBasal.rate val duration = tempBasal.durationInMinutes val minutesRunning = Duration.ofMillis(System.currentTimeMillis() - startTime).toMinutes() podInfoBinding.tempBasal.text = rh.gs( R.string.omnipod_common_overview_temp_basal_value, rate, dateUtil.timeString(startTime), minutesRunning, duration ) } else { podInfoBinding.tempBasal.text = PLACEHOLDER } } private fun updateQueueStatus() { if (isQueueEmpty()) { podInfoBinding.queue.visibility = View.GONE } else { podInfoBinding.queue.visibility = View.VISIBLE podInfoBinding.queue.text = commandQueue.spannedStatus().toString() } } private fun updatePodActionButtons() { updateRefreshStatusButton() updateResumeDeliveryButton() updateSilenceAlertsButton() updateSuspendDeliveryButton() updateSetTimeButton() } private fun disablePodActionButtons() { buttonBinding.buttonSilenceAlerts.isEnabled = false buttonBinding.buttonResumeDelivery.isEnabled = false buttonBinding.buttonSuspendDelivery.isEnabled = false buttonBinding.buttonSetTime.isEnabled = false buttonBinding.buttonRefreshStatus.isEnabled = false } private fun updateRefreshStatusButton() { buttonBinding.buttonRefreshStatus.isEnabled = podStateManager.isUniqueIdSet && isQueueEmpty() } private fun updateResumeDeliveryButton() { if (podStateManager.isPodRunning && (podStateManager.isSuspended || commandQueue.isCustomCommandInQueue(CommandResumeDelivery::class.java)) ) { buttonBinding.buttonResumeDelivery.visibility = View.VISIBLE buttonBinding.buttonResumeDelivery.isEnabled = isQueueEmpty() } else { buttonBinding.buttonResumeDelivery.visibility = View.GONE } } private fun updateSilenceAlertsButton() { if (!isAutomaticallySilenceAlertsEnabled() && podStateManager.isPodRunning && ( podStateManager.activeAlerts!!.size > 0 || commandQueue.isCustomCommandInQueue(CommandSilenceAlerts::class.java) ) ) { buttonBinding.buttonSilenceAlerts.visibility = View.VISIBLE buttonBinding.buttonSilenceAlerts.isEnabled = isQueueEmpty() } else { buttonBinding.buttonSilenceAlerts.visibility = View.GONE } } private fun updateSuspendDeliveryButton() { // If the Pod is currently suspended, we show the Resume delivery button instead. // disable the 'suspendDelivery' button. buttonBinding.buttonSuspendDelivery.visibility = View.GONE } private fun updateSetTimeButton() { if (podStateManager.isActivationCompleted && !podStateManager.sameTimeZone) { buttonBinding.buttonSetTime.visibility = View.VISIBLE buttonBinding.buttonSetTime.isEnabled = !podStateManager.isSuspended && isQueueEmpty() } else { buttonBinding.buttonSetTime.visibility = View.GONE } } private fun isAutomaticallySilenceAlertsEnabled(): Boolean { return sp.getBoolean(R.string.omnipod_common_preferences_automatically_silence_alerts, false) } private fun displayErrorDialog(title: String, message: String, withSound: Boolean) { context?.let { ErrorHelperActivity.runAlarm(it, message, title, if (withSound) R.raw.boluserror else 0) } } private fun displayOkDialog(title: String, message: String) { context?.let { UIRunnable { OKDialog.show(it, title, message, null) }.run() } } private fun readableDuration(duration: Duration): String { val hours = duration.toHours().toInt() val minutes = duration.toMinutes().toInt() val seconds = duration.seconds when { seconds < 10 -> { return rh.gs(R.string.omnipod_common_moments_ago) } seconds < 60 -> { return rh.gs(R.string.omnipod_common_less_than_a_minute_ago) } seconds < 60 * 60 -> { // < 1 hour return rh.gs( R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_minutes, minutes, minutes) ) } seconds < 24 * 60 * 60 -> { // < 1 day val minutesLeft = minutes % 60 if (minutesLeft > 0) return rh.gs( R.string.omnipod_common_time_ago, rh.gs( R.string.omnipod_common_composite_time, rh.gq(R.plurals.omnipod_common_hours, hours, hours), rh.gq(R.plurals.omnipod_common_minutes, minutesLeft, minutesLeft) ) ) return rh.gs( R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_hours, hours, hours) ) } else -> { val days = hours / 24 val hoursLeft = hours % 24 if (hoursLeft > 0) return rh.gs( R.string.omnipod_common_time_ago, rh.gs( R.string.omnipod_common_composite_time, rh.gq(R.plurals.omnipod_common_days, days, days), rh.gq(R.plurals.omnipod_common_hours, hoursLeft, hoursLeft) ) ) return rh.gs( R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_days, days, days) ) } } } private fun isQueueEmpty(): Boolean { return commandQueue.size() == 0 && commandQueue.performing() == null } // FIXME ideally we should just have access to LocalAlertUtils here private fun getPumpUnreachableTimeout(): Duration { return Duration.ofMinutes( sp.getInt( R.string.key_pump_unreachable_threshold_minutes, Constants.DEFAULT_PUMP_UNREACHABLE_THRESHOLD_MINUTES ).toLong() ) } inner class DisplayResultDialogCallback( private val errorMessagePrefix: String, private val withSoundOnError: Boolean ) : Callback() { private var messageOnSuccess: String? = null private var actionOnSuccess: Runnable? = null override fun run() { if (result.success) { val messageOnSuccess = this.messageOnSuccess if (messageOnSuccess != null) { displayOkDialog(rh.gs(R.string.omnipod_common_confirmation), messageOnSuccess) } actionOnSuccess?.run() } else { displayErrorDialog( rh.gs(R.string.omnipod_common_warning), rh.gs( R.string.omnipod_common_two_strings_concatenated_by_colon, errorMessagePrefix, result.comment ), withSoundOnError ) } } fun messageOnSuccess(message: String): DisplayResultDialogCallback { messageOnSuccess = message return this } fun actionOnSuccess(action: Runnable): DisplayResultDialogCallback { actionOnSuccess = action return this } } }
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt
3861077542
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package khttp.helpers class StringIterable(val string: String) : Iterable<Char> { override fun iterator(): Iterator<Char> = this.string.toCharArray().iterator() }
src/test/kotlin/khttp/helpers/StringIterable.kt
2980967762
package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.DanaRSTestBase import org.junit.Assert import org.junit.Test class DanaRsPacketHistoryCarbohydrateTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } if (it is DanaRSPacketHistoryCarbohydrate) { it.rxBus = rxBus } } } @Test fun runTest() { val packet = DanaRSPacketHistoryCarbohydrate(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__CARBOHYDRATE", packet.friendlyName) } }
danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryCarbohydrateTest.kt
3905009757
package venus.simulator import kotlin.test.Test import kotlin.test.assertEquals import venus.assembler.Assembler import venus.linker.Linker class ECALLTest { @Test fun terminateEarly() { val (prog, _) = Assembler.assemble(""" addi a0 x0 10 ecall addi a0 x0 5""") val linked = Linker.link(listOf(prog)) val sim = Simulator(linked) sim.run() assertEquals(10, sim.getReg(10)) } @Test fun malloc() { val (prog, _) = Assembler.assemble(""" # malloc 4 bytes of memory addi a0 x0 9 addi a1 x0 4 ecall mv s0 a0 # store 5 there addi s1 x0 5 sw s1 0(s0) # malloc 4 more bytes addi a0 x0 9 addi a1 x0 4 ecall addi s2 x0 6 # store 6 there sw s2 0(a0) # retrieve the old 5 lw s1 0(s0)""") val linked = Linker.link(listOf(prog)) val sim = Simulator(linked) sim.run() assertEquals(5, sim.getReg(9)) } }
src/test/kotlin/simulator/ECALLTest.kt
1270409603
/* * Copyright 2016 Geetesh Kalakoti <[email protected]> * * 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.geeteshk.hyper.util.net import android.os.Build import android.text.Html import android.text.Spanned object HtmlCompat { @Suppress("DEPRECATION") fun fromHtml(html: String): Spanned { return if (Build.VERSION.SDK_INT < 24) { Html.fromHtml(html) } else { Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT) } } }
app/src/main/java/io/geeteshk/hyper/util/net/HtmlCompat.kt
569283766
package com.jetbrains.edu.learning.ui import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.Separator import com.intellij.openapi.project.Project import com.jetbrains.edu.learning.StudyTaskManager import com.jetbrains.edu.learning.StudyUtils import com.jetbrains.edu.learning.core.EduNames import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder class StudyHint(private val myPlaceholder: AnswerPlaceholder?, project: Project) { companion object { private val OUR_WARNING_MESSAGE = "Put the caret in the answer placeholder to get hint" private val HINTS_NOT_AVAILABLE = "There is no hint for this answer placeholder" } val studyToolWindow: StudyToolWindow private var myShownHintNumber = 0 private var isEditingMode = false private val newHintDefaultText = "Edit this hint" init { val taskManager = StudyTaskManager.getInstance(project) if (StudyUtils.hasJavaFx() && taskManager.shouldUseJavaFx()) { studyToolWindow = StudyJavaFxToolWindow() } else { studyToolWindow = StudySwingToolWindow() } studyToolWindow.init(project, false) if (myPlaceholder == null) { studyToolWindow.setText(OUR_WARNING_MESSAGE) studyToolWindow.setActionToolbar(DefaultActionGroup()) } val course = taskManager.course if (course != null) { val courseMode = course.courseMode val group = DefaultActionGroup() val hints = myPlaceholder?.hints if (hints != null) { if (courseMode == EduNames.STUDY) { if (hints.size > 1) { group.addAll(GoBackward(), GoForward()) } } else { group.addAll(GoBackward(), GoForward(), Separator.getInstance(), EditHint()) } studyToolWindow.setActionToolbar(group) setHintText(hints) } } } private fun setHintText(hints: List<String>) { if (!hints.isEmpty()) { studyToolWindow.setText(hints[myShownHintNumber]) } else { myShownHintNumber = -1 studyToolWindow.setText(HINTS_NOT_AVAILABLE) } } private inner class GoForward : AnAction("Next Hint", "Next Hint", AllIcons.Actions.Forward) { override fun actionPerformed(e: AnActionEvent) { studyToolWindow.setText(myPlaceholder!!.hints[++myShownHintNumber]) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = !isEditingMode && myPlaceholder != null && myShownHintNumber + 1 < myPlaceholder.hints.size } } private inner class GoBackward : AnAction("Previous Hint", "Previous Hint", AllIcons.Actions.Back) { override fun actionPerformed(e: AnActionEvent) { studyToolWindow.setText(myPlaceholder!!.hints[--myShownHintNumber]) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = !isEditingMode && myShownHintNumber - 1 >= 0 } } private inner class EditHint : AnAction("Edit Hint", "Edit Hint", AllIcons.Modules.Edit) { override fun actionPerformed(e: AnActionEvent?) { val dialog = CCCreateAnswerPlaceholderDialog(e!!.project!!, myPlaceholder!!) dialog.show() } override fun update(e: AnActionEvent) { e.presentation.isEnabled = myPlaceholder?.hints?.isEmpty() == false } } private inner class AddHint : AnAction("Add Hint", "Add Hint", AllIcons.General.Add) { override fun actionPerformed(e: AnActionEvent) { myPlaceholder!!.addHint(newHintDefaultText) myShownHintNumber++ studyToolWindow.setText(newHintDefaultText) } override fun update(e: AnActionEvent?) { e?.presentation?.isEnabled = !isEditingMode && myPlaceholder != null } } private inner class RemoveHint : AnAction("Remove Hint", "Remove Hint", AllIcons.General.Remove) { override fun actionPerformed(e: AnActionEvent) { myPlaceholder!!.removeHint(myShownHintNumber) myShownHintNumber += if (myShownHintNumber < myPlaceholder.hints.size) 0 else -1 setHintText(myPlaceholder.hints) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = myPlaceholder != null && myPlaceholder.hints.size > 0 && !isEditingMode } } }
python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyHint.kt
1321113311
/* * Copyright 2020 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.internal import com.squareup.wire.GrpcResponse import okio.Sink import okio.Source actual interface Call { actual fun cancel() actual fun execute(): GrpcResponse } internal actual fun Sink.asGzip(): Sink { throw UnsupportedOperationException("Gzip not implemented for JS") } internal actual fun Source.asGzip(): Source { throw UnsupportedOperationException("Gzip not implemented for JS") } internal actual fun Throwable.addSuppressed(other: Throwable) { }
wire-library/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/internal/platform.kt
712581168
/* * 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.repository.quarterly import app.ss.lessons.data.api.SSQuarterliesApi import app.ss.lessons.data.repository.DataSource import app.ss.lessons.data.repository.DataSourceMediator import app.ss.lessons.data.repository.LocalDataSource import app.ss.models.Language import app.ss.storage.db.dao.LanguagesDao import app.ss.storage.db.entity.LanguageEntity import com.cryart.sabbathschool.core.extensions.connectivity.ConnectivityHelper import com.cryart.sabbathschool.core.extensions.coroutines.DispatcherProvider import com.cryart.sabbathschool.core.response.Resource import javax.inject.Inject import javax.inject.Singleton @Singleton internal class LanguagesDataSource @Inject constructor( dispatcherProvider: DispatcherProvider, connectivityHelper: ConnectivityHelper, private val languagesDao: LanguagesDao, private val quarterliesApi: SSQuarterliesApi ) : DataSourceMediator<Language, LanguagesDataSource.Request>( dispatcherProvider = dispatcherProvider, connectivityHelper = connectivityHelper ) { class Request override val cache: LocalDataSource<Language, Request> = object : LocalDataSource<Language, Request> { override suspend fun get(request: Request): Resource<List<Language>> { val data = languagesDao.get().map { Language(it.code, it.name) } return Resource.success(data) } override suspend fun update(data: List<Language>) { languagesDao.insertAll(data.map { LanguageEntity(it.code, it.name) }) } } override val network: DataSource<Language, Request> = object : DataSource<Language, Request> { override suspend fun get(request: Request): Resource<List<Language>> { val data = quarterliesApi.getLanguages().body()?.map { Language(it.code, it.name) } ?: emptyList() return Resource.success(data) } } }
common/lessons-data/src/main/java/app/ss/lessons/data/repository/quarterly/LanguagesDataSource.kt
887912723
/* * Copyright 2016 Geetesh Kalakoti <[email protected]> * * 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.geeteshk.hyper.git import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.AsyncTask import android.os.Build import android.view.View import androidx.core.app.NotificationCompat import io.geeteshk.hyper.R import org.eclipse.jgit.lib.BatchingProgressMonitor import java.io.File import java.lang.ref.WeakReference abstract class GitTask(var context: WeakReference<Context>, var rootView: WeakReference<View>, var repo: File, private var messages: Array<String>) : AsyncTask<String, String, Boolean>() { val progressMonitor = object : BatchingProgressMonitor() { override fun onUpdate(taskName: String?, workCurr: Int, workTotal: Int, percentDone: Int) { publishProgress(taskName, percentDone.toString(), workCurr.toString(), workTotal.toString()) } override fun onEndTask(taskName: String?, workCurr: Int, workTotal: Int, percentDone: Int) { publishProgress(taskName, workCurr.toString(), workTotal.toString()) } override fun onUpdate(taskName: String?, workCurr: Int) {} override fun onEndTask(taskName: String?, workCurr: Int) {} } var manager: NotificationManager = context.get()!!.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager var builder: NotificationCompat.Builder var id = 1 init { val id = "hyper_git_channel" if (Build.VERSION.SDK_INT >= 26) { val name = context.get()!!.getString(R.string.app_name) val description = context.get()!!.getString(R.string.git) val importance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel(id, name, importance) channel.description = description manager.createNotificationChannel(channel) } builder = NotificationCompat.Builder(context.get()!!, id) } override fun onPreExecute() { super.onPreExecute() builder.setContentTitle(messages[0]) .setSmallIcon(R.drawable.ic_git_small) .setAutoCancel(false) .setOngoing(true) } override fun onProgressUpdate(vararg values: String) { super.onProgressUpdate(*values) builder.setContentText(values[0]) .setProgress(Integer.valueOf(values[2]), Integer.valueOf(values[1]), false) builder.setStyle(NotificationCompat.BigTextStyle().bigText(values[0])) manager.notify(id, builder.build()) } override fun onPostExecute(aBoolean: Boolean?) { super.onPostExecute(aBoolean) builder.setContentText(messages[if (aBoolean!!) { 1 } else { 2 }]) builder.setProgress(0, 0, false) .setAutoCancel(true) .setOngoing(false) manager.notify(id, builder.build()) } }
app/src/main/java/io/geeteshk/hyper/git/GitTask.kt
3585049493
package com.bajdcc.LALR1.grammar.semantic import com.bajdcc.LALR1.grammar.symbol.IQuerySymbol import com.bajdcc.LALR1.semantic.token.IIndexedData /** * 语义分析接口 * * @author bajdcc */ interface ISemanticAnalyzer { /** * 语义处理接口 * * @param indexed 索引包接口 * @param query 单词工厂接口 * @param recorder 语义错误记录接口 * @return 处理后的数据 */ fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any }
src/main/kotlin/com/bajdcc/LALR1/grammar/semantic/ISemanticAnalyzer.kt
4021002588
// 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.refactoring.changeSignature import com.intellij.psi.PsiReference import com.intellij.refactoring.changeSignature.ParameterInfo import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.core.setDefaultValue import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallableDefinitionUsage import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.util.isPrimaryConstructorOfDataClass import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.addRemoveModifier.setModifierList import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.descriptorUtil.isAnnotationConstructor import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.AbstractTypeChecker import org.jetbrains.kotlin.types.TypeCheckerState import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.checker.ClassicTypeSystemContext import org.jetbrains.kotlin.types.checker.createClassicTypeCheckerState import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.model.TypeConstructorMarker class KotlinParameterInfo( val callableDescriptor: CallableDescriptor, val originalIndex: Int = -1, private var name: String, val originalTypeInfo: KotlinTypeInfo = KotlinTypeInfo(false), var defaultValueForCall: KtExpression? = null, var defaultValueAsDefaultParameter: Boolean = false, var valOrVar: KotlinValVar = defaultValOrVar(callableDescriptor), val modifierList: KtModifierList? = null, ) : ParameterInfo { private var _defaultValueForParameter: KtExpression? = null fun setDefaultValueForParameter(expression: KtExpression?) { _defaultValueForParameter = expression } val defaultValue: KtExpression? get() = defaultValueForCall?.takeIf { defaultValueAsDefaultParameter } ?: _defaultValueForParameter var currentTypeInfo: KotlinTypeInfo = originalTypeInfo val defaultValueParameterReferences: Map<PsiReference, DeclarationDescriptor> by lazy { collectDefaultValueParameterReferences(defaultValueForCall) } private fun collectDefaultValueParameterReferences(defaultValueForCall: KtExpression?): Map<PsiReference, DeclarationDescriptor> { val file = defaultValueForCall?.containingFile as? KtFile ?: return emptyMap() if (!file.isPhysical && file.analysisContext == null) return emptyMap() return CollectParameterRefsVisitor(callableDescriptor, defaultValueForCall).run() } override fun getOldIndex(): Int = originalIndex val isNewParameter: Boolean get() = originalIndex == -1 override fun getDefaultValue(): String? = null override fun getName(): String = name override fun setName(name: String?) { this.name = name ?: "" } override fun getTypeText(): String = currentTypeInfo.render() val isTypeChanged: Boolean get() = !currentTypeInfo.isEquivalentTo(originalTypeInfo) override fun isUseAnySingleVariable(): Boolean = false override fun setUseAnySingleVariable(b: Boolean) { throw UnsupportedOperationException() } fun renderType(parameterIndex: Int, inheritedCallable: KotlinCallableDefinitionUsage<*>): String { val defaultRendering = currentTypeInfo.render() val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return defaultRendering val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return defaultRendering val parameter = currentBaseFunction.valueParameters[parameterIndex] if (parameter.isVararg) return defaultRendering val parameterType = parameter.type if (parameterType.isError) return defaultRendering val originalType = inheritedCallable.originalCallableDescriptor.valueParameters.getOrNull(originalIndex)?.type val typeToRender = originalType?.takeIf { val checker = OverridingTypeCheckerContext.createChecker(inheritedCallable.originalCallableDescriptor, currentBaseFunction) AbstractTypeChecker.equalTypes(checker, originalType.unwrap(), parameterType.unwrap()) } ?: parameterType return typeToRender.renderTypeWithSubstitution(typeSubstitutor, defaultRendering, true) } fun getInheritedName(inheritedCallable: KotlinCallableDefinitionUsage<*>): String { val name = this.name.quoteIfNeeded() if (!inheritedCallable.isInherited) return name val baseFunction = inheritedCallable.baseFunction val baseFunctionDescriptor = baseFunction.originalCallableDescriptor val inheritedFunctionDescriptor = inheritedCallable.originalCallableDescriptor val inheritedParameterDescriptors = inheritedFunctionDescriptor.valueParameters if (originalIndex < 0 || originalIndex >= baseFunctionDescriptor.valueParameters.size || originalIndex >= inheritedParameterDescriptors.size ) return name val inheritedParamName = inheritedParameterDescriptors[originalIndex].name.render() val oldParamName = baseFunctionDescriptor.valueParameters[originalIndex].name.render() return when { oldParamName == inheritedParamName && inheritedFunctionDescriptor !is AnonymousFunctionDescriptor -> name else -> inheritedParamName } } fun requiresExplicitType(inheritedCallable: KotlinCallableDefinitionUsage<*>): Boolean { val inheritedFunctionDescriptor = inheritedCallable.originalCallableDescriptor if (inheritedFunctionDescriptor !is AnonymousFunctionDescriptor) return true if (originalIndex < 0) return !inheritedCallable.hasExpectedType val inheritedParameterDescriptor = inheritedFunctionDescriptor.valueParameters[originalIndex] val parameter = DescriptorToSourceUtils.descriptorToDeclaration(inheritedParameterDescriptor) as? KtParameter ?: return false return parameter.typeReference != null } private fun getOriginalParameter(inheritedCallable: KotlinCallableDefinitionUsage<*>): KtParameter? { return (inheritedCallable.declaration as? KtFunction)?.valueParameters?.getOrNull(originalIndex) } private fun buildNewParameter(inheritedCallable: KotlinCallableDefinitionUsage<*>, parameterIndex: Int): KtParameter { val psiFactory = KtPsiFactory(inheritedCallable.project) val buffer = StringBuilder() if (modifierList != null) { buffer.append(modifierList.text).append(' ') } if (valOrVar != KotlinValVar.None) { buffer.append(valOrVar).append(' ') } buffer.append(getInheritedName(inheritedCallable)) if (requiresExplicitType(inheritedCallable)) { buffer.append(": ").append(renderType(parameterIndex, inheritedCallable)) } if (!inheritedCallable.isInherited) { defaultValue?.let { buffer.append(" = ").append(it.text) } } return psiFactory.createParameter(buffer.toString()) } fun getDeclarationSignature(parameterIndex: Int, inheritedCallable: KotlinCallableDefinitionUsage<*>): KtParameter { val originalParameter = getOriginalParameter(inheritedCallable) ?: return buildNewParameter(inheritedCallable, parameterIndex) val psiFactory = KtPsiFactory(originalParameter) val newParameter = originalParameter.copied() modifierList?.let { newParameter.setModifierList(it) } if (valOrVar != newParameter.valOrVarKeyword.toValVar()) { newParameter.setValOrVar(valOrVar) } val newName = getInheritedName(inheritedCallable) if (newParameter.name != newName) { newParameter.setName(newName.quoteIfNeeded()) } if (newParameter.typeReference != null || requiresExplicitType(inheritedCallable)) { newParameter.typeReference = psiFactory.createType(renderType(parameterIndex, inheritedCallable)) } if (!inheritedCallable.isInherited) { defaultValue?.let { newParameter.setDefaultValue(it) } } return newParameter } private class CollectParameterRefsVisitor( private val callableDescriptor: CallableDescriptor, private val expressionToProcess: KtExpression ) : KtTreeVisitorVoid() { private val refs = LinkedHashMap<PsiReference, DeclarationDescriptor>() private val bindingContext = expressionToProcess.analyze(BodyResolveMode.PARTIAL) private val project = expressionToProcess.project fun run(): Map<PsiReference, DeclarationDescriptor> { expressionToProcess.accept(this) return refs } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val ref = expression.mainReference val descriptor = targetToCollect(expression, ref) ?: return refs[ref] = descriptor } private fun targetToCollect(expression: KtSimpleNameExpression, ref: KtReference): DeclarationDescriptor? { val descriptor = ref.resolveToDescriptors(bindingContext).singleOrNull() if (descriptor is ValueParameterDescriptor) { return takeIfOurParameter(descriptor) } if (descriptor is PropertyDescriptor && callableDescriptor is ConstructorDescriptor) { val parameter = DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) if (parameter is KtParameter) { return takeIfOurParameter(bindingContext[BindingContext.VALUE_PARAMETER, parameter]) } } val resolvedCall = expression.getResolvedCall(bindingContext) ?: return null (resolvedCall.resultingDescriptor as? ReceiverParameterDescriptor)?.let { return if (takeIfOurReceiver(it.containingDeclaration) != null) it else null } takeIfOurReceiver(resolvedCall.extensionReceiver as? ImplicitReceiver)?.let { return it } takeIfOurReceiver(resolvedCall.dispatchReceiver as? ImplicitReceiver)?.let { return it } return null } private fun compareDescriptors(currentDescriptor: DeclarationDescriptor?, originalDescriptor: DeclarationDescriptor?): Boolean { return compareDescriptors(project, currentDescriptor, originalDescriptor) } private fun takeIfOurParameter(parameter: DeclarationDescriptor?): ValueParameterDescriptor? { return (parameter as? ValueParameterDescriptor) ?.takeIf { compareDescriptors(it.containingDeclaration, callableDescriptor) } } private fun takeIfOurReceiver(receiverDescriptor: DeclarationDescriptor?): DeclarationDescriptor? { return receiverDescriptor?.takeIf { compareDescriptors(it, callableDescriptor.extensionReceiverParameter?.containingDeclaration) || compareDescriptors(it, callableDescriptor.dispatchReceiverParameter?.containingDeclaration) } } private fun takeIfOurReceiver(receiver: ImplicitReceiver?): DeclarationDescriptor? { return takeIfOurReceiver(receiver?.declarationDescriptor) } } } private fun defaultValOrVar(callableDescriptor: CallableDescriptor): KotlinValVar = if (callableDescriptor.isAnnotationConstructor() || callableDescriptor.isPrimaryConstructorOfDataClass) KotlinValVar.Val else KotlinValVar.None private class OverridingTypeCheckerContext(private val matchingTypeConstructors: Map<TypeConstructorMarker, TypeConstructor>) : ClassicTypeSystemContext { override fun areEqualTypeConstructors(c1: TypeConstructorMarker, c2: TypeConstructorMarker): Boolean { return super.areEqualTypeConstructors(c1, c2) || run { val img1 = matchingTypeConstructors[c1] val img2 = matchingTypeConstructors[c2] img1 != null && img1 == c2 || img2 != null && img2 == c1 } } companion object { fun createChecker(superDescriptor: CallableDescriptor, subDescriptor: CallableDescriptor): TypeCheckerState { val context = OverridingTypeCheckerContext(subDescriptor.typeParameters.zip(superDescriptor.typeParameters).associate { it.first.typeConstructor to it.second.typeConstructor }) return createClassicTypeCheckerState(isErrorTypeEqualsToAnything = false, typeSystemContext = context) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinParameterInfo.kt
1879401236
package bz.stewart.bracken.db.file.parse import java.io.File /** * Created by stew on 3/9/17. */ class EmptyParser :Parser{ override fun parseData(uniqueId: String, data: File, lastModified: File?) { } override fun onComplete() { } }
db/src/main/kotlin/bz/stewart/bracken/db/file/parse/EmptyParser.kt
1772791922
package org.rust.lang.core.psi import com.intellij.psi.PsiElement import org.rust.lang.core.resolve.ref.RustReference interface RustQualifiedReferenceElement : RustNamedElement { val isFullyQualified: Boolean val isModulePrefix: Boolean val isSelf: Boolean val separator: PsiElement? val qualifier: RustQualifiedReferenceElement? override val nameElement: PsiElement? override fun getReference(): RustReference }
src/main/kotlin/org/rust/lang/core/psi/RustQualifiedReferenceElement.kt
1829088501
package org.hexworks.zircon.internal.tileset.transformer import org.hexworks.zircon.api.Modifiers import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture import org.junit.Before import org.junit.Test import java.awt.image.BufferedImage class Java2DVerticalFlipperTest { lateinit var target: Java2DVerticalFlipper @Before fun setUp() { target = Java2DVerticalFlipper() } @Test fun shouldProperlyRun() { val image = BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB) target.transform(DefaultTileTexture(WIDTH, HEIGHT, image, CHAR.toString()), CHAR) } companion object { val WIDTH = 10 val HEIGHT = 10 val CHAR = Tile.newBuilder() .withModifiers(Modifiers.verticalFlip()) .build() } }
zircon.jvm.swing/src/test/kotlin/org/hexworks/zircon/internal/tileset/transformer/Java2DVerticalFlipperTest.kt
3497144766
package org.hexworks.zircon.examples.base import org.hexworks.zircon.api.component.HBox import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.dsl.component.buildVbox import org.hexworks.zircon.api.screen.Screen import org.hexworks.zircon.internal.component.renderer.NoOpComponentRenderer abstract class OneColumnComponentExampleKotlin : ComponentExampleKotlin() { override fun addExamples(exampleArea: HBox) { buildVbox { name = "One Column Example Container" preferredSize = Size.create(exampleArea.width, exampleArea.height) componentRenderer = NoOpComponentRenderer() spacing = 1 }.apply { build(this) exampleArea.addComponent(this) } } }
zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/base/OneColumnComponentExampleKotlin.kt
2790104657
package org.jetbrains.plugins.notebooks.visualization.ui import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.openapi.editor.impl.EditorEmbeddedComponentManager import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.awt.event.HierarchyEvent import java.lang.ref.WeakReference import javax.swing.JComponent import javax.swing.JPanel import javax.swing.JScrollPane import javax.swing.SwingUtilities import javax.swing.plaf.PanelUI /** * A workaround base class for panels with custom UI. Every look and feel change in the IDE (like theme, font family and size, etc.) * leads to call of the `updateUI()`. All default Swing implementations resets the UI to the default one. */ open class SteadyUIPanel(private val steadyUi: PanelUI) : JPanel() { init { // Required for correct UI initialization. It leaks in the super class anyway. @Suppress("LeakingThis") setUI(steadyUi) } override fun updateUI() { // Update the UI. Don't call super.updateUI() to prevent resetting to the default UI. // There's another way to set specific UI for specific components: by defining java.swing.plaf.ComponentUI#createUI and overriding // java.swing.JComponent#getUIClassID. This approach can't be used in our code since it requires UI classes to have empty constructors, // while in reality some additional data should be provided to UI instances in advance. setUI(steadyUi) } } fun EditorEx.addComponentInlay( component: JComponent, isRelatedToPrecedingText: Boolean, showAbove: Boolean, showWhenFolded: Boolean = true, priority: Int, offset: Int, ): Inlay<*> { val inlay = EditorEmbeddedComponentManager.getInstance().addComponent( this, component, EditorEmbeddedComponentManager.Properties( EditorEmbeddedComponentManager.ResizePolicy.none(), null, isRelatedToPrecedingText, showAbove, showWhenFolded, priority, offset, ) )!! updateUiOnParentResizeImpl(component.parent as JComponent, WeakReference(component)) return inlay } private fun updateUiOnParentResizeImpl(parent: JComponent, childRef: WeakReference<JComponent>) { val listener = object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { val child = childRef.get() if (child != null) { child.updateUI() } else { parent.removeComponentListener(this) } } } parent.addComponentListener(listener) } /** * Seeks for an [EditorComponentImpl] in the component hierarchy, calls [updateHandler] initially and every time * the [component] is detached or attached to some component with the actual editor. */ fun registerEditorSizeWatcher( component: JComponent, updateHandler: () -> Unit, ) { var editorComponent: EditorComponentImpl? = null var scrollComponent: JScrollPane? = null updateHandler() // Holds strong reference to the editor. Incautious usage may cause editor leakage. val editorResizeListener = object : ComponentAdapter() { override fun componentResized(e: ComponentEvent): Unit = updateHandler() } component.addHierarchyListener { event -> if (event.changeFlags and HierarchyEvent.PARENT_CHANGED.toLong() != 0L) { val newEditor: EditorComponentImpl? = generateSequence(component.parent) { it.parent } .filterIsInstance<EditorComponentImpl>() .firstOrNull() if (editorComponent !== newEditor) { (scrollComponent ?: editorComponent)?.removeComponentListener(editorResizeListener) editorComponent = newEditor // if editor is located inside a scroll pane, we should listen to its size instead of editor component scrollComponent = generateSequence(editorComponent?.parent) { it.parent } .filterIsInstance<JScrollPane>() .firstOrNull() (scrollComponent ?: editorComponent)?.addComponentListener(editorResizeListener) updateHandler() } } } } val EditorEx.textEditingAreaWidth: Int get() = scrollingModel.visibleArea.width - scrollPane.verticalScrollBar.width fun JComponent.yOffsetFromEditor(editor: Editor): Int? = SwingUtilities.convertPoint(this, 0, 0, editor.contentComponent).y .takeIf { it >= 0 } ?.let { it + insets.top }
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/ui/NotebookEditorUiUtil.kt
4032924168
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtNamedFunction // OPTIONS: usages class A(val n: Int) { operator fun <caret>inc(): A = A(n + 1) } fun test() { var a = A(1) a.inc() ++a a++ } // FIR_COMPARISON // IGNORE_FIR_LOG
plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/inc.0.kt
3611224450
package net.squanchy.search.view import androidx.recyclerview.widget.GridLayoutManager import net.squanchy.search.SearchListElement internal class GridSpanSizeLookup( private val itemRetriever: (Int) -> SearchListElement, private val isAdapterEmpty: () -> Boolean, private val columnCount: Int ) : GridLayoutManager.SpanSizeLookup() { init { super.setSpanIndexCacheEnabled(true) } override fun getSpanSize(position: Int): Int { if (isAdapterEmpty()) { return SINGLE_COLUMN_SPAN_SIZE } else { return getSpanSizeFor(itemRetriever(position)) } } private fun getSpanSizeFor(element: SearchListElement): Int = when (element) { is SearchListElement.EventHeader -> columnCount is SearchListElement.SpeakerHeader -> columnCount is SearchListElement.EventElement -> columnCount is SearchListElement.SpeakerElement -> SINGLE_COLUMN_SPAN_SIZE is SearchListElement.AlgoliaLogo -> columnCount } companion object { private const val SINGLE_COLUMN_SPAN_SIZE = 1 } }
app/src/main/java/net/squanchy/search/view/GridSpanSizeLookup.kt
3227644195
/* * FelicaCardTransitFactory.kt * * Copyright 2018-2019 Google * * 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 au.id.micolous.metrodroid.card.felica import au.id.micolous.metrodroid.transit.CardInfo import au.id.micolous.metrodroid.transit.CardTransitFactory interface FelicaCardTransitFactory : CardTransitFactory<FelicaCard> { override fun check(card: FelicaCard) = earlyCheck(card.systems.keys.toList()) fun earlyCheck(systemCodes: List<Int>): Boolean fun getCardInfo(systemCodes: List<Int>): CardInfo? = allCards[0] }
src/commonMain/kotlin/au/id/micolous/metrodroid/card/felica/FelicaCardTransitFactory.kt
2140150108
fun main(args: Array<String>) { println(sumNumbersToN(10)) } /** * @return The sum of the numbers from 1 to n */ fun sumNumbersToN(n: Int) : Int { var sum = 0 for (i in 1..n) { sum += i } return sum }
kotlin/Mastering-Kotlin-master/Chapter03/src/Example1.kt
3770138317
package com.rafaelfiume.prosciutto.test import org.apache.commons.io.IOUtils import org.junit.Rule import org.junit.Test import org.junit.rules.ExpectedException import java.io.IOException import java.net.HttpURLConnection import java.net.URL import com.rafaelfiume.prosciutto.test.SalumeApiContractExampleReader.supplierAdviceForExpertRequest import com.rafaelfiume.prosciutto.test.SalumeApiContractExampleReader.supplierAdviceForExpertResponse import org.hamcrest.Matchers.containsString import org.junit.Assert.assertThat class StubbedServerTest { @Rule @JvmField var server = DependsOnServerRunningRule() @Rule @JvmField var exception: ExpectedException = ExpectedException.none() @Test @Throws(IOException::class) fun shouldReturnPrimedSuccessfulResponse() { whenPrimingSupplierResponseWith(supplierAdviceForExpertResponse()) assertThat(get(supplierAdviceForExpertRequest()), containsString("<product-advisor>")) } @Test @Throws(IOException::class) fun shouldThrowPrimedException() { whenPrimingServerErrorWhenRequesting("/I/would/like/to/buy/bananas") exception.expect(RuntimeException::class.java) exception.expectMessage("Response code for url <<http://localhost:8081/I/would/like/to/buy/bananas>> is: 500") get("http://localhost:8081/I/would/like/to/buy/bananas") } private fun whenPrimingSupplierResponseWith(response: String) { server.primeSuccessfulResponse("/salume/supplier/advise/for/Expert", response) } private fun whenPrimingServerErrorWhenRequesting(response: String) { server.primeServerErrorWhenRequesting(response) } // TODO Duplicated :( See integration package @Throws(IOException::class) private operator fun get(url: String): String { var http: HttpURLConnection? = null try { http = URL(url).openConnection() as HttpURLConnection if (http.responseCode != 200) { throw RuntimeException("Response code for url <<$url>> is: ${http.responseCode}") } return IOUtils.toString(http.inputStream) } finally { http!!.disconnect() } } }
test-support/src/test/kotlin/com/rafaelfiume/prosciutto/test/StubbedServerTest.kt
2276352751
package org.snakeskin.init import org.snakeskin.runtime.SnakeskinModules import org.snakeskin.runtime.SnakeskinRuntime class RevInit: Initializer { override fun preStartup() { SnakeskinRuntime.registerModule(SnakeskinModules.REV) } override fun postStartup() { //no-op } }
SnakeSkin-REV/src/main/kotlin/org/snakeskin/init/RevInit.kt
912319217
package com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.impl import com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.CheckTranslationPossibleUseCase import com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.LanguageCode import com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.datainterface.SupportedLanguagesAgent import com.kiwiandroiddev.sc2buildassistant.subscribeTestObserver import io.reactivex.Observable import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.MockitoAnnotations /** * Created by matthome on 31/07/17. */ class CheckTranslationPossibleUseCaseImplTest { @Mock lateinit var mockSupportedLanguagesAgent: SupportedLanguagesAgent lateinit var checkTranslationPossibleUseCase: CheckTranslationPossibleUseCase @Before fun setUp() { MockitoAnnotations.initMocks(this) checkTranslationPossibleUseCase = CheckTranslationPossibleUseCaseImpl(mockSupportedLanguagesAgent) } private fun givenSupportedLanguagesAgentThrowsError(error: RuntimeException) { `when`(mockSupportedLanguagesAgent.supportedLanguages()) .thenReturn(Observable.error(error)) } private fun givenSupportedLanguageCodes(vararg languageCodes: LanguageCode) { `when`(mockSupportedLanguagesAgent.supportedLanguages()) .thenReturn(Observable.fromArray(*languageCodes)) } private fun givenNoLanguageCodesAreSupported() { `when`(mockSupportedLanguagesAgent.supportedLanguages()) .thenReturn(Observable.empty()) } @Test fun fromDeToEn_getSupportedLanguagesAgentThrowsError_returnsFalse() { val error = RuntimeException("No network connection!") givenSupportedLanguagesAgentThrowsError(error) checkTranslationPossibleUseCase .canTranslateFromLanguage(fromLanguageCode = "de", toLanguageCode = "en") .subscribeTestObserver() .assertResult(false) } @Test fun fromDeToEn_getSupportedLanguagesAgentReturnsEmptyList_returnsFalse() { givenNoLanguageCodesAreSupported() checkTranslationPossibleUseCase .canTranslateFromLanguage(fromLanguageCode = "de", toLanguageCode = "en") .subscribeTestObserver() .assertResult(false) } @Test fun fromDeToEn_getSupportedLanguagesAgentReturnsEnAndDe_returnsTrue() { givenSupportedLanguageCodes("de", "en") checkTranslationPossibleUseCase .canTranslateFromLanguage(fromLanguageCode = "de", toLanguageCode = "en") .subscribeTestObserver() .assertResult(true) } @Test fun fromEsToRu_getSupportedLanguagesAgentReturnsEnAndDe_returnsFalse() { givenSupportedLanguageCodes("de", "en") checkTranslationPossibleUseCase .canTranslateFromLanguage(fromLanguageCode = "es", toLanguageCode = "ru") .subscribeTestObserver() .assertResult(false) } @Test fun fromEsToRu_getSupportedLanguagesAgentReturnsEnDeEsRu_returnsTrue() { givenSupportedLanguageCodes("en", "de", "es", "ru") checkTranslationPossibleUseCase .canTranslateFromLanguage(fromLanguageCode = "es", toLanguageCode = "ru") .subscribeTestObserver() .assertResult(true) } }
app/src/test/java/com/kiwiandroiddev/sc2buildassistant/feature/translate/domain/impl/CheckTranslationPossibleUseCaseImplTest.kt
1091707335
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * 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.jetbrains.packagesearch.intellij.plugin.util import com.intellij.util.text.VersionComparatorUtil import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion /** * Compares two raw version names, best-effort. If at all possible, you should use the [NormalizedPackageVersion] to compare versions with a lot of * additional heuristics, including prioritizing semantic version names over non-semantic ones. * * This expands on what [VersionComparatorUtil] provide, so you should prefer this to [VersionComparatorUtil.COMPARATOR]. * * @see versionTokenPriorityProvider * @see VersionComparatorUtil */ object VersionNameComparator : Comparator<String> { override fun compare(first: String?, second: String?): Int = VersionComparatorUtil.compare(first, second, ::versionTokenPriorityProvider) }
plugins/package-search/src/intellij/plugin/util/VersionNameComparator.kt
2745005008
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * 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.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models import com.intellij.util.text.VersionComparatorUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.util.versionTokenPriorityProvider import kotlinx.serialization.Serializable import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.packagesearch.api.v2.ApiStandardPackage import org.jetbrains.packagesearch.packageversionutils.PackageVersionUtils @Serializable sealed class PackageVersion : Comparable<PackageVersion> { abstract val versionName: String abstract val isStable: Boolean abstract val releasedAt: Long? @get:Nls abstract val displayName: String override fun compareTo(other: PackageVersion): Int = VersionComparatorUtil.compare(versionName, other.versionName, ::versionTokenPriorityProvider) @Serializable object Missing : PackageVersion() { override val versionName = "" override val isStable = true override val releasedAt: Long? = null @Nls override val displayName = PackageSearchBundle.message("packagesearch.ui.missingVersion") @NonNls override fun toString() = "[Missing version]" } @Serializable data class Named( override val versionName: String, override val isStable: Boolean, override val releasedAt: Long? ) : PackageVersion() { init { require(versionName.isNotBlank()) { "A Named version name cannot be blank." } } @Suppress("HardCodedStringLiteral") @Nls override val displayName = versionName @NonNls override fun toString() = versionName fun semanticVersionComponent(): SemVerComponent? { val groupValues = SEMVER_REGEX.find(versionName)?.groupValues ?: return null if (groupValues.size <= 1) return null val semanticVersion = groupValues[1].takeIf { it.isNotBlank() } ?: return null return SemVerComponent(semanticVersion, this) } data class SemVerComponent(val semanticVersion: String, val named: Named) companion object { private val SEMVER_REGEX = "^((?:\\d+\\.){0,3}\\d+)".toRegex(option = RegexOption.IGNORE_CASE) } } companion object { fun from(rawVersion: ApiStandardPackage.ApiStandardVersion): PackageVersion { if (rawVersion.version.isBlank()) return Missing return Named(versionName = rawVersion.version.trim(), isStable = rawVersion.stable, releasedAt = rawVersion.lastChanged) } fun from(rawVersion: String?): PackageVersion { if (rawVersion.isNullOrBlank()) return Missing return Named(rawVersion.trim(), isStable = PackageVersionUtils.evaluateStability(rawVersion), releasedAt = null) } } }
plugins/package-search/src/intellij/plugin/ui/toolwindow/models/PackageVersion.kt
4128662854
// 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.workspaceModel.storage.impl import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.ReplaceBySourceAsTree.OperationsApplier import it.unimi.dsi.fastutil.Hash import it.unimi.dsi.fastutil.longs.Long2ObjectMap import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap import org.jetbrains.annotations.TestOnly import java.util.* /** * # Replace By Source ~~as tree~~ * * Replace By Source, or RBS for short. * * "As tree" is not a correct fact. It was previously processed as tree, before we committed to multiple parents. * So, this is still a directed graph. * * During the RBS, we collect a set of operations. After the set is collected, we apply them on a target storage. * Theoretically, it's possible to create a dry run, if needed. * Operations are supposed to be isolated and complete. That means that target storage doesn't become in inconsistent state at * any moment of the RBS. * * This RBS implementation doesn't have expected exception and should always succeed. * If this RBS doesn't have sense from the abstract point of view (for example, during the RBS we transfer some entity, * but we can't find a parent for this entity in the target store), we still get into some consistent state. As for the example, * this entity won't be transferred into the target storage. * * * # Implementation details * * The operations are collected in separate data structures: For adding, replacing and removing. * Relabel operation is also known as "Replace". * Add operations should be applied in order, while for other operations the order is not determined. * * During the RBS we maintain a separate state for each of processed entity to avoid processing the same entity twice. * Two separate states are presented: for target and ReplaceWith storages. * * # Debugging * * You can use [OperationsApplier.dumpOperations] for listing the operations on the storage. * * # Future improvements * * - Make type graphs. Separate graphs into independent parts (how is it called correctly?) * - Work on separate graph parts as on independent items */ internal class ReplaceBySourceAsTree : ReplaceBySourceOperation { private lateinit var targetStorage: MutableEntityStorageImpl private lateinit var replaceWithStorage: AbstractEntityStorage private lateinit var entityFilter: (EntitySource) -> Boolean internal val replaceOperations = ArrayList<RelabelElement>() internal val removeOperations = ArrayList<RemoveElement>() internal val addOperations = ArrayList<AddElement>() internal val targetState = Long2ObjectOpenHashMap<ReplaceState>() internal val replaceWithState = Long2ObjectOpenHashMap<ReplaceWithState>() @set:TestOnly internal var shuffleEntities: Long = -1L private val replaceWithProcessingCache = HashMap<Pair<EntityId?, Int>, Pair<DataCache, MutableList<ChildEntityId>>>() override fun replace( targetStorage: MutableEntityStorageImpl, replaceWithStorage: AbstractEntityStorage, entityFilter: (EntitySource) -> Boolean, ) { this.targetStorage = targetStorage this.replaceWithStorage = replaceWithStorage this.entityFilter = entityFilter // Process entities from the target storage val targetEntitiesToReplace = targetStorage.entitiesBySource(entityFilter) val targetEntities = targetEntitiesToReplace.values.flatMap { it.values }.flatten().toMutableList() if (shuffleEntities != -1L && targetEntities.size > 1) { targetEntities.shuffle(Random(shuffleEntities)) } for (targetEntityToReplace in targetEntities) { TargetProcessor().processEntity(targetEntityToReplace) } // Process entities from the replaceWith storage val replaceWithEntitiesToReplace = replaceWithStorage.entitiesBySource(entityFilter) val replaceWithEntities = replaceWithEntitiesToReplace.values.flatMap { it.values }.flatten().toMutableList() if (shuffleEntities != -1L && replaceWithEntities.size > 1) { replaceWithEntities.shuffle(Random(shuffleEntities)) } for (replaceWithEntityToReplace in replaceWithEntities) { ReplaceWithProcessor().processEntity(replaceWithEntityToReplace) } // This method can be used for debugging // OperationsApplier().dumpOperations() // Apply collected operations on the target storage OperationsApplier().apply() } // This class is just a wrapper to combine functions logically private inner class OperationsApplier { fun apply() { val replaceToTarget = HashMap<EntityId, EntityId>() for (addOperation in addOperations) { val parents = addOperation.parents?.mapTo(HashSet()) { when (it) { is ParentsRef.AddedElement -> replaceToTarget.getValue(it.replaceWithEntityId) is ParentsRef.TargetRef -> it.targetEntityId } } addElement(parents, addOperation.replaceWithSource, replaceToTarget) } for (operation in replaceOperations) { val targetEntity = targetStorage.entityDataByIdOrDie(operation.targetEntityId).createEntity(targetStorage) val replaceWithEntity = replaceWithStorage.entityDataByIdOrDie(operation.replaceWithEntityId).createEntity(replaceWithStorage) val parents = operation.parents?.mapTo(HashSet()) { val targetEntityId = when (it) { is ParentsRef.AddedElement -> replaceToTarget.getValue(it.replaceWithEntityId) is ParentsRef.TargetRef -> it.targetEntityId } targetStorage.entityDataByIdOrDie(targetEntityId).createEntity(targetStorage) } targetStorage.modifyEntity(WorkspaceEntity.Builder::class.java, targetEntity) { (this as ModifiableWorkspaceEntityBase<*, *>).relabel(replaceWithEntity, parents) } targetStorage.indexes.updateExternalMappingForEntityId(operation.replaceWithEntityId, operation.targetEntityId, replaceWithStorage.indexes) } for (removeOperation in removeOperations) { targetStorage.removeEntityByEntityId(removeOperation.targetEntityId) } } private fun addElement(parents: Set<EntityId>?, replaceWithDataSource: EntityId, replaceToTarget: HashMap<EntityId, EntityId>) { val targetParents = mutableListOf<WorkspaceEntity>() parents?.forEach { parent -> targetParents += targetStorage.entityDataByIdOrDie(parent).createEntity(targetStorage) } val modifiableEntity = replaceWithStorage.entityDataByIdOrDie(replaceWithDataSource).createDetachedEntity(targetParents) modifiableEntity as ModifiableWorkspaceEntityBase<out WorkspaceEntity, out WorkspaceEntityData<*>> // We actually bind parents in [createDetachedEntity], but we can't do it for external entities (that are defined in a separate module) // Here we bind them again, so I guess we can remove "parents binding" from [createDetachedEntity], but let's do it twice for now. // Actually, I hope to get rid of [createDetachedEntity] at some moment. targetParents.groupBy { it::class }.forEach { (_, ents) -> modifiableEntity.linkExternalEntity(ents.first().getEntityInterface().kotlin, false, ents) } targetStorage.addEntity(modifiableEntity) targetStorage.indexes.updateExternalMappingForEntityId(replaceWithDataSource, modifiableEntity.id, replaceWithStorage.indexes) replaceToTarget[replaceWithDataSource] = modifiableEntity.id } /** * First print the operations, then print the information about entities */ fun dumpOperations(): String { val targetEntities: MutableSet<EntityId> = mutableSetOf() val replaceWithEntities: MutableSet<EntityId> = mutableSetOf() return buildString { appendLine("---- New entities -------") for (addOperation in addOperations) { appendLine(infoOf(addOperation.replaceWithSource, replaceWithStorage, true)) replaceWithEntities += addOperation.replaceWithSource if (addOperation.parents == null) { appendLine("No parent entities") } else { appendLine("Parents:") addOperation.parents.forEach { parent -> when (parent) { is ParentsRef.AddedElement -> { appendLine(" - ${infoOf(parent.replaceWithEntityId, replaceWithStorage, true)} <--- New Added Entity") replaceWithEntities += parent.replaceWithEntityId } is ParentsRef.TargetRef -> { appendLine(" - ${infoOf(parent.targetEntityId, targetStorage, true)} <--- Existing Entity") targetEntities += parent.targetEntityId } } } } appendLine() } appendLine("---- No More New Entities -------") appendLine("---- Removes -------") removeOperations.map { it.targetEntityId }.forEach { entityId -> appendLine(infoOf(entityId, targetStorage, true)) targetEntities += entityId } appendLine("---- No More Removes -------") appendLine() appendLine("---- Replaces -------") replaceOperations.forEach { operation -> appendLine( infoOf(operation.targetEntityId, targetStorage, true) + " -> " + infoOf(operation.replaceWithEntityId, replaceWithStorage, true) + " | " + "Count of parents: ${operation.parents?.size}") targetEntities += operation.targetEntityId replaceWithEntities += operation.replaceWithEntityId } appendLine("---- No More Replaces -------") appendLine() appendLine("---- Entities -------") appendLine() appendLine("---- Target Storage -------") targetEntities.forEach { appendLine(infoOf(it, targetStorage, false)) appendLine() } appendLine() appendLine("---- Replace With Storage -------") replaceWithEntities.forEach { appendLine(infoOf(it, replaceWithStorage, false)) appendLine() } } } private fun infoOf(entityId: EntityId, store: AbstractEntityStorage, short: Boolean): String { val entityData = store.entityDataByIdOrDie(entityId) val entity = entityData.createEntity(store) return if (entity is WorkspaceEntityWithSymbolicId) entity.symbolicId.toString() else if (short) "$entity" else "$entity | $entityData" } } // This class is just a wrapper to combine functions logically private inner class ReplaceWithProcessor { fun processEntity(replaceWithEntity: WorkspaceEntity) { replaceWithEntity as WorkspaceEntityBase if (replaceWithState[replaceWithEntity.id] != null) return val trackToParents = TrackToParents(replaceWithEntity.id) buildRootTrack(trackToParents, replaceWithStorage) processEntity(trackToParents) } private fun processEntity(replaceWithTrack: TrackToParents): ParentsRef? { val replaceWithEntityId = replaceWithTrack.entity val replaceWithEntityState = replaceWithState[replaceWithEntityId] when (replaceWithEntityState) { ReplaceWithState.ElementMoved -> return ParentsRef.AddedElement(replaceWithEntityId) is ReplaceWithState.NoChange -> return ParentsRef.TargetRef(replaceWithEntityState.targetEntityId) ReplaceWithState.NoChangeTraceLost -> return null is ReplaceWithState.Relabel -> return ParentsRef.TargetRef(replaceWithEntityState.targetEntityId) null -> Unit } val replaceWithEntityData = replaceWithStorage.entityDataByIdOrDie(replaceWithEntityId) val replaceWithEntity = replaceWithEntityData.createEntity(replaceWithStorage) as WorkspaceEntityBase if (replaceWithTrack.parents.isEmpty()) { return findAndReplaceRootEntity(replaceWithEntity) } else { if (replaceWithEntity is WorkspaceEntityWithSymbolicId) { val targetEntity = targetStorage.resolve(replaceWithEntity.symbolicId) val parentsAssociation = replaceWithTrack.parents.mapNotNullTo(HashSet()) { processEntity(it) } return processExactEntity(targetEntity, replaceWithEntity, parentsAssociation) } else { val parentsAssociation = replaceWithTrack.parents.mapNotNullTo(HashSet()) { processEntity(it) } if (parentsAssociation.isNotEmpty()) { val targetEntityData = parentsAssociation.filterIsInstance<ParentsRef.TargetRef>().firstNotNullOfOrNull { parent -> findEntityInTargetStore(replaceWithEntityData, parent.targetEntityId, replaceWithEntityId.clazz) } val targetEntity = targetEntityData?.createEntity(targetStorage) as? WorkspaceEntityBase return processExactEntity(targetEntity, replaceWithEntity, parentsAssociation) } else { replaceWithEntityId.addState(ReplaceWithState.NoChangeTraceLost) return null } } } } private fun findAndReplaceRootEntity(replaceWithEntity: WorkspaceEntityBase): ParentsRef? { val replaceWithEntityId = replaceWithEntity.id val currentState = replaceWithState[replaceWithEntityId] // This was just checked before this call assert(currentState == null) val targetEntity = findRootEntityInStorage(replaceWithEntity, targetStorage, replaceWithStorage, targetState) val parents = null return processExactEntity(targetEntity, replaceWithEntity, parents) } private fun processExactEntity(targetEntity: WorkspaceEntity?, replaceWithEntity: WorkspaceEntityBase, parents: Set<ParentsRef>?): ParentsRef? { val replaceWithEntityId = replaceWithEntity.id if (targetEntity == null) { if (entityFilter(replaceWithEntity.entitySource)) { addSubtree(parents, replaceWithEntityId) return ParentsRef.AddedElement(replaceWithEntityId) } else { replaceWithEntityId.addState(ReplaceWithState.NoChangeTraceLost) return null } } else { val targetEntityId = (targetEntity as WorkspaceEntityBase).id val targetCurrentState = targetState[targetEntityId] when (targetCurrentState) { is ReplaceState.NoChange -> return ParentsRef.TargetRef(targetEntityId) is ReplaceState.Relabel -> return ParentsRef.TargetRef(targetEntityId) ReplaceState.Remove -> return null null -> Unit } when { entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> { if (replaceWithEntity.entitySource !is DummyParentEntitySource) { replaceWorkspaceData(targetEntity.id, replaceWithEntity.id, parents) } else { doNothingOn(targetEntityId, replaceWithEntityId) } return ParentsRef.TargetRef(targetEntityId) } entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> { removeWorkspaceData(targetEntity.id, replaceWithEntity.id) return null } !entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> { if (targetEntity is WorkspaceEntityWithSymbolicId) { if (replaceWithEntity.entitySource !is DummyParentEntitySource) { replaceWorkspaceData(targetEntityId, replaceWithEntityId, parents) } else { doNothingOn(targetEntityId, replaceWithEntityId) } return ParentsRef.TargetRef(targetEntityId) } else { addSubtree(parents, replaceWithEntityId) return ParentsRef.AddedElement(replaceWithEntityId) } } !entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> { doNothingOn(targetEntity.id, replaceWithEntityId) return ParentsRef.TargetRef(targetEntityId) } else -> error("Unexpected branch") } } } private fun findAndReplaceRootEntityInTargetStore(replaceWithRootEntity: WorkspaceEntityBase): ParentsRef? { val replaceRootEntityId = replaceWithRootEntity.id val replaceWithCurrentState = replaceWithState[replaceRootEntityId] when (replaceWithCurrentState) { is ReplaceWithState.NoChange -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId) ReplaceWithState.NoChangeTraceLost -> return null is ReplaceWithState.Relabel -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId) ReplaceWithState.ElementMoved -> TODO() null -> Unit } val targetEntity = findRootEntityInStorage(replaceWithRootEntity, targetStorage, replaceWithStorage, targetState) return processExactEntity(targetEntity, replaceWithRootEntity, null) } /** * This is a very similar thing as [findSameEntity]. But it finds an entity in the target storage (or the entity that will be added) */ fun findSameEntityInTargetStore(replaceWithTrack: TrackToParents): ParentsRef? { // Check if this entity was already processed val replaceWithCurrentState = replaceWithState[replaceWithTrack.entity] when (replaceWithCurrentState) { is ReplaceWithState.NoChange -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId) ReplaceWithState.NoChangeTraceLost -> return null is ReplaceWithState.Relabel -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId) ReplaceWithState.ElementMoved -> return ParentsRef.AddedElement(replaceWithTrack.entity) null -> Unit } val replaceWithEntityData = replaceWithStorage.entityDataByIdOrDie(replaceWithTrack.entity) if (replaceWithTrack.parents.isEmpty()) { val targetRootEntityId = findAndReplaceRootEntityInTargetStore( replaceWithEntityData.createEntity(replaceWithStorage) as WorkspaceEntityBase) return targetRootEntityId } else { val parentsAssociation = replaceWithTrack.parents.associateWith { findSameEntityInTargetStore(it) } val entriesList = parentsAssociation.entries.toList() val targetParents = mutableSetOf<EntityId>() var targetEntityData: WorkspaceEntityData<out WorkspaceEntity>? = null for (i in entriesList.indices) { val value = entriesList[i].value if (value is ParentsRef.TargetRef) { targetEntityData = findEntityInTargetStore(replaceWithEntityData, value.targetEntityId, replaceWithTrack.entity.clazz) if (targetEntityData != null) { targetParents += entriesList[i].key.entity break } } } if (targetEntityData == null) { for (entry in entriesList) { val value = entry.value if (value is ParentsRef.AddedElement) { return ParentsRef.AddedElement(replaceWithTrack.entity) } } } return targetEntityData?.createEntityId()?.let { ParentsRef.TargetRef(it) } } } private fun addSubtree(parents: Set<ParentsRef>?, replaceWithEntityId: EntityId) { val currentState = replaceWithState[replaceWithEntityId] when (currentState) { ReplaceWithState.ElementMoved -> return is ReplaceWithState.NoChange -> error("Unexpected state") ReplaceWithState.NoChangeTraceLost -> error("Unexpected state") is ReplaceWithState.Relabel -> error("Unexpected state") null -> Unit } addElementOperation(parents, replaceWithEntityId) replaceWithStorage.refs.getChildrenRefsOfParentBy(replaceWithEntityId.asParent()).values.flatten().forEach { val replaceWithChildEntityData = replaceWithStorage.entityDataByIdOrDie(it.id) if (!entityFilter(replaceWithChildEntityData.entitySource)) return@forEach val trackToParents = TrackToParents(it.id) buildRootTrack(trackToParents, replaceWithStorage) val sameEntity = findSameEntityInTargetStore(trackToParents) if (sameEntity is ParentsRef.TargetRef) { return@forEach } val otherParents = trackToParents.parents.mapNotNull { findSameEntityInTargetStore(it) } addSubtree((otherParents + ParentsRef.AddedElement(replaceWithEntityId)).toSet(), it.id) } } } // This class is just a wrapper to combine functions logically private inner class TargetProcessor { fun processEntity(targetEntityToReplace: WorkspaceEntity) { targetEntityToReplace as WorkspaceEntityBase val trackToParents = TrackToParents(targetEntityToReplace.id) buildRootTrack(trackToParents, targetStorage) // This method not only finds the same entity in the ReplaceWith storage, but also processes all entities it meets. // So, for processing an entity, it's enough to call this methos on the entity. findSameEntity(trackToParents) } /** * This method searched for the "associated" entity of [targetEntityTrack] in the repalceWith storage * Here, let's use "associated" termin to define what we're looking for. If the entity have a [SymbolicEntityId], * this is super simple. "associated" entity is just an entity from the different storage with the same SymbolicId. * * Things go complicated if there is no SymbolicId. In this case we build a track to the root entities in the graph, trying * to find same roots in the replaceWith storage and building a "track" to the entity in the replaceWith storage. This * traced entity is an "associated" entity for our current entity. * * This is a recursive algorithm * - Get all parents of the entity * - if there are NO parents: * - Try to find associated entity in replaceWith storage (by SymbolicId in most cases) * - if there are parents: * - Run this algorithm on all parents to find associated parents in the replaceWith storage * - Based on found parents in replaceWith storage, find an associated entity for our currenly searched entity */ private fun findSameEntity(targetEntityTrack: TrackToParents): EntityId? { // Check if this entity was already processed val targetEntityState = targetState[targetEntityTrack.entity] if (targetEntityState != null) { when (targetEntityState) { is ReplaceState.NoChange -> return targetEntityState.replaceWithEntityId is ReplaceState.Relabel -> return targetEntityState.replaceWithEntityId ReplaceState.Remove -> return null } } val targetEntityData = targetStorage.entityDataByIdOrDie(targetEntityTrack.entity) if (targetEntityTrack.parents.isEmpty()) { // If the entity doesn't have parents, it's a root entity for this subtree (subgraph?) return findAndReplaceRootEntity(targetEntityData) } else { val (targetParents, replaceWithEntity) = processParentsFromReplaceWithStorage(targetEntityTrack, targetEntityData) return processExactEntity(targetParents, targetEntityData, replaceWithEntity) } } private fun processExactEntity(targetParents: MutableSet<ParentsRef>?, targetEntityData: WorkspaceEntityData<out WorkspaceEntity>, replaceWithEntity: WorkspaceEntityBase?): EntityId? { // Here we check if any of the required parents is missing the our new parents val requiredParentMissing = if (targetParents != null) { val targetParentClazzes = targetParents.map { when (it) { is ParentsRef.AddedElement -> it.replaceWithEntityId.clazz is ParentsRef.TargetRef -> it.targetEntityId.clazz } } targetEntityData.getRequiredParents().any { it.toClassId() !in targetParentClazzes } } else false val targetEntity = targetEntityData.createEntity(targetStorage) as WorkspaceEntityBase if (replaceWithEntity == null || requiredParentMissing) { // Here we don't have an associated entity in the replaceWith storage. Decide if we remove our entity or just keep it when (entityFilter(targetEntity.entitySource)) { true -> { removeWorkspaceData(targetEntity.id, null) return null } false -> { doNothingOn(targetEntity.id, null) return null } } } else { when { entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> { if (replaceWithEntity.entitySource !is DummyParentEntitySource) { replaceWorkspaceData(targetEntity.id, replaceWithEntity.id, targetParents) } else { doNothingOn(targetEntity.id, replaceWithEntity.id) } return replaceWithEntity.id } entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> { removeWorkspaceData(targetEntity.id, replaceWithEntity.id) return null } !entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> { if (replaceWithEntity.entitySource !is DummyParentEntitySource) { replaceWorkspaceData(targetEntity.id, replaceWithEntity.id, targetParents) } else { doNothingOn(targetEntity.id, replaceWithEntity.id) } return replaceWithEntity.id } !entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> { doNothingOn(targetEntity.id, replaceWithEntity.id) return replaceWithEntity.id } else -> error("Unexpected branch") } } } /** * An interesting logic here. We've found associated parents for the target entity. * Now, among these parents we have to find a child, that will be similar to "our" entity in target storage. * * In addition, we're currently missing "new" parents in the replaceWith storage. * So, the return type is a set of parents (existing and new) and an "associated" entity in the replaceWith storage. */ private fun processParentsFromReplaceWithStorage( targetEntityTrack: TrackToParents, targetEntityData: WorkspaceEntityData<out WorkspaceEntity> ): Pair<MutableSet<ParentsRef>, WorkspaceEntityBase?> { // Our future set of parents val targetParents = mutableSetOf<ParentsRef>() val targetEntity = targetEntityData.createEntity(targetStorage) var replaceWithEntity: WorkspaceEntityBase? = null if (targetEntity is WorkspaceEntityWithSymbolicId) { replaceWithEntity = replaceWithStorage.resolve(targetEntity.symbolicId) as? WorkspaceEntityBase } else { // Here we're just traversing parents. If we find a parent that does have a child entity that is equal to our entity, stop and save // this "equaled" entity as our "associated" entity. // After that we're checking that other parents does have this child among their children. If not, we do not register this parent as // "new" parent for our entity. // // Another approach would be finding the "most common" child among of all parents. But currently we use this approach // because I think that it's "good enough" and the "most common child" may be not what we're looking for. // So, here we search for the first equal entity val parentsAssociation = targetEntityTrack.parents.associateWith { findSameEntity(it) } val entriesList = parentsAssociation.entries.toList() var index = 0 for (i in entriesList.indices) { index = i val (caching, replaceWithEntityIds) = replaceWithProcessingCache.getOrPut(entriesList[i].value to targetEntityTrack.entity.clazz) { val ids = LinkedList(childrenInReplaceWith(entriesList[i].value, targetEntityTrack.entity.clazz)) DataCache(ids.size, EntityDataStrategy()) to ids } replaceWithEntity = replaceWithEntityIds.removeSomeWithCaching(targetEntityData, caching, replaceWithStorage) ?.createEntity(replaceWithStorage) as? WorkspaceEntityBase if (replaceWithEntity != null) { assert(replaceWithState[replaceWithEntity.id] == null) targetParents += ParentsRef.TargetRef(entriesList[i].key.entity) break } } // Here we know our "associated" entity, so we just check what parents remain with it. entriesList.drop(index + 1).forEach { tailItem -> // Should we use cache as in above? val replaceWithEntityIds = childrenInReplaceWith(tailItem.value, targetEntityTrack.entity.clazz).toMutableList() val caching = DataCache(replaceWithEntityIds.size, EntityDataStrategy()) var replaceWithMyEntityData = replaceWithEntityIds.removeSomeWithCaching(targetEntityData, caching, replaceWithStorage) while (replaceWithMyEntityData != null && replaceWithEntity!!.id != replaceWithMyEntityData.createEntityId()) { replaceWithMyEntityData = replaceWithEntityIds.removeSomeWithCaching(targetEntityData, caching, replaceWithStorage) } if (replaceWithMyEntityData != null) { targetParents += ParentsRef.TargetRef(tailItem.key.entity) } } } // And here we get other parent' of the associated entity. // This is actually a complicated operation because it's not enough just to find parents in replaceWith storage. // We should also understand if this parent is a new entity or it already exists in the target storage. if (replaceWithEntity != null) { val replaceWithTrackToParents = TrackToParents(replaceWithEntity.id) buildRootTrack(replaceWithTrackToParents, replaceWithStorage) val alsoTargetParents = replaceWithTrackToParents.parents.map { ReplaceWithProcessor().findSameEntityInTargetStore(it) } targetParents.addAll(alsoTargetParents.filterNotNull()) } return Pair(targetParents, replaceWithEntity) } /** * Process root entity of the storage */ fun findAndReplaceRootEntity(targetEntityData: WorkspaceEntityData<out WorkspaceEntity>): EntityId? { val targetRootEntityId = targetEntityData.createEntityId() val currentTargetState = targetState[targetRootEntityId] assert(currentTargetState == null) { "This state was already checked before this function" } val replaceWithEntity = findRootEntityInStorage(targetEntityData.createEntity(targetStorage) as WorkspaceEntityBase, replaceWithStorage, targetStorage, replaceWithState) as? WorkspaceEntityBase return processExactEntity(null, targetEntityData, replaceWithEntity) } } private class EntityDataStrategy : Hash.Strategy<WorkspaceEntityData<out WorkspaceEntity>> { override fun equals(a: WorkspaceEntityData<out WorkspaceEntity>?, b: WorkspaceEntityData<out WorkspaceEntity>?): Boolean { if (a == null || b == null) { return false } return a.equalsByKey(b) } override fun hashCode(o: WorkspaceEntityData<out WorkspaceEntity>?): Int { return o?.hashCodeByKey() ?: 0 } } private fun MutableList<ChildEntityId>.removeSomeWithCaching(key: WorkspaceEntityData<out WorkspaceEntity>, cache: Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>>, storage: AbstractEntityStorage): WorkspaceEntityData<out WorkspaceEntity>? { val foundInCache = cache.removeSome(key) if (foundInCache != null) return foundInCache val thisIterator = this.iterator() while (thisIterator.hasNext()) { val id = thisIterator.next() val value = storage.entityDataByIdOrDie(id.id) if (value.equalsByKey(key)) { thisIterator.remove() return value } thisIterator.remove() addValueToMap(cache, value) } return null } private fun <K, V> Object2ObjectOpenCustomHashMap<K, List<V>>.removeSome(key: K): V? { val existingValue = this[key] ?: return null return if (existingValue.size == 1) { this.remove(key) existingValue.single() } else { val firstElement = existingValue[0] this[key] = existingValue.drop(1) firstElement } } private fun addElementOperation(targetParentEntity: Set<ParentsRef>?, replaceWithEntity: EntityId) { addOperations += AddElement(targetParentEntity, replaceWithEntity) replaceWithEntity.addState(ReplaceWithState.ElementMoved) } private fun replaceWorkspaceData(targetEntityId: EntityId, replaceWithEntityId: EntityId, parents: Set<ParentsRef>?) { replaceOperations.add(RelabelElement(targetEntityId, replaceWithEntityId, parents)) targetEntityId.addState(ReplaceState.Relabel(replaceWithEntityId, parents)) replaceWithEntityId.addState(ReplaceWithState.Relabel(targetEntityId)) } private fun removeWorkspaceData(targetEntityId: EntityId, replaceWithEntityId: EntityId?) { removeOperations.add(RemoveElement(targetEntityId)) targetEntityId.addState(ReplaceState.Remove) replaceWithEntityId?.addState(ReplaceWithState.NoChangeTraceLost) } private fun doNothingOn(targetEntityId: EntityId, replaceWithEntityId: EntityId?) { targetEntityId.addState(ReplaceState.NoChange(replaceWithEntityId)) replaceWithEntityId?.addState(ReplaceWithState.NoChange(targetEntityId)) } private fun EntityId.addState(state: ReplaceState) { val currentState = targetState[this] require(currentState == null) { "Unexpected existing state for $this: $currentState" } targetState[this] = state } private fun EntityId.addState(state: ReplaceWithState) { val currentState = replaceWithState[this] require(currentState == null) replaceWithState[this] = state } private fun findEntityInTargetStore(replaceWithEntityData: WorkspaceEntityData<out WorkspaceEntity>, targetParentEntityId: EntityId, childClazz: Int): WorkspaceEntityData<out WorkspaceEntity>? { var targetEntityData1: WorkspaceEntityData<out WorkspaceEntity>? val targetEntityIds = childrenInTarget(targetParentEntityId, childClazz) val targetChildrenMap = makeEntityDataCollection(targetEntityIds, targetStorage) targetEntityData1 = targetChildrenMap.removeSome(replaceWithEntityData) while (targetEntityData1 != null && replaceWithState[targetEntityData1.createEntityId()] != null) { targetEntityData1 = targetChildrenMap.removeSome(replaceWithEntityData) } return targetEntityData1 } private fun makeEntityDataCollection(targetChildEntityIds: List<ChildEntityId>, storage: AbstractEntityStorage): Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>> { val targetChildrenMap = Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>>( targetChildEntityIds.size, EntityDataStrategy()) targetChildEntityIds.forEach { id -> val value = storage.entityDataByIdOrDie(id.id) addValueToMap(targetChildrenMap, value) } return targetChildrenMap } private fun addValueToMap(targetChildrenMap: Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>>, value: WorkspaceEntityData<out WorkspaceEntity>) { val existingValue = targetChildrenMap[value] targetChildrenMap[value] = if (existingValue != null) existingValue + value else listOf(value) } private val targetChildrenCache = HashMap<EntityId, Map<ConnectionId, List<ChildEntityId>>>() private val replaceWithChildrenCache = HashMap<EntityId, Map<ConnectionId, List<ChildEntityId>>>() private fun childrenInReplaceWith(entityId: EntityId?, childClazz: Int): List<ChildEntityId> { return childrenInStorage(entityId, childClazz, replaceWithStorage, replaceWithChildrenCache) } private fun childrenInTarget(entityId: EntityId?, childClazz: Int): List<ChildEntityId> { return childrenInStorage(entityId, childClazz, targetStorage, targetChildrenCache) } companion object { /** * Build track from this entity to it's parents. There is no return value, we modify [track] variable. */ private fun buildRootTrack(track: TrackToParents, storage: AbstractEntityStorage) { val parents = storage.refs.getParentRefsOfChild(track.entity.asChild()) parents.values.forEach { parentEntityId -> val parentTrack = TrackToParents(parentEntityId.id) buildRootTrack(parentTrack, storage) track.parents += parentTrack parentTrack.child = track } } private fun childrenInStorage(entityId: EntityId?, childrenClass: Int, storage: AbstractEntityStorage, childrenCache: HashMap<EntityId, Map<ConnectionId, List<ChildEntityId>>>): List<ChildEntityId> { val targetEntityIds = if (entityId != null) { val targetChildren = childrenCache.getOrPut(entityId) { storage.refs.getChildrenRefsOfParentBy(entityId.asParent()) } val targetFoundChildren = targetChildren.filterKeys { sameClass(it.childClass, childrenClass, it.connectionType) } require(targetFoundChildren.size < 2) { "Got unexpected amount of children" } if (targetFoundChildren.isEmpty()) { emptyList() } else { val (_, targetChildEntityIds) = targetFoundChildren.entries.single() targetChildEntityIds } } else { emptyList() } return targetEntityIds } /** * Search entity from [oppositeStorage] in [goalStorage] */ private fun findRootEntityInStorage(rootEntity: WorkspaceEntityBase, goalStorage: AbstractEntityStorage, oppositeStorage: AbstractEntityStorage, goalState: Long2ObjectMap<out Any>): WorkspaceEntity? { return if (rootEntity is WorkspaceEntityWithSymbolicId) { val symbolicId = rootEntity.symbolicId goalStorage.resolve(symbolicId) } else { val oppositeEntityData = oppositeStorage.entityDataByIdOrDie(rootEntity.id) goalStorage.entities(rootEntity.id.clazz.findWorkspaceEntity()) .filter { val itId = (it as WorkspaceEntityBase).id if (goalState[itId] != null) return@filter false goalStorage.entityDataByIdOrDie(itId).equalsByKey(oppositeEntityData) && goalStorage.refs.getParentRefsOfChild(itId.asChild()) .isEmpty() } .firstOrNull() } } } } typealias DataCache = Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>> internal data class RelabelElement(val targetEntityId: EntityId, val replaceWithEntityId: EntityId, val parents: Set<ParentsRef>?) internal data class RemoveElement(val targetEntityId: EntityId) internal data class AddElement(val parents: Set<ParentsRef>?, val replaceWithSource: EntityId) internal sealed interface ReplaceState { data class Relabel(val replaceWithEntityId: EntityId, val parents: Set<ParentsRef>? = null) : ReplaceState data class NoChange(val replaceWithEntityId: EntityId?) : ReplaceState object Remove : ReplaceState } internal sealed interface ReplaceWithState { object ElementMoved : ReplaceWithState data class NoChange(val targetEntityId: EntityId) : ReplaceWithState data class Relabel(val targetEntityId: EntityId) : ReplaceWithState object NoChangeTraceLost : ReplaceWithState } sealed interface ParentsRef { data class TargetRef(val targetEntityId: EntityId) : ParentsRef data class AddedElement(val replaceWithEntityId: EntityId) : ParentsRef } class TrackToParents( val entity: EntityId, var child: TrackToParents? = null, val parents: MutableList<TrackToParents> = ArrayList(), )
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/ReplaceBySourceAsTree.kt
4239180591
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.actions.OptimizeImportsProcessor import com.intellij.codeInspection.LocalQuickFixOnPsiElement import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.psi.KtFile /** * Simple quickfix for running import optimizer on Kotlin file. */ class KotlinOptimizeImportsQuickFix(file: KtFile) : LocalQuickFixOnPsiElement(file) { override fun getText() = KotlinBundle.message("optimize.imports") override fun getFamilyName() = name override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) { OptimizeImportsProcessor(project, file).run() } }
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/inspections/KotlinOptimizeImportsQuickFix.kt
1127841644
// 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.gradle.frameworkSupport.buildscript import org.gradle.util.GradleVersion import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptElement.Statement.Expression.BlockElement import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptElementBuilder import org.jetbrains.plugins.gradle.frameworkSupport.script.ScriptTreeBuilder import java.util.function.Consumer interface GradleBuildScriptBuilderCore<out BSB : GradleBuildScriptBuilderCore<BSB>> : ScriptElementBuilder { val gradleVersion: GradleVersion /** * ... * import [import] * buildscript { ... } * ... * repositories { ... } * dependencies { ... } * ... */ fun addImport(import: String): BSB /** * buildscript { * ... * [prefix] * repositories { ... } * dependencies { ... } * ... * } */ fun addBuildScriptPrefix(vararg prefix: String): BSB fun withBuildScriptPrefix(configure: ScriptTreeBuilder.() -> Unit): BSB fun withBuildScriptPrefix(configure: Consumer<ScriptTreeBuilder>): BSB /** * buildscript { * dependencies { * ... * [dependency] * } * } */ fun addBuildScriptDependency(dependency: String): BSB fun withBuildScriptDependency(configure: ScriptTreeBuilder.() -> Unit): BSB fun withBuildScriptDependency(configure: Consumer<ScriptTreeBuilder>): BSB /** * buildscript { * repositories { * ... * [repository] * } * } */ fun addBuildScriptRepository(repository: String): BSB fun withBuildScriptRepository(configure: ScriptTreeBuilder.() -> Unit): BSB fun withBuildScriptRepository(configure: Consumer<ScriptTreeBuilder>): BSB /** * buildscript { * ... * repositories { ... } * dependencies { ... } * ... * [postfix] * } */ fun addBuildScriptPostfix(vararg postfix: String): BSB fun withBuildScriptPostfix(configure: ScriptTreeBuilder.() -> Unit): BSB fun withBuildScriptPostfix(configure: Consumer<ScriptTreeBuilder>): BSB /** * plugins { * ... * [plugin] * } */ fun addPlugin(plugin: String): BSB fun withPlugin(configure: ScriptTreeBuilder.() -> Unit): BSB /** * buildscript { ... } * ... * [prefix] * repositories { ... } * dependencies { ... } * ... */ fun addPrefix(vararg prefix: String): BSB fun withPrefix(configure: ScriptTreeBuilder.() -> Unit): BSB fun withPrefix(configure: Consumer<ScriptTreeBuilder>): BSB /** * dependencies { * ... * [dependency] * } */ fun addDependency(dependency: String): BSB fun withDependency(configure: ScriptTreeBuilder.() -> Unit): BSB fun withDependency(configure: Consumer<ScriptTreeBuilder>): BSB /** * repositories { * ... * [repository] * } */ fun addRepository(repository: String): BSB fun withRepository(configure: ScriptTreeBuilder.() -> Unit): BSB fun withRepository(configure: Consumer<ScriptTreeBuilder>): BSB /** * buildscript { ... } * ... * repositories { ... } * dependencies { ... } * ... * [postfix] */ fun addPostfix(vararg postfix: String): BSB fun withPostfix(configure: ScriptTreeBuilder.() -> Unit): BSB fun withPostfix(configure: Consumer<ScriptTreeBuilder>): BSB /** * @return content for build.gradle */ fun generate(): String /** * @return partial AST for build.gradle */ fun generateTree(): BlockElement }
plugins/gradle/src/org/jetbrains/plugins/gradle/frameworkSupport/buildscript/GradleBuildScriptBuilderCore.kt
3359908240
package com.onyx.request.pojo import com.onyx.buffer.BufferStreamable /** * Created by timothy.osborn on 4/13/15. * * POJO for query result */ class QueryResultResponseBody constructor() : BufferStreamable { @Suppress("MemberVisibilityCanPrivate") var maxResults: Int = 0 var results: MutableList<Any> = ArrayList() constructor(maxResults: Int, results: MutableList<Any>):this() { this.maxResults = maxResults this.results = results } }
onyx-web-database/src/main/kotlin/com/onyx/request/pojo/QueryResultResponseBody.kt
4051330648
package org.kethereum.erc831 import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class TheERC831ExtensionFun { @Test fun canDetectEthereumURL() { assertThat("ethereum:0x00AB42".isEthereumURLString()).isTrue() } @Test fun canRejectNonEtherumURL() { assertThat("other:0x00AB42".isEthereumURLString()).isFalse() } }
erc831/src/test/kotlin/org/kethereum/erc831/TheERC831ExtensionFun.kt
1175584620
// Copyright (c) 2016, Miquel Martí <[email protected]> // See LICENSE for licensing information package cat.mvmike.minimalcalendarwidget.domain import android.appwidget.AppWidgetManager import android.content.Context import android.content.res.Configuration.ORIENTATION_LANDSCAPE import android.os.Bundle private const val DEFAULT_MONTH_HEADER_LABEL_LENGTH = Int.MAX_VALUE private const val DEFAULT_DAY_HEADER_LABEL_LENGTH = 3 private const val DEFAULT_HEADER_TEXT_RELATIVE_SIZE = 1f private const val DEFAULT_DAY_CELL_TEXT_RELATIVE_SIZE = 1f data class Format( val width: Int ) { private val monthHeaderLabelLength: Int = when { width >= 180 -> DEFAULT_MONTH_HEADER_LABEL_LENGTH else -> 3 } private val dayHeaderLabelLength: Int = when { width >= 180 -> DEFAULT_DAY_HEADER_LABEL_LENGTH else -> 1 } val headerTextRelativeSize: Float = when { width >= 220 -> DEFAULT_HEADER_TEXT_RELATIVE_SIZE width >= 200 -> 0.9f else -> 0.8f } val dayCellTextRelativeSize: Float = when { width >= 260 -> 1.2f width >= 240 -> 1.1f width >= 220 -> DEFAULT_DAY_CELL_TEXT_RELATIVE_SIZE width >= 200 -> 0.9f else -> 0.8f } fun getMonthHeaderLabel(value: String) = value.take(monthHeaderLabelLength) fun getDayHeaderLabel(value: String) = value.take(dayHeaderLabelLength) } fun getFormat(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) = runCatching { appWidgetManager.getAppWidgetOptions(appWidgetId) .getWidth(context) ?.let { Format(it) } }.getOrNull() private fun Bundle.getWidth(context: Context) = when (context.resources.configuration.orientation) { ORIENTATION_LANDSCAPE -> getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT) else -> getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH) }.takeIf { it > 0 }
app/src/main/kotlin/cat/mvmike/minimalcalendarwidget/domain/Format.kt
1254391511
/* * EpochDateTypeAdapter.kt * * This file is part of FareBot. * Learn more at: https://codebutler.github.io/farebot/ * * Copyright (C) 2017 Eric Butler <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.farebot.app.core.serialize.gson import com.google.gson.TypeAdapter import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import java.util.Date class EpochDateTypeAdapter : TypeAdapter<Date>() { override fun write(out: JsonWriter, value: Date) { out.value(value.time) } override fun read(`in`: JsonReader): Date { return Date(`in`.nextLong()) } }
farebot-app/src/main/java/com/codebutler/farebot/app/core/serialize/gson/EpochDateTypeAdapter.kt
3136218891
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.kayenta.pipeline import com.netflix.spinnaker.orca.CancellableStage import com.netflix.spinnaker.orca.ext.withTask import com.netflix.spinnaker.orca.kayenta.KayentaService import com.netflix.spinnaker.orca.kayenta.tasks.MonitorKayentaCanaryTask import com.netflix.spinnaker.orca.kayenta.tasks.RunKayentaCanaryTask import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilder import com.netflix.spinnaker.orca.pipeline.TaskNode import com.netflix.spinnaker.orca.pipeline.model.Stage import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import java.lang.String.format import java.util.Collections.emptyMap @Component class RunCanaryPipelineStage( private val kayentaService: KayentaService ) : StageDefinitionBuilder, CancellableStage { private val log = LoggerFactory.getLogger(javaClass) override fun taskGraph(stage: Stage, builder: TaskNode.Builder) { builder .withTask<RunKayentaCanaryTask>("runCanary") .withTask<MonitorKayentaCanaryTask>("monitorCanary") } override fun getType(): String { return STAGE_TYPE } override fun cancel(stage: Stage): CancellableStage.Result { val context = stage.context val canaryPipelineExecutionId = context["canaryPipelineExecutionId"] as String? if (canaryPipelineExecutionId != null) { log.info(format("Cancelling stage (stageId: %s: executionId: %s, canaryPipelineExecutionId: %s, context: %s)", stage.id, stage.execution.id, canaryPipelineExecutionId, stage.context)) try { kayentaService.cancelPipelineExecution(canaryPipelineExecutionId, "") } catch (e: Exception) { log.error(format("Failed to cancel stage (stageId: %s, executionId: %s), e: %s", stage.id, stage.execution.id, e.message), e) } } else { log.info(format("Not cancelling stage (stageId: %s: executionId: %s, context: %s) since no canary pipeline execution id exists", stage.id, stage.execution.id, stage.context)) } return CancellableStage.Result(stage, emptyMap<Any, Any>()) } companion object { @JvmStatic val STAGE_TYPE = "runCanary" } }
orca-kayenta/src/main/kotlin/com/netflix/spinnaker/orca/kayenta/pipeline/RunCanaryPipelineStage.kt
2564784930
package com.airbnb.lottie.samples.api import com.airbnb.lottie.samples.model.AnimationResponse import com.airbnb.lottie.samples.model.AnimationResponseV2 import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface LottiefilesApi { @GET("v1/recent") suspend fun getRecent(@Query("page") page: Int): AnimationResponse @GET("v1/popular") suspend fun getPopular(@Query("page") page: Int): AnimationResponse @GET("v2/featured") suspend fun getCollection(): AnimationResponseV2 @GET("v1/search/{query}") suspend fun search(@Path("query") query: String, @Query("page") page: Int): AnimationResponse }
sample/src/main/kotlin/com/airbnb/lottie/samples/api/LottiefilesApi.kt
3155466845
package org.fountainmc.api.entity.data.hanging import org.fountainmc.api.entity.data.EntityData /** * A painting's data. */ interface PaintingData : HangingEntityData { /** * Get the width of the painting in blocks. * @return the width of the painting */ val width: Int /** * Get the height of the painting in blocks. * @return the height of the painting */ val height: Int /** * Copy all of the mutable properties from the given data into this object. * * The [width] and [height] won't be copied, * as it can't be sensibly modified for existing paintings. */ override fun copyDataFrom(data: EntityData) { super.copyDataFrom(data) } }
src/main/kotlin/org/fountainmc/api/entity/data/hanging/PaintingData.kt
512364294
// Kotlin - 1.1.4 fun multiply(x: Double, y: Double): Double { return x * y }
Codewars/8kyu/multiply/Kotlin/solution1.kt
251025138
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package stb.templates import org.lwjgl.generator.* import stb.* val stb_rect_pack = "STBRectPack".nativeClass(Module.STB, prefix = "STBRP", prefixMethod = "stbrp_") { includeSTBAPI( """#define STBRP_ASSERT #define STB_RECT_PACK_IMPLEMENTATION #include "stb_rect_pack.h"""") documentation = """ Native bindings to stb_rect_pack.h from the ${url("https://github.com/nothings/stb", "stb library")}. Useful for e.g. packing rectangular textures into an atlas. Does not do rotation. This library currently uses the Skyline Bottom-Left algorithm. Not necessarily the awesomest packing method, but better than the totally naive one in stb_truetype (which is primarily what this is meant to replace). """ IntConstant( "Mostly for internal use, but this is the maximum supported coordinate value.", "_MAXVAL"..0x7fffffff ) EnumConstant( "Packing heuristics", "HEURISTIC_Skyline_default".enum, "HEURISTIC_Skyline_BL_sortHeight".."STBRP_HEURISTIC_Skyline_default", "HEURISTIC_Skyline_BF_sortHeight".enum ) int( "pack_rects", """ Assigns packed locations to rectangles. The rectangles are of type ##STBRPRect, stored in the array {@code rects}, and there are {@code num_rects} many of them. Rectangles which are successfully packed have the {@code was_packed} flag set to a non-zero value and {@code x} and {@code y} store the minimum location on each axis (i.e. bottom-left in cartesian coordinates, top-left if you imagine y increasing downwards). Rectangles which do not fit have the {@code was_packed} flag set to 0. You should not try to access the {@code rects} array from another thread while this function is running, as the function temporarily reorders the array while it executes. To pack into another rectangle, you need to call #init_target() again. To continue packing into the same rectangle, you can call this function again. Calling this multiple times with multiple rect arrays will probably produce worse packing results than calling it a single time with the full rectangle array, but the option is available. """, stbrp_context.p("context", "an ##STBRPContext struct"), stbrp_rect.p("rects", "an array of ##STBRPRect structs"), AutoSize("rects")..int("num_rects", "the number of structs in {@code rects}"), returnDoc = "1 if all of the rectangles were successfully packed and 0 otherwise" ) void( "init_target", """ Initialize a rectangle packer to: pack a rectangle that is {@code width} by {@code height} in dimensions using temporary storage provided by the array {@code nodes}, which is {@code num_nodes} long. You must call this function every time you start packing into a new target. There is no "shutdown" function. The {@code nodes} memory must stay valid for the following #pack_rects() call (or calls), but can be freed after the call (or calls) finish. Note: to guarantee best results, either: ${ol( "make sure {@code num_nodes &ge; width}", "or, call #setup_allow_out_of_mem() with {@code allow_out_of_mem = 1}" )} If you don't do either of the above things, widths will be quantized to multiples of small integers to guarantee the algorithm doesn't run out of temporary storage. If you do \#2, then the non-quantized algorithm will be used, but the algorithm may run out of temporary storage and be unable to pack some rectangles. """, stbrp_context.p("context", "an ##STBRPContext struct"), int("width", "the rectangle width"), int("height", "the rectangle height"), stbrp_node.p("nodes", "an array of ##STBRPNode structs"), AutoSize("nodes")..int("num_nodes", "the number of structs in {@code nodes}") ) void( "setup_allow_out_of_mem", """ Optionally call this function after init but before doing any packing to change the handling of the out-of-temp-memory scenario, described in #init_target(). If you call init again, this will be reset to the default (false). """, stbrp_context.p("context", "an ##STBRPContext struct"), intb("allow_out_of_mem", "1 to allow running out of temporary storage") ) void( "setup_heuristic", """ Optionally select which packing heuristic the library should use. Different heuristics will produce better/worse results for different data sets. If you call init again, this will be reset to the default. """, stbrp_context.p("context", "an ##STBRPContext struct"), int("heuristic", "the packing heuristic") ) }
modules/lwjgl/stb/src/templates/kotlin/stb/templates/stb_rect_pack.kt
2565670582
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengles.templates import org.lwjgl.generator.* import opengles.* val OES_texture_border_clamp = "OESTextureBorderClamp".nativeClassGLES("OES_texture_border_clamp", postfix = OES) { documentation = """ Native bindings to the $registryLink extension. OpenGL ES provides only a single clamping wrap mode: CLAMP_TO_EDGE. However, the ability to clamp to a constant border color can be useful to quickly detect texture coordinates that exceed their expected limits or to dummy out any such accesses with transparency or a neutral color in tiling or light maps. This extension defines an additional texture clamping algorithm. CLAMP_TO_BORDER_OES clamps texture coordinates at all mipmap levels such that NEAREST and LINEAR filters of clamped coordinates return only the constant border color. This does not add the ability for textures to specify borders using glTexImage2D, but only to clamp to a constant border value set using glTexParameter and glSamplerParameter. Requires ${GLES20.core}. """ IntConstant( """ Accepted by the {@code pname} parameter of TexParameteriv, TexParameterfv, SamplerParameteriv, SamplerParameterfv, TexParameterIivOES, TexParameterIuivOES, SamplerParameterIivOES, SamplerParameterIuivOES, GetTexParameteriv, GetTexParameterfv, GetTexParameterIivOES, GetTexParameterIuivOES, GetSamplerParameteriv, GetSamplerParameterfv, GetSamplerParameterIivOES, and GetSamplerParameterIuivOES. """, "TEXTURE_BORDER_COLOR_OES"..0x1004 ) IntConstant( """ Accepted by the {@code param} parameter of TexParameteri, TexParameterf, SamplerParameteri and SamplerParameterf, and by the {@code params} parameter of TexParameteriv, TexParameterfv, TexParameterIivOES, TexParameterIuivOES, SamplerParameterIivOES, SamplerParameterIuivOES and returned by the {@code params} parameter of GetTexParameteriv, GetTexParameterfv, GetTexParameterIivOES, GetTexParameterIuivOES, GetSamplerParameteriv, GetSamplerParameterfv, GetSamplerParameterIivOES, and GetSamplerParameterIuivOES when their {@code pname} parameter is TEXTURE_WRAP_S, TEXTURE_WRAP_T, or TEXTURE_WRAP_R. """, "CLAMP_TO_BORDER_OES"..0x812D ) void( "TexParameterIivOES", "", GLenum("target", ""), GLenum("pname", ""), SingleValue("param")..Check(1)..GLint.const.p("params", "") ) void( "TexParameterIuivOES", "", GLenum("target", ""), GLenum("pname", ""), SingleValue("param")..Check(1)..GLuint.const.p("params", "") ) void( "GetTexParameterIivOES", "", GLenum("target", ""), GLenum("pname", ""), ReturnParam..Check(1)..GLint.p("params", "") ) void( "GetTexParameterIuivOES", "", GLenum("target", ""), GLenum("pname", ""), ReturnParam..Check(1)..GLuint.p("params", "") ) void( "SamplerParameterIivOES", "", GLuint("sampler", ""), GLenum("pname", ""), SingleValue("param")..Check(1)..GLint.const.p("params", "") ) void( "SamplerParameterIuivOES", "", GLuint("sampler", ""), GLenum("pname", ""), SingleValue("param")..Check(1)..GLuint.const.p("params", "") ) void( "GetSamplerParameterIivOES", "", GLuint("sampler", ""), GLenum("pname", ""), ReturnParam..Check(1)..GLint.p("params", "") ) void( "GetSamplerParameterIuivOES", "", GLuint("sampler", ""), GLenum("pname", ""), ReturnParam..Check(1)..GLuint.p("params", "") ) }
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/OES_texture_border_clamp.kt
494085263
package com.sys1yagi.mastodon.android.extensions import android.content.Context import android.support.annotation.DimenRes import android.widget.Toast import com.sys1yagi.mastodon.android.DroiDonApplication fun Context.getDimensionPixelSize(@DimenRes resId: Int) = resources.getDimensionPixelSize(resId) fun Context.toast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() }
app/src/main/java/com/sys1yagi/mastodon/android/extensions/ContextExtensions.kt
3156967952
package task import org.slf4j.LoggerFactory import org.springframework.core.Ordered import org.springframework.core.annotation.Order import org.springframework.stereotype.Component import org.springframework.util.StringUtils import org.springframework.web.filter.OncePerRequestFilter import java.util.* import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletRequestWrapper import javax.servlet.http.HttpServletResponse /** * @author rinp * @since 2016/08/12 */ private val log = LoggerFactory.getLogger("filter") @Component @Order(org.springframework.core.Ordered.HIGHEST_PRECEDENCE) @Suppress("unused") open class HttpMethodOverrideHeaderFilter : OncePerRequestFilter() { override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain?) { if ("POST" != request.method) { filterChain?.doFilter(request, response) return } val headerValue: String? = request.getHeader(X_HTTP_METHOD_OVERRIDE_HEADER); if (headerValue != null && StringUtils.hasLength(headerValue)) { val method = headerValue.toUpperCase(); val wrapper = HttpMethodRequestWrapper(method, request) filterChain?.doFilter(wrapper, response); return } filterChain?.doFilter(request, response); } val X_HTTP_METHOD_OVERRIDE_HEADER = "X-HTTP-Method-Override"; /** * Simple {@link HttpServletRequest} wrapper that returns the supplied method for * {@link HttpServletRequest#getMethod()}. */ class HttpMethodRequestWrapper : HttpServletRequestWrapper { constructor(method: String, request: HttpServletRequest) : super(request) { this._method = method; } lateinit var _method: String override fun getMethod(): String { return this._method } } }
src/main/kotlin/todo/Filter.kt
2211282542
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.program.programindicatorengine.internal.function import org.hisp.dhis.android.core.parser.internal.expression.CommonExpressionVisitor import org.hisp.dhis.parser.expression.antlr.ExpressionParser.ExprContext internal class D2Count : ProgramCountFunction() { override fun countIf(ctx: ExprContext, visitor: CommonExpressionVisitor, value: String?): Boolean { return true } override fun getConditionalSql(ctx: ExprContext, visitor: CommonExpressionVisitor): String { return "IS NOT NULL" } }
core/src/main/java/org/hisp/dhis/android/core/program/programindicatorengine/internal/function/D2Count.kt
2691778411
/* * Copyright (C) 2015 Hannes Dorfmann * Copyright (C) 2015 Tickaroo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.tickaroo.tikxml.annotationprocessing.elementlist import com.tickaroo.tikxml.annotation.Element import com.tickaroo.tikxml.annotation.Path import com.tickaroo.tikxml.annotation.Xml /** * @author Hannes Dorfmann */ @Xml(name = "catalogue") data class CatalogueDataClass ( @field:Path("books") @field:Element var books: List<BookDataClass>? = null )
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/elementlist/CatalogueDataClass.kt
1826178545
package net.russianword.android import net.russianword.android.api.Task import java.io.Serializable import java.util.* const val USER_STATE_BUNDLE_ID = "userState" enum class State { NOT_AUTHENTICATED, AUTHENTICATING, NOT_LOADED, LOADING, LOADED, DISPLAYED, ANSWER_READY, SENDING_ANSWER } data class ProcessState(@Volatile var currentState: State = State.NOT_AUTHENTICATED, @Volatile var userId: String? = null, @Volatile var task: Task? = null, @Volatile var preparedAnswers: Set<String>? = HashSet()) : Serializable
app/src/main/java/net/russianword/android/ProcessState.kt
4197910154
// IS_APPLICABLE: false fun foo() { val a = if(true) { <selection>"aaa"</selection> } else { "bbb" } }
plugins/kotlin/idea/tests/testData/codeInsight/surroundWith/tryFinally/usedAsExpression.kt
968341386
package m1 public fun testUseAsReceiver(api: javaInterface.API) { api.useM1A<String> { this.length } api.useM1B<String> { <error descr="[NO_THIS] 'this' is not defined in this context">this</error>.<error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">length</error> } api.useM2A<String> { this.length } api.useM2B<String> { <error descr="[NO_THIS] 'this' is not defined in this context">this</error>.<error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">length</error> } } public fun testUseAsParameter(api: javaInterface.API) { api.useM1A<String> { <error descr="[UNRESOLVED_REFERENCE] Unresolved reference: it">it</error>.<error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">length</error> } api.useM1B<String> { it.length } api.useM2A<String> { <error descr="[UNRESOLVED_REFERENCE] Unresolved reference: it">it</error>.<error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved">length</error> } api.useM2B<String> { it.length } }
plugins/kotlin/idea/tests/testData/multiModuleHighlighting/samWithReceiverExtension/m1/m1.kt
2381933928
// FIR_IDENTICAL // FIR_COMPARISON class LocalType val property get(): <caret> // EXIST: LocalType
plugins/kotlin/completion/tests/testData/basic/common/primitiveCompletion/topLevelPropertyGetterTypeCompletion.kt
54599206
// 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.openapi.vcs.changes.committed import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.ui.dsl.builder.* object CacheSettingsDialog { @JvmStatic fun showSettingsDialog(project: Project): Boolean = ShowSettingsUtil.getInstance().editConfigurable(project, CacheSettingsPanel(project)) } internal class CacheSettingsPanel(project: Project) : BoundConfigurable(message("cache.settings.dialog.title")) { private val cache = CommittedChangesCache.getInstance(project) private val cacheState = CommittedChangesCacheState().apply { copyFrom(cache.state) } override fun apply() { super.apply() cache.loadState(cacheState) } override fun createPanel(): DialogPanel = panel { if (cache.isMaxCountSupportedForProject) countRow() else daysRow() row { val refreshCheckBox = checkBox(message("changes.refresh.changes.every")) .bindSelected(cacheState::isRefreshEnabled) intTextField(1..60 * 24) .bindIntText(cacheState::refreshInterval) .enabledIf(refreshCheckBox.selected) .gap(RightGap.SMALL) label(message("changes.minutes")) }.layout(RowLayout.PARENT_GRID) } private fun Panel.countRow() = row(message("changes.changelists.to.cache.initially")) { intTextField(1..100000) .bindIntText(cacheState::initialCount) } private fun Panel.daysRow() = row(message("changes.days.of.history.to.cache.initially")) { intTextField(1..720) .bindIntText(cacheState::initialDays) } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CacheSettingsPanel.kt
3179804407
package org.yframework.android.common import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Toast import com.becypress.framework.android.BuildConfig import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException /** * Description: CommonExtens<br> * Comments Name: CommonExtens<br> * Date: 2019-08-20 22:09<br> * Author: ysj<br> * EditorDate: 2019-08-20 22:09<br> * Editor: ysj */ enum class TipTypeEnum { NORMAL, SUCCESS, WARNING, ERROR } fun Activity.tip( msg: CharSequence, type: TipTypeEnum = TipTypeEnum.NORMAL, duration: Int = Toast.LENGTH_SHORT ) { runOnUiThread { when (type) { TipTypeEnum.NORMAL -> Toast.makeText(this, msg, duration).show() TipTypeEnum.SUCCESS -> Toast.makeText(this, msg, duration).show() TipTypeEnum.WARNING -> Toast.makeText(this, msg, duration).show() TipTypeEnum.ERROR -> Toast.makeText(this, msg, duration).show() } } } fun Activity.dispatchFailure(error: Throwable?) { error?.let { if (BuildConfig.DEBUG) { it.printStackTrace() } when { it is NullPointerException -> { } error is SocketTimeoutException -> it.message?.let { tip("网络连接超时", TipTypeEnum.ERROR ) } it is UnknownHostException || it is ConnectException -> //网络未连接 it.message?.let { tip("网络未连接", TipTypeEnum.ERROR) } else -> it.message?.let { message -> tip(message, TipTypeEnum.ERROR ) } } } } fun Activity.navigateUpToActivity(c: Class<*>, bundle: Bundle? = null, killed: Boolean? = true) { val intent = Intent(this, c) bundle?.let { intent.putExtras(it) } startActivity(intent) if (killed!!) finish() }
yframework-android/framework/src/main/java/org/yframework/android/common/CommonExtens.kt
3938181658
package com.programming.kotlin.chapter03 fun showFirstCharacter(input:String):Char{ if(input.isEmpty()) throw IllegalArgumentException() return input.first() }
Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Static.kt
4016884233
package eu.kanade.tachiyomi.data.source.online.russian import android.content.Context import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.source.Language import eu.kanade.tachiyomi.data.source.RU import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.data.source.online.ParsedOnlineSource import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.* import java.util.regex.Pattern class Readmanga(override val id: Int) : ParsedOnlineSource() { override val name = "Readmanga" override val baseUrl = "http://readmanga.me" override val lang: Language get() = RU override val supportsLatest = true override fun popularMangaInitialUrl() = "$baseUrl/list?sortType=rate" override fun latestUpdatesInitialUrl() = "$baseUrl/list?sortType=updated" override fun searchMangaInitialUrl(query: String, filters: List<Filter>) = "$baseUrl/search?q=$query&${filters.map { it.id + "=in" }.joinToString("&")}" override fun popularMangaSelector() = "div.desc" override fun latestUpdatesSelector() = "div.desc" override fun popularMangaFromElement(element: Element, manga: Manga) { element.select("h3 > a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.attr("title") } } override fun latestUpdatesFromElement(element: Element, manga: Manga) { popularMangaFromElement(element, manga) } override fun popularMangaNextPageSelector() = "a.nextLink" override fun latestUpdatesNextPageSelector() = "a.nextLink" override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element, manga: Manga) { element.select("h3 > a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.attr("title") } } // max 200 results override fun searchMangaNextPageSelector() = null override fun mangaDetailsParse(document: Document, manga: Manga) { val infoElement = document.select("div.leftContent").first() manga.author = infoElement.select("span.elem_author").first()?.text() manga.genre = infoElement.select("span.elem_genre").text().replace(" ,", ",") manga.description = infoElement.select("div.manga-description").text() manga.status = parseStatus(infoElement.html()) manga.thumbnail_url = infoElement.select("img").attr("data-full") } private fun parseStatus(element: String): Int { when { element.contains("<h3>Запрещена публикация произведения по копирайту</h3>") -> return Manga.LICENSED element.contains("<h1 class=\"names\"> Сингл") || element.contains("<b>Перевод:</b> завершен") -> return Manga.COMPLETED element.contains("<b>Перевод:</b> продолжается") -> return Manga.ONGOING else -> return Manga.UNKNOWN } } override fun chapterListSelector() = "div.chapters-link tbody tr" override fun chapterFromElement(element: Element, chapter: Chapter) { val urlElement = element.select("a").first() chapter.setUrlWithoutDomain(urlElement.attr("href") + "?mature=1") chapter.name = urlElement.text().replace(" новое", "") chapter.date_upload = element.select("td:eq(1)").first()?.text()?.let { SimpleDateFormat("dd/MM/yy", Locale.US).parse(it).time } ?: 0 } override fun parseChapterNumber(chapter: Chapter) { chapter.chapter_number = -2f } override fun pageListParse(response: Response, pages: MutableList<Page>) { val html = response.body().string() val beginIndex = html.indexOf("rm_h.init( [") val endIndex = html.indexOf("], 0, false);", beginIndex) val trimmedHtml = html.substring(beginIndex, endIndex) val p = Pattern.compile("'.+?','.+?',\".+?\"") val m = p.matcher(trimmedHtml) var i = 0 while (m.find()) { val urlParts = m.group().replace("[\"\']+".toRegex(), "").split(',') pages.add(Page(i++, "", urlParts[1] + urlParts[0] + urlParts[2])) } } override fun pageListParse(document: Document, pages: MutableList<Page>) { } override fun imageUrlParse(document: Document) = "" /* [...document.querySelectorAll("tr.advanced_option:nth-child(1) > td:nth-child(3) span.js-link")].map((el,i) => { * const onClick=el.getAttribute('onclick');const id=onClick.substr(31,onClick.length-33); * return `Filter("${id}", "${el.textContent.trim()}")` }).join(',\n') * on http://readmanga.me/search */ override fun getFilterList(): List<Filter> = listOf( Filter("el_5685", "арт"), Filter("el_2155", "боевик"), Filter("el_2143", "боевые искусства"), Filter("el_2148", "вампиры"), Filter("el_2142", "гарем"), Filter("el_2156", "гендерная интрига"), Filter("el_2146", "героическое фэнтези"), Filter("el_2152", "детектив"), Filter("el_2158", "дзёсэй"), Filter("el_2141", "додзинси"), Filter("el_2118", "драма"), Filter("el_2154", "игра"), Filter("el_2119", "история"), Filter("el_2137", "кодомо"), Filter("el_2136", "комедия"), Filter("el_2147", "махо-сёдзё"), Filter("el_2126", "меха"), Filter("el_2132", "мистика"), Filter("el_2133", "научная фантастика"), Filter("el_2135", "повседневность"), Filter("el_2151", "постапокалиптика"), Filter("el_2130", "приключения"), Filter("el_2144", "психология"), Filter("el_2121", "романтика"), Filter("el_2124", "самурайский боевик"), Filter("el_2159", "сверхъестественное"), Filter("el_2122", "сёдзё"), Filter("el_2128", "сёдзё-ай"), Filter("el_2134", "сёнэн"), Filter("el_2139", "сёнэн-ай"), Filter("el_2129", "спорт"), Filter("el_2138", "сэйнэн"), Filter("el_2153", "трагедия"), Filter("el_2150", "триллер"), Filter("el_2125", "ужасы"), Filter("el_2140", "фантастика"), Filter("el_2131", "фэнтези"), Filter("el_2127", "школа"), Filter("el_2149", "этти"), Filter("el_2123", "юри") ) }
app/src/main/java/eu/kanade/tachiyomi/data/source/online/russian/Readmanga.kt
3526694045
package pl.elpassion.elspace.hub.project import io.reactivex.Observable interface ProjectRepository { fun getProjects(): Observable<List<Project>> }
el-space-app/src/main/java/pl/elpassion/elspace/hub/project/ProjectRepository.kt
1803541545
package net.pagejects.core.forms import com.codeborne.selenide.SelenideElement import net.pagejects.core.annotation.PublicAPI import net.pagejects.core.util.TypeConverter /** * Default implementation of the [net.pagejects.core.FormFieldHandler] * * @author Andrey Paslavsky * @since 0.1 */ @PublicAPI class DefaultFormFieldHandler : AbstractFormFieldHandler() { override fun fillValue(element: SelenideElement, value: Any?) { if (element.isCheckbox) { element.isSelected = true == TypeConverter.convert(value, Boolean::class) } else { element.value = TypeConverter.convert(value, String::class) } } override fun readInternalValueFrom(element: SelenideElement): String? = if (element.isCheckbox) { element.isSelected.toString() } else { element.value } private val SelenideElement.isCheckbox: Boolean get() = "input".equals(tagName, true) && "checkbox".equals(attr("type"), true) }
src/main/kotlin/net/pagejects/core/forms/DefaultFormFieldHandler.kt
3653038366
package org.craftsmenlabs.socketoutlet.core data class ErrorMessage(val message: String, val throwable: Throwable? = null)
core/src/main/java/org/craftsmenlabs/socketoutlet/core/ErrorMessage.kt
2006369036
package io.georocket.util import io.georocket.ServerAPIException import io.vertx.core.eventbus.ReplyException import org.antlr.v4.runtime.misc.ParseCancellationException import java.io.FileNotFoundException /** * Helper class for [Throwable]s * @author Michel Kraemer * @since 1.2.0 */ object ThrowableHelper { /** * Convert a throwable to an HTTP status code * @param t the throwable to convert * @return the HTTP status code */ fun throwableToCode(t: Throwable?): Int { return when (t) { is ReplyException -> t.failureCode() is IllegalArgumentException, is ParseCancellationException -> 400 is FileNotFoundException -> 404 is HttpException -> t.statusCode else -> 500 } } /** * Get the given throwable's message or return a default one if it is * `null` * @param t the throwable's message * @param defaultMessage the message to return if the one of the throwable * is `null` * @return the message */ fun throwableToMessage(t: Throwable, defaultMessage: String): String { return if (t is ServerAPIException) { t.toJson().toString() } else t.message ?: return defaultMessage } }
src/main/kotlin/io/georocket/util/ThrowableHelper.kt
3006173206
package com.esafirm.androidplayground.utils import io.kotlintest.specs.StringSpec import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.runBlockingTest import kotlinx.coroutines.withContext @ExperimentalCoroutinesApi class CoroutineUnconfinedTest : StringSpec({ val testDispatcher = TestCoroutineDispatcher() "Suspend function will resume on default dispatcher" { runBlockingTest { launch { printCurrentThread("#AA") delay(500) printCurrentThread("#AA") } launch { printCurrentThread("#AB") delay(1000) printCurrentThread("#AB") } } } "Unconfined on multiple call in one launc" { launch(Dispatchers.Unconfined) { printCurrentThread("#AA - Unconfined") delay(100) printCurrentThread("#AB - Unconfined") } } "TestDispatcher on multiple call in one launch" { launch(testDispatcher) { printCurrentThread("#AA - Test") delay(100) printCurrentThread("#AB - Test") simulateSuspendFunction(100) printCurrentThread("#AC - Test") } testDispatcher.advanceUntilIdle() } "Test dispatcher on nested context" { launch(testDispatcher) { withContext(testDispatcher) { printCurrentThread("#AA - Nested") delay(100) printCurrentThread("#AB - Nested") simulateSuspendFunction(100) printCurrentThread("#AC - Nested") } } testDispatcher.advanceUntilIdle() } }) @Suppress("BlockingMethodInNonBlockingContext") private suspend fun simulateSuspendFunction(time: Long) { Thread.sleep(time) } @Suppress("NOTHING_TO_INLINE") private inline fun printCurrentThread(callerId: String) { println("$callerId Current thread: ${Thread.currentThread().name}") }
app/src/test/java/com/esafirm/androidplayground/utils/CoroutineUnconfinedTest.kt
4067194003
// 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.ide.actions import com.intellij.ide.IdeBundle import com.intellij.ide.actions.CopyReferenceUtil.* import com.intellij.navigation.JBProtocolNavigateCommand.Companion.FQN_KEY import com.intellij.navigation.JBProtocolNavigateCommand.Companion.NAVIGATE_COMMAND import com.intellij.navigation.JBProtocolNavigateCommand.Companion.PATH_KEY import com.intellij.navigation.JBProtocolNavigateCommand.Companion.PROJECT_NAME_KEY import com.intellij.navigation.JBProtocolNavigateCommand.Companion.REFERENCE_TARGET import com.intellij.navigation.JBProtocolNavigateCommand.Companion.SELECTION import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.JetBrainsProtocolHandler import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import com.intellij.util.PlatformUtils import com.intellij.util.PlatformUtils.* import java.awt.datatransfer.StringSelection import java.util.stream.Collectors import java.util.stream.IntStream class CopyTBXReferenceAction : DumbAwareAction() { init { isEnabledInModalContext = true setInjectedContext(true) } override fun update(e: AnActionEvent) { var plural = false var enabled: Boolean var paths = false val dataContext = e.dataContext val editor = CommonDataKeys.EDITOR.getData(dataContext) if (editor != null && FileDocumentManager.getInstance().getFile(editor.document) != null) { enabled = true } else { val elements = getElementsToCopy(editor, dataContext) enabled = !elements.isEmpty() plural = elements.size > 1 paths = elements.stream().allMatch { el -> el is PsiFileSystemItem && getQualifiedNameFromProviders(el) == null } } enabled = enabled && (ActionPlaces.MAIN_MENU == e.place) e.presentation.isEnabled = enabled if (ActionPlaces.isPopupPlace(e.place)) { e.presentation.isVisible = enabled } else { e.presentation.isVisible = true } e.presentation.text = if (paths) if (plural) "Cop&y Toolbox Relative Paths URL" else "Cop&y Toolbox Relative Path URL" else if (plural) "Cop&y Toolbox References URL" else "Cop&y Toolbox Reference URL" } override fun actionPerformed(e: AnActionEvent) { val dataContext = e.dataContext val editor = CommonDataKeys.EDITOR.getData(dataContext) val project = CommonDataKeys.PROJECT.getData(dataContext) val elements = getElementsToCopy(editor, dataContext) if (project == null) { LOG.warn("'Copy TBX Reference' action cannot find project.") return } var copy = createJetbrainsLink(project, elements, editor) if (copy != null) { CopyPasteManager.getInstance().setContents(CopyReferenceFQNTransferable(copy)) setStatusBarText(project, IdeBundle.message("message.reference.to.fqn.has.been.copied", copy)) } else if (editor != null) { val document = editor.document val file = PsiDocumentManager.getInstance(project).getCachedPsiFile(document) if (file != null) { val logicalPosition = editor.caretModel.logicalPosition val path = "${getFileFqn(file)}:${logicalPosition.line + 1}:${logicalPosition.column + 1}" copy = createLink(editor, project, createRefs(true, path, "")) CopyPasteManager.getInstance().setContents(StringSelection(copy)) setStatusBarText(project, "$copy has been copied") } return } highlight(editor, project, elements) } companion object { private val LOG = Logger.getInstance(CopyTBXReferenceAction::class.java) private const val JETBRAINS_NAVIGATE = JetBrainsProtocolHandler.PROTOCOL private val IDE_TAGS = mapOf(IDEA_PREFIX to "idea", IDEA_CE_PREFIX to "idea", APPCODE_PREFIX to "appcode", CLION_PREFIX to "clion", PYCHARM_PREFIX to "pycharm", PYCHARM_CE_PREFIX to "pycharm", PYCHARM_EDU_PREFIX to "pycharm", PHP_PREFIX to "php-storm", RUBY_PREFIX to "rubymine", WEB_PREFIX to "web-storm", RIDER_PREFIX to "rd", GOIDE_PREFIX to "goland") fun createJetbrainsLink(project: Project, elements: List<PsiElement>, editor: Editor?): String? { val refsParameters = IntArray(elements.size) { i -> i } .associateBy({ it }, { elementToFqn(elements[it], editor) }) .filter { it.value != null } .mapValues { FileUtil.getLocationRelativeToUserHome(it.value, false) } .entries .ifEmpty { return null } .joinToString("") { createRefs(isFile(elements[it.key]), it.value, parameterIndex(it.key, elements.size)) } return createLink(editor, project, refsParameters) } private fun isFile(element: PsiElement) = element is PsiFileSystemItem && getQualifiedNameFromProviders(element) == null private fun parameterIndex(index: Int, size: Int) = if (size == 1) "" else "${index + 1}" private fun createRefs(isFile: Boolean, reference: String?, index: String) = "&${if (isFile) PATH_KEY else FQN_KEY}${index}=$reference" private fun createLink(editor: Editor?, project: Project, refsParameters: String?): String? { val tool = IDE_TAGS[PlatformUtils.getPlatformPrefix()] if (tool == null) { LOG.warn("Cannot find TBX tool for IDE: ${PlatformUtils.getPlatformPrefix()}") return null } val selectionParameters = getSelectionParameters(editor) ?: "" val projectParameter = "$PROJECT_NAME_KEY=${project.name}" return "$JETBRAINS_NAVIGATE$tool/$NAVIGATE_COMMAND/$REFERENCE_TARGET?$projectParameter$refsParameters$selectionParameters" } private fun getSelectionParameters(editor: Editor?): String? { if (editor == null) { return null } ApplicationManager.getApplication().assertReadAccessAllowed() if (editor.caretModel.supportsMultipleCarets()) { val carets = editor.caretModel.allCarets return IntStream.range(0, carets.size).mapToObj { i -> getSelectionParameters(editor, carets[i], parameterIndex(i, carets.size)) } .filter { it != null }.collect(Collectors.joining()) } else { return getSelectionParameters(editor, editor.caretModel.currentCaret, "") } } private fun getSelectionParameters(editor: Editor, caret: Caret, index: String): String? = getSelectionRange(editor, caret)?.let { "&$SELECTION$index=$it" } private fun getSelectionRange(editor: Editor, caret: Caret): String? { if (!caret.hasSelection()) { return null } val selectionStart = editor.visualToLogicalPosition(caret.selectionStartPosition) val selectionEnd = editor.visualToLogicalPosition(caret.selectionEndPosition) return String.format("%d:%d-%d:%d", selectionStart.line + 1, selectionStart.column + 1, selectionEnd.line + 1, selectionEnd.column + 1) } } }
platform/lang-impl/src/com/intellij/ide/actions/CopyTBXReferenceAction.kt
278804611
package com.akhbulatov.wordkeeper.presentation.ui.global.base import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity abstract class BaseActivity(@LayoutRes contentLayoutId: Int) : AppCompatActivity(contentLayoutId)
app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/global/base/BaseActivity.kt
508473467
package com.akhbulatov.wordkeeper.presentation.ui.wordcategories import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.akhbulatov.wordkeeper.domain.global.models.WordCategory import com.akhbulatov.wordkeeper.domain.wordcategory.WordCategoryInteractor import com.akhbulatov.wordkeeper.presentation.global.mvvm.BaseViewModel import com.akhbulatov.wordkeeper.presentation.global.navigation.Screens import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch import ru.terrakok.cicerone.Router import javax.inject.Inject class WordCategoriesViewModel @Inject constructor( private val router: Router, private val wordCategoryInteractor: WordCategoryInteractor ) : BaseViewModel() { private val _viewState = MutableLiveData<ViewState>() val viewState: LiveData<ViewState> get() = _viewState private val currentViewState: ViewState get() = _viewState.value!! private var loadedWordCategories = listOf<WordCategory>() init { _viewState.value = ViewState() } fun loadWordCategories() { viewModelScope.launch { wordCategoryInteractor.getWordCategories() .onStart { _viewState.value = currentViewState.copy(emptyProgress = true) } .onEach { _viewState.value = currentViewState.copy(emptyProgress = false) } .catch { _viewState.value = currentViewState.copy( emptyProgress = false, emptyError = Pair(true, it.message) ) } .collect { loadedWordCategories = it if (it.isNotEmpty()) { _viewState.value = currentViewState.copy( emptyData = false, emptyError = Pair(false, null), wordCategories = Pair(true, it) ) } else { _viewState.value = currentViewState.copy( emptyData = true, emptyError = Pair(false, null), wordCategories = Pair(false, it) ) } } } } fun onWordCategoryClicked(wordCategory: WordCategory) { router.navigateTo(Screens.CategoryWords(wordCategory.name)) } fun onAddWordCategoryClicked(name: String) { val wordCategory = WordCategory(name = name) viewModelScope.launch { wordCategoryInteractor.addWordCategory(wordCategory) } } fun onEditWordCategoryClicked(id: Long, name: String) { val wordCategory = WordCategory( id = id, name = name ) viewModelScope.launch { wordCategoryInteractor.editWordCategory(wordCategory) } } fun onDeleteWordCategoryWithWordsClicked(wordCategory: WordCategory) { viewModelScope.launch { wordCategoryInteractor.deleteWordCategoryWithWords(wordCategory) } } fun onSearchWordCategoryChanged(query: String) { viewModelScope.launch { if (query.isNotBlank()) { val foundWords = wordCategoryInteractor.searchWordCategories(query, loadedWordCategories) _viewState.value = currentViewState.copy( emptySearchResult = Pair(foundWords.isEmpty(), query), wordCategories = Pair(true, foundWords) ) } else { _viewState.value = currentViewState.copy( emptySearchResult = Pair(false, null), wordCategories = Pair(true, loadedWordCategories) ) } } } fun onCloseSearchWordCategoryClicked() { _viewState.value = currentViewState.copy( emptySearchResult = Pair(false, null), wordCategories = Pair(true, loadedWordCategories) ) } data class ViewState( val emptyProgress: Boolean = false, val emptyData: Boolean = false, val emptyError: Pair<Boolean, String?> = Pair(false, null), val emptySearchResult: Pair<Boolean, String?> = Pair(false, null), val wordCategories: Pair<Boolean, List<WordCategory>> = Pair(false, emptyList()) ) }
app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/wordcategories/WordCategoriesViewModel.kt
3517214109
package com.alexstyl.specialdates import com.alexstyl.specialdates.events.namedays.NamedayLocale import com.alexstyl.specialdates.events.peopleevents.EventType import com.alexstyl.specialdates.person.StarSign interface Strings { fun viewConversation(): String fun dailyReminder(): String fun facebookMessenger(): String fun nameOf(starSign: StarSign): String fun turnsAge(age: Int): String fun inviteFriend(): String fun todaysNamedays(numberOfNamedays: Int): String fun donateAmount(amount: String): String fun eventOnDate(eventLabel: String, dateLabel: String): String fun appName(): String fun shareText(): String fun today(): String fun tomorrow(): String fun todayCelebrateTwo(nameOne: String, nameTwo: String): String fun todayCelebrateMany(name: String, numberLeft: Int): String fun nameOfEvent(event: EventType): String fun postOnFacebook(): String fun facebook(): String fun localeName(locale: NamedayLocale): String fun viewFacebookProfile(): String fun importFromFacebook(): String fun namedays(): String fun bankholidays(): String fun contacts(): String fun bankholidaySubtitle(): String fun call(): String fun sendWishes(): String fun dontForgetToSendWishes(): String fun contactUpdateFailed(): String fun contactUpdated(): String fun contactAdded():String fun contactAddedFailed(): String }
memento/src/main/java/com/alexstyl/specialdates/Strings.kt
2299467354
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes.BIPUSH import org.objectweb.asm.Opcodes.PUTFIELD import org.objectweb.asm.Type.INT_TYPE import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.withDimensions import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 class Decimator : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == Any::class.type } .and { it.instanceFields.size == 3 } .and { it.instanceFields.count { it.type == INT_TYPE.withDimensions(2) } == 1 } class resample : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == ByteArray::class.type } } class inputRate : OrderMapper.InConstructor.Field(Decimator::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class outputRate : OrderMapper.InConstructor.Field(Decimator::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class table : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == INT_TYPE.withDimensions(2) } } @MethodParameters("rate") class scaleRate : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.instructions.none { it.opcode == BIPUSH && it.intOperand == 6 } } } @MethodParameters("position") class scalePosition : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.instructions.any { it.opcode == BIPUSH && it.intOperand == 6 } } } }
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Decimator.kt
3706949178
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * 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.jetbrains.packagesearch.intellij.plugin.util import com.intellij.ui.content.ContentManager import com.intellij.ui.content.ContentManagerEvent import com.intellij.ui.content.ContentManagerListener @Suppress("FunctionName") internal fun SelectionChangedListener(action: (ContentManagerEvent) -> Unit) = object : ContentManagerListener { override fun selectionChanged(event: ContentManagerEvent) = action(event) } internal fun ContentManager.addSelectionChangedListener(action: (ContentManagerEvent) -> Unit) = SelectionChangedListener(action).also { addContentManagerListener(it) }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/GenericUtils.kt
1571391148
package com.github.bumblebee.command.youtube import com.github.bumblebee.command.SingleArgumentCommand import com.github.bumblebee.command.youtube.entity.Subscription import com.github.bumblebee.command.youtube.service.YoutubeSubscriptionService import com.github.bumblebee.service.RandomPhraseService import com.github.telegram.api.BotApi import com.github.telegram.domain.Update import org.springframework.stereotype.Component @Component class YoutubeUnsubscribeCommand(private val botApi: BotApi, private val service: YoutubeSubscriptionService, private val randomPhraseService: RandomPhraseService) : SingleArgumentCommand() { override fun handleCommand(update: Update, chatId: Long, argument: String?) { if (argument == null) { botApi.sendMessage(chatId, randomPhraseService.surprise()) return } val channelId: String = argument service.getSubscriptions().forEach { sub -> if (sub.channelId == channelId) { processUnsubscription(sub, channelId, chatId) return } } botApi.sendMessage(chatId, "Channel to unsubscribe not exist!") } private fun processUnsubscription(sub: Subscription, channelId: String, chatId: Long) { val chats = sub.chats for (chat in chats) { if (chat.chatId == chatId) { if (chats.size == 1) { removeChannel(sub, channelId, chatId) return } if (chats.size > 1) { chats.remove(chat) service.storeSubscription(sub) botApi.sendMessage(chatId, "Chat successfully unsubscribed!") return } } } } private fun removeChannel(sub: Subscription, channelId: String, chatId: Long) { if (service.unsubscribeChannel(channelId)) { service.deleteSubscription(sub) service.getSubscriptions().remove(sub) botApi.sendMessage(chatId, "Channel removed!") } } }
telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/youtube/YoutubeUnsubscribeCommand.kt
3110042410
package com.virtlink.terms import com.google.common.collect.Interners /** * Term factory that ensures maximal sharing. */ open class InterningTermFactory(): DefaultTermFactory() { //class InterningTermFactory(private val innerTermFactory: TermFactory): TermFactory() { // /** // * Initializes this factory with the default term factory. // */ // constructor() : this(DefaultTermFactory()) /** * The term interner, which ensures that two instances of the same term * refer to the same object in memory (reference equality). */ private val interner = Interners.newWeakInterner<ITerm>() // // override fun createString(value: String): StringTerm // = getTerm(this.innerTermFactory.createString(value)) // // override fun createInt(value: Int): IntTerm // = getTerm(this.innerTermFactory.createInt(value)) // // override fun <T: ITerm> createList(elements: List<T>): ListTerm<T> // = getTerm(this.innerTermFactory.createList(elements)) // // override fun <T : ITerm> createOption(value: T?): OptionTerm<T> // = getTerm(this.innerTermFactory.createOption(value)) // // override fun createTerm(constructor: ITermConstructor, children: List<ITerm>): ITerm // = getTerm(this.innerTermFactory.createTerm(constructor, children)) // // override fun registerBuilder(constructor: ITermConstructor, builder: (ITermConstructor, List<ITerm>) -> ITerm) // = this.innerTermFactory.registerBuilder(constructor, builder) // // override fun unregisterBuilder(constructor: ITermConstructor) // = this.innerTermFactory.unregisterBuilder(constructor) /** * Gets the interned term that is equal to the given term; * or the given term when the term was not interned yet. * * This is the core method that ensures maximal sharing. * * @param term The input term. * @return The resulting term. */ override fun <T: ITerm> getTerm(term: T): T { @Suppress("UNCHECKED_CAST") return this.interner.intern(term) as T } }
paplj/src/main/kotlin/com/virtlink/terms/InterningTermFactory.kt
2979973900
package com.github.bumblebee.command.start import com.github.bumblebee.bot.consumer.UpdateHandler import com.github.telegram.api.BotApi import com.github.telegram.domain.ParseMode import com.github.telegram.domain.Update import org.apache.commons.io.IOUtils import org.springframework.core.io.ClassPathResource import org.springframework.stereotype.Component import java.nio.charset.StandardCharsets @Component class StartCommand(val botApi: BotApi) : UpdateHandler { private val helpText: String by lazy { ClassPathResource("start.md").inputStream.use { IOUtils.toString(it, StandardCharsets.UTF_8) } } override fun onUpdate(update: Update): Boolean { botApi.sendMessage( chatId = update.message!!.chat.id, text = helpText, parseMode = ParseMode.MARKDOWN ) return true } }
telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/start/StartCommand.kt
3674890232
// 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.execution.impl import com.intellij.CommonBundle import com.intellij.build.BuildContentManager import com.intellij.execution.* import com.intellij.execution.configuration.CompatibilityAwareRunProfile import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.configurations.RunConfiguration.RestartSingletonResult import com.intellij.execution.configurations.RunProfile import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.filters.TextConsoleBuilderFactory import com.intellij.execution.impl.ExecutionManagerImpl.Companion.DELEGATED_RUN_PROFILE_KEY import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector.RunConfigurationFinishType import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector.UI_SHOWN_STAGE import com.intellij.execution.process.* import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionEnvironmentBuilder import com.intellij.execution.runners.ExecutionUtil import com.intellij.execution.runners.ProgramRunner import com.intellij.execution.target.TargetEnvironmentAwareRunProfile import com.intellij.execution.target.TargetProgressIndicator import com.intellij.execution.target.getEffectiveTargetName import com.intellij.execution.ui.ConsoleView import com.intellij.execution.ui.RunContentDescriptor import com.intellij.execution.ui.RunContentManager import com.intellij.ide.SaveAndSyncHandler import com.intellij.internal.statistic.StructuredIdeActivity import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ReadAction import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.* import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.ToolWindow import com.intellij.ui.AppUIUtil import com.intellij.ui.UIBundle import com.intellij.ui.content.ContentManager import com.intellij.ui.content.impl.ContentImpl import com.intellij.util.Alarm import com.intellij.util.SmartList import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.ContainerUtil import org.jetbrains.annotations.* import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.resolvedPromise import java.awt.BorderLayout import java.io.OutputStream import java.util.* import java.util.concurrent.Callable import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Consumer import javax.swing.JPanel import javax.swing.SwingUtilities class ExecutionManagerImpl(private val project: Project) : ExecutionManager(), Disposable { companion object { val LOG = logger<ExecutionManagerImpl>() private val EMPTY_PROCESS_HANDLERS = emptyArray<ProcessHandler>() internal val DELEGATED_RUN_PROFILE_KEY = Key.create<RunProfile>("DELEGATED_RUN_PROFILE_KEY") @JvmField val EXECUTION_SESSION_ID_KEY = ExecutionManager.EXECUTION_SESSION_ID_KEY @JvmField val EXECUTION_SKIP_RUN = ExecutionManager.EXECUTION_SKIP_RUN @JvmStatic fun getInstance(project: Project) = project.service<ExecutionManager>() as ExecutionManagerImpl @JvmStatic fun isProcessRunning(descriptor: RunContentDescriptor?): Boolean { val processHandler = descriptor?.processHandler return processHandler != null && !processHandler.isProcessTerminated } @JvmStatic fun stopProcess(descriptor: RunContentDescriptor?) { stopProcess(descriptor?.processHandler) } @JvmStatic fun stopProcess(processHandler: ProcessHandler?) { if (processHandler == null) { return } processHandler.putUserData(ProcessHandler.TERMINATION_REQUESTED, true) if (processHandler is KillableProcess && processHandler.isProcessTerminating) { // process termination was requested, but it's still alive // in this case 'force quit' will be performed processHandler.killProcess() return } if (!processHandler.isProcessTerminated) { if (processHandler.detachIsDefault()) { processHandler.detachProcess() } else { processHandler.destroyProcess() } } } @JvmStatic fun getAllDescriptors(project: Project): List<RunContentDescriptor> { return project.serviceIfCreated<RunContentManager>()?.allDescriptors ?: emptyList() } @ApiStatus.Internal @JvmStatic fun setDelegatedRunProfile(runProfile: RunProfile, runProfileToDelegate: RunProfile) { if (runProfile !== runProfileToDelegate && runProfile is UserDataHolder) { DELEGATED_RUN_PROFILE_KEY[runProfile] = runProfileToDelegate } } } init { val connection = ApplicationManager.getApplication().messageBus.connect(this) connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosed(project: Project) { if (project === [email protected]) { inProgress.clear() } } }) } @set:TestOnly @Volatile var forceCompilationInTests = false private val awaitingTerminationAlarm = Alarm() private val awaitingRunProfiles = HashMap<RunProfile, ExecutionEnvironment>() private val runningConfigurations: MutableList<RunningConfigurationEntry> = ContainerUtil.createLockFreeCopyOnWriteList() private val inProgress = Collections.synchronizedSet(HashSet<InProgressEntry>()) private fun processNotStarted(environment: ExecutionEnvironment, activity: StructuredIdeActivity?, e : Throwable? = null) { RunConfigurationUsageTriggerCollector.logProcessFinished(activity, RunConfigurationFinishType.FAILED_TO_START) val executorId = environment.executor.id inProgress.remove(InProgressEntry(executorId, environment.runner.runnerId)) project.messageBus.syncPublisher(EXECUTION_TOPIC).processNotStarted(executorId, environment, e) } /** * Internal usage only. Maybe removed or changed in any moment. No backward compatibility. */ @ApiStatus.Internal override fun startRunProfile(environment: ExecutionEnvironment, starter: () -> Promise<RunContentDescriptor?>) { doStartRunProfile(environment) { // errors are handled by startRunProfile starter() .then { descriptor -> if (descriptor != null) { descriptor.executionId = environment.executionId val toolWindowId = RunContentManager.getInstance(environment.project).getContentDescriptorToolWindowId(environment) if (toolWindowId != null) { descriptor.contentToolWindowId = toolWindowId } environment.runnerAndConfigurationSettings?.let { descriptor.isActivateToolWindowWhenAdded = it.isActivateToolWindowBeforeRun } } environment.callback?.let { it.processStarted(descriptor) environment.callback = null } descriptor } } } override fun startRunProfile(starter: RunProfileStarter, environment: ExecutionEnvironment) { doStartRunProfile(environment) { starter.executeAsync(environment) } } private fun doStartRunProfile(environment: ExecutionEnvironment, task: () -> Promise<RunContentDescriptor>) { val activity = triggerUsage(environment) RunManager.getInstance(environment.project).refreshUsagesList(environment.runProfile) val project = environment.project val reuseContent = RunContentManager.getInstance(project).getReuseContent(environment) if (reuseContent != null) { reuseContent.executionId = environment.executionId environment.contentToReuse = reuseContent } val executor = environment.executor inProgress.add(InProgressEntry(executor.id, environment.runner.runnerId)) project.messageBus.syncPublisher(EXECUTION_TOPIC).processStartScheduled(executor.id, environment) val startRunnable = Runnable { if (project.isDisposed) { return@Runnable } project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarting(executor.id, environment) fun handleError(e: Throwable) { processNotStarted(environment, activity, e) if (e !is ProcessCanceledException) { ProgramRunnerUtil.handleExecutionError(project, environment, e, environment.runProfile) LOG.debug(e) } } try { task() .onSuccess { descriptor -> AppUIUtil.invokeLaterIfProjectAlive(project) { if (descriptor == null) { processNotStarted(environment, activity) return@invokeLaterIfProjectAlive } val entry = RunningConfigurationEntry(descriptor, environment.runnerAndConfigurationSettings, executor) runningConfigurations.add(entry) Disposer.register(descriptor, Disposable { runningConfigurations.remove(entry) }) if (!descriptor.isHiddenContent && !environment.isHeadless) { RunContentManager.getInstance(project).showRunContent(executor, descriptor, environment.contentToReuse) } activity?.stageStarted(UI_SHOWN_STAGE) environment.contentToReuse = descriptor val processHandler = descriptor.processHandler if (processHandler != null) { if (!processHandler.isStartNotified) { project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarting(executor.id, environment, processHandler) processHandler.startNotify() } inProgress.remove(InProgressEntry(executor.id, environment.runner.runnerId)) project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarted(executor.id, environment, processHandler) val listener = ProcessExecutionListener(project, executor.id, environment, processHandler, descriptor, activity) processHandler.addProcessListener(listener) // Since we cannot guarantee that the listener is added before process handled is start notified, // we have to make sure the process termination events are delivered to the clients. // Here we check the current process state and manually deliver events, while // the ProcessExecutionListener guarantees each such event is only delivered once // either by this code, or by the ProcessHandler. val terminating = processHandler.isProcessTerminating val terminated = processHandler.isProcessTerminated if (terminating || terminated) { listener.processWillTerminate(ProcessEvent(processHandler), false /* doesn't matter */) if (terminated) { val exitCode = if (processHandler.isStartNotified) processHandler.exitCode ?: -1 else -1 listener.processTerminated(ProcessEvent(processHandler, exitCode)) } } } } } .onError(::handleError) } catch (e: Throwable) { handleError(e) } } if (!forceCompilationInTests && ApplicationManager.getApplication().isUnitTestMode) { startRunnable.run() } else { compileAndRun(Runnable { ApplicationManager.getApplication().invokeLater(startRunnable, project.disposed) }, environment, Runnable { if (!project.isDisposed) { processNotStarted(environment, activity) } }) } } override fun dispose() { for (entry in runningConfigurations) { Disposer.dispose(entry.descriptor) } runningConfigurations.clear() } @Suppress("OverridingDeprecatedMember") override fun getContentManager() = RunContentManager.getInstance(project) override fun getRunningProcesses(): Array<ProcessHandler> { var handlers: MutableList<ProcessHandler>? = null for (descriptor in getAllDescriptors(project)) { val processHandler = descriptor.processHandler ?: continue if (handlers == null) { handlers = SmartList() } handlers.add(processHandler) } return handlers?.toTypedArray() ?: EMPTY_PROCESS_HANDLERS } override fun compileAndRun(startRunnable: Runnable, environment: ExecutionEnvironment, onCancelRunnable: Runnable?) { var id = environment.executionId if (id == 0L) { id = environment.assignNewExecutionId() } val profile = environment.runProfile if (profile !is RunConfiguration) { startRunnable.run() return } val beforeRunTasks = doGetBeforeRunTasks(profile) if (beforeRunTasks.isEmpty()) { startRunnable.run() return } val context = environment.dataContext val projectContext = context ?: SimpleDataContext.getProjectContext(project) val runBeforeRunExecutorMap = Collections.synchronizedMap(linkedMapOf<BeforeRunTask<*>, Executor>()) ApplicationManager.getApplication().executeOnPooledThread { for (task in beforeRunTasks) { val provider = BeforeRunTaskProvider.getProvider(project, task.providerId) if (provider == null || task !is RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask) { continue } val settings = task.settings if (settings != null) { // as side-effect here we setup runners list ( required for com.intellij.execution.impl.RunManagerImpl.canRunConfiguration() ) var executor = if (Registry.`is`("lock.run.executor.for.before.run.tasks", false)) { DefaultRunExecutor.getRunExecutorInstance() } else { environment.executor } val builder = ExecutionEnvironmentBuilder.createOrNull(executor, settings) if (builder == null || !RunManagerImpl.canRunConfiguration(settings, executor)) { executor = DefaultRunExecutor.getRunExecutorInstance() if (!RunManagerImpl.canRunConfiguration(settings, executor)) { // we should stop here as before run task cannot be executed at all (possibly it's invalid) onCancelRunnable?.run() ExecutionUtil.handleExecutionError(environment, ExecutionException( ExecutionBundle.message("dialog.message.cannot.start.before.run.task", settings))) return@executeOnPooledThread } } runBeforeRunExecutorMap[task] = executor } } for (task in beforeRunTasks) { if (project.isDisposed) { return@executeOnPooledThread } @Suppress("UNCHECKED_CAST") val provider = BeforeRunTaskProvider.getProvider(project, task.providerId) as BeforeRunTaskProvider<BeforeRunTask<*>>? if (provider == null) { LOG.warn("Cannot find BeforeRunTaskProvider for id='${task.providerId}'") continue } val builder = ExecutionEnvironmentBuilder(environment).contentToReuse(null) val executor = runBeforeRunExecutorMap[task] if (executor != null) { builder.executor(executor) } val taskEnvironment = builder.build() taskEnvironment.executionId = id EXECUTION_SESSION_ID_KEY.set(taskEnvironment, id) try { if (!provider.executeTask(projectContext, profile, taskEnvironment, task)) { if (onCancelRunnable != null) { SwingUtilities.invokeLater(onCancelRunnable) } return@executeOnPooledThread } } catch (e: ProcessCanceledException) { if (onCancelRunnable != null) { SwingUtilities.invokeLater(onCancelRunnable) } return@executeOnPooledThread } } doRun(environment, startRunnable) } } private fun doRun(environment: ExecutionEnvironment, startRunnable: Runnable) { val allowSkipRun = environment.getUserData(EXECUTION_SKIP_RUN) if (allowSkipRun != null && allowSkipRun) { processNotStarted(environment, null) return } // important! Do not use DumbService.smartInvokeLater here because it depends on modality state // and execution of startRunnable could be skipped if modality state check fails SwingUtilities.invokeLater { if (project.isDisposed) { return@invokeLater } val settings = environment.runnerAndConfigurationSettings if (settings != null && !settings.type.isDumbAware && DumbService.isDumb(project)) { DumbService.getInstance(project).runWhenSmart(startRunnable) } else { try { startRunnable.run() } catch (ignored: IndexNotReadyException) { ExecutionUtil.handleExecutionError(environment, ExecutionException( ExecutionBundle.message("dialog.message.cannot.start.while.indexing.in.progress"))) } } } } override fun restartRunProfile(project: Project, executor: Executor, target: ExecutionTarget, configuration: RunnerAndConfigurationSettings?, processHandler: ProcessHandler?, environmentCustomization: Consumer<in ExecutionEnvironment>?) { val builder = createEnvironmentBuilder(project, executor, configuration) if (processHandler != null) { for (descriptor in getAllDescriptors(project)) { if (descriptor.processHandler === processHandler) { builder.contentToReuse(descriptor) break } } } val environment = builder.target(target).build() environmentCustomization?.accept(environment) restartRunProfile(environment) } override fun restartRunProfile(environment: ExecutionEnvironment) { val configuration = environment.runnerAndConfigurationSettings val runningIncompatible: List<RunContentDescriptor> if (configuration == null) { runningIncompatible = emptyList() } else { runningIncompatible = getIncompatibleRunningDescriptors(configuration) } val contentToReuse = environment.contentToReuse val runningOfTheSameType = if (configuration != null && !configuration.configuration.isAllowRunningInParallel) { getRunningDescriptors(Condition { it.isOfSameType(configuration) }) } else if (isProcessRunning(contentToReuse)) { listOf(contentToReuse!!) } else { emptyList() } val runningToStop = ContainerUtil.concat(runningOfTheSameType, runningIncompatible) if (runningToStop.isNotEmpty()) { if (configuration != null) { if (runningOfTheSameType.isNotEmpty() && (runningOfTheSameType.size > 1 || contentToReuse == null || runningOfTheSameType.first() !== contentToReuse)) { val result = configuration.configuration.restartSingleton(environment) if (result == RestartSingletonResult.NO_FURTHER_ACTION) { return } if (result == RestartSingletonResult.ASK_AND_RESTART && !userApprovesStopForSameTypeConfigurations(environment.project, configuration.name, runningOfTheSameType.size)) { return } } if (runningIncompatible.isNotEmpty() && !userApprovesStopForIncompatibleConfigurations(project, configuration.name, runningIncompatible)) { return } } for (descriptor in runningToStop) { stopProcess(descriptor) } } if (awaitingRunProfiles[environment.runProfile] === environment) { // defense from rerunning exactly the same ExecutionEnvironment return } awaitingRunProfiles[environment.runProfile] = environment awaitTermination(object : Runnable { override fun run() { if (awaitingRunProfiles[environment.runProfile] !== environment) { // a new rerun has been requested before starting this one, ignore this rerun return } if ((configuration != null && !configuration.type.isDumbAware && DumbService.getInstance(project).isDumb) || inProgress.contains(InProgressEntry(environment.executor.id, environment.runner.runnerId))) { awaitTermination(this, 100) return } for (descriptor in runningOfTheSameType) { val processHandler = descriptor.processHandler if (processHandler != null && !processHandler.isProcessTerminated) { awaitTermination(this, 100) return } } awaitingRunProfiles.remove(environment.runProfile) // start() can be called during restartRunProfile() after pretty long 'awaitTermination()' so we have to check if the project is still here if (environment.project.isDisposed) { return } val settings = environment.runnerAndConfigurationSettings executeConfiguration(environment, settings != null && settings.isEditBeforeRun) } }, 50) } private class MyProcessHandler : ProcessHandler() { override fun destroyProcessImpl() {} override fun detachProcessImpl() {} override fun detachIsDefault(): Boolean { return false } override fun getProcessInput(): OutputStream? = null public override fun notifyProcessTerminated(exitCode: Int) { super.notifyProcessTerminated(exitCode) } } override fun executePreparationTasks(environment: ExecutionEnvironment, currentState: RunProfileState): Promise<Any?> { if (!(environment.runProfile is TargetEnvironmentAwareRunProfile)) { return resolvedPromise() } val targetEnvironmentAwareRunProfile = environment.runProfile as TargetEnvironmentAwareRunProfile if (!targetEnvironmentAwareRunProfile.needPrepareTarget()) { return resolvedPromise() } val processHandler = MyProcessHandler() val consoleView = TextConsoleBuilderFactory.getInstance().createBuilder(environment.project).console ProcessTerminatedListener.attach(processHandler) consoleView.attachToProcess(processHandler) val component = TargetPrepareComponent(consoleView) val buildContentManager = BuildContentManager.getInstance(environment.project) val contentName = targetEnvironmentAwareRunProfile.getEffectiveTargetName(environment.project)?.let { ExecutionBundle.message("tab.title.prepare.environment", it, environment.runProfile.name) } ?: ExecutionBundle.message("tab.title.prepare.target.environment", environment.runProfile.name) val toolWindow = buildContentManager.orCreateToolWindow val contentManager: ContentManager = toolWindow.contentManager val contentImpl = ContentImpl(component, contentName, true) contentImpl.putUserData(ToolWindow.SHOW_CONTENT_ICON, java.lang.Boolean.TRUE) contentImpl.icon = environment.runProfile.icon for (content in contentManager.contents) { if (contentName != content.displayName) continue if (content.isPinned) continue val contentComponent = content.component if (contentComponent !is TargetPrepareComponent) continue if (contentComponent.isPreparationFinished()) { contentManager.removeContent(content, true) } } contentManager.addContent(contentImpl) contentManager.setSelectedContent(contentImpl) toolWindow.activate(null) val promise = AsyncPromise<Any?>() ApplicationManager.getApplication().executeOnPooledThread { try { processHandler.startNotify() val targetProgressIndicator = object : TargetProgressIndicator { @Volatile var stopped = false override fun addText(text: @Nls String, key: Key<*>) { processHandler.notifyTextAvailable(text, key) } override fun isCanceled(): Boolean { return false } override fun stop() { stopped = true } override fun isStopped(): Boolean = stopped } promise.setResult(environment.prepareTargetEnvironment(currentState, targetProgressIndicator)) } catch (t: Throwable) { LOG.warn(t) promise.setError(ExecutionBundle.message("message.error.happened.0", t.localizedMessage)) processHandler.notifyTextAvailable(StringUtil.notNullize(t.localizedMessage), ProcessOutputType.STDERR) processHandler.notifyTextAvailable("\n", ProcessOutputType.STDERR) } finally { val exitCode = if (promise.isSucceeded) 0 else -1 processHandler.notifyProcessTerminated(exitCode) component.setPreparationFinished() } } return promise } @ApiStatus.Internal fun executeConfiguration(environment: ExecutionEnvironment, showSettings: Boolean, assignNewId: Boolean = true) { val runnerAndConfigurationSettings = environment.runnerAndConfigurationSettings val project = environment.project var runner = environment.runner if (runnerAndConfigurationSettings != null) { val targetManager = ExecutionTargetManager.getInstance(project) if (!targetManager.doCanRun(runnerAndConfigurationSettings.configuration, environment.executionTarget)) { ExecutionUtil.handleExecutionError(environment, ExecutionException(ProgramRunnerUtil.getCannotRunOnErrorMessage( environment.runProfile, environment.executionTarget))) processNotStarted(environment, null) return } if (!DumbService.isDumb(project)) { if (showSettings && runnerAndConfigurationSettings.isEditBeforeRun) { if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) { processNotStarted(environment, null) return } editConfigurationUntilSuccess(environment, assignNewId) } else { inProgress.add(InProgressEntry(environment.executor.id, environment.runner.runnerId)) ReadAction.nonBlocking(Callable { RunManagerImpl.canRunConfiguration(environment) }) .finishOnUiThread(ModalityState.NON_MODAL) { canRun -> inProgress.remove(InProgressEntry(environment.executor.id, environment.runner.runnerId)) if (canRun) { executeConfiguration(environment, environment.runner, assignNewId, this.project, environment.runnerAndConfigurationSettings) return@finishOnUiThread } if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) { processNotStarted(environment, null) return@finishOnUiThread } editConfigurationUntilSuccess(environment, assignNewId) } .expireWith(this) .submit(AppExecutorUtil.getAppExecutorService()) } return } } executeConfiguration(environment, runner, assignNewId, project, runnerAndConfigurationSettings) } private fun editConfigurationUntilSuccess(environment: ExecutionEnvironment, assignNewId: Boolean) { ReadAction.nonBlocking(Callable { RunManagerImpl.canRunConfiguration(environment) }) .finishOnUiThread(ModalityState.NON_MODAL) { canRun -> val runAnyway = if (!canRun) { val message = ExecutionBundle.message("dialog.message.configuration.still.incorrect.do.you.want.to.edit.it.again") val title = ExecutionBundle.message("dialog.title.change.configuration.settings") Messages.showYesNoDialog(project, message, title, CommonBundle.message("button.edit"), ExecutionBundle.message("run.continue.anyway"), Messages.getErrorIcon()) != Messages.YES } else true if (canRun || runAnyway) { val runner = ProgramRunner.getRunner(environment.executor.id, environment.runnerAndConfigurationSettings!!.configuration) if (runner == null) { ExecutionUtil.handleExecutionError(environment, ExecutionException(ExecutionBundle.message("dialog.message.cannot.find.runner", environment.runProfile.name))) } else { executeConfiguration(environment, runner, assignNewId, project, environment.runnerAndConfigurationSettings) } return@finishOnUiThread } if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) { processNotStarted(environment, null) return@finishOnUiThread } editConfigurationUntilSuccess(environment, assignNewId) } .expireWith(this) .submit(AppExecutorUtil.getAppExecutorService()) } private fun executeConfiguration(environment: ExecutionEnvironment, runner: @NotNull ProgramRunner<*>, assignNewId: Boolean, project: @NotNull Project, runnerAndConfigurationSettings: @Nullable RunnerAndConfigurationSettings?) { try { var effectiveEnvironment = environment if (runner != effectiveEnvironment.runner) { effectiveEnvironment = ExecutionEnvironmentBuilder(effectiveEnvironment).runner(runner).build() } if (assignNewId) { effectiveEnvironment.assignNewExecutionId() } runner.execute(effectiveEnvironment) } catch (e: ExecutionException) { ProgramRunnerUtil.handleExecutionError(project, environment, e, runnerAndConfigurationSettings?.configuration) } } override fun isStarting(executorId: String, runnerId: String): Boolean { return inProgress.contains(InProgressEntry(executorId, runnerId)) } private fun awaitTermination(request: Runnable, delayMillis: Long) { val app = ApplicationManager.getApplication() if (app.isUnitTestMode) { app.invokeLater(request, ModalityState.any()) } else { awaitingTerminationAlarm.addRequest(request, delayMillis) } } private fun getIncompatibleRunningDescriptors(configurationAndSettings: RunnerAndConfigurationSettings): List<RunContentDescriptor> { val configurationToCheckCompatibility = configurationAndSettings.configuration return getRunningDescriptors(Condition { runningConfigurationAndSettings -> val runningConfiguration = runningConfigurationAndSettings.configuration if (runningConfiguration is CompatibilityAwareRunProfile) { runningConfiguration.mustBeStoppedToRun(configurationToCheckCompatibility) } else { false } }) } fun getRunningDescriptors(condition: Condition<in RunnerAndConfigurationSettings>): List<RunContentDescriptor> { val result = SmartList<RunContentDescriptor>() for (entry in runningConfigurations) { if (entry.settings != null && condition.value(entry.settings)) { val processHandler = entry.descriptor.processHandler if (processHandler != null /*&& !processHandler.isProcessTerminating()*/ && !processHandler.isProcessTerminated) { result.add(entry.descriptor) } } } return result } fun getDescriptors(condition: Condition<in RunnerAndConfigurationSettings>): List<RunContentDescriptor> { val result = SmartList<RunContentDescriptor>() for (entry in runningConfigurations) { if (entry.settings != null && condition.value(entry.settings)) { result.add(entry.descriptor) } } return result } fun getExecutors(descriptor: RunContentDescriptor): Set<Executor> { val result = HashSet<Executor>() for (entry in runningConfigurations) { if (descriptor === entry.descriptor) { result.add(entry.executor) } } return result } fun getConfigurations(descriptor: RunContentDescriptor): Set<RunnerAndConfigurationSettings> { val result = HashSet<RunnerAndConfigurationSettings>() for (entry in runningConfigurations) { if (descriptor === entry.descriptor && entry.settings != null) { result.add(entry.settings) } } return result } } @ApiStatus.Internal fun RunnerAndConfigurationSettings.isOfSameType(runnerAndConfigurationSettings: RunnerAndConfigurationSettings): Boolean { if (this === runnerAndConfigurationSettings) return true val thisConfiguration = configuration val thatConfiguration = runnerAndConfigurationSettings.configuration if (thisConfiguration === thatConfiguration) return true if (this is RunnerAndConfigurationSettingsImpl && runnerAndConfigurationSettings is RunnerAndConfigurationSettingsImpl && this.filePathIfRunningCurrentFile != null) { // These are special run configurations, which are used for running 'Current File' (a special item in the combobox). They are not stored in RunManager. return this.filePathIfRunningCurrentFile == runnerAndConfigurationSettings.filePathIfRunningCurrentFile } if (thisConfiguration is UserDataHolder) { val originalRunProfile = DELEGATED_RUN_PROFILE_KEY[thisConfiguration] ?: return false if (originalRunProfile === thatConfiguration) return true if (thatConfiguration is UserDataHolder) return originalRunProfile === DELEGATED_RUN_PROFILE_KEY[thatConfiguration] } return false } private fun triggerUsage(environment: ExecutionEnvironment): StructuredIdeActivity? { val runConfiguration = environment.runnerAndConfigurationSettings?.configuration val configurationFactory = runConfiguration?.factory ?: return null return RunConfigurationUsageTriggerCollector.trigger(environment.project, configurationFactory, environment.executor, runConfiguration) } private fun createEnvironmentBuilder(project: Project, executor: Executor, configuration: RunnerAndConfigurationSettings?): ExecutionEnvironmentBuilder { val builder = ExecutionEnvironmentBuilder(project, executor) val runner = configuration?.let { ProgramRunner.getRunner(executor.id, it.configuration) } if (runner == null && configuration != null) { ExecutionManagerImpl.LOG.error("Cannot find runner for ${configuration.name}") } else if (runner != null) { builder.runnerAndSettings(runner, configuration) } return builder } private fun userApprovesStopForSameTypeConfigurations(project: Project, configName: String, instancesCount: Int): Boolean { val config = RunManagerImpl.getInstanceImpl(project).config if (!config.isRestartRequiresConfirmation) { return true } @Suppress("DuplicatedCode") val option = object : DialogWrapper.DoNotAskOption { override fun isToBeShown() = config.isRestartRequiresConfirmation override fun setToBeShown(value: Boolean, exitCode: Int) { config.isRestartRequiresConfirmation = value } override fun canBeHidden() = true override fun shouldSaveOptionsOnCancel() = false override fun getDoNotShowMessage(): String { return UIBundle.message("dialog.options.do.not.show") } } return Messages.showOkCancelDialog( project, ExecutionBundle.message("rerun.singleton.confirmation.message", configName, instancesCount), ExecutionBundle.message("process.is.running.dialog.title", configName), ExecutionBundle.message("rerun.confirmation.button.text"), CommonBundle.getCancelButtonText(), Messages.getQuestionIcon(), option) == Messages.OK } private fun userApprovesStopForIncompatibleConfigurations(project: Project, configName: String, runningIncompatibleDescriptors: List<RunContentDescriptor>): Boolean { val config = RunManagerImpl.getInstanceImpl(project).config if (!config.isStopIncompatibleRequiresConfirmation) { return true } @Suppress("DuplicatedCode") val option = object : DialogWrapper.DoNotAskOption { override fun isToBeShown() = config.isStopIncompatibleRequiresConfirmation override fun setToBeShown(value: Boolean, exitCode: Int) { config.isStopIncompatibleRequiresConfirmation = value } override fun canBeHidden() = true override fun shouldSaveOptionsOnCancel() = false override fun getDoNotShowMessage(): String { return UIBundle.message("dialog.options.do.not.show") } } val names = StringBuilder() for (descriptor in runningIncompatibleDescriptors) { val name = descriptor.displayName if (names.isNotEmpty()) { names.append(", ") } names.append(if (name.isNullOrEmpty()) ExecutionBundle.message("run.configuration.no.name") else String.format("'%s'", name)) } return Messages.showOkCancelDialog( project, ExecutionBundle.message("stop.incompatible.confirmation.message", configName, names.toString(), runningIncompatibleDescriptors.size), ExecutionBundle.message("incompatible.configuration.is.running.dialog.title", runningIncompatibleDescriptors.size), ExecutionBundle.message("stop.incompatible.confirmation.button.text"), CommonBundle.getCancelButtonText(), Messages.getQuestionIcon(), option) == Messages.OK } private class ProcessExecutionListener(private val project: Project, private val executorId: String, private val environment: ExecutionEnvironment, private val processHandler: ProcessHandler, private val descriptor: RunContentDescriptor, private val activity: StructuredIdeActivity?) : ProcessAdapter() { private val willTerminateNotified = AtomicBoolean() private val terminateNotified = AtomicBoolean() override fun processTerminated(event: ProcessEvent) { if (project.isDisposed || !terminateNotified.compareAndSet(false, true)) { return } ApplicationManager.getApplication().invokeLater(Runnable { val ui = descriptor.runnerLayoutUi if (ui != null && !ui.isDisposed) { ui.updateActionsNow() } }, ModalityState.any(), project.disposed) project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processTerminated(executorId, environment, processHandler, event.exitCode) val runConfigurationFinishType = if (event.processHandler.getUserData(ProcessHandler.TERMINATION_REQUESTED) == true) RunConfigurationFinishType.TERMINATED else RunConfigurationFinishType.UNKNOWN RunConfigurationUsageTriggerCollector.logProcessFinished(activity, runConfigurationFinishType) processHandler.removeProcessListener(this) SaveAndSyncHandler.getInstance().scheduleRefresh() } override fun processWillTerminate(event: ProcessEvent, shouldNotBeUsed: Boolean) { if (project.isDisposed || !willTerminateNotified.compareAndSet(false, true)) { return } project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processTerminating(executorId, environment, processHandler) } } private data class InProgressEntry(val executorId: String, val runnerId: String) private data class RunningConfigurationEntry(val descriptor: RunContentDescriptor, val settings: RunnerAndConfigurationSettings?, val executor: Executor) private class TargetPrepareComponent(val console: ConsoleView) : JPanel(BorderLayout()), Disposable { init { add(console.component, BorderLayout.CENTER) } @Volatile private var finished = false fun isPreparationFinished() = finished fun setPreparationFinished() { finished = true } override fun dispose() { Disposer.dispose(console) } }
platform/execution-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.kt
3175845155
package com.github.vhromada.catalog.domain import javax.persistence.Column import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.SequenceGenerator import javax.persistence.Table /** * A class represents song. * * @author Vladimir Hromada */ @Entity @Table(name = "songs") @Suppress("JpaDataSourceORMInspection") data class Song( /** * ID */ @Id @SequenceGenerator(name = "song_generator", sequenceName = "songs_sq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "song_generator") var id: Int?, /** * UUID */ val uuid: String, /** * Name */ @Column(name = "song_name") var name: String, /** * Length */ @Column(name = "song_length") var length: Int, /** * Note */ var note: String?, /** * Music */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "music") var music: Music? = null ) : Audit() { /** * Merges song. * * @param song song */ fun merge(song: Song) { name = song.name length = song.length note = song.note } override fun toString(): String { return "Song(id=$id, uuid=$uuid, name=$name, length=$length, note=$note, music=${music?.id})" } }
core/src/main/kotlin/com/github/vhromada/catalog/domain/Song.kt
2475779993
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mockwebserver3 import java.io.IOException import java.net.Inet6Address import java.net.Socket import javax.net.ssl.SSLSocket import okhttp3.Handshake import okhttp3.Handshake.Companion.handshake import okhttp3.Headers import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.TlsVersion import okio.Buffer /** An HTTP request that came into the mock web server. */ class RecordedRequest @JvmOverloads constructor( val requestLine: String, /** All headers. */ val headers: Headers, /** * The sizes of the chunks of this request's body, or an empty list if the request's body * was empty or unchunked. */ val chunkSizes: List<Int>, /** The total size of the body of this POST request (before truncation).*/ val bodySize: Long, /** The body of this POST request. This may be truncated. */ val body: Buffer, /** * The index of this request on its HTTP connection. Since a single HTTP connection may serve * multiple requests, each request is assigned its own sequence number. */ val sequenceNumber: Int, socket: Socket, /** * The failure MockWebServer recorded when attempting to decode this request. If, for example, * the inbound request was truncated, this exception will be non-null. */ val failure: IOException? = null ) { val method: String? val path: String? /** * The TLS handshake of the connection that carried this request, or null if the request was * received without TLS. */ val handshake: Handshake? val requestUrl: HttpUrl? @get:JvmName("-deprecated_utf8Body") @Deprecated( message = "Use body.readUtf8()", replaceWith = ReplaceWith("body.readUtf8()"), level = DeprecationLevel.ERROR) val utf8Body: String get() = body.readUtf8() /** Returns the connection's TLS version or null if the connection doesn't use SSL. */ val tlsVersion: TlsVersion? get() = handshake?.tlsVersion init { if (socket is SSLSocket) { try { this.handshake = socket.session.handshake() } catch (e: IOException) { throw IllegalArgumentException(e) } } else { this.handshake = null } if (requestLine.isNotEmpty()) { val methodEnd = requestLine.indexOf(' ') val pathEnd = requestLine.indexOf(' ', methodEnd + 1) this.method = requestLine.substring(0, methodEnd) var path = requestLine.substring(methodEnd + 1, pathEnd) if (!path.startsWith("/")) { path = "/" } this.path = path val scheme = if (socket is SSLSocket) "https" else "http" val localPort = socket.localPort val hostAndPort = headers[":authority"] ?: headers["Host"] ?: when (val inetAddress = socket.localAddress) { is Inet6Address -> "[${inetAddress.hostAddress}]:$localPort" else -> "${inetAddress.hostAddress}:$localPort" } // Allow null in failure case to allow for testing bad requests this.requestUrl = "$scheme://$hostAndPort$path".toHttpUrlOrNull() } else { this.requestUrl = null this.method = null this.path = null } } @Deprecated( message = "Use body.readUtf8()", replaceWith = ReplaceWith("body.readUtf8()"), level = DeprecationLevel.WARNING) fun getUtf8Body(): String = body.readUtf8() /** Returns the first header named [name], or null if no such header exists. */ fun getHeader(name: String): String? = headers.values(name).firstOrNull() override fun toString(): String = requestLine }
mockwebserver/src/main/kotlin/mockwebserver3/RecordedRequest.kt
2257983369
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.checkin import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.actions.AbstractLayoutCodeProcessor import com.intellij.codeInsight.actions.RearrangeCodeProcessor import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.getPsiFiles import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.openapi.vfs.VirtualFile class RearrangeCheckinHandlerFactory : CheckinHandlerFactory() { override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler = RearrangeBeforeCheckinHandler(panel.project) } class RearrangeBeforeCheckinHandler(project: Project) : CodeProcessorCheckinHandler(project) { override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent = BooleanCommitOption(project, VcsBundle.message("checkbox.checkin.options.rearrange.code"), true, settings::REARRANGE_BEFORE_PROJECT_COMMIT) .withCheckinHandler(this) override fun isEnabled(): Boolean = settings.REARRANGE_BEFORE_PROJECT_COMMIT override fun getProgressMessage(): String = VcsBundle.message("progress.text.rearranging.code") override fun createCodeProcessor(files: List<VirtualFile>): AbstractLayoutCodeProcessor = RearrangeCodeProcessor(project, getPsiFiles(project, files), COMMAND_NAME, null, true) companion object { @JvmField @NlsSafe val COMMAND_NAME: String = CodeInsightBundle.message("process.rearrange.code.before.commit") } }
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/RearrangeBeforeCheckinHandler.kt
2159954936
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.data.session.json import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.samples.apps.iosched.model.Speaker import java.lang.reflect.Type /** * Deserializer for [Speaker]s. */ class SpeakerDeserializer : JsonDeserializer<Speaker> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext? ): Speaker { val obj = json?.asJsonObject!! val social = obj.getAsJsonObject("socialLinks") return Speaker( id = obj.get("id").asString, name = obj.get("name").asString, imageUrl = obj.get("thumbnailUrl")?.asString ?: "", company = obj.get("company")?.asString ?: "", biography = obj.get("bio")?.asString ?: "", websiteUrl = social?.get("Website")?.asString, twitterUrl = social?.get("Twitter")?.asString, githubUrl = social?.get("GitHub")?.asString, linkedInUrl = social?.get("LinkedIn")?.asString ) } }
shared/src/main/java/com/google/samples/apps/iosched/shared/data/session/json/SpeakerDeserializer.kt
3552769146
package io.github.chrislo27.rhre3.util import com.badlogic.gdx.graphics.Color import io.github.chrislo27.toolboks.transition.Transition import io.github.chrislo27.toolboks.transition.TransitionScreen import io.github.chrislo27.toolboks.util.gdxutils.fillRect /** * Fades TO the specified colour to opaque. */ class FadeOut(duration: Float, val color: Color) : Transition(duration) { override fun render(transitionScreen: TransitionScreen<*>, screenRender: () -> Unit) { screenRender() val batch = transitionScreen.main.batch batch.begin() batch.setColor(color.r, color.g, color.b, color.a * transitionScreen.percentageCurrent) batch.fillRect(0f, 0f, transitionScreen.main.defaultCamera.viewportWidth * 1f, transitionScreen.main.defaultCamera.viewportHeight * 1f) batch.setColor(1f, 1f, 1f, 1f) batch.end() } override fun dispose() { } } /** * Fades AWAY from the specified colour to transparent */ class FadeIn(duration: Float, val color: Color) : Transition(duration) { override fun render(transitionScreen: TransitionScreen<*>, screenRender: () -> Unit) { screenRender() val batch = transitionScreen.main.batch batch.begin() batch.setColor(color.r, color.g, color.b, color.a * (1f - transitionScreen.percentageCurrent)) batch.fillRect(0f, 0f, transitionScreen.main.defaultCamera.viewportWidth * 1f, transitionScreen.main.defaultCamera.viewportHeight * 1f) batch.setColor(1f, 1f, 1f, 1f) batch.end() } override fun dispose() { } }
core/src/main/kotlin/io/github/chrislo27/rhre3/util/Fades.kt
237703557
import org.junit.Ignore import org.junit.Test import java.time.DayOfWeek import java.time.LocalDate import kotlin.test.assertEquals class MeetupTest { @Test fun testMonteenthOfMay2013() { val expected = LocalDate.of(2013, 5, 13) val meetup = Meetup(5, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testMonteenthOfAugust2013() { val expected = LocalDate.of(2013, 8, 19) val meetup = Meetup(8, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testMonteenthOfSeptember2013() { val expected = LocalDate.of(2013, 9, 16) val meetup = Meetup(9, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testTuesteenthOfMarch2013() { val expected = LocalDate.of(2013, 3, 19) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testTuesteenthOfApril2013() { val expected = LocalDate.of(2013, 4, 16) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testTuesteenthOfAugust2013() { val expected = LocalDate.of(2013, 8, 13) val meetup = Meetup(8, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testWednesteenthOfJanuary2013() { val expected = LocalDate.of(2013, 1, 16) val meetup = Meetup(1, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testWednesteenthOfFebruary2013() { val expected = LocalDate.of(2013, 2, 13) val meetup = Meetup(2, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testWednesteenthOfJune2013() { val expected = LocalDate.of(2013, 6, 19) val meetup = Meetup(6, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testThursteenthOfMay2013() { val expected = LocalDate.of(2013, 5, 16) val meetup = Meetup(5, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testThursteenthOfJune2013() { val expected = LocalDate.of(2013, 6, 13) val meetup = Meetup(6, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testThursteenthOfSeptember2013() { val expected = LocalDate.of(2013, 9, 19) val meetup = Meetup(9, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testFriteenthOfApril2013() { val expected = LocalDate.of(2013, 4, 19) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testFriteenthOfAugust2013() { val expected = LocalDate.of(2013, 8, 16) val meetup = Meetup(8, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testFriteenthOfSeptember2013() { val expected = LocalDate.of(2013, 9, 13) val meetup = Meetup(9, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testSaturteenthOfFebruary2013() { val expected = LocalDate.of(2013, 2, 16) val meetup = Meetup(2, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testSaturteenthOfApril2013() { val expected = LocalDate.of(2013, 4, 13) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testSaturteenthOfOctober2013() { val expected = LocalDate.of(2013, 10, 19) val meetup = Meetup(10, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testSunteenthOfMay2013() { val expected = LocalDate.of(2013, 5, 19) val meetup = Meetup(5, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testSunteenthOfJune2013() { val expected = LocalDate.of(2013, 6, 16) val meetup = Meetup(6, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testSunteenthOfOctober2013() { val expected = LocalDate.of(2013, 10, 13) val meetup = Meetup(10, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.TEENTH)) } @Ignore @Test fun testFirstMondayOfMarch2013() { val expected = LocalDate.of(2013, 3, 4) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstMondayOfApril2013() { val expected = LocalDate.of(2013, 4, 1) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstTuesdayOfMay2013() { val expected = LocalDate.of(2013, 5, 7) val meetup = Meetup(5, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstTuesdayOfJune2013() { val expected = LocalDate.of(2013, 6, 4) val meetup = Meetup(6, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstWednesdayOfJuly2013() { val expected = LocalDate.of(2013, 7, 3) val meetup = Meetup(7, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstWednesdayOfAugust2013() { val expected = LocalDate.of(2013, 8, 7) val meetup = Meetup(8, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstThursdayOfSeptember2013() { val expected = LocalDate.of(2013, 9, 5) val meetup = Meetup(9, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstThursdayOfOctober2013() { val expected = LocalDate.of(2013, 10, 3) val meetup = Meetup(10, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstFridayOfNovember2013() { val expected = LocalDate.of(2013, 11, 1) val meetup = Meetup(11, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstFridayOfDecember2013() { val expected = LocalDate.of(2013, 12, 6) val meetup = Meetup(12, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstSaturdayOfJanuary2013() { val expected = LocalDate.of(2013, 1, 5) val meetup = Meetup(1, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstSaturdayOfFebruary2013() { val expected = LocalDate.of(2013, 2, 2) val meetup = Meetup(2, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstSundayOfMarch2013() { val expected = LocalDate.of(2013, 3, 3) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testFirstSundayOfApril2013() { val expected = LocalDate.of(2013, 4, 7) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FIRST)) } @Ignore @Test fun testSecondMondayOfMarch2013() { val expected = LocalDate.of(2013, 3, 11) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondMondayOfApril2013() { val expected = LocalDate.of(2013, 4, 8) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondTuesdayOfMay2013() { val expected = LocalDate.of(2013, 5, 14) val meetup = Meetup(5, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondTuesdayOfJune2013() { val expected = LocalDate.of(2013, 6, 11) val meetup = Meetup(6, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondWednesdayOfJuly2013() { val expected = LocalDate.of(2013, 7, 10) val meetup = Meetup(7, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondWednesdayOfAugust2013() { val expected = LocalDate.of(2013, 8, 14) val meetup = Meetup(8, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondThursdayOfSeptember2013() { val expected = LocalDate.of(2013, 9, 12) val meetup = Meetup(9, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondThursdayOfOctober2013() { val expected = LocalDate.of(2013, 10, 10) val meetup = Meetup(10, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondFridayOfNovember2013() { val expected = LocalDate.of(2013, 11, 8) val meetup = Meetup(11, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondFridayOfDecember2013() { val expected = LocalDate.of(2013, 12, 13) val meetup = Meetup(12, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondSaturdayOfJanuary2013() { val expected = LocalDate.of(2013, 1, 12) val meetup = Meetup(1, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondSaturdayOfFebruary2013() { val expected = LocalDate.of(2013, 2, 9) val meetup = Meetup(2, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondSundayOfMarch2013() { val expected = LocalDate.of(2013, 3, 10) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testSecondSundayOfApril2013() { val expected = LocalDate.of(2013, 4, 14) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.SECOND)) } @Ignore @Test fun testThirdMondayOfMarch2013() { val expected = LocalDate.of(2013, 3, 18) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdMondayOfApril2013() { val expected = LocalDate.of(2013, 4, 15) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdTuesdayOfMay2013() { val expected = LocalDate.of(2013, 5, 21) val meetup = Meetup(5, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdTuesdayOfJune2013() { val expected = LocalDate.of(2013, 6, 18) val meetup = Meetup(6, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdWednesdayOfJuly2013() { val expected = LocalDate.of(2013, 7, 17) val meetup = Meetup(7, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdWednesdayOfAugust2013() { val expected = LocalDate.of(2013, 8, 21) val meetup = Meetup(8, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdThursdayOfSeptember2013() { val expected = LocalDate.of(2013, 9, 19) val meetup = Meetup(9, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdThursdayOfOctober2013() { val expected = LocalDate.of(2013, 10, 17) val meetup = Meetup(10, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdFridayOfNovember2013() { val expected = LocalDate.of(2013, 11, 15) val meetup = Meetup(11, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdFridayOfDecember2013() { val expected = LocalDate.of(2013, 12, 20) val meetup = Meetup(12, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdSaturdayOfJanuary2013() { val expected = LocalDate.of(2013, 1, 19) val meetup = Meetup(1, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdSaturdayOfFebruary2013() { val expected = LocalDate.of(2013, 2, 16) val meetup = Meetup(2, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdSundayOfMarch2013() { val expected = LocalDate.of(2013, 3, 17) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testThirdSundayOfApril2013() { val expected = LocalDate.of(2013, 4, 21) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.THIRD)) } @Ignore @Test fun testFourthMondayOfMarch2013() { val expected = LocalDate.of(2013, 3, 25) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthMondayOfApril2013() { val expected = LocalDate.of(2013, 4, 22) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthTuesdayOfMay2013() { val expected = LocalDate.of(2013, 5, 28) val meetup = Meetup(5, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthTuesdayOfJune2013() { val expected = LocalDate.of(2013, 6, 25) val meetup = Meetup(6, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthWednesdayOfJuly2013() { val expected = LocalDate.of(2013, 7, 24) val meetup = Meetup(7, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthWednesdayOfAugust2013() { val expected = LocalDate.of(2013, 8, 28) val meetup = Meetup(8, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthThursdayOfSeptember2013() { val expected = LocalDate.of(2013, 9, 26) val meetup = Meetup(9, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthThursdayOfOctober2013() { val expected = LocalDate.of(2013, 10, 24) val meetup = Meetup(10, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthFridayOfNovember2013() { val expected = LocalDate.of(2013, 11, 22) val meetup = Meetup(11, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthFridayOfDecember2013() { val expected = LocalDate.of(2013, 12, 27) val meetup = Meetup(12, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthSaturdayOfJanuary2013() { val expected = LocalDate.of(2013, 1, 26) val meetup = Meetup(1, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthSaturdayOfFebruary2013() { val expected = LocalDate.of(2013, 2, 23) val meetup = Meetup(2, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthSundayOfMarch2013() { val expected = LocalDate.of(2013, 3, 24) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testFourthSundayOfApril2013() { val expected = LocalDate.of(2013, 4, 28) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FOURTH)) } @Ignore @Test fun testLastMondayOfMarch2013() { val expected = LocalDate.of(2013, 3, 25) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastMondayOfApril2013() { val expected = LocalDate.of(2013, 4, 29) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.MONDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastTuesdayOfMay2013() { val expected = LocalDate.of(2013, 5, 28) val meetup = Meetup(5, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastTuesdayOfJune2013() { val expected = LocalDate.of(2013, 6, 25) val meetup = Meetup(6, 2013) assertEquals(expected, meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastWednesdayOfJuly2013() { val expected = LocalDate.of(2013, 7, 31) val meetup = Meetup(7, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastWednesdayOfAugust2013() { val expected = LocalDate.of(2013, 8, 28) val meetup = Meetup(8, 2013) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastThursdayOfSeptember2013() { val expected = LocalDate.of(2013, 9, 26) val meetup = Meetup(9, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastThursdayOfOctober2013() { val expected = LocalDate.of(2013, 10, 31) val meetup = Meetup(10, 2013) assertEquals(expected, meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastFridayOfNovember2013() { val expected = LocalDate.of(2013, 11, 29) val meetup = Meetup(11, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastFridayOfDecember2013() { val expected = LocalDate.of(2013, 12, 27) val meetup = Meetup(12, 2013) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastSaturdayOfJanuary2013() { val expected = LocalDate.of(2013, 1, 26) val meetup = Meetup(1, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastSaturdayOfFebruary2013() { val expected = LocalDate.of(2013, 2, 23) val meetup = Meetup(2, 2013) assertEquals(expected, meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastSundayOfMarch2013() { val expected = LocalDate.of(2013, 3, 31) val meetup = Meetup(3, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastSundayOfApril2013() { val expected = LocalDate.of(2013, 4, 28) val meetup = Meetup(4, 2013) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastWednesdayOfFebruary2012() { val expected = LocalDate.of(2012, 2, 29) val meetup = Meetup(2, 2012) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastWednesdayOfDecember2014() { val expected = LocalDate.of(2014, 12, 31) val meetup = Meetup(12, 2014) assertEquals(expected, meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testLastSundayOfFebruary2015() { val expected = LocalDate.of(2015, 2, 22) val meetup = Meetup(2, 2015) assertEquals(expected, meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.LAST)) } @Ignore @Test fun testFirstFridayOfDecember2012() { val expected = LocalDate.of(2012, 12, 7) val meetup = Meetup(12, 2012) assertEquals(expected, meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FIRST)) } }
exercises/practice/meetup/src/test/kotlin/MeetupTest.kt
3389159695
package ch.difty.scipamato.core.persistence.user import ch.difty.scipamato.common.persistence.AbstractFilterConditionMapper import ch.difty.scipamato.common.persistence.FilterConditionMapper import ch.difty.scipamato.core.db.tables.ScipamatoUser import ch.difty.scipamato.core.entity.search.UserFilter import org.jooq.Condition /** * Mapper turning the provider [UserFilter] into a jOOQ [Condition]. */ @FilterConditionMapper class UserFilterConditionMapper : AbstractFilterConditionMapper<UserFilter>() { override fun internalMap(filter: UserFilter): List<Condition> { val conditions = mutableListOf<Condition>() filter.nameMask?.let { val likeExpression = "%$it%" conditions.add( ScipamatoUser.SCIPAMATO_USER.USER_NAME.likeIgnoreCase(likeExpression) .or(ScipamatoUser.SCIPAMATO_USER.FIRST_NAME.likeIgnoreCase(likeExpression)) .or(ScipamatoUser.SCIPAMATO_USER.LAST_NAME.likeIgnoreCase(likeExpression)) ) } filter.emailMask?.let { conditions.add(ScipamatoUser.SCIPAMATO_USER.EMAIL.likeIgnoreCase("%$it%")) } filter.enabled?.let { conditions.add(ScipamatoUser.SCIPAMATO_USER.ENABLED.eq(it)) } return conditions } }
core/core-persistence-jooq/src/main/java/ch/difty/scipamato/core/persistence/user/UserFilterConditionMapper.kt
2155507389
// 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.java.codeInspection.enhancedSwitch import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.enhancedSwitch.SwitchLabeledRuleCanBeCodeBlockInspection /** * @author Pavel.Dolgov */ class SwitchLabeledRuleCanBeCodeBlockFixTest : LightQuickFixParameterizedTestCase() { override fun configureLocalInspectionTools(): Array<LocalInspectionTool> = arrayOf(SwitchLabeledRuleCanBeCodeBlockInspection()) override fun getBasePath() = "/inspection/switchLabeledRuleCanBeCodeBlockFix" }
java/java-tests/testSrc/com/intellij/java/codeInspection/enhancedSwitch/SwitchLabeledRuleCanBeCodeBlockFixTest.kt
81611982
package ch.difty.scipamato.core.web.paper.entry import ch.difty.scipamato.common.web.Mode import ch.difty.scipamato.core.entity.Paper.NewsletterLink import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapButton import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.BootstrapDefaultDataTable import io.mockk.verify import org.amshove.kluent.shouldBeTrue import org.apache.wicket.markup.html.form.Form import org.junit.jupiter.api.Test @Suppress("SpellCheckingInspection") internal class EditablePaperPanelInViewModeTest : EditablePaperPanelTest() { override val mode: Mode get() = Mode.VIEW override fun assertSpecificComponents() { var b = PANEL_ID tester.assertComponent(b, EditablePaperPanel::class.java) assertCommonComponents(b) b += ":form" assertTextFieldWithLabel("$b:id", 1L, "ID") assertTextFieldWithLabel("$b:number", 100L, "SciPaMaTo-Core-No.") assertTextFieldWithLabel("$b:publicationYear", 2017, "Pub. Year") assertTextFieldWithLabel("$b:pmId", 1234, "PMID") tester.assertInvisible("$b:submit") assertTextFieldWithLabel("$b:createdDisplayValue", "u1 (2017-02-01 13:34:45)", "Created") assertTextFieldWithLabel("$b:modifiedDisplayValue", "u2 (2017-03-01 13:34:45)", "Last Modified") tester.assertComponent("$b:back", BootstrapButton::class.java) tester.assertComponent("$b:previous", BootstrapButton::class.java) tester.assertComponent("$b:next", BootstrapButton::class.java) // disabled as paperManagerMock is not mocked here tester.isDisabled("$b:previous") tester.isDisabled("$b:next") tester.assertInvisible("$b:exclude") tester.assertInvisible("$b:pubmedRetrieval") tester.assertInvisible("$b:modAssociation") tester.clickLink("panel:form:tabs:tabs-container:tabs:5:link") val bb = "$b:tabs:panel:tab6Form" tester.assertInvisible("$bb:dropzone") tester.assertComponent("$bb:attachments", BootstrapDefaultDataTable::class.java) tester.assertComponent(bb, Form::class.java) verifyCodeAndCodeClassCalls(1, 1) verify(exactly = 2) { paperServiceMock.findPageOfIdsByFilter(any(), any()) } } @Test fun isAssociatedWithNewsletter_withNewsletterLink() { val p = makePanel() p.modelObject.newsletterLink = NewsletterLink(1, "i1", 1, 1, "t1", "hl") p.isAssociatedWithNewsletter.shouldBeTrue() } @Test override fun specificFields_areDisabled() { tester.startComponentInPage(makePanel()) tester.isDisabled("panel:form:id") tester.isDisabled("panel:form:firstAuthorOverridden") tester.isDisabled("panel:form:createdDisplayValue") tester.isDisabled("panel:form:modifiedDisplayValue") verify(exactly = 2) { paperServiceMock.findPageOfIdsByFilter(any(), any()) } } }
core/core-web/src/test/kotlin/ch/difty/scipamato/core/web/paper/entry/EditablePaperPanelInViewModeTest.kt
1080393309
// 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 git4idea.repo import com.intellij.dvcs.repo.Repository import com.intellij.vcs.log.Hash import git4idea.GitLocalBranch import git4idea.GitReference import git4idea.GitRemoteBranch import gnu.trove.THashMap import org.jetbrains.annotations.NonNls data class GitRepoInfo(val currentBranch: GitLocalBranch?, val currentRevision: String?, val state: Repository.State, val remotes: Collection<GitRemote>, val localBranchesWithHashes: Map<GitLocalBranch, Hash>, val remoteBranchesWithHashes: Map<GitRemoteBranch, Hash>, val branchTrackInfos: Collection<GitBranchTrackInfo>, val submodules: Collection<GitSubmoduleInfo>, val hooksInfo: GitHooksInfo, val isShallow: Boolean) { val branchTrackInfosMap = THashMap<String, GitBranchTrackInfo>(GitReference.BRANCH_NAME_HASHING_STRATEGY).apply { branchTrackInfos.associateByTo(this) { it.localBranch.name } } val remoteBranches: Collection<GitRemoteBranch> @Deprecated("") get() = remoteBranchesWithHashes.keys @NonNls override fun toString() = "GitRepoInfo{current=$currentBranch, remotes=$remotes, localBranches=$localBranchesWithHashes, " + "remoteBranches=$remoteBranchesWithHashes, trackInfos=$branchTrackInfos, submodules=$submodules, hooks=$hooksInfo}" }
plugins/git4idea/src/git4idea/repo/GitRepoInfo.kt
4060112011
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.androidsdk.crypto.verification import android.os.Handler import android.os.Looper import org.matrix.androidsdk.core.JsonUtility import org.matrix.androidsdk.core.Log import org.matrix.androidsdk.core.callback.ApiCallback import org.matrix.androidsdk.core.model.MatrixError import org.matrix.androidsdk.crypto.MXCrypto import org.matrix.androidsdk.crypto.data.MXDeviceInfo import org.matrix.androidsdk.crypto.data.MXUsersDevicesMap import org.matrix.androidsdk.crypto.interfaces.CryptoEvent import org.matrix.androidsdk.crypto.interfaces.CryptoSession import org.matrix.androidsdk.crypto.rest.model.crypto.* import java.util.* import kotlin.collections.HashMap /** * Manages all current verifications transactions with short codes. * Short codes interactive verification is a more user friendly way of verifying devices * that is still maintaining a good level of security (alternative to the 43-character strings compare method). */ class VerificationManager ( private val session: CryptoSession, private val mxCrypto: MXCrypto ) : VerificationTransaction.Listener { interface VerificationManagerListener { fun transactionCreated(tx: VerificationTransaction) fun transactionUpdated(tx: VerificationTransaction) fun markedAsManuallyVerified(userId: String, deviceId: String) } private val uiHandler = Handler(Looper.getMainLooper()) // map [sender : [transaction]] private val txMap = HashMap<String, HashMap<String, VerificationTransaction>>() // Event received from the sync fun onToDeviceEvent(event: CryptoEvent) { mxCrypto.getDecryptingThreadHandler().post { when (event.getType()) { CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_START -> { onStartRequestReceived(event) } CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_CANCEL -> { onCancelReceived(event) } CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_ACCEPT -> { onAcceptReceived(event) } CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_KEY -> { onKeyReceived(event) } CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_MAC -> { onMacReceived(event) } else -> { //ignore } } } } private var listeners = ArrayList<VerificationManagerListener>() fun addListener(listener: VerificationManagerListener) { uiHandler.post { if (!listeners.contains(listener)) { listeners.add(listener) } } } fun removeListener(listener: VerificationManagerListener) { uiHandler.post { listeners.remove(listener) } } private fun dispatchTxAdded(tx: VerificationTransaction) { uiHandler.post { listeners.forEach { try { it.transactionCreated(tx) } catch (e: Throwable) { Log.e(LOG_TAG, "## Error while notifying listeners", e) } } } } private fun dispatchTxUpdated(tx: VerificationTransaction) { uiHandler.post { listeners.forEach { try { it.transactionUpdated(tx) } catch (e: Throwable) { Log.e(LOG_TAG, "## Error while notifying listeners", e) } } } } fun markedLocallyAsManuallyVerified(userId: String, deviceID: String) { mxCrypto.setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED, deviceID, userId, object : ApiCallback<Void> { override fun onSuccess(info: Void?) { uiHandler.post { listeners.forEach { try { it.markedAsManuallyVerified(userId, deviceID) } catch (e: Throwable) { Log.e(LOG_TAG, "## Error while notifying listeners", e) } } } } override fun onUnexpectedError(e: Exception?) { Log.e(SASVerificationTransaction.LOG_TAG, "## Manual verification failed in state", e) } override fun onNetworkError(e: Exception?) { Log.e(SASVerificationTransaction.LOG_TAG, "## Manual verification failed in state", e) } override fun onMatrixError(e: MatrixError?) { Log.e(SASVerificationTransaction.LOG_TAG, "## Manual verification failed in state " + e?.mReason) } }) } private fun onStartRequestReceived(event: CryptoEvent) { val startReq = JsonUtility.getBasicGson() .fromJson(event.content, KeyVerificationStart::class.java) val otherUserId = event.getSender() if (!startReq.isValid()) { Log.e(SASVerificationTransaction.LOG_TAG, "## received invalid verification request") if (startReq.transactionID != null) { cancelTransaction( session, startReq.transactionID!!, otherUserId, startReq?.fromDevice ?: event.senderKey, CancelCode.UnknownMethod ) } return } //Download device keys prior to everything checkKeysAreDownloaded( session, otherUserId, startReq, success = { Log.d(SASVerificationTransaction.LOG_TAG, "## SAS onStartRequestReceived ${startReq.transactionID!!}") val tid = startReq.transactionID!! val existing = getExistingTransaction(otherUserId, tid) val existingTxs = getExistingTransactionsForUser(otherUserId) if (existing != null) { //should cancel both! Log.d(SASVerificationTransaction.LOG_TAG, "## SAS onStartRequestReceived - Request exist with same if ${startReq.transactionID!!}") existing.cancel(session, CancelCode.UnexpectedMessage) cancelTransaction(session, tid, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) } else if (existingTxs?.isEmpty() == false) { Log.d(SASVerificationTransaction.LOG_TAG, "## SAS onStartRequestReceived - There is already a transaction with this user ${startReq.transactionID!!}") //Multiple keyshares between two devices: any two devices may only have at most one key verification in flight at a time. existingTxs.forEach { it.cancel(session, CancelCode.UnexpectedMessage) } cancelTransaction(session, tid, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) } else { //Ok we can create if (KeyVerificationStart.VERIF_METHOD_SAS == startReq.method) { Log.d(SASVerificationTransaction.LOG_TAG, "## SAS onStartRequestReceived - request accepted ${startReq.transactionID!!}") val tx = IncomingSASVerificationTransaction(startReq.transactionID!!, otherUserId) addTransaction(tx) tx.acceptToDeviceEvent(session, otherUserId, startReq) } else { Log.e(SASVerificationTransaction.LOG_TAG, "## SAS onStartRequestReceived - unknown method ${startReq.method}") cancelTransaction(session, tid, otherUserId, startReq.fromDevice ?: event.senderKey, CancelCode.UnknownMethod) } } }, error = { cancelTransaction(session, startReq.transactionID!!, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) }) } private fun checkKeysAreDownloaded(session: CryptoSession, otherUserId: String, startReq: KeyVerificationStart, success: (MXUsersDevicesMap<MXDeviceInfo>) -> Unit, error: () -> Unit) { mxCrypto.getDeviceList().downloadKeys(listOf(otherUserId), true, object : ApiCallback<MXUsersDevicesMap<MXDeviceInfo>> { override fun onUnexpectedError(e: Exception) { mxCrypto.getDecryptingThreadHandler().post { error() } } override fun onNetworkError(e: Exception) { mxCrypto.getDecryptingThreadHandler().post { error() } } override fun onMatrixError(e: MatrixError) { mxCrypto.getDecryptingThreadHandler().post { error() } } override fun onSuccess(info: MXUsersDevicesMap<MXDeviceInfo>) { mxCrypto.getDecryptingThreadHandler().post { if (info.getUserDeviceIds(otherUserId).contains(startReq.fromDevice)) { success(info) } else { error() } } } }) } private fun onCancelReceived(event: CryptoEvent) { Log.d(LOG_TAG, "## SAS onCancelReceived") val cancelReq = JsonUtility.getBasicGson() .fromJson(event.content, KeyVerificationCancel::class.java) if (!cancelReq.isValid()) { //ignore Log.e(LOG_TAG, "## Received invalid accept request") return } val otherUserId = event.getSender() Log.d(LOG_TAG, "## SAS onCancelReceived otherUser:$otherUserId reason:${cancelReq.reason}") val existing = getExistingTransaction(otherUserId, cancelReq.transactionID!!) if (existing == null) { Log.e(LOG_TAG, "## Received invalid cancel request") return } if (existing is SASVerificationTransaction) { existing.cancelledReason = safeValueOf(cancelReq.code) existing.state = SASVerificationTransaction.SASVerificationTxState.OnCancelled } } private fun onAcceptReceived(event: CryptoEvent) { val acceptReq = JsonUtility.getBasicGson() .fromJson(event.content, KeyVerificationAccept::class.java) if (!acceptReq.isValid()) { //ignore Log.e(LOG_TAG, "## Received invalid accept request") return } val otherUserId = event.getSender() val existing = getExistingTransaction(otherUserId, acceptReq.transactionID!!) if (existing == null) { Log.e(LOG_TAG, "## Received invalid accept request") return } if (existing is SASVerificationTransaction) { existing.acceptToDeviceEvent(session, otherUserId, acceptReq) } else { //not other types now } } private fun onKeyReceived(event: CryptoEvent) { val keyReq = JsonUtility.getBasicGson() .fromJson(event.content, KeyVerificationKey::class.java) if (!keyReq.isValid()) { //ignore Log.e(LOG_TAG, "## Received invalid key request") return } val otherUserId = event.getSender() val existing = getExistingTransaction(otherUserId, keyReq.transactionID!!) if (existing == null) { Log.e(LOG_TAG, "## Received invalid accept request") return } if (existing is SASVerificationTransaction) { existing.acceptToDeviceEvent(session, otherUserId, keyReq) } else { //not other types now } } private fun onMacReceived(event: CryptoEvent) { val macReq = JsonUtility.getBasicGson() .fromJson(event.content, KeyVerificationMac::class.java) if (!macReq.isValid()) { //ignore Log.e(LOG_TAG, "## Received invalid key request") return } val otherUserId = event.getSender() val existing = getExistingTransaction(otherUserId, macReq.transactionID!!) if (existing == null) { Log.e(LOG_TAG, "## Received invalid accept request") return } if (existing is SASVerificationTransaction) { existing.acceptToDeviceEvent(session, otherUserId, macReq) } else { //not other types known for now } } fun getExistingTransaction(otherUser: String, tid: String): VerificationTransaction? { synchronized(lock = txMap) { return txMap[otherUser]?.get(tid) } } private fun getExistingTransactionsForUser(otherUser: String): Collection<VerificationTransaction>? { synchronized(txMap) { return txMap[otherUser]?.values } } private fun removeTransaction(otherUser: String, tid: String) { synchronized(txMap) { txMap[otherUser]?.remove(tid)?.removeListener(this) } } private fun addTransaction(tx: VerificationTransaction) { tx.otherUserId.let { otherUserId -> synchronized(txMap) { if (txMap[otherUserId] == null) { txMap[otherUserId] = HashMap() } txMap[otherUserId]?.set(tx.transactionId, tx) dispatchTxAdded(tx) tx.addListener(this) } } } fun beginKeyVerificationSAS(userId: String, deviceID: String): String? { return beginKeyVerification(KeyVerificationStart.VERIF_METHOD_SAS, userId, deviceID) } fun beginKeyVerification(method: String, userId: String, deviceID: String): String? { val txID = createUniqueIDForTransaction(userId, deviceID) //should check if already one (and cancel it) if (KeyVerificationStart.VERIF_METHOD_SAS == method) { val tx = OutgoingSASVerificationRequest(txID, userId, deviceID) addTransaction(tx) mxCrypto.getDecryptingThreadHandler().post { tx.start(session) } return txID } else { throw IllegalArgumentException("Unknown verification method") } } /** * This string must be unique for the pair of users performing verification for the duration that the transaction is valid */ private fun createUniqueIDForTransaction(userId: String, deviceID: String): String { val buff = StringBuffer() buff .append(session.myUserId).append("|") .append(mxCrypto.myDevice.deviceId).append("|") .append(userId).append("|") .append(deviceID).append("|") .append(UUID.randomUUID().toString()) return buff.toString() } override fun transactionUpdated(tx: VerificationTransaction) { dispatchTxUpdated(tx) if (tx is SASVerificationTransaction && (tx.state == SASVerificationTransaction.SASVerificationTxState.Cancelled || tx.state == SASVerificationTransaction.SASVerificationTxState.OnCancelled || tx.state == SASVerificationTransaction.SASVerificationTxState.Verified) ) { //remove this.removeTransaction(tx.otherUserId, tx.transactionId) } } companion object { val LOG_TAG: String = VerificationManager::class.java.name fun cancelTransaction(session: CryptoSession, transactionId: String, userId: String, userDevice: String, code: CancelCode) { val cancelMessage = KeyVerificationCancel.create(transactionId, code) val contentMap = MXUsersDevicesMap<Any>() contentMap.setObject(cancelMessage, userId, userDevice) session.requireCrypto() .getCryptoRestClient() .sendToDevice(CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_CANCEL, contentMap, transactionId, object : ApiCallback<Void> { override fun onSuccess(info: Void?) { Log.d(SASVerificationTransaction.LOG_TAG, "## SAS verification [$transactionId] canceled for reason ${code.value}") } override fun onUnexpectedError(e: Exception?) { Log.e(SASVerificationTransaction.LOG_TAG, "## SAS verification [$transactionId] failed to cancel.", e) } override fun onNetworkError(e: Exception?) { Log.e(SASVerificationTransaction.LOG_TAG, "## SAS verification [$transactionId] failed to cancel.", e) } override fun onMatrixError(e: MatrixError?) { Log.e(SASVerificationTransaction.LOG_TAG, "## SAS verification [$transactionId] failed to cancel. ${e?.localizedMessage}") } }) } } }
matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/verification/VerificationManager.kt
3090413337
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NAMED_ARGUMENTS_NOT_ALLOWED") // KT-21913 package kotlinx.coroutines.selects import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlinx.coroutines.intrinsics.* import kotlin.test.* class SelectRendezvousChannelTest : TestBase() { @Test fun testSelectSendSuccess() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(2) assertEquals("OK", channel.receive()) finish(6) } yield() // to launched coroutine expect(3) select<Unit> { channel.onSend("OK") { expect(4) } } expect(5) } @Test fun testSelectSendSuccessWithDefault() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(2) assertEquals("OK", channel.receive()) finish(6) } yield() // to launched coroutine expect(3) select<Unit> { channel.onSend("OK") { expect(4) } default { expectUnreached() } } expect(5) } @Test fun testSelectSendWaitWithDefault() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) select<Unit> { channel.onSend("OK") { expectUnreached() } default { expect(2) } } expect(3) // make sure receive blocks (select above is over) launch { expect(5) assertEquals("CHK", channel.receive()) finish(8) } expect(4) yield() expect(6) channel.send("CHK") expect(7) } @Test fun testSelectSendWait() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(3) assertEquals("OK", channel.receive()) expect(4) } expect(2) select<Unit> { channel.onSend("OK") { expect(5) } } finish(6) } @Test fun testSelectReceiveSuccess() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(2) channel.send("OK") finish(6) } yield() // to launched coroutine expect(3) select<Unit> { channel.onReceive { v -> expect(4) assertEquals("OK", v) } } expect(5) } @Test fun testSelectReceiveSuccessWithDefault() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(2) channel.send("OK") finish(6) } yield() // to launched coroutine expect(3) select<Unit> { channel.onReceive { v -> expect(4) assertEquals("OK", v) } default { expectUnreached() } } expect(5) } @Test fun testSelectReceiveWaitWithDefault() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) select<Unit> { channel.onReceive { expectUnreached() } default { expect(2) } } expect(3) // make sure send blocks (select above is over) launch { expect(5) channel.send("CHK") finish(8) } expect(4) yield() expect(6) assertEquals("CHK", channel.receive()) expect(7) } @Test fun testSelectReceiveWait() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(3) channel.send("OK") expect(4) } expect(2) select<Unit> { channel.onReceive { v -> expect(5) assertEquals("OK", v) } } finish(6) } @Test fun testSelectReceiveClosed() = runTest(expected = { it is ClosedReceiveChannelException }) { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) channel.close() finish(2) select<Unit> { channel.onReceive { expectUnreached() } } expectUnreached() } @Test fun testSelectReceiveWaitClosed() = runTest(expected = {it is ClosedReceiveChannelException}) { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(3) channel.close() finish(4) } expect(2) select<Unit> { channel.onReceive { expectUnreached() } } expectUnreached() } @Test fun testSelectSendResourceCleanup() = runTest { val channel = Channel<Int>(Channel.RENDEZVOUS) val n = 1_000 expect(1) repeat(n) { i -> select { channel.onSend(i) { expectUnreached() } default { expect(i + 2) } } } finish(n + 2) } @Test fun testSelectReceiveResourceCleanup() = runTest { val channel = Channel<Int>(Channel.RENDEZVOUS) val n = 1_000 expect(1) repeat(n) { i -> select { channel.onReceive { expectUnreached() } default { expect(i + 2) } } } finish(n + 2) } @Test fun testSelectAtomicFailure() = runTest { val c1 = Channel<Int>(Channel.RENDEZVOUS) val c2 = Channel<Int>(Channel.RENDEZVOUS) expect(1) launch { expect(3) val res = select<String> { c1.onReceive { v1 -> expect(4) assertEquals(42, v1) yield() // back to main expect(7) "OK" } c2.onReceive { "FAIL" } } expect(8) assertEquals("OK", res) } expect(2) c1.send(42) // send to coroutine, suspends expect(5) c2.close() // makes sure that selected expression does not fail! expect(6) yield() // back finish(9) } @Test fun testSelectWaitDispatch() = runTest { val c = Channel<Int>(Channel.RENDEZVOUS) expect(1) launch { expect(3) val res = select<String> { c.onReceive { v -> expect(6) assertEquals(42, v) yield() // back to main expect(8) "OK" } } expect(9) assertEquals("OK", res) } expect(2) yield() // to launch expect(4) c.send(42) // do not suspend expect(5) yield() // to receive expect(7) yield() // again finish(10) } @Test fun testSelectReceiveCatchingWaitClosed() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(3) channel.close() expect(4) } expect(2) select<Unit> { channel.onReceiveCatching { expect(5) assertTrue(it.isClosed) assertNull(it.exceptionOrNull()) } } finish(6) } @Test fun testSelectReceiveCatchingWaitClosedWithCause() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(3) channel.close(TestException()) expect(4) } expect(2) select<Unit> { channel.onReceiveCatching { expect(5) assertTrue(it.isClosed) assertTrue(it.exceptionOrNull() is TestException) } } finish(6) } @Test fun testSelectReceiveCatchingForClosedChannel() = runTest { val channel = Channel<Unit>() channel.close() expect(1) select<Unit> { expect(2) channel.onReceiveCatching { assertTrue(it.isClosed) assertNull(it.exceptionOrNull()) finish(3) } } } @Test fun testSelectReceiveCatching() = runTest { val channel = Channel<Int>(Channel.RENDEZVOUS) val iterations = 10 expect(1) val job = launch { repeat(iterations) { select<Unit> { channel.onReceiveCatching { v -> expect(4 + it * 2) assertEquals(it, v.getOrThrow()) } } } } expect(2) repeat(iterations) { expect(3 + it * 2) channel.send(it) yield() } job.join() finish(3 + iterations * 2) } @Test fun testSelectReceiveCatchingDispatch() = runTest { val c = Channel<Int>(Channel.RENDEZVOUS) expect(1) launch { expect(3) val res = select<String> { c.onReceiveCatching { v -> expect(6) assertEquals(42, v.getOrThrow()) yield() // back to main expect(8) "OK" } } expect(9) assertEquals("OK", res) } expect(2) yield() // to launch expect(4) c.send(42) // do not suspend expect(5) yield() // to receive expect(7) yield() // again finish(10) } @Test fun testSelectSendWhenClosed() = runTest { expect(1) val c = Channel<Int>(Channel.RENDEZVOUS) val sender = launch(start = CoroutineStart.UNDISPATCHED) { expect(2) c.send(1) // enqueue sender expectUnreached() } c.close() // then close assertFailsWith<ClosedSendChannelException> { // select sender should fail expect(3) select { c.onSend(2) { expectUnreached() } } } sender.cancel() finish(4) } // only for debugging internal fun <R> SelectBuilder<R>.default(block: suspend () -> R) { this as SelectBuilderImpl // type assertion if (!trySelect()) return block.startCoroutineUnintercepted(this) } @Test fun testSelectSendAndReceive() = runTest { val c = Channel<Int>() assertFailsWith<IllegalStateException> { select<Unit> { c.onSend(1) { expectUnreached() } c.onReceive { expectUnreached() } } } checkNotBroken(c) } @Test fun testSelectReceiveAndSend() = runTest { val c = Channel<Int>() assertFailsWith<IllegalStateException> { select<Unit> { c.onReceive { expectUnreached() } c.onSend(1) { expectUnreached() } } } checkNotBroken(c) } // makes sure the channel is not broken private suspend fun checkNotBroken(c: Channel<Int>) { coroutineScope { launch { c.send(42) } assertEquals(42, c.receive()) } } }
kotlinx-coroutines-core/common/test/selects/SelectRendezvousChannelTest.kt
388522615
package com.rightfromleftsw.weather.presentation.presentation /** * Interface class to act as a base for any class that is to take the role of the IPresenter in the * Model-BaseView-IPresenter pattern. */ interface BasePresenter { fun start() fun stop() }
presentation/src/main/java/com/rightfromleftsw/weather/presentation/presentation/BasePresenter.kt
2461530074
/* * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ // This file was automatically generated from channels.md by Knit tool. Do not edit. package kotlinx.coroutines.guide.exampleChannel06 import kotlinx.coroutines.* import kotlinx.coroutines.channels.* fun main() = runBlocking<Unit> { val producer = produceNumbers() repeat(5) { launchProcessor(it, producer) } delay(950) producer.cancel() // cancel producer coroutine and thus kill them all } fun CoroutineScope.produceNumbers() = produce<Int> { var x = 1 // start from 1 while (true) { send(x++) // produce next delay(100) // wait 0.1s } } fun CoroutineScope.launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch { for (msg in channel) { println("Processor #$id received $msg") } }
kotlinx-coroutines-core/jvm/test/guide/example-channel-06.kt
4031031186
/* * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlin.test.* class ShareInTest : TestBase() { @Test fun testReplay0Eager() = runTest { expect(1) val flow = flowOf("OK") val shared = flow.shareIn(this, SharingStarted.Eagerly) yield() // actually start sharing // all subscribers miss "OK" val jobs = List(10) { shared.onEach { expectUnreached() }.launchIn(this) } yield() // ensure nothing is collected jobs.forEach { it.cancel() } finish(2) } @Test fun testReplay0Lazy() = testReplayZeroOrOne(0) @Test fun testReplay1Lazy() = testReplayZeroOrOne(1) private fun testReplayZeroOrOne(replay: Int) = runTest { expect(1) val doneBarrier = Job() val flow = flow { expect(2) emit("OK") doneBarrier.join() emit("DONE") } val sharingJob = Job() val shared = flow.shareIn(this + sharingJob, started = SharingStarted.Lazily, replay = replay) yield() // should not start sharing // first subscriber gets "OK", other subscribers miss "OK" val n = 10 val replayOfs = replay * (n - 1) val subscriberJobs = List(n) { index -> val subscribedBarrier = Job() val job = shared .onSubscription { subscribedBarrier.complete() } .onEach { value -> when (value) { "OK" -> { expect(3 + index) if (replay == 0) { // only the first subscriber collects "OK" without replay assertEquals(0, index) } } "DONE" -> { expect(4 + index + replayOfs) } else -> expectUnreached() } } .takeWhile { it != "DONE" } .launchIn(this) subscribedBarrier.join() // wait until the launched job subscribed before launching the next one job } doneBarrier.complete() subscriberJobs.joinAll() expect(4 + n + replayOfs) sharingJob.cancel() finish(5 + n + replayOfs) } @Test fun testUpstreamCompleted() = testUpstreamCompletedOrFailed(failed = false) @Test fun testUpstreamFailed() = testUpstreamCompletedOrFailed(failed = true) private fun testUpstreamCompletedOrFailed(failed: Boolean) = runTest { val emitted = Job() val terminate = Job() val sharingJob = CompletableDeferred<Unit>() val upstream = flow { emit("OK") emitted.complete() terminate.join() if (failed) throw TestException() } val shared = upstream.shareIn(this + sharingJob, SharingStarted.Eagerly, 1) assertEquals(emptyList(), shared.replayCache) emitted.join() // should start sharing, emit & cache assertEquals(listOf("OK"), shared.replayCache) terminate.complete() sharingJob.complete(Unit) sharingJob.join() // should complete sharing assertEquals(listOf("OK"), shared.replayCache) // cache is still there if (failed) { assertTrue(sharingJob.getCompletionExceptionOrNull() is TestException) } else { assertNull(sharingJob.getCompletionExceptionOrNull()) } } @Test fun testWhileSubscribedBasic() = testWhileSubscribed(1, SharingStarted.WhileSubscribed()) @Test fun testWhileSubscribedCustomAtLeast1() = testWhileSubscribed(1, SharingStarted.WhileSubscribedAtLeast(1)) @Test fun testWhileSubscribedCustomAtLeast2() = testWhileSubscribed(2, SharingStarted.WhileSubscribedAtLeast(2)) @OptIn(ExperimentalStdlibApi::class) private fun testWhileSubscribed(threshold: Int, started: SharingStarted) = runTest { expect(1) val flowState = FlowState() val n = 3 // max number of subscribers val log = Channel<String>(2 * n) suspend fun checkStartTransition(subscribers: Int) { when (subscribers) { in 0 until threshold -> assertFalse(flowState.started) threshold -> { flowState.awaitStart() // must eventually start the flow for (i in 1..threshold) { assertEquals("sub$i: OK", log.receive()) // threshold subs must receive the values } } in threshold + 1..n -> assertTrue(flowState.started) } } suspend fun checkStopTransition(subscribers: Int) { when (subscribers) { in threshold + 1..n -> assertTrue(flowState.started) threshold - 1 -> flowState.awaitStop() // upstream flow must be eventually stopped in 0..threshold - 2 -> assertFalse(flowState.started) // should have stopped already } } val flow = flow { flowState.track { emit("OK") delay(Long.MAX_VALUE) // await forever, will get cancelled } } val shared = flow.shareIn(this, started) repeat(5) { // repeat scenario a few times yield() assertFalse(flowState.started) // flow is not running even if we yield // start 3 subscribers val subs = ArrayList<Job>() for (i in 1..n) { subs += shared .onEach { value -> // only the first threshold subscribers get the value when (i) { in 1..threshold -> log.trySend("sub$i: $value") else -> expectUnreached() } } .onCompletion { log.trySend("sub$i: completion") } .launchIn(this) checkStartTransition(i) } // now cancel all subscribers for (i in 1..n) { subs.removeFirst().cancel() // cancel subscriber assertEquals("sub$i: completion", log.receive()) // subscriber shall shutdown checkStopTransition(n - i) } } coroutineContext.cancelChildren() // cancel sharing job finish(2) } @Suppress("TestFunctionName") private fun SharingStarted.Companion.WhileSubscribedAtLeast(threshold: Int) = SharingStarted { subscriptionCount -> subscriptionCount.map { if (it >= threshold) SharingCommand.START else SharingCommand.STOP } } private class FlowState { private val timeLimit = 10000L private val _started = MutableStateFlow(false) val started: Boolean get() = _started.value fun start() = check(_started.compareAndSet(expect = false, update = true)) fun stop() = check(_started.compareAndSet(expect = true, update = false)) suspend fun awaitStart() = withTimeout(timeLimit) { _started.first { it } } suspend fun awaitStop() = withTimeout(timeLimit) { _started.first { !it } } } private suspend fun FlowState.track(block: suspend () -> Unit) { start() try { block() } finally { stop() } } @Test fun testShouldStart() = runTest { val flow = flow { expect(2) emit(1) expect(3) }.shareIn(this, SharingStarted.Lazily) expect(1) flow.onSubscription { throw CancellationException("") } .catch { e -> assertTrue { e is CancellationException } } .collect() yield() finish(4) } @Test fun testShouldStartScalar() = runTest { val j = Job() val shared = flowOf(239).stateIn(this + j, SharingStarted.Lazily, 42) assertEquals(42, shared.first()) yield() assertEquals(239, shared.first()) j.cancel() } }
kotlinx-coroutines-core/common/test/flow/sharing/ShareInTest.kt
1746308804
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.changes import com.intellij.diff.util.DiffUserDataKeys import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.diff.impl.GenericDataProvider import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData import com.intellij.ui.IdeBorderFactory import com.intellij.ui.SideBorder import com.intellij.util.ui.ComponentWithEmptyText import com.intellij.util.ui.tree.TreeUtil import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewSupport import org.jetbrains.plugins.github.pullrequest.comment.action.GHPRDiffReviewThreadsReloadAction import org.jetbrains.plugins.github.pullrequest.comment.action.GHPRDiffReviewThreadsToggleAction import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings import org.jetbrains.plugins.github.util.GHToolbarLabelAction import java.awt.event.FocusEvent import java.awt.event.FocusListener import javax.swing.border.Border import javax.swing.tree.DefaultTreeModel internal class GHPRChangesBrowser(private val model: GHPRChangesModel, private val diffHelper: GHPRChangesDiffHelper, private val project: Project) : ChangesBrowserBase(project, false, false), ComponentWithEmptyText { init { init() model.addStateChangesListener { myViewer.rebuildTree() } } override fun canShowDiff(): Boolean { val selection = VcsTreeModelData.getListSelectionOrAll(myViewer) return selection.list.any { it is Change && ChangeDiffRequestProducer.canCreate(project, it) } } override fun getDiffRequestProducer(userObject: Any): ChangeDiffRequestChain.Producer? { return if (userObject is Change) { val dataKeys: MutableMap<Key<out Any>, Any?> = mutableMapOf() val diffComputer = diffHelper.getDiffComputer(userObject) if (diffComputer != null) { dataKeys[DiffUserDataKeysEx.CUSTOM_DIFF_COMPUTER] = diffComputer } val reviewSupport = diffHelper.getReviewSupport(userObject) if (reviewSupport != null) { dataKeys[GHPRDiffReviewSupport.KEY] = reviewSupport dataKeys[DiffUserDataKeys.DATA_PROVIDER] = GenericDataProvider().apply { putData(GHPRDiffReviewSupport.DATA_KEY, reviewSupport) } dataKeys[DiffUserDataKeys.CONTEXT_ACTIONS] = listOf(GHToolbarLabelAction("Review:"), GHPRDiffReviewThreadsToggleAction(), GHPRDiffReviewThreadsReloadAction()) } ChangeDiffRequestProducer.create(myProject, userObject, dataKeys) } else null } override fun getEmptyText() = myViewer.emptyText override fun createTreeList(project: Project, showCheckboxes: Boolean, highlightProblems: Boolean): ChangesBrowserTreeList { return super.createTreeList(project, showCheckboxes, highlightProblems).also { it.addFocusListener(object : FocusListener { override fun focusGained(e: FocusEvent?) { if (it.isSelectionEmpty && !it.isEmpty) TreeUtil.selectFirstNode(it) } override fun focusLost(e: FocusEvent?) {} }) } } override fun createViewerBorder(): Border = IdeBorderFactory.createBorder(SideBorder.TOP) override fun buildTreeModel(): DefaultTreeModel { return model.buildChangesTree(grouping) } class ToggleZipCommitsAction : ToggleAction("Commit"), DumbAware { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isEnabledAndVisible = e.getData(DATA_KEY) is GHPRChangesBrowser } override fun isSelected(e: AnActionEvent): Boolean { val project = e.project ?: return false return !GithubPullRequestsProjectUISettings.getInstance(project).zipChanges } override fun setSelected(e: AnActionEvent, state: Boolean) { val project = e.project ?: return GithubPullRequestsProjectUISettings.getInstance(project).zipChanges = !state } } }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/changes/GHPRChangesBrowser.kt
3733863541
// 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 org.jetbrains.jps.ant import com.intellij.openapi.util.io.FileUtil import com.intellij.testFramework.UsefulTestCase import com.intellij.util.SystemProperties import com.intellij.util.io.directoryContent import gnu.trove.THashSet import org.jetbrains.jps.ant.model.JpsAntExtensionService import org.jetbrains.jps.ant.model.impl.artifacts.JpsAntArtifactExtensionImpl import org.jetbrains.jps.model.artifact.JpsArtifactService import org.jetbrains.jps.model.serialization.JpsSerializationTestCase import java.io.File class JpsAntSerializationTest : JpsSerializationTestCase() { private lateinit var antHome: File override fun setUp() { super.setUp() antHome = createTempDir("antHome") } fun testLoadArtifactProperties() { loadProject(PROJECT_PATH) val artifacts = JpsArtifactService.getInstance().getSortedArtifacts(myProject) assertEquals(2, artifacts.size) val dir = artifacts[0] assertEquals("dir", dir.name) val preprocessing = JpsAntExtensionService.getPreprocessingExtension(dir)!! assertTrue(preprocessing.isEnabled) assertEquals(getUrl("build.xml"), preprocessing.fileUrl) assertEquals("show-message", preprocessing.targetName) assertEquals(JpsAntArtifactExtensionImpl.ARTIFACT_OUTPUT_PATH_PROPERTY, assertOneElement(preprocessing.antProperties).getPropertyName()) val postprocessing = JpsAntExtensionService.getPostprocessingExtension(dir)!! assertEquals(getUrl("build.xml"), postprocessing.fileUrl) assertEquals("create-file", postprocessing.targetName) val properties = postprocessing.antProperties assertEquals(2, properties.size) assertEquals(JpsAntArtifactExtensionImpl.ARTIFACT_OUTPUT_PATH_PROPERTY, properties[0].propertyName) assertEquals(dir.outputPath, properties[0].propertyValue) assertEquals("message.text", properties[1].propertyName) assertEquals("post", properties[1].propertyValue) val jar = artifacts[1] assertEquals("jar", jar.name) assertNull(JpsAntExtensionService.getPostprocessingExtension(jar)) assertNull(JpsAntExtensionService.getPreprocessingExtension(jar)) } fun testLoadAntInstallations() { directoryContent { file("foo.jar") dir("lib") { file("bar.jar") } }.generate(antHome) loadGlobalSettings(OPTIONS_PATH) val installation = JpsAntExtensionService.findAntInstallation(myModel, "Apache Ant version 1.8.2") assertNotNull(installation) assertEquals(FileUtil.toSystemIndependentName(installation!!.antHome.absolutePath), FileUtil.toSystemIndependentName(File(SystemProperties.getUserHome(), "applications/apache-ant-1.8.2").absolutePath)) val installation2 = JpsAntExtensionService.findAntInstallation(myModel, "Patched Ant") assertNotNull(installation2) UsefulTestCase.assertSameElements(toFiles(installation2!!.classpath), File(antHome, "foo.jar"), File(antHome, "lib/bar.jar")) } override fun getPathVariables(): Map<String, String> { val pathVariables = super.getPathVariables() pathVariables.put("MY_ANT_HOME_DIR", antHome.absolutePath) return pathVariables } fun testLoadAntConfiguration() { loadProject(PROJECT_PATH) loadGlobalSettings(OPTIONS_PATH) val buildXmlUrl = getUrl("build.xml") val options = JpsAntExtensionService.getOptions(myProject, buildXmlUrl) assertEquals(128, options.maxHeapSize) assertEquals("-J-Dmy.ant.prop=123", options.antCommandLineParameters) assertContainsElements(toFiles(options.additionalClasspath), File(getAbsolutePath("lib/jdom.jar")), File(getAbsolutePath("ant-lib/a.jar"))) val property = assertOneElement(options.properties) assertEquals("my.property", property.getPropertyName()) assertEquals("its value", property.getPropertyValue()) val emptyFileUrl = getUrl("empty.xml") val options2 = JpsAntExtensionService.getOptions(myProject, emptyFileUrl) assertEquals(256, options2.maxHeapSize) assertEquals(10, options2.maxStackSize) assertEquals("1.6", options2.customJdkName) val bundled = JpsAntExtensionService.getAntInstallationForBuildFile(myModel, buildXmlUrl)!! assertEquals("Bundled Ant", bundled.name) val installation = JpsAntExtensionService.getAntInstallationForBuildFile(myModel, emptyFileUrl)!! assertEquals("Apache Ant version 1.8.2", installation.name) } companion object { const val PROJECT_PATH = "plugins/ant/jps-plugin/testData/ant-project" const val OPTIONS_PATH = "plugins/ant/jps-plugin/testData/config/options" private fun toFiles(classpath: List<String>): Set<File> { val result = THashSet(FileUtil.FILE_HASHING_STRATEGY) for (path in classpath) { result.add(File(path)) } return result } } }
plugins/ant/jps-plugin/testSrc/org/jetbrains/jps/ant/JpsAntSerializationTest.kt
3316611138
package com.dbflow5.adapter import android.content.ContentValues import com.dbflow5.annotation.PrimaryKey import com.dbflow5.database.DatabaseStatement import com.dbflow5.database.DatabaseWrapper /** * Description: Used for our internal Adapter classes such as generated [ModelAdapter]. */ interface InternalAdapter<in TModel> { /** * @return The table name of this adapter. */ val name: String /** * Saves the specified model to the DB. * * @param model The model to save/insert/update * @param databaseWrapper The manually specified wrapper. */ fun save(model: TModel, databaseWrapper: DatabaseWrapper): Boolean /** * Saves a [Collection] of models to the DB. * * @param models The [Collection] of models to save. * @param databaseWrapper The manually specified wrapper * @return the count of models saved or updated. */ fun saveAll(models: Collection<TModel>, databaseWrapper: DatabaseWrapper): Long /** * Inserts the specified model into the DB. * * @param model The model to insert. * @param databaseWrapper The manually specified wrapper. */ fun insert(model: TModel, databaseWrapper: DatabaseWrapper): Long /** * Inserts a [Collection] of models into the DB. * * @param models The [Collection] of models to save. * @param databaseWrapper The manually specified wrapper * @return the count inserted */ fun insertAll(models: Collection<TModel>, databaseWrapper: DatabaseWrapper): Long /** * Updates the specified model into the DB. * * @param model The model to update. * @param databaseWrapper The manually specified wrapper. */ fun update(model: TModel, databaseWrapper: DatabaseWrapper): Boolean /** * Updates a [Collection] of models in the DB. * * @param models The [Collection] of models to save. * @param databaseWrapper The manually specified wrapper * @return count of successful updates. */ fun updateAll(models: Collection<TModel>, databaseWrapper: DatabaseWrapper): Long /** * Deletes the model from the DB * * @param model The model to delete * @param databaseWrapper The manually specified wrapper. */ fun delete(model: TModel, databaseWrapper: DatabaseWrapper): Boolean /** * Updates a [Collection] of models in the DB. * * @param models The [Collection] of models to save. * @param databaseWrapper The manually specified wrapper * @return count of successful deletions. */ fun deleteAll(models: Collection<TModel>, databaseWrapper: DatabaseWrapper): Long /** * Binds to a [DatabaseStatement] for insert. * * @param sqLiteStatement The statement to bind to. * @param model The model to read from. */ fun bindToInsertStatement(sqLiteStatement: DatabaseStatement, model: TModel) /** * Binds a [TModel] to the specified db statement * * @param contentValues The content values to fill. * @param model The model values to put on the contentvalues */ fun bindToContentValues(contentValues: ContentValues, model: TModel) /** * Binds a [TModel] to the specified db statement, leaving out the [PrimaryKey.autoincrement] * column. * * @param contentValues The content values to fill. * @param model The model values to put on the content values. */ fun bindToInsertValues(contentValues: ContentValues, model: TModel) /** * Binds values of the model to an update [DatabaseStatement]. It repeats each primary * key binding twice to ensure proper update statements. */ fun bindToUpdateStatement(updateStatement: DatabaseStatement, model: TModel) /** * Binds values of the model to a delete [DatabaseStatement]. */ fun bindToDeleteStatement(deleteStatement: DatabaseStatement, model: TModel) /** * If a model has an autoincrementing primary key, then * this method will be overridden. * * @param model The model object to store the key * @param id The key to store */ fun updateAutoIncrement(model: TModel, id: Number) /** * @return true if the [InternalAdapter] can be cached. */ fun cachingEnabled(): Boolean }
lib/src/main/kotlin/com/dbflow5/adapter/InternalAdapter.kt
1969803527
/** <slate_header> url: www.slatekit.com git: www.github.com/code-helix/slatekit org: www.codehelix.co author: Kishore Reddy copyright: 2016 CodeHelix Solutions Inc. license: refer to website and/or github about: A Kotlin utility library, tool-kit and server backend. mantra: Simplicity above all else </slate_header> */ /** * Created by kishorereddy on 5/19/17. */ package slatekit.tools object Consts { val version = "0.9.0" }
src/lib/kotlin/slatekit/src/consts.kt
3091034267
package com.alibaba.user_api_test.ttl import com.alibaba.noTtlAgentRun import com.alibaba.ttl.TransmittableThreadLocal.Transmitter import io.kotest.core.spec.style.AnnotationSpec import io.kotest.core.test.config.TestCaseConfig import io.kotest.matchers.booleans.shouldBeTrue import io.mockk.* import org.apache.commons.lang3.JavaVersion import org.apache.commons.lang3.SystemUtils /** * Test [Transmitter] from user code(different package) */ class TransmittableThreadLocal_Transmitter_registerTransmittee_UserTest : AnnotationSpec() { @Suppress("OVERRIDE_DEPRECATION") override fun defaultTestCaseConfig(): TestCaseConfig { // If run under Agent and under java 11+, fail to find proxy classes; // so just skipped. // // error info: // java.lang.NoClassDefFoundError: io/mockk/proxy/jvm/advice/jvm/JvmMockKProxyInterceptor // more info error info see: // https://github.com/alibaba/transmittable-thread-local/runs/7826806473?check_suite_focus=true if (SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8)) { return TestCaseConfig(enabled = true) } return TestCaseConfig(enabled = noTtlAgentRun()) } @Test fun test_registerTransmittee_crr() { // ======================================== // 0. mocks creation and stubbing // ======================================== val transmittee = mockk<Transmitter.Transmittee<List<String>, Set<Int>>>() @Suppress("UnusedEquals", "ReplaceCallWithBinaryOperator") excludeRecords { transmittee.equals(any()) transmittee.hashCode() } every { transmittee.capture() } returns listOf("42", "43") every { transmittee.replay(listOf("42", "43")) } returns setOf(42, 43) every { transmittee.restore(setOf(42, 43)) } just Runs try { // ======================================== // 1. mock record(aka. invocation) // ======================================== Transmitter.registerTransmittee(transmittee).shouldBeTrue() val captured = Transmitter.capture() val backup = Transmitter.replay(captured) Transmitter.restore(backup) // ======================================== // 2. mock verification // ======================================== verifySequence { transmittee.capture() transmittee.replay(any()) transmittee.restore(any()) } confirmVerified(transmittee) } finally { Transmitter.unregisterTransmittee(transmittee).shouldBeTrue() } } @Test fun test_registerTransmittee_clear_restore() { // ======================================== // 0. mocks creation and stubbing // ======================================== val transmittee = mockk<Transmitter.Transmittee<List<String>, Set<Int>>>() @Suppress("UnusedEquals", "ReplaceCallWithBinaryOperator") excludeRecords { transmittee.equals(any()) transmittee.hashCode() } every { transmittee.clear() } returns setOf(42, 43) every { transmittee.restore(setOf(42, 43)) } just Runs try { // ======================================== // 1. mock record(aka. invocation) // ======================================== Transmitter.registerTransmittee(transmittee).shouldBeTrue() val backup = Transmitter.clear() Transmitter.restore(backup) // ======================================== // 2. mock verification // ======================================== verifySequence { transmittee.clear() transmittee.restore(any()) } confirmVerified(transmittee) } finally { Transmitter.unregisterTransmittee(transmittee).shouldBeTrue() } } }
ttl2-compatible/src/test/java/com/alibaba/user_api_test/ttl/TransmittableThreadLocal_Transmitter_registerTransmittee_UserTest.kt
4046280722
package com.github.triplet.gradle.play.tasks.internal.workers import com.github.triplet.gradle.play.internal.toConfig import com.github.triplet.gradle.play.tasks.internal.PublishArtifactTaskBase import com.github.triplet.gradle.play.tasks.internal.PublishTaskBase internal fun PublishTaskBase.paramsForBase(params: PlayWorkerBase.PlayPublishingParams) { params.config.set(extension.toConfig()) params.apiService.set(apiService) if (params is PublishArtifactWorkerBase.ArtifactPublishingParams) { this as PublishArtifactTaskBase params.releaseNotesDir.set(releaseNotesDir) params.consoleNamesDir.set(consoleNamesDir) } } internal fun PlayWorkerBase.PlayPublishingParams.copy(into: PlayWorkerBase.PlayPublishingParams) { into.config.set(config) into.apiService.set(apiService) } internal fun EditWorkerBase.EditPublishingParams.copy(into: EditWorkerBase.EditPublishingParams) { (this as PlayWorkerBase.PlayPublishingParams).copy(into) } internal fun PublishArtifactWorkerBase.ArtifactPublishingParams.copy( into: PublishArtifactWorkerBase.ArtifactPublishingParams, ) { (this as EditWorkerBase.EditPublishingParams).copy(into) into.releaseNotesDir.set(releaseNotesDir) into.consoleNamesDir.set(consoleNamesDir) }
play/plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/internal/workers/Params.kt
874443577
package i_introduction._5_String_Templates import org.junit.Assert import org.junit.Test import java.util.regex.Pattern class _04_String_Templates() { @Test fun match() { Assert.assertTrue(Pattern.compile(task4()).matcher("Douglas Adams (11 MAR 1952)").find()) } @Test fun match1() { Assert.assertTrue(Pattern.compile(task4()).matcher("Stephen Fry (24 AUG 1957)").find()) } @Test fun doNotMatch() { Assert.assertFalse(Pattern.compile(task4()).matcher("Stephen Fry (24 RRR 1957)").find()) } }
src/test/java/src/i_introduction/_5_String_Templates/_04_String_Templates.kt
886693398
open class A { open fun foo() { } } interface Z { fun <caret>foo() } class B: A(), Z { override fun foo() { } }
plugins/kotlin/idea/tests/testData/refactoring/safeDelete/deleteFunction/kotlinFunction/overrideAndImplement3.kt
388952519
// FIR_COMPARISON class C { val field = 0 class NestedClass inner class InnerClass inner class N { fun foo(){ <caret> } } } fun C.extensionForC(){} // EXIST: field // EXIST: NestedClass // EXIST: InnerClass // EXIST: extensionForC
plugins/kotlin/completion/tests/testData/basic/common/InInnerClass.kt
3382426227
// "Create class 'Foo'" "true" interface I fun <T : I> foo() {} fun x() { foo<<caret>Foo>() }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/typeReference/typeArgumentWithBound.kt
271056876
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.caches.resolve import com.intellij.testFramework.IdeaTestUtil import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class Java8MultiModuleHighlightingTest : AbstractMultiModuleHighlightingTest() { override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("multiModuleHighlighting") fun testDifferentJdk() { val module1 = module("jdk8") { IdeaTestUtil.getMockJdk18() } val module2 = module("jdk6") { IdeaTestUtil.getMockJdk16() } module1.addDependency(module2) checkHighlightingInProject() } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/caches/resolve/Java8MultiModuleHighlightingTest.kt
2240504314
// 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.workspaceModel.ide.impl.legacyBridge.project import com.intellij.openapi.project.Project import com.intellij.openapi.project.RootsChangeRescanningInfo import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.impl.OrderRootsCache import com.intellij.openapi.roots.impl.ProjectRootManagerComponent import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.EmptyRunnable import com.intellij.util.indexing.BuildableRootsChangeRescanningInfo import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.OrderRootsCacheBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleDependencyIndex import com.intellij.workspaceModel.ide.legacyBridge.ModuleDependencyListener class ProjectRootManagerBridge(project: Project) : ProjectRootManagerComponent(project) { init { if (!project.isDefault) { moduleDependencyIndex.addListener(ModuleDependencyListenerImpl()) } } private val moduleDependencyIndex get() = ModuleDependencyIndex.getInstance(project) override fun getActionToRunWhenProjectJdkChanges(): Runnable { return Runnable { super.getActionToRunWhenProjectJdkChanges().run() if (moduleDependencyIndex.hasProjectSdkDependency()) fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addInheritedSdk()) } } override fun getOrderRootsCache(project: Project): OrderRootsCache { return OrderRootsCacheBridge(project, project) } fun isFiringEvent(): Boolean = isFiringEvent fun setupTrackedLibrariesAndJdks() { moduleDependencyIndex.setupTrackedLibrariesAndJdks() } private fun fireRootsChanged(info: RootsChangeRescanningInfo) { if (myProject.isOpen) { makeRootsChange(EmptyRunnable.INSTANCE, info) } } inner class ModuleDependencyListenerImpl : ModuleDependencyListener { private var insideRootsChange = false override fun referencedLibraryAdded(library: Library) { if (shouldListen(library)) { fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addLibrary(library)) } } override fun referencedLibraryChanged(library: Library) { if (insideRootsChange || !shouldListen(library)) return insideRootsChange = true try { fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addLibrary(library)) } finally { insideRootsChange = false } } override fun referencedLibraryRemoved(library: Library) { if (shouldListen(library)) { fireRootsChanged(RootsChangeRescanningInfo.NO_RESCAN_NEEDED) } } private fun shouldListen(library: Library): Boolean { //project-level libraries are stored in WorkspaceModel, and changes in their roots are handled by RootsChangeWatcher return library.table?.tableLevel != LibraryTablesRegistrar.PROJECT_LEVEL } override fun referencedSdkAdded(sdk: Sdk) { fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addSdk(sdk)) } override fun referencedSdkChanged(sdk: Sdk) { fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addSdk(sdk)) } override fun referencedSdkRemoved(sdk: Sdk) { fireRootsChanged(RootsChangeRescanningInfo.NO_RESCAN_NEEDED) } } }
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/project/ProjectRootManagerBridge.kt
169702140
package activitystarter.compiler.processing import activitystarter.Arg import activitystarter.compiler.error.Errors import activitystarter.compiler.error.error import activitystarter.compiler.model.ConverterModel import activitystarter.compiler.model.ProjectConfig import activitystarter.compiler.model.classbinding.KnownClassType import activitystarter.compiler.model.param.ArgumentModel import activitystarter.compiler.model.param.FieldAccessor import activitystarter.compiler.model.param.ParamType import activitystarter.compiler.utils.getElementType import com.squareup.javapoet.TypeName import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement import javax.lang.model.type.ExecutableType import javax.lang.model.type.TypeMirror class ArgumentFactory(val enclosingElement: TypeElement, val config: ProjectConfig) { fun create(element: Element, packageName: String, knownClassType: KnownClassType): ArgumentModel? = when (element.kind) { ElementKind.FIELD -> createFromField(element, packageName, knownClassType) ElementKind.METHOD -> createFromGetter(element, packageName, knownClassType) else -> null } private fun createFromField(element: Element, packageName: String, knownClassType: KnownClassType): ArgumentModel? { val elementType: TypeMirror = getElementType(element) val paramType = ParamType.fromType(elementType) val accessor: FieldAccessor = FieldAccessor.fromElement(element) val error = getFieldError(knownClassType, paramType, accessor) if (error != null) { showProcessingError(element, error) return null } val name: String = element.simpleName.toString() val annotation = element.getAnnotation(Arg::class.java) val keyFromAnnotation = annotation?.key val isParceler = annotation?.parceler ?: false val optional: Boolean = annotation?.optional ?: false val key: String = if (keyFromAnnotation.isNullOrBlank()) "$packageName.${name}StarterKey" else keyFromAnnotation!! val typeName: TypeName = TypeName.get(elementType) val (converter, saveParamType) = getConverterAndSaveType(isParceler, elementType, paramType, element) ?: return null return ArgumentModel(name, key, paramType, typeName, saveParamType, optional, accessor, converter, isParceler) } fun createFromGetter(getterElement: Element, packageName: String?, knownClassType: KnownClassType): ArgumentModel? { if (!getterElement.simpleName.startsWith("get")) { showProcessingError(getterElement, "Function is not getter") return null } val name = getterElement.simpleName.toString().substringAfter("get").decapitalize() val getter = getterElement.asType() as? ExecutableType if (getter == null) { showProcessingError(getterElement, "Type is not method") return null } val returnType: TypeMirror = getter.returnType val paramType = ParamType.fromType(returnType) val accessor: FieldAccessor = FieldAccessor.fromGetter(getterElement, name) val error = getGetterError(knownClassType, paramType, accessor) if (error != null) { showProcessingError(getterElement, error) return null } val annotation = getterElement.getAnnotation(Arg::class.java) val keyFromAnnotation = annotation?.key val parceler = annotation?.parceler ?: false val optional: Boolean = annotation?.optional ?: false val key: String = if (keyFromAnnotation.isNullOrBlank()) "$packageName.${name}StarterKey" else keyFromAnnotation!! val typeName: TypeName = TypeName.get(returnType) val (converter, saveParamType) = getConverterAndSaveType(parceler, returnType, paramType, getterElement) ?: return null return ArgumentModel(name, key, paramType, typeName, saveParamType, optional, accessor, converter, parceler) } private fun getConverterAndSaveType(isParceler: Boolean, elementType: TypeMirror, paramType: ParamType, element: Element): Pair<ConverterModel?, ParamType>? { if (isParceler) { return null to ParamType.ParcelableSubtype } else { val converter = config.converterFor(elementType) val saveParamType = converter?.toParamType ?: paramType if (saveParamType == ParamType.ObjectSubtype) { showProcessingError(element, Errors.notSupportedType.replace("{Type}", paramType.name).replace("{Field}", element.simpleName?.toString() ?: "")) return null } return converter to saveParamType } } private fun getFieldError(knownClassType: KnownClassType, paramTypeNullable: ParamType?, accessor: FieldAccessor) = when { enclosingElement.kind != ElementKind.CLASS -> Errors.notAClass enclosingElement.modifiers.contains(Modifier.PRIVATE) -> Errors.privateClass paramTypeNullable == null -> Errors.notSupportedType.replace("{Type}", paramTypeNullable?.name ?: "null").replace("{Field}", accessor.fieldName) !accessor.isAccessible() -> Errors.inaccessibleField paramTypeNullable.typeUsedBySupertype() && knownClassType == KnownClassType.BroadcastReceiver -> Errors.notBasicTypeInReceiver else -> null } private fun getGetterError(knownClassType: KnownClassType, paramTypeNullable: ParamType?, accessor: FieldAccessor) = when { enclosingElement.kind != ElementKind.CLASS -> Errors.notAClass enclosingElement.modifiers.contains(Modifier.PRIVATE) -> Errors.privateClass paramTypeNullable == null -> Errors.notSupportedType.replace("{Type}", paramTypeNullable?.name ?: "null").replace("{Field}", accessor.fieldName) paramTypeNullable.typeUsedBySupertype() && knownClassType == KnownClassType.BroadcastReceiver -> Errors.notBasicTypeInReceiver else -> null } private fun showProcessingError(element: Element, text: String) { error(enclosingElement, "@%s %s $text (%s)", Arg::class.java.simpleName, enclosingElement.qualifiedName, element.simpleName) } class ProcessingError(override val message: String) : Throwable(message) }
activitystarter-compiler/src/main/java/activitystarter/compiler/processing/ArgumentFactory.kt
713978326
package flank.exection.parallel import flank.exection.parallel.internal.validateExecutionGraphs /** * Validate the given [Tasks] and [ParallelState] for finding missing dependencies or broken paths. * * @param initial The initial arguments for tasks execution. * @return Valid [Tasks] if graph has no broken paths or missing dependencies. */ fun Tasks.validate(initial: ParallelState = emptyMap()): Tasks = validateExecutionGraphs(initial)
tool/execution/parallel/src/main/kotlin/flank/exection/parallel/Validate.kt
659885711
package com.kickstarter.libs import androidx.test.core.app.ApplicationProvider import com.kickstarter.KSRobolectricTestCase import com.kickstarter.mock.factories.PXClientFactory import okhttp3.Protocol import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody.Companion.toResponseBody import org.junit.Test import rx.observers.TestSubscriber import java.util.HashMap class PerimeterXTest : KSRobolectricTestCase() { lateinit var build: Build private val mockRequest = Request.Builder() .url("http://url.com") .build() private val mockResponse = Response.Builder() .request(mockRequest) .protocol(Protocol.HTTP_2) .message("") .code(403) .body("body".toResponseBody()) .build() private val mockBody = mockResponse.body?.string() ?: "" override fun setUp() { super.setUp() build = requireNotNull(environment().build()) } @Test fun testCookieForWebView() { val pxClient = PXClientFactory.pxChallengedSuccessful(build) val cookie = pxClient.getCookieForWebView() val assertValue = "_pxmvid=${pxClient.visitorId()}" assert(cookie.contains(assertValue)) } @Test fun testVisitiorId() { val pxClient = PXClientFactory.pxChallengedSuccessful(build) val vid = pxClient.visitorId() assertNotNull(vid) assertEquals(vid, "VID") } @Test fun testHeaders() { val pxClient = PXClientFactory.pxChallengedSuccessful(build) val pxHeader = pxClient.httpHeaders() val headerVariable = mutableMapOf("h1" to "value1", "h2" to "value2") assert(pxHeader.isNotEmpty()) assertEquals(pxHeader.size, 2) assertEquals(pxHeader.keys, headerVariable.keys) assertEquals(pxHeader.values.toString(), headerVariable.values.toString()) } @Test fun testAddHeaderToBuilder() { val pxClient = PXClientFactory.pxChallengedSuccessful(build) val mockRequestBuilder = Request.Builder() .url("http://url.com") val headerVariable = mutableMapOf("h1" to "value1", "h2" to "value2") pxClient.addHeaderTo(mockRequestBuilder) val request = mockRequestBuilder.build() val first = request.headers[headerVariable.keys.first()] val last = request.headers[headerVariable.keys.last()] assertEquals(first, headerVariable[headerVariable.keys.first()]) assertEquals(last, headerVariable[headerVariable.keys.last()]) } @Test fun testChallengedResponse() { val build = requireNotNull(environment().build()) val clientNotChallenged = PXClientFactory.pxNotChallenged(build) val clientWithChallenged = PXClientFactory.pxChallengedSuccessful(build) val challenge1 = clientWithChallenged.isChallenged(mockBody) val challenge2 = clientNotChallenged.isChallenged(mockBody) assertTrue(challenge1) assertFalse(challenge2) } @Test fun testIntercept_whenCaptchaSuccess() { val pxClient = PXClientFactory.pxChallengedSuccessful(build) val testIsManagerReady = TestSubscriber.create<Boolean>() val testCaptchaSuccess = TestSubscriber.create<Boolean>() val testCaptchaCanceled = TestSubscriber.create<String>() val testHeadersAdded = TestSubscriber.create<HashMap<String, String>>() pxClient.isReady.subscribe(testIsManagerReady) pxClient.isCaptchaSuccess.subscribe(testCaptchaSuccess) pxClient.headersAdded.subscribe(testHeadersAdded) pxClient.isCaptchaCanceled.subscribe(testCaptchaCanceled) pxClient.start(ApplicationProvider.getApplicationContext()) pxClient.intercept(mockResponse) testIsManagerReady.assertValue(true) testCaptchaSuccess.assertValue(true) testCaptchaCanceled.assertNoValues() testHeadersAdded.assertValueCount(1) } @Test fun testIntercept_whenCaptchaCanceled() { val build = requireNotNull(environment().build()) val client = PXClientFactory.pxChallengedCanceled(build) val testCaptchaSuccess = TestSubscriber.create<Boolean>() val testCaptchaCanceled = TestSubscriber.create<String>() client.isCaptchaSuccess.subscribe(testCaptchaSuccess) client.isCaptchaCanceled.subscribe(testCaptchaCanceled) client.start(ApplicationProvider.getApplicationContext()) client.intercept(mockResponse) testCaptchaCanceled.assertValue("Back Button") testCaptchaSuccess.assertNoValues() } @Test fun testIntercept_whenNoChallenged_NoCaptcha() { val client = PXClientFactory.pxNotChallenged(build) val testCaptchaSuccess = TestSubscriber.create<Boolean>() val testCaptchaCanceled = TestSubscriber.create<String>() client.isCaptchaSuccess.subscribe(testCaptchaSuccess) client.isCaptchaCanceled.subscribe(testCaptchaCanceled) client.start(ApplicationProvider.getApplicationContext()) client.intercept(mockResponse) assertFalse(client.isChallenged(mockBody)) testCaptchaCanceled.assertNoValues() testCaptchaSuccess.assertNoValues() } }
app/src/test/java/com/kickstarter/libs/PerimeterXTest.kt
673833307