content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package au.com.tilbrook.android.rxkotlin
import android.app.Application
import com.squareup.leakcanary.LeakCanary
import com.squareup.leakcanary.RefWatcher
import timber.log.Timber
class MyApp : Application() {
lateinit var refWatcher: RefWatcher
override fun onCreate() {
super.onCreate()
instance = applicationContext as MyApp
refWatcher = LeakCanary.install(this)
Timber.plant(Timber.DebugTree())
}
companion object {
lateinit var instance: MyApp
}
}
| app/src/main/kotlin/au/com/tilbrook/android/rxkotlin/MyApp.kt | 3875693440 |
package org.dvbviewer.controller.data.recording.retrofit
import okhttp3.MediaType
import okhttp3.RequestBody
import org.dvbviewer.controller.data.entities.Recording
import retrofit2.Converter
internal class RecordingRequestBodyConverter : Converter<List<Recording>, RequestBody> {
override fun convert(value: List<Recording>): RequestBody {
return RequestBody.create(MEDIA_TYPE, value.toString())
}
companion object {
private val MEDIA_TYPE = MediaType.parse("text")
}
} | dvbViewerController/src/main/java/org/dvbviewer/controller/data/recording/retrofit/RecordingRequestBodyConverter.kt | 2612596307 |
package lt.markmerkk.utils
import com.nhaarman.mockitokotlin2.doNothing
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.whenever
import lt.markmerkk.Config
import lt.markmerkk.ConfigPathProvider
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import java.util.Properties
class AdvHashSettingsGetIntTest {
@Mock lateinit var configPathProvider: ConfigPathProvider
@Mock lateinit var configSetSettings: ConfigSetSettings
private lateinit var config: Config
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
doNothing().whenever(configSetSettings).load()
doNothing().whenever(configSetSettings).save()
doReturn("/").whenever(configSetSettings)
.currentConfig()
config = Config(
debug = false,
appName = "wt4",
appFlavor = "basic",
versionName = "test_version",
versionCode = 1,
cpp = configPathProvider,
configSetSettings = configSetSettings,
gaKey = "test"
)
}
@Test
fun stringOutput() {
// Arrange
val settings = AdvHashSettings(config)
val outputProperties = Properties()
outputProperties.put("valid_key", "dmFsaWRfdmFsdWU=")
// Act
settings.onLoad(outputProperties)
val resultValue = settings.getInt(key = "valid_key", defaultValue = -1)
// Assert
assertThat(resultValue).isEqualTo(-1)
}
@Test
fun validOutput() {
// Arrange
val settings = AdvHashSettings(config)
val outputProperties = Properties()
outputProperties.put("valid_key", "MTA=")
// Act
settings.onLoad(outputProperties)
val resultValue = settings.getInt(key = "valid_key", defaultValue = -1)
// Assert
assertThat(resultValue).isEqualTo(10)
}
@Test
fun validInput() {
// Arrange
val settings = AdvHashSettings(config)
val properties = Properties()
// Act
settings.set("valid_key", 10.toString())
settings.onSave(properties)
settings.save()
// Assert
assertThat(properties["valid_key"]).isEqualTo("MTA=")
}
} | components/src/test/java/lt/markmerkk/utils/AdvHashSettingsGetIntTest.kt | 4080447725 |
package io.armcha.ribble.presentation.screen.shot_detail
import io.armcha.ribble.domain.entity.Comment
import io.armcha.ribble.presentation.base_mvp.api.ApiContract
/**
* Created by Chatikyan on 05.08.2017.
*/
interface ShotDetailContract {
interface View : ApiContract.View {
fun onDataReceive(commentList: List<Comment>)
fun getShotId(): String?
fun showNoComments()
}
interface Presenter : ApiContract.Presenter<View> {
fun handleShotLike(shotId: String?)
}
} | app/src/main/kotlin/io/armcha/ribble/presentation/screen/shot_detail/ShotDetailContract.kt | 891665483 |
package org.bh.tools.ui
import com.sun.java.swing.plaf.motif.MotifLookAndFeel
import org.bh.tools.ui.LafChangeErrorType.*
import org.bh.tools.util.MutableArrayPP
import java.awt.Window
import java.awt.event.ActionListener
import javax.swing.UIManager
import javax.swing.UnsupportedLookAndFeelException
import javax.swing.plaf.metal.MetalLookAndFeel
import javax.swing.plaf.nimbus.NimbusLookAndFeel
/**
* Copyright BHStudios ©2016 BH-1-PS. Made for BH Tic Tac Toe IntelliJ Project.
*
* A convenience class for changing the Java Look-And-Feel.
*
* @author Ben Leggiero
* @since 2016-10-01
* @version 2.0.0
*/
class LookAndFeelChanger {
companion object {
private var _changeListeners = MutableArrayPP<LafChangeListener>()
internal val _defaultLaf = UIManager.getLookAndFeel()
fun setLookAndFeel(lafEnum: LookAndFeelEnum,
force: Boolean = false,
errorHandler: LafChangeErrorHandler = NullLafChangeErrorHandler) {
setLookAndFeel(className = lafEnum.lafClassName, force = force, errorHandler = errorHandler)
}
@Throws(UnsupportedLookAndFeelException::class, ClassNotFoundException::class, InstantiationException::class, IllegalAccessException::class)
fun setLookAndFeel(className: CharSequence, force: Boolean = false, errorHandler: LafChangeErrorHandler) {
if (!force && UIManager.getLookAndFeel().javaClass.name == className) {
return
}
val previousLaf = UIManager.getLookAndFeel()
try {
UIManager.setLookAndFeel(className.toString())
val windows = Window.getWindows()
var isFrame: Boolean
var state: Int
for (i in windows.indices) {
val r = java.awt.Rectangle(windows[i].bounds)//Changed to new rather than assignment {Feb 22, 2012 (1.1.1) for Marian}
isFrame = windows[i] is java.awt.Frame
state = if (isFrame) (windows[i] as java.awt.Frame).state else java.awt.Frame.NORMAL
// windows[i].pack();//Commented out Feb 27, 2012 (1.1.1) for Marian - Though it makes the window look better in the end, it introduces unneeded lag and interfered with CompAction animations
javax.swing.SwingUtilities.updateComponentTreeUI(windows[i])
if (isFrame) {
(windows[i] as java.awt.Frame).state = state
}
if (!isFrame || state != java.awt.Frame.MAXIMIZED_BOTH) {
windows[i].bounds = r
}
}
} catch (ex: UnsupportedLookAndFeelException) {
UIManager.setLookAndFeel(previousLaf)
} catch (t: Throwable) {
try {
UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName())
} catch (t2: ClassNotFoundException) {
errorHandler(NotALaf)
} catch (t2: InstantiationException) {
errorHandler(CouldNotCreateLaf)
} catch (t2: IllegalAccessException) {
errorHandler(InaccessibleLafConstructor)
} catch (t2: UnsupportedLookAndFeelException) {
errorHandler(UnsupportedLaf)
} catch (t2: Throwable) {
errorHandler(UnknownError)
}
}
val evt = LafChangeEvent()
for (changeListener in _changeListeners)
changeListener?.lafChanged(evt)
}
// val _systemLaf: LookAndFeel by lazy { Class.forName(UIManager.getSystemLookAndFeelClassName()).newInstance() as LookAndFeel }
}
}
enum class LookAndFeelEnum(val lafClassName: CharSequence) {
Default(LookAndFeelChanger._defaultLaf.javaClass.name),
System(UIManager.getSystemLookAndFeelClassName()),
Metal(MetalLookAndFeel::class.java.name),
Nimbus(NimbusLookAndFeel::class.java.name),
Motif(MotifLookAndFeel::class.java.name),
}
typealias LafChangeErrorHandler = (type: LafChangeErrorType) -> Unit
val NullLafChangeErrorHandler: LafChangeErrorHandler = { x -> }
enum class LafChangeErrorType {
NotALaf,
CouldNotCreateLaf,
InaccessibleLafConstructor,
UnsupportedLaf,
UnknownError
}
class LafChangeEvent() {
}
interface LafChangeListener : ActionListener {
fun lafChanged(event: LafChangeEvent)
}
| BHToolbox/src/org/bh/tools/ui/LookAndFeelChanger.kt | 700604210 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.ui.offlinebasemap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.ground.MainActivity
import com.google.android.ground.databinding.OfflineBaseMapsFragBinding
import com.google.android.ground.ui.common.AbstractFragment
import com.google.android.ground.ui.common.Navigator
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* Fragment containing a list of downloaded areas on the device. An area is a set of offline raster
* tiles. Users can manage their areas within this fragment. They can delete areas they no longer
* need or access the UI used to select and download a new area to the device.
*/
@AndroidEntryPoint
class OfflineAreasFragment : AbstractFragment() {
@Inject lateinit var navigator: Navigator
private lateinit var offlineAreaListAdapter: OfflineAreaListAdapter
private lateinit var viewModel: OfflineAreasViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = getViewModel(OfflineAreasViewModel::class.java)
offlineAreaListAdapter = OfflineAreaListAdapter(navigator)
viewModel.offlineAreas.observe(this) { offlineAreaListAdapter.update(it) }
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
super.onCreateView(inflater, container, savedInstanceState)
val binding = OfflineBaseMapsFragBinding.inflate(inflater, container, false)
binding.viewModel = viewModel
binding.lifecycleOwner = this
(requireActivity() as MainActivity).setActionBar(binding.offlineAreasToolbar, true)
val recyclerView = binding.offlineAreasList
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = offlineAreaListAdapter
return binding.root
}
}
| ground/src/main/java/com/google/android/ground/ui/offlinebasemap/OfflineAreasFragment.kt | 642286580 |
/*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.widgets.views
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import org.isoron.uhabits.BaseViewTest
import org.isoron.uhabits.R
import org.isoron.uhabits.core.utils.DateUtils.Companion.getTodayWithOffset
import org.isoron.uhabits.utils.PaletteUtils.getAndroidTestColor
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
@RunWith(AndroidJUnit4::class)
@MediumTest
class CheckmarkWidgetViewTest : BaseViewTest() {
private lateinit var view: CheckmarkWidgetView
@Before
override fun setUp() {
super.setUp()
setTheme(R.style.WidgetTheme)
val habit = fixtures.createShortHabit()
val computedEntries = habit.computedEntries
val scores = habit.scores
val today = getTodayWithOffset()
val score = scores[today].value
view = CheckmarkWidgetView(targetContext).apply {
activeColor = getAndroidTestColor(0)
entryState = computedEntries.get(today).value
entryValue = computedEntries.get(today).value
percentage = score.toFloat()
name = habit.name
}
view.refresh()
measureView(view, dpToPixels(100), dpToPixels(125))
}
@Test
@Throws(IOException::class)
fun testRender_checked() {
assertRenders(view, PATH + "checked.png")
}
@Test
@Throws(IOException::class)
fun testRender_largeSize() {
measureView(view, dpToPixels(300), dpToPixels(300))
assertRenders(view, PATH + "large_size.png")
}
companion object {
private const val PATH = "widgets/CheckmarkWidgetView/"
}
}
| uhabits-android/src/androidTest/java/org/isoron/uhabits/widgets/views/CheckmarkWidgetViewTest.kt | 3817178077 |
/*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* 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 fredboat.event
import com.fredboat.sentinel.entities.MessageReceivedEvent
import com.google.common.cache.CacheBuilder
import fredboat.command.info.HelpCommand
import fredboat.command.info.ShardsCommand
import fredboat.command.info.StatsCommand
import fredboat.commandmeta.CommandContextParser
import fredboat.commandmeta.CommandInitializer
import fredboat.commandmeta.CommandManager
import fredboat.commandmeta.abs.CommandContext
import fredboat.config.property.AppConfigProperties
import fredboat.definitions.PermissionLevel
import fredboat.feature.metrics.Metrics
import fredboat.perms.Permission.MESSAGE_READ
import fredboat.perms.Permission.MESSAGE_WRITE
import fredboat.perms.PermissionSet
import fredboat.perms.PermsUtil
import fredboat.sentinel.InternalGuild
import fredboat.sentinel.Sentinel
import fredboat.sentinel.User
import fredboat.sentinel.getGuild
import fredboat.util.ratelimit.Ratelimiter
import io.prometheus.client.guava.cache.CacheMetricsCollector
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit
@Component
class MessageEventHandler(
private val sentinel: Sentinel,
private val ratelimiter: Ratelimiter,
private val commandContextParser: CommandContextParser,
private val commandManager: CommandManager,
private val appConfig: AppConfigProperties,
cacheMetrics: CacheMetricsCollector
) : SentinelEventHandler() {
companion object {
private val log: Logger = LoggerFactory.getLogger(MessageEventHandler::class.java)
// messageId <-> messageId
val messagesToDeleteIfIdDeleted = CacheBuilder.newBuilder()
.recordStats()
.expireAfterWrite(6, TimeUnit.HOURS)
.build<Long, Long>()!!
}
init {
cacheMetrics.addCache("messagesToDeleteIfIdDeleted", messagesToDeleteIfIdDeleted)
}
override fun onGuildMessage(event: MessageReceivedEvent) {
if (ratelimiter.isBlacklisted(event.author)) {
Metrics.blacklistedMessagesReceived.inc()
return
}
if (sentinel.selfUser.id == event.author) log.info(if(event.content.isBlank()) "<empty>" else event.content)
if (event.fromBot) return
//Preliminary permission filter to avoid a ton of parsing
//Let messages pass on to parsing that contain "help" since we want to answer help requests even from channels
// where we can't talk in
val permissions = PermissionSet(event.channelPermissions)
if (permissions hasNot (MESSAGE_READ + MESSAGE_WRITE)
&& !event.content.contains(CommandInitializer.HELP_COMM_NAME)) return
GlobalScope.launch {
val context = commandContextParser.parse(event) ?: return@launch
// Renew the time to prevent invalidation
(context.guild as InternalGuild).lastUsed = System.currentTimeMillis()
log.info(event.content)
//ignore all commands in channels where we can't write, except for the help command
if (permissions hasNot (MESSAGE_READ + MESSAGE_WRITE) && context.command !is HelpCommand) {
log.info("Ignoring command {} because this bot cannot write in that channel", context.command.name)
return@launch
}
Metrics.commandsReceived.labels(context.command.javaClass.simpleName).inc()
//ignore commands of disabled modules for plebs
//BOT_ADMINs can always use all commands everywhere
val module = context.command.module
if (module != null
&& !context.enabledModules.contains(module)
&& !PermsUtil.checkPerms(PermissionLevel.BOT_ADMIN, context.member)) {
log.debug("Ignoring command {} because its module {} is disabled",
context.command.name, module.name)
return@launch
}
limitOrExecuteCommand(context)
}
}
/**
* Check the rate limit of the user and execute the command if everything is fine.
* @param context Command context of the command to be invoked.
*/
private suspend fun limitOrExecuteCommand(context: CommandContext) {
if (ratelimiter.isRatelimited(context, context.command)) {
return
}
Metrics.executionTime.labels(context.command.javaClass.simpleName).startTimer().use {
commandManager.prefixCalled(context)
}
//NOTE: Some commands, like ;;mal, run async and will not reflect the real performance of FredBoat
// their performance should be judged by the totalResponseTime metric instead
}
override fun onPrivateMessage(author: User, content: String) {
if (ratelimiter.isBlacklisted(author.id)) {
Metrics.blacklistedMessagesReceived.inc()
return
}
//Technically not possible anymore to receive private messages from bots but better safe than sorry
//Also ignores our own messages since we're a bot
if (author.isBot) {
return
}
//quick n dirty bot admin / owner check
if (appConfig.adminIds.contains(author.id) || sentinel.applicationInfo.ownerId == author.id) {
//hack in / hardcode some commands; this is not meant to look clean
val lowered = content.toLowerCase()
if (lowered.contains("shard")) {
GlobalScope.launch {
for (message in ShardsCommand.getShardStatus(author.sentinel, content)) {
author.sendPrivate(message).subscribe()
}
}
return
} else if (lowered.contains("stats")) {
GlobalScope.launch {
author.sendPrivate(StatsCommand.getStats(null)).subscribe()
}
return
}
}
HelpCommand.sendGeneralHelp(author, content)
}
override fun onGuildMessageDelete(guildId: Long, channelId: Long, messageId: Long) {
val toDelete = messagesToDeleteIfIdDeleted.getIfPresent(messageId) ?: return
messagesToDeleteIfIdDeleted.invalidate(toDelete)
getGuild(guildId) { guild ->
val channel = guild.getTextChannel(channelId) ?: return@getGuild
sentinel.deleteMessages(channel, listOf(toDelete)).subscribe()
}
}
} | FredBoat/src/main/java/fredboat/event/MessageEventHandler.kt | 2073175390 |
package me.kerooker.rpgnpcgenerator.view.random.npc
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.constraintlayout.widget.ConstraintLayout
import kotlinx.android.synthetic.main.randomnpc_element_list_view.view.add_item_button
import kotlinx.android.synthetic.main.randomnpc_element_list_view.view.add_item_text
import kotlinx.android.synthetic.main.randomnpc_element_list_view.view.list
import me.kerooker.rpgnpcgenerator.R
interface OnPositionedRandomizeClick {
fun onRandomClick(index: Int)
}
interface OnPositionedDeleteClick {
fun onDeleteClick(index: Int)
}
interface IndexedManualInputListener {
fun onManualInput(index: Int, text: String)
}
class RandomNpcListView(
context: Context,
attrs: AttributeSet
) : ConstraintLayout(context, attrs) {
private val listView by lazy { list }
private val adapter by lazy { RandomNpcListAdapter(listView) }
init {
View.inflate(context, R.layout.randomnpc_element_list_view, this)
val attributes = context.obtainStyledAttributes(attrs, R.styleable.RandomNpcListView)
adapter.hint = attributes.getString(R.styleable.RandomNpcListView_list_hint)!!
attributes.recycle()
add_item_button.setOnClickListener { addItem() }
add_item_text.setOnClickListener { addItem() }
}
private fun addItem() {
val nextIndex = listView.childCount
adapter.onPositionedRandomizeClick.onRandomClick(nextIndex)
scrollToAddButton()
}
@Suppress("MagicNumber")
private fun scrollToAddButton() {
postDelayed(
{
val addButton = add_item_button
val rect = Rect(0, 0, addButton.width, addButton.height)
addButton.requestRectangleOnScreen(rect, false)
}, 100
)
}
fun setElements(elements: List<String>) {
adapter.elements = elements
}
fun setOnPositionedRandomizeClick(onPositionedRandomizeClick: OnPositionedRandomizeClick) {
adapter.onPositionedRandomizeClick = onPositionedRandomizeClick
}
fun setOnPositionedDeleteClick(onPositionedDeleteClick: OnPositionedDeleteClick) {
adapter.onPositionedDeleteClick = onPositionedDeleteClick
}
fun setOnIndexedManualInputListener(indexedManualInputListener: IndexedManualInputListener) {
adapter.indexedManualInputListener = indexedManualInputListener
}
}
class RandomNpcListAdapter(
private val listView: LinearLayout
) {
lateinit var onPositionedRandomizeClick: OnPositionedRandomizeClick
lateinit var onPositionedDeleteClick: OnPositionedDeleteClick
lateinit var indexedManualInputListener: IndexedManualInputListener
var hint: String = ""
var elements: List<String> = emptyList()
set(value) {
field = value
updateElements()
}
private fun updateElements() {
elements.forEachIndexed { index, s ->
updateOrCreate(index, s)
}
removeRemainingViews()
}
private fun updateOrCreate(index: Int, string: String) {
val currentPosition = listView.getChildAt(index)
if(currentPosition == null) create(index, string) else update(index, string)
}
private fun create(index: Int, string: String) {
val view = createView(string)
listView.addView(view, index)
}
private fun createView(string: String): View {
val inflater = LayoutInflater.from(listView.context)
val view =
inflater.inflate(R.layout.randomnpc_element_list_view_item, listView, false) as RandomNpcElementListview
view.prepareTexts(string)
view.prepareListeners()
return view
}
private fun update(index: Int, text: String) {
val view = listView.getChildAt(index) as RandomNpcElementListview
view.prepareTexts(text)
}
private fun RandomNpcElementListview.prepareTexts(text: String) {
setText(text)
setHint(hint)
}
private fun RandomNpcElementListview.prepareListeners() {
onRandomClick = {
val index = listView.indexOfChild(this)
onPositionedRandomizeClick.onRandomClick(index)
}
onDeleteClick = {
val index = listView.indexOfChild(this)
listView.removeViewAt(index)
onPositionedDeleteClick.onDeleteClick(index)
}
onManualInput = object : ManualInputListener {
override fun onManualInput(text: String) {
val index = listView.indexOfChild(this@prepareListeners)
indexedManualInputListener.onManualInput(index, text)
}
}
}
private fun removeRemainingViews() {
val elementsSize = elements.size
val childrenSize = listView.childCount
val difference = childrenSize - elementsSize
if(difference <= 0) return
repeat(difference) {
val lastIndex = listView.childCount - 1
listView.removeViewAt(lastIndex)
}
}
}
| app/src/main/java/me/kerooker/rpgnpcgenerator/view/random/npc/RandomNpcListView.kt | 1645478092 |
// 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.debugger.stackFrame
import com.intellij.debugger.impl.DebuggerUtilsEx
import com.intellij.debugger.jdi.LocalVariableProxyImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.xdebugger.frame.XStackFrame
import com.sun.jdi.LocalVariable
import com.sun.jdi.Location
import com.sun.jdi.Method
import com.sun.jdi.StackFrame
import org.jetbrains.kotlin.idea.debugger.*
import org.jetbrains.kotlin.load.java.JvmAbi
object InlineStackTraceCalculator {
fun calculateInlineStackTrace(frameProxy: StackFrameProxyImpl): List<XStackFrame> =
frameProxy.stackFrame.computeKotlinStackFrameInfos().map {
it.toXStackFrame(frameProxy)
}.reversed()
// Calculate the variables that are visible in the top stack frame.
fun calculateVisibleVariables(frameProxy: StackFrameProxyImpl): List<LocalVariableProxyImpl> =
frameProxy.stackFrame.computeKotlinStackFrameInfos().last().visibleVariableProxies(frameProxy)
}
private val INLINE_LAMBDA_REGEX =
"${JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT.replace("$", "\\$")}-(.+)-[^\$]+\\$([^\$]+)\\$.*"
.toRegex()
class KotlinStackFrameInfo(
// The scope introduction variable for an inline stack frame, i.e., $i$f$function
// or $i$a$lambda. The name of this variable determines the label for an inline
// stack frame. This is null for non-inline stack frames.
val scopeVariable: VariableWithLocation?,
// For inline lambda stack frames we need to include the visible variables from the
// enclosing stack frame.
private val enclosingStackFrame: KotlinStackFrameInfo?,
// All variables that were added in this stack frame.
val visibleVariablesWithLocations: MutableList<VariableWithLocation>,
// For an inline stack frame, the number of calls from the nearest non-inline function.
// TODO: Remove. This is only used in the evaluator, to look up variables, but the depth
// is not sufficient to determine which frame a variable is in.
val depth: Int,
) {
// The location for this stack frame, i.e., the current location of the StackFrame for the
// most recent frame or the location of an inline function call for any enclosing frame.
// This depends on the next stack frame info and is initialized after the KotlinStackFrameInfo.
var callLocation: Location? = null
val displayName: String?
get() {
val scopeVariableName = scopeVariable?.name
?: return null
if (scopeVariableName.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION)) {
return scopeVariableName.substringAfter(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION)
}
val groupValues = INLINE_LAMBDA_REGEX.matchEntire(scopeVariableName)?.groupValues
if (groupValues != null) {
val lambdaName = groupValues.getOrNull(1)
val declarationFunctionName = groupValues.getOrNull(2)
return "lambda '$lambdaName' in '$declarationFunctionName'"
} else {
return scopeVariableName
}
}
val visibleVariables: List<LocalVariable>
get() = filterRepeatedVariables(
visibleVariablesWithLocations
.mapTo(enclosingStackFrame?.visibleVariables?.toMutableList() ?: mutableListOf()) {
it.variable
}
)
fun visibleVariableProxies(frameProxy: StackFrameProxyImpl): List<LocalVariableProxyImpl> =
visibleVariables.map { LocalVariableProxyImpl(frameProxy, it) }
fun toXStackFrame(frameProxy: StackFrameProxyImpl): XStackFrame {
val variables = visibleVariableProxies(frameProxy)
displayName?.let { name ->
return InlineStackFrame(callLocation, name, frameProxy, depth, variables)
}
return KotlinStackFrame(safeInlineStackFrameProxy(callLocation, 0, frameProxy), variables)
}
}
fun StackFrame.computeKotlinStackFrameInfos(): List<KotlinStackFrameInfo> {
val location = location()
val method = location.safeMethod() ?: return emptyList()
val allVisibleVariables = method.sortedVariablesWithLocation().filter {
it.variable.isVisible(this)
}
return computeStackFrameInfos(allVisibleVariables).also {
fetchCallLocations(method, it, location)
}
}
// Constructs a list of inline stack frames from a list of currently visible variables
// in introduction order.
//
// In order to construct the inline stack frame we need to associate each variable with
// a call to an inline function and keep track of the currently active inline function.
// Consider the following code.
//
// fun f() {
// val x = 0
// g {
// h(2)
// }
// }
//
// inline fun g(block: () -> Unit) {
// var y = 1
// block()
// }
//
// inline fun h(a: Int) {
// var z = 3
// /* breakpoint */ ...
// }
//
// When stopped at the breakpoint in `h`, we have the following visible variables.
//
// | Variable | Depth | Scope | Frames | Pending |
// |-------------------|-------|-------|-----------------------|----------|
// | x | 0 | f | f:[x] | |
// | $i$f$g | 1 | g | f:[x], g:[] | |
// | y$iv | 1 | g | f:[x], g:[y$iv] | |
// | $i$a$-g-Class$f$1 | 0 | f$1 | f:[x] | |
// | a$iv | 1 | h | f:[x] | 1:[a$iv] |
// | $i$f$h | 1 | h | f:[x], h:[a$iv] | |
// | z$iv | 1 | h | f:[x], h:[a$iv, z$iv] | |
//
// There are two kinds of variables. Scope introduction variables are prefixed with
// $i$f or $i$a and represent calls to inline functions or calls to function arguments
// of inline functions respectively. All remaining variables represent source code
// variables along with an inline depth represented by the number of `$iv` suffixes.
//
// This function works by simulating the current active call stack while iterating
// over the variables in introduction order. New frames are introduced or removed
// when encountering scope introduction variables. Each variable encountered
// is either associated to the currently active stack frame or to the next
// stack frame at its depth (since arguments of inline functions appear before the
// corresponding scope introduction variable).
private fun computeStackFrameInfos(sortedVariables: List<VariableWithLocation>): List<KotlinStackFrameInfo> {
// List of all stack frames in introduction order. We always start with a non-inline stack frame.
val stackFrameInfos = mutableListOf(KotlinStackFrameInfo(null, null, mutableListOf(), 0))
// Variables which should appear in a future stack frame. On the jvm these are arguments
// to the next inline function call. On dex there are also variables which were moved
// before or after their stack frame.
val pendingVariables = mutableMapOf<Int, MutableList<VariableWithLocation>>()
// The current call stack, as a list of active frame indices into stackFrameInfos. This is always non-empty.
var activeFrames = mutableListOf(0)
for (variable in sortedVariables) {
// When we encounter a call to an inline function, we start a new stack frame
// without any enclosing frame.
if (variable.name.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION)) {
val depth = activeFrames.size
stackFrameInfos += KotlinStackFrameInfo(
variable,
null,
pendingVariables[depth] ?: mutableListOf(),
depth
)
pendingVariables.remove(depth)
activeFrames += stackFrameInfos.size - 1
continue
}
val depth = getInlineDepth(variable.name)
when {
// When we encounter a call to an inline function argument, we are
// moving up the call stack to the depth of the function argument.
variable.name.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT) -> {
// for lambda arguments to inline only functions the depth doesn't change,
// i.e., we would have depth + 1 == activeFrames.size.
if (depth + 1 < activeFrames.size) {
activeFrames = activeFrames.subList(0, depth + 1)
}
// TODO: If we get unlucky, we may encounter an inline lambda before its enclosing frame.
// There's no good workaround in this case, since we can't distinguish between
// inline function calls inside such a lambda and the calls corresponding to the
// enclosing frame. We should communicate this situation somehow.
if (depth < activeFrames.size) {
stackFrameInfos += KotlinStackFrameInfo(
variable,
stackFrameInfos[activeFrames[depth]],
pendingVariables[depth] ?: mutableListOf(),
depth
)
pendingVariables.remove(depth)
activeFrames[depth] = stackFrameInfos.size - 1
}
}
// Process variables in the current frame.
depth == activeFrames.size - 1 -> {
stackFrameInfos[activeFrames[depth]].visibleVariablesWithLocations += variable
}
// Process arguments to the next inline function call or variables that were
// moved to the wrong location on dex.
else -> {
pendingVariables.getOrPut(depth) { mutableListOf() } += variable
}
}
}
// For valid debug information there should be no pending variables at this point,
// except possibly when we are stopped while evaluating default arguments to an inline
// function.
for ((depth, variables) in pendingVariables.entries) {
if (depth < activeFrames.size) {
stackFrameInfos[activeFrames[depth]].visibleVariablesWithLocations += variables
} else {
// This can happen in two cases: Either we are stopped right before an inline call
// when some arguments are already in variables or the debug information is invalid
// and some variables were moved after a call to an inline lambda.
// Instead of throwing them away we'll add these variables to the last call stack at
// the desired depth (there probably won't be one in the first case).
stackFrameInfos.lastOrNull {
it.depth == depth
}?.visibleVariablesWithLocations?.addAll(variables)
}
}
return stackFrameInfos
}
// Heuristic to guess inline call locations based on the variables in a `KotlinStackFrameInfo`
// and the `KotlinDebug` SMAP stratum.
//
// There is currently no way of reliably computing inline call locations using the Kotlin
// debug information. We can try to compute the call location based on the locations of the
// local variables in an inline stack frame or based on the KotlinDebug stratum for the
// one case where this will work.
//
// ---
//
// On the JVM it seems reasonable to determine the call location using the location
// immediately preceding a scope introduction variable.
//
// The JVM IR backend generates a line number before every inline call. For inline
// functions without default arguments the scope introduction variable starts at the first
// line of an inline function. In this particular case, the previous location corresponds
// to the call location. This is not true for the old JVM backend or for inline functions
// with default arguments.
//
// There is not much we can do for the old JVM backend, since there are cases where we simply
// do not have a line number for an inline call. We're ignoring this issue since the old
// backend is already deprecated.
//
// In order to handle inline functions with default arguments we could take the location
// immediately preceding all variables in the inline stack frame. This would include the function
// arguments. However, there still wouldn't be any guarantee that this corresponds to the call
// location, since the inliner does not introduce a new variable for inline function arguments
// if the argument at the call site is already in a variable. This is an optimization that
// always leads to invalid debug information and this case is not an exception.
//
// Finally, it is also not clear how to reliably determine whether we are in an inline default
// stub, so all in all it is probably better to just use the scope introduction variable and accept
// that the call location will be incorrect in inline default stubs.
//
// Finally, of course, on dex the situation is worse since we cannot rely on the locations
// of local variables due to spilling.
//
// ---
//
// The KotlinDebug stratum records the location of the first inline call in a function and
// can thus be used to determine the call location of the first inline stack frame. This
// information is produced by the inliner itself and should be correct.
//
// The only heuristic step is an issue with the API: We need to produce a JDI [Location],
// but the KotlinDebug SMAP only provides us with a file and line pair. This means that
// we actually don't know the code index of the call. OTOH, there is no real reason why
// the UI would need the code index at all and this is something we could fix by moving
// away from using JDI data structures for the UI representation.
//
// Note though, that the KotlinDebug stratum only records the location of the first call to
// an inline *function*, so it is useless for nested calls or calls to inline only functions.
// The latter result in calls to lambda arguments which don't appear in the KotlinDebug stratum.
//
// Moreover, the KotlinDebug stratum only applies to remapped line numbers, so it cannot be
// used in top-level inline lambda arguments.
private fun fetchCallLocations(
method: Method,
kotlinStackFrameInfos: List<KotlinStackFrameInfo>,
defaultLocation: Location,
) {
kotlinStackFrameInfos.lastOrNull()?.callLocation = defaultLocation
// If there are no inline calls we don't need to fetch the line locations.
// It's important to exit early here, since fetching line locations might involve
// a round-trip to the debuggee vm.
if (kotlinStackFrameInfos.size <= 1)
return
val allLocations = DebuggerUtilsEx.allLineLocations(method)
if (allLocations == null) {
// In case of broken debug information we use the same location for all stack frames.
kotlinStackFrameInfos.forEach { it.callLocation = defaultLocation }
return
}
// If the current location is covered by the KotlinDebug stratum then we can use it to
// look up the location of the first call to an inline function (but not to an inline
// lambda argument).
var startIndex = 1
kotlinStackFrameInfos[1].scopeVariable?.takeIf {
it.name.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION)
}?.let { firstInlineScopeVariable ->
// We cannot use the current location to look up the location in the KotlinDebug
// stratum, since it might be in a top-level inline lambda and hence not covered
// by KotlinDebug.
//
// The scope introduction variable on the other hand should start inside an
// inline function.
val startOffset = firstInlineScopeVariable.location
val callLineNumber = startOffset.safeLineNumber("KotlinDebug")
val callSourceName = startOffset.safeSourceName("KotlinDebug")
if (callLineNumber != -1 && callSourceName != null) {
// Find the closest location to startOffset with the correct line number and source name.
val callLocation = allLocations.lastOrNull { location ->
location < startOffset &&
location.safeLineNumber() == callLineNumber &&
location.safeSourceName() == callSourceName
}
if (callLocation != null) {
kotlinStackFrameInfos[0].callLocation = callLocation
startIndex++
}
}
}
for (index in startIndex until kotlinStackFrameInfos.size) {
// Find the index of the location closest to the start of the scope variable.
// NOTE: [Method.allLineLocations] returns locations ordered by codeIndex.
val scopeIndex =
kotlinStackFrameInfos[index]
.scopeVariable
?.location
?.let(allLocations::binarySearch)
// If there is no scope introduction variable, or if it effectively starts on the first
// location we use the default location. The latter case can only happen if the user
// called a Kotlin inline function directly from Java. We will incorrectly present
// an inline stack frame in this case, but this is not a supported use case anyway.
val prev = kotlinStackFrameInfos[index - 1]
if (scopeIndex == null || scopeIndex in -1..0) {
prev.callLocation = defaultLocation
continue
}
var locationIndex = if (scopeIndex > 0) {
// If the scope variable starts on a line we take the previous line.
scopeIndex - 1
} else /* if (scopeIndex <= -2) */ {
// If the returned location is < 0, then the element should be inserted at position
// `-locationIndex - 1` to preserve the sorting order and the element at position
// `-locationIndex - 2` contains the previous line number.
-scopeIndex - 2
}
// Skip to the previous location if the call location lands on a synthetic fake.kt:1 line.
// These lines are inserted by the compiler to force new line numbers for single line lambdas.
if (DebuggerUtils.isKotlinFakeLineNumber(allLocations[locationIndex])) {
locationIndex = (locationIndex - 1).coerceAtLeast(0)
}
prev.callLocation = allLocations[locationIndex]
}
}
| plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stackFrame/InlineStackTraceCalculator.kt | 3045881282 |
// 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.editorconfig.language.codeinsight.annotators
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.SyntaxTraverser
import org.editorconfig.language.highlighting.EditorConfigSyntaxHighlighter
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.*
import org.editorconfig.language.schema.descriptors.impl.EditorConfigDeclarationDescriptor
class EditorConfigAnnotatorVisitor(private val holder: AnnotationHolder) : EditorConfigVisitor() {
override fun visitQualifiedOptionKey(key: EditorConfigQualifiedOptionKey) {
checkEdgeDots(key.firstChild, key.firstChild.nextSibling)
checkEdgeDots(key.lastChild, key.lastChild.prevSibling)
checkInnerDots(key)
}
private fun checkInnerDots(key: EditorConfigQualifiedOptionKey) {
var firstDot: PsiElement? = null
var lastDot: PsiElement? = null
SyntaxTraverser.psiTraverser().children(key).forEach {
when {
it.node.elementType == EditorConfigElementTypes.DOT -> {
if (firstDot == null) {
firstDot = it
}
lastDot = it
}
firstDot != lastDot -> {
val message = EditorConfigBundle.get("annotator.error.multiple-dots")
val start = firstDot!!.textRange.startOffset
val end = lastDot!!.textRange.endOffset // + lastDot!!.textLength
val range = TextRange.create(start, end)
holder.newAnnotation(HighlightSeverity.ERROR, message).range(range).create()
firstDot = null
lastDot = null
}
else -> {
firstDot = null
lastDot = null
}
}
}
}
private fun checkEdgeDots(edgeElement: PsiElement, neighbourElement: PsiElement?) {
if (edgeElement.node.elementType != EditorConfigElementTypes.DOT) return
if (neighbourElement?.node?.elementType == EditorConfigElementTypes.DOT) return
val message = EditorConfigBundle.get("annotator.error.key.dangling-dot")
holder.newAnnotation(HighlightSeverity.ERROR, message).range(edgeElement).create()
}
override fun visitOption(option: EditorConfigOption) {
checkLineBreaks(option)
}
private fun checkLineBreaks(option: EditorConfigOption) {
if (!option.textContains('\n')) return
val message = EditorConfigBundle["annotator.error.option.suspicious.line.break"]
holder.newAnnotation(HighlightSeverity.ERROR, message).range(option).create()
}
override fun visitFlatOptionKey(flatKey: EditorConfigFlatOptionKey) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(flatKey).textAttributes(EditorConfigSyntaxHighlighter.PROPERTY_KEY).create()
}
override fun visitQualifiedKeyPart(keyPart: EditorConfigQualifiedKeyPart) {
val descriptor = keyPart.getDescriptor(false)
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(keyPart).textAttributes(
if (descriptor is EditorConfigDeclarationDescriptor) EditorConfigSyntaxHighlighter.PROPERTY_KEY
else EditorConfigSyntaxHighlighter.KEY_DESCRIPTION).create()
}
override fun visitOptionValueIdentifier(identifier: EditorConfigOptionValueIdentifier) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(identifier).textAttributes(EditorConfigSyntaxHighlighter.PROPERTY_VALUE).create()
}
override fun visitRawOptionValue(rawOptionValue: EditorConfigRawOptionValue) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(rawOptionValue).textAttributes(EditorConfigSyntaxHighlighter.PROPERTY_VALUE).create()
}
override fun visitFlatPattern(flatPattern: EditorConfigFlatPattern) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(flatPattern).textAttributes(EditorConfigSyntaxHighlighter.PATTERN).create()
if (!flatPattern.textContains('\\')) return
val text = flatPattern.text
val offset = flatPattern.textOffset
var index = 0
while (index < text.length) {
if (text[index] == '\\') {
val range = TextRange(offset + index, offset + index + 2)
index += 1
if (EditorConfigSyntaxHighlighter.VALID_ESCAPES.contains(text[index])) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(range).textAttributes(EditorConfigSyntaxHighlighter.VALID_CHAR_ESCAPE).create()
}
else {
val message = EditorConfigBundle["annotator.error.illegal.char.escape"]
holder.newAnnotation(HighlightSeverity.INFORMATION, message).range(range).textAttributes(EditorConfigSyntaxHighlighter.INVALID_CHAR_ESCAPE).create()
}
}
index += 1
}
}
override fun visitAsteriskPattern(pattern: EditorConfigAsteriskPattern) {
special(pattern)
}
override fun visitDoubleAsteriskPattern(pattern: EditorConfigDoubleAsteriskPattern) {
special(pattern)
}
private fun special(pattern: PsiElement) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(pattern).textAttributes(
EditorConfigSyntaxHighlighter.SPECIAL_SYMBOL).create()
}
override fun visitCharClassExclamation(exclamation: EditorConfigCharClassExclamation) {
special(exclamation)
}
override fun visitQuestionPattern(pattern: EditorConfigQuestionPattern) {
special(pattern)
}
override fun visitCharClassLetter(letter: EditorConfigCharClassLetter) = when {
!letter.isEscape -> holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(letter).textAttributes(EditorConfigSyntaxHighlighter.PATTERN).create()
letter.isValidEscape -> holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(letter).textAttributes(EditorConfigSyntaxHighlighter.VALID_CHAR_ESCAPE).create()
else -> holder.newAnnotation(HighlightSeverity.INFORMATION, EditorConfigBundle.get("annotator.error.illegal.char.escape")).range(letter).textAttributes(EditorConfigSyntaxHighlighter.INVALID_CHAR_ESCAPE).create()
}
override fun visitRootDeclarationKey(key: EditorConfigRootDeclarationKey) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(key).textAttributes(EditorConfigSyntaxHighlighter.PROPERTY_KEY).create()
}
override fun visitRootDeclarationValue(value: EditorConfigRootDeclarationValue) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(value).textAttributes(EditorConfigSyntaxHighlighter.PROPERTY_VALUE).create()
}
}
| plugins/editorconfig/src/org/editorconfig/language/codeinsight/annotators/EditorConfigAnnotatorVisitor.kt | 1483894237 |
class Foo : Bar() {
fun test(): String {
return <caret>Companion.bar
}
companion object {
val bar: String = "bar"
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantCompanionReference/javaFakeGetter.kt | 724395944 |
import javaApi.JavaClass
import kotlinApi.KotlinClass
internal class X {
operator fun get(index: Int): Int {
return 0
}
}
internal class C {
fun foo(map: HashMap<String?, String?>): String? {
return map["a"]
}
fun foo(x: X): Int {
return x[0]
}
fun foo(kotlinClass: KotlinClass): Int {
return kotlinClass.get(0) // not operator!
}
fun foo(javaClass: JavaClass): Int {
return javaClass[0]
}
} | plugins/kotlin/j2k/new/tests/testData/newJ2k/postProcessing/GetOperator.kt | 663220904 |
package com.jcs.suadeome.professionals
import com.jcs.suadeome.services.Service
import com.jcs.suadeome.types.Id
import org.skife.jdbi.v2.Handle
import java.util.*
class ProfessionalRepository(val openHandle: Handle) {
fun professionalsByService(services: List<Service>): List<Professional> {
if (services.isEmpty()) return Collections.emptyList()
val placeHolders = services.mapIndexed { i, service -> ":id$i" }.joinToString(",")
val whereClause = if (placeHolders.isBlank()) "" else "WHERE service_id IN ( $placeHolders )"
val query = openHandle.createQuery("""
SELECT id, name, phone, service_id
FROM professionals
$whereClause
ORDER BY name
""")
services.forEachIndexed { i, service ->
query.bind("id$i", service.id.value)
}
val rows = query.list()
val professionals = rows.map { rowToProfessional(it) }
return professionals
}
private fun rowToProfessional(row: Map<String, Any>): Professional {
val id = Id(row["id"].toString())
val name = row["name"].toString()
val phone = PhoneNumber(row["phone"].toString())
val serviceId = Id(row["service_id"].toString())
return Professional(id, name, phone, serviceId)
}
fun createProfessional(professional: Professional) {
val query = """
INSERT INTO professionals (id, name, phone, service_id, created_by, created_at)
VALUES (:id, :name, :phone, :serviceId, :user, :now)
"""
openHandle.createStatement(query)
.bind("id", professional.id.value)
.bind("name", professional.name)
.bind("phone", professional.phone.number)
.bind("serviceId", professional.serviceId.value)
.bind("user", 1)
.bind("now", Date())
.execute()
}
}
| src/main/kotlin/com/jcs/suadeome/professionals/ProfessionalRepository.kt | 3351957792 |
// snippet-sourcedescription:[ScenarioPartiQ.kt demonstrates how to work with PartiQL for Amazon DynamoDB.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon DynamoDB]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.dynamodb
// snippet-start:[dynamodb.kotlin.scenario.partiql.import]
import aws.sdk.kotlin.services.dynamodb.DynamoDbClient
import aws.sdk.kotlin.services.dynamodb.model.AttributeDefinition
import aws.sdk.kotlin.services.dynamodb.model.AttributeValue
import aws.sdk.kotlin.services.dynamodb.model.CreateTableRequest
import aws.sdk.kotlin.services.dynamodb.model.DeleteTableRequest
import aws.sdk.kotlin.services.dynamodb.model.ExecuteStatementRequest
import aws.sdk.kotlin.services.dynamodb.model.ExecuteStatementResponse
import aws.sdk.kotlin.services.dynamodb.model.KeySchemaElement
import aws.sdk.kotlin.services.dynamodb.model.KeyType
import aws.sdk.kotlin.services.dynamodb.model.ProvisionedThroughput
import aws.sdk.kotlin.services.dynamodb.model.ScalarAttributeType
import aws.sdk.kotlin.services.dynamodb.waiters.waitUntilTableExists
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import java.io.File
import kotlin.system.exitProcess
// snippet-end:[dynamodb.kotlin.scenario.partiql.import]
/**
Before running this Kotlin code example, set up your development environment, including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
// snippet-start:[dynamodb.kotlin.scenario.partiql.main]
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<fileName>
Where:
fileName - The path to the moviedata.json you can download from the Amazon DynamoDB Developer Guide.
"""
if (args.size != 1) {
println(usage)
exitProcess(1)
}
val ddb = DynamoDbClient { region = "us-east-1" }
val tableName = "MoviesPartiQ"
// Get the moviedata.json from the Amazon DynamoDB Developer Guide.
val fileName = args[0]
println("Creating an Amazon DynamoDB table named MoviesPartiQ with a key named id and a sort key named title.")
createTablePartiQL(ddb, tableName, "year")
loadDataPartiQL(ddb, fileName)
println("******* Getting data from the MoviesPartiQ table.")
getMoviePartiQL(ddb)
println("******* Putting a record into the MoviesPartiQ table.")
putRecordPartiQL(ddb)
println("******* Updating a record.")
updateTableItemPartiQL(ddb)
println("******* Querying the movies released in 2013.")
queryTablePartiQL(ddb)
println("******* Deleting the MoviesPartiQ table.")
deleteTablePartiQL(tableName)
}
suspend fun createTablePartiQL(ddb: DynamoDbClient, tableNameVal: String, key: String) {
val attDef = AttributeDefinition {
attributeName = key
attributeType = ScalarAttributeType.N
}
val attDef1 = AttributeDefinition {
attributeName = "title"
attributeType = ScalarAttributeType.S
}
val keySchemaVal = KeySchemaElement {
attributeName = key
keyType = KeyType.Hash
}
val keySchemaVal1 = KeySchemaElement {
attributeName = "title"
keyType = KeyType.Range
}
val provisionedVal = ProvisionedThroughput {
readCapacityUnits = 10
writeCapacityUnits = 10
}
val request = CreateTableRequest {
attributeDefinitions = listOf(attDef, attDef1)
keySchema = listOf(keySchemaVal, keySchemaVal1)
provisionedThroughput = provisionedVal
tableName = tableNameVal
}
val response = ddb.createTable(request)
ddb.waitUntilTableExists { // suspend call
tableName = tableNameVal
}
println("The table was successfully created ${response.tableDescription?.tableArn}")
}
suspend fun loadDataPartiQL(ddb: DynamoDbClient, fileName: String) {
val sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}"
val parser = JsonFactory().createParser(File(fileName))
val rootNode = ObjectMapper().readTree<JsonNode>(parser)
val iter: Iterator<JsonNode> = rootNode.iterator()
var currentNode: ObjectNode
var t = 0
while (iter.hasNext()) {
if (t == 200)
break
currentNode = iter.next() as ObjectNode
val year = currentNode.path("year").asInt()
val title = currentNode.path("title").asText()
val info = currentNode.path("info").toString()
val parameters: MutableList<AttributeValue> = ArrayList<AttributeValue>()
parameters.add(AttributeValue.N(year.toString()))
parameters.add(AttributeValue.S(title))
parameters.add(AttributeValue.S(info))
executeStatementPartiQL(ddb, sqlStatement, parameters)
println("Added Movie $title")
parameters.clear()
t++
}
}
suspend fun getMoviePartiQL(ddb: DynamoDbClient) {
val sqlStatement = "SELECT * FROM MoviesPartiQ where year=? and title=?"
val parameters: MutableList<AttributeValue> = ArrayList<AttributeValue>()
parameters.add(AttributeValue.N("2012"))
parameters.add(AttributeValue.S("The Perks of Being a Wallflower"))
val response = executeStatementPartiQL(ddb, sqlStatement, parameters)
println("ExecuteStatement successful: $response")
}
suspend fun putRecordPartiQL(ddb: DynamoDbClient) {
val sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}"
val parameters: MutableList<AttributeValue> = java.util.ArrayList()
parameters.add(AttributeValue.N("2020"))
parameters.add(AttributeValue.S("My Movie"))
parameters.add(AttributeValue.S("No Info"))
executeStatementPartiQL(ddb, sqlStatement, parameters)
println("Added new movie.")
}
suspend fun updateTableItemPartiQL(ddb: DynamoDbClient) {
val sqlStatement = "UPDATE MoviesPartiQ SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack\' where year=? and title=?"
val parameters: MutableList<AttributeValue> = java.util.ArrayList()
parameters.add(AttributeValue.N("2013"))
parameters.add(AttributeValue.S("The East"))
executeStatementPartiQL(ddb, sqlStatement, parameters)
println("Item was updated!")
}
// Query the table where the year is 2013.
suspend fun queryTablePartiQL(ddb: DynamoDbClient) {
val sqlStatement = "SELECT * FROM MoviesPartiQ where year = ?"
val parameters: MutableList<AttributeValue> = java.util.ArrayList()
parameters.add(AttributeValue.N("2013"))
val response = executeStatementPartiQL(ddb, sqlStatement, parameters)
println("ExecuteStatement successful: $response")
}
suspend fun deleteTablePartiQL(tableNameVal: String) {
val request = DeleteTableRequest {
tableName = tableNameVal
}
DynamoDbClient { region = "us-east-1" }.use { ddb ->
ddb.deleteTable(request)
println("$tableNameVal was deleted")
}
}
suspend fun executeStatementPartiQL(
ddb: DynamoDbClient,
statementVal: String,
parametersVal: List<AttributeValue>
): ExecuteStatementResponse {
val request = ExecuteStatementRequest {
statement = statementVal
parameters = parametersVal
}
return ddb.executeStatement(request)
}
// snippet-end:[dynamodb.kotlin.scenario.partiql.main]
| kotlin/services/dynamodb/src/main/kotlin/com/kotlin/dynamodb/ScenarioPartiQ.kt | 3597429295 |
/*
* Copyright © 2019. Sir Wellington.
* 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.
*/
@file:JvmName("NumberAssertions")
package tech.sirwellington.alchemy.arguments.assertions
import tech.sirwellington.alchemy.arguments.AlchemyAssertion
import tech.sirwellington.alchemy.arguments.FailedAssertionException
import tech.sirwellington.alchemy.arguments.checkThat
import java.lang.Math.abs
/**
* @author SirWellington
*/
/**
* Asserts that an integer is `>` the supplied value.
* @param exclusiveLowerBound The argument must be `> exclusiveLowerBound`.
*
*
* @return
*/
fun greaterThan(exclusiveLowerBound: Int): AlchemyAssertion<Int>
{
checkThat(exclusiveLowerBound != Integer.MAX_VALUE, "Integers cannot exceed ${Int.MAX_VALUE}")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number > exclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be > $exclusiveLowerBound")
}
}
}
/**
* Asserts that a long is `> exclusiveLowerBound`.
* @param exclusiveLowerBound The argument must be `>` this value.
*
*
* @return
*/
fun greaterThan(exclusiveLowerBound: Long): AlchemyAssertion<Long>
{
checkThat(exclusiveLowerBound != Long.MAX_VALUE, "Longs cannot exceed ${Long.MAX_VALUE}")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number > exclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be > $exclusiveLowerBound")
}
}
}
/**
* Asserts that a double is `> exclusiveLowerBound` within `delta` margin of error.
* @param exclusiveLowerBound The argument is expected to be `>` this value.
*
* @param delta The allowable margin of error for the `>` operation.
*
*
* @return
*/
@JvmOverloads
fun greaterThan(exclusiveLowerBound: Double, delta: Double = 0.0): AlchemyAssertion<Double>
{
checkThat(exclusiveLowerBound < Double.MAX_VALUE, "Doubles cannot exceed ${Double.MAX_VALUE}")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number!! + abs(delta) > exclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be > $exclusiveLowerBound +- $delta")
}
}
}
/**
* Asserts that an integer is `>=` the supplied value.
*
* @param inclusiveLowerBound The argument integer must be `>= inclusiveLowerBound`
*
*
* @return
*/
fun greaterThanOrEqualTo(inclusiveLowerBound: Int): AlchemyAssertion<Int>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number >= inclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be greater than or equal to $inclusiveLowerBound")
}
}
}
/**
* Asserts that a long is `>= inclusiveLowerBound`.
* @param inclusiveLowerBound The argument integer must be `>= inclusiveUpperBound`
*
*
* @return
*/
fun greaterThanOrEqualTo(inclusiveLowerBound: Long): AlchemyAssertion<Long>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number >= inclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be greater than or equal to $inclusiveLowerBound")
}
}
}
/**
* Asserts that a double is `>= inclusiveLowerBound` within `delta` margin-of-error.
* @param inclusiveLowerBound The argument double must be `>= inclusiveLowerBound` within the margin of error.
* @param delta The allowable margin-of-error for the `>= ` comparison.
*
*
* @return
*/
@JvmOverloads
fun greaterThanOrEqualTo(inclusiveLowerBound: Double, delta: Double = 0.0): AlchemyAssertion<Double>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number + abs(delta) >= inclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be >= $inclusiveLowerBound +- $delta")
}
}
}
/**
* Asserts that an integer is positive, or `> 0`
* @return
*/
fun positiveInteger(): AlchemyAssertion<Int>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
if (number <= 0)
{
throw FailedAssertionException("Expected positive integer: $number")
}
}
}
/**
* Asserts that an integer is negative, or `< 0`.
* @return
*/
fun negativeInteger(): AlchemyAssertion<Int>
{
return lessThan(0)
}
/**
* Asserts that an integer is `<=` the supplied value.
* @param inclusiveUpperBound The argument must be `<= inclusiveUpperBound`.
*
*
* @return
*/
fun lessThanOrEqualTo(inclusiveUpperBound: Int): AlchemyAssertion<Int>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number <= inclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be less than or equal to $inclusiveUpperBound")
}
}
}
/**
* Asserts that a long is `<=` the supplied value.
* @param inclusiveUpperBound The argument must be `<= inclusiveUpperBound`.
*
*
* @return
*/
fun lessThanOrEqualTo(inclusiveUpperBound: Long): AlchemyAssertion<Long>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number <= inclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be less than or equal to $inclusiveUpperBound")
}
}
}
/**
* Asserts that a double is `<=` the supplied value, within a `delta` margin-of-error.
* @param inclusiveUpperBound
*
* @param delta The allowable margin-of-error in the `<= ` comparison
*
*
* @return
*/
@JvmOverloads fun lessThanOrEqualTo(inclusiveUpperBound: Double, delta: Double = 0.0): AlchemyAssertion<Double>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number!! - abs(delta) <= inclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be <= $inclusiveUpperBound +- $delta")
}
}
}
/**
* Asserts that a Long is positive, or `> 0`
* @return
*/
fun positiveLong(): AlchemyAssertion<Long>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
if (number <= 0)
{
throw FailedAssertionException("Expected positive long: $number")
}
}
}
/**
* Asserts that a Long is negative, or `< 0`.
* @return
*/
fun negativeLong(): AlchemyAssertion<Long>
{
return lessThan(0L)
}
/**
* Asserts than an integer is `<` the supplied value.
* @param exclusiveUpperBound The argument must be `< exclusiveUpperBound`.
*
*
* @return
*/
fun lessThan(exclusiveUpperBound: Int): AlchemyAssertion<Int>
{
checkThat(exclusiveUpperBound != Integer.MIN_VALUE, "Ints cannot be less than ${Int.MIN_VALUE}")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number < exclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be < " + exclusiveUpperBound)
}
}
}
/**
* Asserts than a long is `<` the supplied value.
* @param exclusiveUpperBound The argument must be `< exclusiveUpperBound`.
*
*
* @return
*/
fun lessThan(exclusiveUpperBound: Long): AlchemyAssertion<Long>
{
checkThat(exclusiveUpperBound != java.lang.Long.MIN_VALUE, "Longs cannot be less than " + java.lang.Long.MIN_VALUE)
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number < exclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be < " + exclusiveUpperBound)
}
}
}
/**
* Asserts that a double is `<` the supplied value, within `delta` margin-of-error.
*
* @param exclusiveUpperBound The argument must be `< exclusiveUpperBound`.
* @param delta The allowable margin-of-error.
*
*
* @return
*/
@JvmOverloads
fun lessThan(exclusiveUpperBound: Double, delta: Double = 0.0): AlchemyAssertion<Double>
{
checkThat(exclusiveUpperBound > -java.lang.Double.MAX_VALUE, "Doubles cannot be less than " + -java.lang.Double.MAX_VALUE)
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number - abs(delta) < exclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be < $exclusiveUpperBound")
}
}
}
/**
* Asserts that an integer argument is in the specified (inclusive) range.
*
* @param min The lower bound for the range, inclusive
* @param max The upper bound for the range, inclusive
*
* @return
*
* @throws IllegalArgumentException If `min >= max`. `min` should always be less than `max`.
*/
@Throws(IllegalArgumentException::class)
fun numberBetween(min: Int, max: Int): AlchemyAssertion<Int>
{
checkThat(min < max, "Minimum must be less than Max.")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinRange = number in min..max
if (!isWithinRange)
{
throw FailedAssertionException("Expected a number between $min and $max but got $number instead")
}
}
}
/**
* Asserts that a long argument is in the specified (inclusive) range.
* @param min The lower bound for the range, inclusive
*
* @param max The upper bound for the range, inclusive
*
*
* @return
*
*
* @throws IllegalArgumentException If `min >= max`. `min` should always be less
*/
@Throws(IllegalArgumentException::class)
fun numberBetween(min: Long, max: Long): AlchemyAssertion<Long>
{
checkThat(min < max, "Minimum must be less than Max.")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinRange = number in min..max
if (!isWithinRange)
{
throw FailedAssertionException("Expected a number between $min and $max but got $number instead")
}
}
}
| src/main/java/tech/sirwellington/alchemy/arguments/assertions/NumberAssertions.kt | 3794137776 |
package org.github.mbarberot.mtg.grimoire.core.stores
import org.github.mbarberot.mtg.grimoire.core.models.Version
interface VersionStore {
fun getVersion(): Version
fun createVersion(): Version
fun updateVersion(version: Version)
} | src/main/kotlin/org/github/mbarberot/mtg/grimoire/core/stores/VersionStore.kt | 3115330529 |
package fr.openium.auvergnewebcams.utils
import timber.log.Timber
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL
/**
* Created by Openium on 19/02/2019.
*/
object LoadWebCamUtils {
fun getMediaViewSurf(urlBase: String?): String {
var media = ""
if (!urlBase.isNullOrEmpty()) {
try {
val urlLD = String.format("%s/last", urlBase)
val url = URL(urlLD)
val bufferedReader = BufferedReader(InputStreamReader(url.openStream()))
var line = bufferedReader.readLine()
while (line != null && line.isNotBlank()) {
media += line
line = bufferedReader.readLine()
}
bufferedReader.close()
} catch (e: Exception) {
Timber.e(e)
}
}
return media
}
} | app/src/main/java/fr/openium/auvergnewebcams/utils/LoadWebCamUtils.kt | 2871742517 |
package jp.juggler.subwaytooter.dialog
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.view.View
import android.view.WindowManager
import android.widget.CheckBox
import android.widget.EditText
import android.widget.TextView
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.entity.TootAccount
import jp.juggler.subwaytooter.api.entity.TootStatus
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.subwaytooter.util.matchHost
import jp.juggler.util.showToast
object ReportForm {
@SuppressLint("InflateParams")
fun showReportForm(
activity: Activity,
accessInfo: SavedAccount,
who: TootAccount,
status: TootStatus?,
onClickOk: (dialog: Dialog, comment: String, forward: Boolean) -> Unit
) {
val view = activity.layoutInflater.inflate(R.layout.dlg_report_user, null, false)
val tvUser: TextView = view.findViewById(R.id.tvUser)
val tvStatusCaption: TextView = view.findViewById(R.id.tvStatusCaption)
val tvStatus: TextView = view.findViewById(R.id.tvStatus)
val etComment: EditText = view.findViewById(R.id.etComment)
val cbForward: CheckBox = view.findViewById(R.id.cbForward)
val tvForwardDesc: TextView = view.findViewById(R.id.tvForwardDesc)
val canForward = !accessInfo.matchHost(who) && !accessInfo.isMisskey
cbForward.isChecked = false
if (!canForward) {
cbForward.visibility = View.GONE
tvForwardDesc.visibility = View.GONE
} else {
cbForward.visibility = View.VISIBLE
tvForwardDesc.visibility = View.VISIBLE
cbForward.text = activity.getString(R.string.report_forward_to, who.apDomain.pretty)
}
tvUser.text = who.acct.pretty
if (status == null) {
tvStatusCaption.visibility = View.GONE
tvStatus.visibility = View.GONE
} else {
tvStatus.text = status.decoded_content
}
val dialog = Dialog(activity)
dialog.setContentView(view)
view.findViewById<View>(R.id.btnOk).setOnClickListener(View.OnClickListener {
val comment = etComment.text.toString().trim()
if (comment.isEmpty()) {
activity.showToast(true, R.string.comment_empty)
return@OnClickListener
}
onClickOk(dialog, comment, cbForward.isChecked)
})
view.findViewById<View>(R.id.btnCancel).setOnClickListener { dialog.cancel() }
dialog.window?.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT
)
dialog.show()
}
}
| app/src/main/java/jp/juggler/subwaytooter/dialog/ReportForm.kt | 2070146335 |
package com.github.nukc.recycleradapter
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
private interface Provider<T, VH : RecyclerView.ViewHolder> {
/**
* Return the view type of the item at <code>position</code> for the purposes
* of view recycling.
* <p>The default implementation of this method returns 0, making the assumption of
* a single view type for the adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
*
* @see RecyclerAdapter.getItemViewType
* @return integer value identifying the type of the view needed to represent the item of
* the provider. Type codes need not be contiguous.
*/
@LayoutRes
fun getLayoutResId(): Int
/**
* Same as getLayoutResId()
*
* @see RecyclerAdapter.getItemViewType
* @param position position to query
* @param data within the RecyclerAdapter's items data set to query
* @return integer value identifying the type of the view needed to represent the item at
* <code>position</code>. Type codes need not be contiguous.
*/
@LayoutRes
fun getLayoutResId(position: Int, data: T): Int = -1
/**
* Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent
* an item.
* <p>
* This new ViewHolder should be constructed with a new View that can represent the items
* of the given type. You can either create a new View manually or inflate it from an XML
* layout file.
* <p>
* The new ViewHolder will be used to display items of the adapter using
* {@link #onBindViewHolder(ViewHolder, int, List)}. Since it will be re-used to display
* different items in the data set, it is a good idea to cache references to sub views of
* the View to avoid unnecessary {@link View#findViewById(int)} calls.
*
* @param parent The ViewGroup into which the new View will be added after it is bound to
* an adapter position.
* @param viewType The view type of the new View.
*
* @return A new ViewHolder that holds a View of the given view type.
* @see getLayoutResId or
* @see getLayoutResId(Int, T)
* @see bind(ViewHolder, int)
*/
fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH
/**
* Called by RecyclerView to display the data at the specified position. This method
* should update the contents of the {@link ViewHolder#itemView} to reflect the item at
* the given position.
* <p>
* Note that unlike {@link android.widget.ListView}, RecyclerView will not call this method
* again if the position of the item changes in the data set unless the item itself is
* invalidated or the new position cannot be determined. For this reason, you should only
* use the <code>position</code> parameter while acquiring the related data item inside
* this method and should not keep a copy of it. If you need the position of an item later
* on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will
* have the updated adapter position.
* <p>
* Partial bind vs full bind:
* <p>
* The payloads parameter is a merge list from {@link #notifyItemChanged(int, Object)} or
* {@link #notifyItemRangeChanged(int, int, Object)}. If the payloads list is not empty,
* the ViewHolder is currently bound to old data and Adapter may run an efficient partial
* update using the payload info. If the payload is empty, Adapter must run a full bind.
* Adapter should not assume that the payload passed in notify methods will be received by
* onBindViewHolder(). For example when the view is not attached to the screen, the
* payload in notifyItemChange() will be simply dropped.
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param data The data of the item within the adapter's data set.
* @param payloads A non-null list of merged payloads. Can be empty list if requires full
* update.
*/
fun bind(holder: VH, data: T, payloads: List<Any>)
/**
* Return the stable ID for the item at <code>position</code>. If {@link #hasStableIds()}
* would return false this method should return {@link #NO_ID}. The default implementation
* of this method returns {@link #NO_ID}.
*/
fun getItemId(position: Int): Long = position.toLong()
/**
* Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled
* due to its transient state. Upon receiving this callback, Adapter can clear the
* animation(s) that effect the View's transient state and return <code>true</code> so that
* the View can be recycled. Keep in mind that the View in question is already removed from
* the RecyclerView.
* <p>
* In some cases, it is acceptable to recycle a View although it has transient state. Most
* of the time, this is a case where the transient state will be cleared in
* {@link #onBindViewHolder(ViewHolder, int)} call when View is rebound to a new position.
* For this reason, RecyclerView leaves the decision to the Adapter and uses the return
* value of this method to decide whether the View should be recycled or not.
* <p>
* Note that when all animations are created by {@link RecyclerView.ItemAnimator}, you
* should never receive this callback because RecyclerView keeps those Views as children
* until their animations are complete. This callback is useful when children of the item
* views create animations which may not be easy to implement using an {@link ItemAnimator}.
* <p>
* You should <em>never</em> fix this issue by calling
* <code>holder.itemView.setHasTransientState(false);</code> unless you've previously called
* <code>holder.itemView.setHasTransientState(true);</code>. Each
* <code>View.setHasTransientState(true)</code> call must be matched by a
* <code>View.setHasTransientState(false)</code> call, otherwise, the state of the View
* may become inconsistent. You should always prefer to end or cancel animations that are
* triggering the transient state instead of handling it manually.
*
* @param holder The ViewHolder containing the View that could not be recycled due to its
* transient state.
* @return True if the View should be recycled, false otherwise. Note that if this method
* returns <code>true</code>, RecyclerView <em>will ignore</em> the transient state of
* the View and recycle it regardless. If this method returns <code>false</code>,
* RecyclerView will check the View's transient state again before giving a final decision.
* Default implementation returns false.
*/
fun onFailedToRecycleView(holder: VH): Boolean = false
/**
* Called when a view created by this adapter has been recycled.
*
* <p>A view is recycled when a {@link LayoutManager} decides that it no longer
* needs to be attached to its parent {@link RecyclerView}. This can be because it has
* fallen out of visibility or a set of cached views represented by views still
* attached to the parent RecyclerView. If an item view has large or expensive data
* bound to it such as large bitmaps, this may be a good place to release those
* resources.</p>
* <p>
* RecyclerView calls this method right before clearing ViewHolder's internal data and
* sending it to RecycledViewPool. This way, if ViewHolder was holding valid information
* before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get
* its adapter position.
*
* @param holder The ViewHolder for the view being recycled
*/
fun onViewRecycled(holder: VH)
/**
* Called when a view created by this adapter has been attached to a window.
*
* <p>This can be used as a reasonable signal that the view is about to be seen
* by the user. If the adapter previously freed any resources in
* {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow}
* those resources should be restored here.</p>
*
* @param holder Holder of the view being attached
*/
fun onViewAttachedToWindow(holder: VH)
/**
* Called when a view created by this adapter has been detached from its window.
*
* <p>Becoming detached from the window is not necessarily a permanent condition;
* the consumer of an Adapter's views may choose to cache views offscreen while they
* are not visible, attaching and detaching them as appropriate.</p>
*
* @param holder Holder of the view being detached
*/
fun onViewDetachedFromWindow(holder: VH)
}
abstract class BaseProvider<T : Any, VH : RecyclerView.ViewHolder>(val type: Class<*>) : Provider<T, VH> | recycleradapter/src/main/java/com/github/nukc/recycleradapter/Provider.kt | 1854779307 |
/*
* Free, open-source undetected color cheat for Overwatch!
* Copyright (C) 2017 Thomas G. Nappo
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jire.overwatcheat.settings
import kotlin.reflect.KProperty
class FloatSetting(name: String, var value: Float) : ConfiguredSetting(name) {
override fun parse(string: String) {
value = string.toFloat()
}
operator fun getValue(thisRef: Any?, property: KProperty<*>) = value
} | src/main/kotlin/org/jire/overwatcheat/settings/FloatSetting.kt | 3630455498 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInspection
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection
import com.intellij.codeInspection.ex.EntryPointsManagerBase
import com.intellij.codeInspection.ex.InspectionManagerEx
import com.intellij.codeInspection.reference.RefClass
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
class UnusedDeclarationClassPatternsTest : LightCodeInsightFixtureTestCase() {
fun testClassPattern() {
val unusedDeclarationInspection = UnusedDeclarationInspection(true)
myFixture.enableInspections(unusedDeclarationInspection)
val classPattern = EntryPointsManagerBase.ClassPattern()
classPattern.hierarchically = true
classPattern.pattern = "java.lang.Runnable"
val patterns = EntryPointsManagerBase.getInstance(project).patterns
try {
patterns.add(classPattern)
myFixture.configureByText("C.java", "public abstract class C implements Runnable {}")
myFixture.checkHighlighting()
}
finally {
patterns.remove(classPattern)
myFixture.disableInspections(unusedDeclarationInspection)
}
}
fun testMethodPattern() {
val unusedDeclarationInspection = UnusedDeclarationInspection(true)
myFixture.enableInspections(unusedDeclarationInspection)
val classPattern = EntryPointsManagerBase.ClassPattern()
classPattern.pattern = "C"
classPattern.method = "*"
val patterns = EntryPointsManagerBase.getInstance(project).patterns
try {
patterns.add(classPattern)
myFixture.configureByText("C.java", "public abstract class C { void foo() {} public static void main(String[] args) {}}")
myFixture.checkHighlighting()
}
finally {
patterns.remove(classPattern)
myFixture.disableInspections(unusedDeclarationInspection)
}
}
fun testMethodPattern1() {
val unusedDeclarationInspection = UnusedDeclarationInspection(true)
myFixture.enableInspections(unusedDeclarationInspection)
val classPattern = EntryPointsManagerBase.ClassPattern()
classPattern.pattern = "C"
classPattern.method = "foo*"
val patterns = EntryPointsManagerBase.getInstance(project).patterns
try {
patterns.add(classPattern)
myFixture.configureByText("C.java", "public abstract class C { void fooBar() {} public static void main(String[] args) {}}")
myFixture.checkHighlighting()
}
finally {
patterns.remove(classPattern)
myFixture.disableInspections(unusedDeclarationInspection)
}
}
fun testNoClassPattern() {
val unusedDeclarationInspection = UnusedDeclarationInspection(true)
try {
myFixture.enableInspections(unusedDeclarationInspection)
myFixture.configureByText("C.java", "public abstract class <warning descr=\"Class 'C' is never used\">C</warning> implements Runnable {}")
myFixture.checkHighlighting()
}
finally {
myFixture.disableInspections(unusedDeclarationInspection)
}
}
fun testAddEntryPoint() {
val aClass = myFixture.addClass("public class Foo {}")
val entryPointsManager = EntryPointsManagerBase.getInstance(project)
val context = (InspectionManager.getInstance(project) as InspectionManagerEx).createNewGlobalContext()
try {
val refClass = context.refManager.getReference(aClass)
assertNotNull(refClass)
val patterns = entryPointsManager.patterns
assertEmpty(patterns)
//add class as entry point
entryPointsManager.addEntryPoint(refClass!!, true)
assertSize(1, patterns)
assertEquals("Foo", patterns.iterator().next().pattern)
//remove class entry point with constructors - ensure nothing is left in the entries
entryPointsManager.removeEntryPoint(refClass)
for (constructor in (refClass as RefClass).constructors) {
entryPointsManager.removeEntryPoint(constructor)
}
assertEmpty(patterns)
assertEmpty(entryPointsManager.getEntryPoints(context.refManager))
}
finally {
context.cleanup()
}
}
fun testAddRemoveMethodEntryPoint() {
val aClass = myFixture.addClass("public class Foo {void foo(){}}")
val entryPointsManager = EntryPointsManagerBase.getInstance(project)
val context = (InspectionManager.getInstance(project) as InspectionManagerEx).createNewGlobalContext()
try {
val refMethod = context.refManager.getReference(aClass.methods[0])
assertNotNull(refMethod)
val refClass = context.refManager.getReference(aClass)
assertNotNull(refClass)
val patterns = entryPointsManager.patterns
assertEmpty(patterns)
entryPointsManager.addEntryPoint(refMethod!!, true)
assertSize(1, patterns)
val classPattern = patterns.iterator().next()
assertEquals("Foo", classPattern.pattern)
assertEquals("foo", classPattern.method)
entryPointsManager.removeEntryPoint(refMethod)
assertEmpty(patterns)
assertEmpty(entryPointsManager.getEntryPoints(context.refManager))
}
finally {
context.cleanup()
}
}
} | java/java-tests/testSrc/com/intellij/java/codeInspection/UnusedDeclarationClassPatternsTest.kt | 1491190744 |
package de.ph1b.audiobook.features.bookOverview.list
import de.ph1b.audiobook.data.Book
import de.ph1b.audiobook.features.bookOverview.list.header.BookOverviewHeaderComponent
import de.ph1b.audiobook.features.bookOverview.list.header.OpenCategoryListener
import de.ph1b.audiobook.misc.recyclerComponent.CompositeListAdapter
import java.util.UUID
typealias BookClickListener = (Book, BookOverviewClick) -> Unit
class BookOverviewAdapter(
bookClickListener: BookClickListener,
openCategoryListener: OpenCategoryListener
) : CompositeListAdapter<BookOverviewItem>(BookOverviewDiff()) {
init {
addComponent(GridBookOverviewComponent(bookClickListener))
addComponent(ListBookOverviewComponent(bookClickListener))
addComponent(BookOverviewHeaderComponent(openCategoryListener))
}
fun reloadBookCover(bookId: UUID) {
for (i in 0 until itemCount) {
val item = getItem(i)
if (item is BookOverviewModel && item.book.id == bookId) {
notifyItemChanged(i)
break
}
}
}
fun itemAtPositionIsHeader(position: Int): Boolean {
val item = getItem(position)
return item is BookOverviewHeaderModel
}
}
| app/src/main/java/de/ph1b/audiobook/features/bookOverview/list/BookOverviewAdapter.kt | 909495947 |
package com.cv4j.app.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.cv4j.app.R
import com.cv4j.app.activity.pixels.*
import com.cv4j.app.app.BaseFragment
import kotlinx.android.synthetic.main.fragment_pixel_operator.*
/**
*
* @FileName:
* com.cv4j.app.fragment.PixelOperatorFragment
* @author: Tony Shen
* @date: 2020-05-04 12:57
* @version: V1.0 <描述当前版本功能>
*/
class PixelOperatorFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_pixel_operator, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
text1.setOnClickListener {
val i = Intent(mContext, ArithmeticAndLogicOperationActivity::class.java)
i.putExtra("Title", text1.text.toString())
startActivity(i)
}
text2.setOnClickListener {
val i = Intent(mContext, SubImageActivity::class.java)
i.putExtra("Title", text2.text.toString())
startActivity(i)
}
text3.setOnClickListener {
val i = Intent(mContext, PrincipalColorExtractorActivity::class.java)
i.putExtra("Title", text3.text.toString())
startActivity(i)
}
text4.setOnClickListener {
val i = Intent(mContext, ResizeActivity::class.java)
i.putExtra("Title", text4.text.toString())
startActivity(i)
}
text5.setOnClickListener {
val i = Intent(mContext, FlipActivity::class.java)
i.putExtra("Title", text5.text.toString())
startActivity(i)
}
text6.setOnClickListener {
val i = Intent(mContext, RotateActivity::class.java)
i.putExtra("Title", text6.text.toString())
startActivity(i)
}
}
} | app/src/main/java/com/cv4j/app/fragment/PixelOperatorFragment.kt | 4137578532 |
package org.intellij.markdown.parser.sequentialparsers
import java.util.ArrayList
public abstract class SequentialParserManager {
abstract fun getParserSequence(): List<SequentialParser>;
public fun runParsingSequence(tokensCache: TokensCache, rangesToParse: Collection<Range<Int>>): Collection<SequentialParser.Node> {
val result = ArrayList<SequentialParser.Node>()
var parsingSpaces = ArrayList<Collection<Range<Int>>>()
parsingSpaces.add(rangesToParse)
for (sequentialParser in getParserSequence()) {
val nextLevelSpaces = ArrayList<Collection<Range<Int>>>()
for (parsingSpace in parsingSpaces) {
val currentResult = sequentialParser.parse(tokensCache, parsingSpace)
result.addAll(currentResult.parsedNodes)
nextLevelSpaces.addAll(currentResult.rangesToProcessFurther)
}
parsingSpaces = nextLevelSpaces
}
return result
}
}
| src/org/intellij/markdown/parser/sequentialparsers/SequentialParserManager.kt | 605302035 |
// 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.testFramework.fixtures.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.externalSystem.util.refreshAndWait
import com.intellij.openapi.module.Module
import com.intellij.openapi.observable.operations.CompoundParallelOperationTrace
import com.intellij.openapi.observable.operations.ObservableOperationTrace
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.modules
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.closeProjectAsync
import com.intellij.testFramework.common.runAll
import com.intellij.testFramework.fixtures.SdkTestFixture
import com.intellij.testFramework.openProjectAsync
import com.intellij.testFramework.runInEdtAndWait
import kotlinx.coroutines.runBlocking
import org.gradle.util.GradleVersion
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.plugins.gradle.testFramework.fixtures.FileTestFixture
import org.jetbrains.plugins.gradle.testFramework.fixtures.GradleTestFixture
import org.jetbrains.plugins.gradle.testFramework.fixtures.GradleTestFixtureFactory
import org.jetbrains.plugins.gradle.testFramework.util.generateWrapper
import org.jetbrains.plugins.gradle.testFramework.util.openProjectAsyncAndWait
import org.jetbrains.plugins.gradle.testFramework.util.withSuppressedErrors
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.gradle.util.waitForProjectReload
import java.util.concurrent.TimeUnit
internal class GradleTestFixtureImpl private constructor(
override val projectName: String,
override val gradleVersion: GradleVersion,
private val sdkFixture: SdkTestFixture,
override val fileFixture: FileTestFixture
) : GradleTestFixture {
private lateinit var _project: Project
private lateinit var testDisposable: Disposable
private val projectOperations = CompoundParallelOperationTrace<Any>()
override val project: Project get() = _project
override val module: Module get() = project.modules.single { it.name == project.name }
constructor(
projectName: String,
gradleVersion: GradleVersion,
configureProject: FileTestFixture.Builder.() -> Unit
) : this(
projectName, gradleVersion,
GradleTestFixtureFactory.getFixtureFactory().createGradleJvmTestFixture(gradleVersion),
GradleTestFixtureFactory.getFixtureFactory().createFileTestFixture("GradleTestFixture/$gradleVersion/$projectName") {
configureProject()
excludeFiles(".gradle", "build")
withFiles { generateWrapper(it, gradleVersion) }
withFiles { runBlocking { createProjectCaches(it) } }
}
)
override fun setUp() {
testDisposable = Disposer.newDisposable()
sdkFixture.setUp()
fileFixture.setUp()
installTaskExecutionWatcher()
installProjectReloadWatcher()
_project = runBlocking { openProjectAsync(fileFixture.root) }
}
override fun tearDown() {
runAll(
{ fileFixture.root.refreshAndWait() },
{ projectOperations.waitForOperation() },
{ if (_project.isInitialized) runBlocking { _project.closeProjectAsync() } },
{ Disposer.dispose(testDisposable) },
{ fileFixture.tearDown() },
{ sdkFixture.tearDown() }
)
}
private fun installTaskExecutionWatcher() {
val listener = object : ExternalSystemTaskNotificationListenerAdapter() {
override fun onStart(id: ExternalSystemTaskId, workingDir: String?) {
projectOperations.startTask(id)
}
override fun onEnd(id: ExternalSystemTaskId) {
projectOperations.finishTask(id)
}
}
val progressManager = ExternalSystemProgressNotificationManager.getInstance()
progressManager.addNotificationListener(listener, testDisposable)
}
private fun installProjectReloadWatcher() {
val reloadListener = object : ExternalSystemTaskNotificationListenerAdapter() {
override fun onStart(id: ExternalSystemTaskId, workingDir: String?) {
if (workingDir == fileFixture.root.path) {
if (id.type == ExternalSystemTaskType.RESOLVE_PROJECT) {
fileFixture.addIllegalOperationError("Unexpected project reload: $workingDir")
}
}
}
}
val progressManager = ExternalSystemProgressNotificationManager.getInstance()
progressManager.addNotificationListener(reloadListener, testDisposable)
}
override fun reloadProject() {
if (fileFixture.isModified()) {
fileFixture.addIllegalOperationError("Unexpected reload with modified project files")
}
fileFixture.withSuppressedErrors {
waitForProjectReload {
ExternalSystemUtil.refreshProject(
fileFixture.root.path,
ImportSpecBuilder(project, GradleConstants.SYSTEM_ID)
)
}
fileFixture.root.refreshAndWait()
}
}
companion object {
fun ObservableOperationTrace.waitForOperation() {
val promise = AsyncPromise<Nothing?>()
afterOperation { promise.setResult(null) }
if (isOperationCompleted()) {
promise.setResult(null)
}
runInEdtAndWait {
PlatformTestUtil.waitForPromise<Nothing?>(promise, TimeUnit.MINUTES.toMillis(1))
}
}
private suspend fun createProjectCaches(projectRoot: VirtualFile) {
val project = openProjectAsyncAndWait(projectRoot)
try {
projectRoot.refreshAndWait()
}
finally {
project.closeProjectAsync(save = true)
}
}
}
}
| plugins/gradle/testSources/org/jetbrains/plugins/gradle/testFramework/fixtures/impl/GradleTestFixtureImpl.kt | 657971859 |
// 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.*
class MakeConstructorParameterPropertyFix(
element: KtParameter, private val kotlinValVar: KotlinValVar, className: String?
) : KotlinQuickFixAction<KtParameter>(element) {
override fun getFamilyName() = KotlinBundle.message("make.constructor.parameter.a.property.0", "")
private val suffix = if (className != null) KotlinBundle.message("in.class.0", className) else ""
override fun getText() = KotlinBundle.message("make.constructor.parameter.a.property.0", suffix)
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
val element = element ?: return false
return !element.hasValOrVar()
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
element.addBefore(kotlinValVar.createKeyword(KtPsiFactory(project))!!, element.nameIdentifier)
element.addModifier(KtTokens.PRIVATE_KEYWORD)
element.visibilityModifier()?.let { private ->
editor?.apply {
selectionModel.setSelection(private.startOffset, private.endOffset)
caretModel.moveToOffset(private.endOffset)
}
}
}
companion object Factory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val ktReference = Errors.UNRESOLVED_REFERENCE.cast(diagnostic).a as? KtNameReferenceExpression ?: return emptyList()
val valOrVar = if (ktReference.getAssignmentByLHS() != null) KotlinValVar.Var else KotlinValVar.Val
val ktParameter = ktReference.getPrimaryConstructorParameterWithSameName() ?: return emptyList()
val containingClass = ktParameter.containingClass()!!
val className = if (containingClass != ktReference.containingClass()) containingClass.nameAsSafeName.asString() else null
return listOf(MakeConstructorParameterPropertyFix(ktParameter, valOrVar, className))
}
}
}
fun KtNameReferenceExpression.getPrimaryConstructorParameterWithSameName(): KtParameter? {
return nonStaticOuterClasses()
.mapNotNull { it.primaryConstructor?.valueParameters?.firstOrNull { it.name == getReferencedName() } }
.firstOrNull()
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeConstructorParameterPropertyFix.kt | 1521038665 |
package org.runestar.client.plugins.dev
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.Fonts
import org.runestar.client.api.game.live.Canvas
import org.runestar.client.api.game.live.Mouse
import org.runestar.client.api.plugins.PluginSettings
import java.awt.Color
class MouseDebug : DisposablePlugin<PluginSettings>() {
override val defaultSettings = PluginSettings()
override fun onStart() {
add(Canvas.repaints.subscribe { g ->
val x = 5
var y = 40
g.font = Fonts.PLAIN_12
g.color = Color.WHITE
val strings = ArrayList<String>()
strings.apply {
add("mouse")
add("location: ${Mouse.location}")
add("viewportLocation: ${Mouse.viewportLocation}")
add("isInViewport: ${Mouse.isInViewport}")
add("entityCount: ${Mouse.entityCount}")
add("tags:")
}
strings.forEach { s ->
g.drawString(s, x, y)
y += g.font.size + 5
}
})
}
} | plugins-dev/src/main/java/org/runestar/client/plugins/dev/MouseDebug.kt | 2904130297 |
package com.igorini.kotlin.android.app.view.common
import android.app.Activity
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
fun <T : View> Activity.bindView(viewId: Int) = lazy { findViewById<T>(viewId) }
fun <T : View> RecyclerView.ViewHolder.bindView(viewId: Int) = lazy { itemView.findViewById<T>(viewId) }
fun ImageView.loadImage(photoUrl: String) = Glide.with(context).load(photoUrl).into(this)
| app/src/main/java/com/igorini/kotlin/android/app/view/common/ViewExt.kt | 270528546 |
package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.DependsOn
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.Class2
import org.runestar.client.updater.mapper.Field2
@DependsOn(Node::class, IterableNodeDeque::class)
class IterableNodeDequeDescendingIterator : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.interfaces.contains(Iterator::class.type) }
.and { it.instanceFields.count { it.type == type<Node>() } == 2 }
.and { it.instanceFields.count { it.type == type<IterableNodeDeque>() } == 1 }
.and { it.instanceFields.size == 3 }
@DependsOn(IterableNodeDeque::class)
class deque : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<IterableNodeDeque>() }
}
// current
// last
} | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/IterableNodeDequeDescendingIterator.kt | 4244702890 |
/*
* Copyright (C) 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 okhttp3.nativeImage
import okhttp3.SampleTest
import okhttp3.findTests
import okhttp3.testSelectors
import okhttp3.treeListener
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor
import org.junit.platform.engine.discovery.DiscoverySelectors
class NativeImageTestsTest {
@Test
fun testFindsFixedTestsForImage() {
val testSelector = testSelectors()
val x = findTests(testSelector)
x.find { it is ClassBasedTestDescriptor && it.testClass == SampleTest::class.java }
}
@Test
fun testFindsModuleTests() {
val testSelector = DiscoverySelectors.selectPackage("okhttp3")
val x = findTests(listOf(testSelector))
x.find { it is ClassBasedTestDescriptor && it.testClass == SampleTest::class.java }
}
@Test
fun testFindsProjectTests() {
val testSelector = DiscoverySelectors.selectPackage("okhttp3")
val x = findTests(listOf(testSelector))
x.find { it is ClassBasedTestDescriptor && it.testClass == SampleTest::class.java }
}
@Test
fun testTreeListener() {
val listener = treeListener()
assertNotNull(listener)
}
} | native-image-tests/src/test/kotlin/okhttp3/nativeImage/NativeImageTestsTest.kt | 126115538 |
package pe.devpicon.android.marvelheroes.data.local
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "character")
data class CharacterEntity(
@PrimaryKey val id: Long,
val name: String,
val description: String,
val thumbnailUrl: String
)
@Entity(tableName = "comic")
data class ComicEntity(
@PrimaryKey val id: Long,
val title: String,
val description: String?,
val thumbnailUrl: String,
val characterId: Long
) | app/src/main/kotlin/pe/devpicon/android/marvelheroes/data/local/Entities.kt | 1832787305 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.util.SmartList
import com.intellij.util.ThreeState
import com.intellij.xdebugger.XSourcePositionWrapper
import com.intellij.xdebugger.frame.*
import com.intellij.xdebugger.frame.presentation.XKeywordValuePresentation
import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation
import com.intellij.xdebugger.frame.presentation.XStringValuePresentation
import com.intellij.xdebugger.frame.presentation.XValuePresentation
import org.jetbrains.concurrency.*
import org.jetbrains.debugger.values.*
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.regex.Pattern
import javax.swing.Icon
fun VariableView(variable: Variable, context: VariableContext) = VariableView(variable.name, variable, context)
class VariableView(override val variableName: String, private val variable: Variable, private val context: VariableContext) : XNamedValue(variableName), VariableContext {
@Volatile private var value: Value? = null
// lazy computed
private var _memberFilter: MemberFilter? = null
@Volatile private var remainingChildren: List<Variable>? = null
@Volatile private var remainingChildrenOffset: Int = 0
override fun watchableAsEvaluationExpression() = context.watchableAsEvaluationExpression()
override val viewSupport: DebuggerViewSupport
get() = context.viewSupport
override val parent = context
override val memberFilter: Promise<MemberFilter>
get() = context.viewSupport.getMemberFilter(this)
override val evaluateContext: EvaluateContext
get() = context.evaluateContext
override val scope: Scope?
get() = context.scope
override val vm: Vm?
get() = context.vm
override fun computePresentation(node: XValueNode, place: XValuePlace) {
value = variable.value
if (value != null) {
computePresentation(value!!, node)
return
}
if (variable !is ObjectProperty || variable.getter == null) {
// it is "used" expression (WEB-6779 Debugger/Variables: Automatically show used variables)
evaluateContext.evaluate(variable.name)
.done(node) {
if (it.wasThrown) {
setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(it.value, null), null, node)
}
else {
value = it.value
computePresentation(it.value, node)
}
}
.rejected(node) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(null, it.message), it.message, node) }
return
}
node.setPresentation(null, object : XValuePresentation() {
override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) {
renderer.renderValue("\u2026")
}
}, false)
node.setFullValueEvaluator(object : XFullValueEvaluator(" (invoke getter)") {
override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) {
var valueModifier = variable.valueModifier
var nonProtoContext = context
while (nonProtoContext is VariableView && nonProtoContext.variableName == PROTOTYPE_PROP) {
valueModifier = nonProtoContext.variable.valueModifier
nonProtoContext = nonProtoContext.parent
}
valueModifier!!.evaluateGet(variable, evaluateContext)
.done(node) {
callback.evaluated("")
setEvaluatedValue(it, null, node)
}
}
}.setShowValuePopup(false))
}
private fun setEvaluatedValue(value: Value?, error: String?, node: XValueNode) {
if (value == null) {
node.setPresentation(AllIcons.Debugger.Db_primitive, null, error ?: "Internal Error", false)
}
else {
this.value = value
computePresentation(value, node)
}
}
private fun computePresentation(value: Value, node: XValueNode) {
when (value.type) {
ValueType.OBJECT, ValueType.NODE -> context.viewSupport.computeObjectPresentation((value as ObjectValue), variable, context, node, icon)
ValueType.FUNCTION -> node.setPresentation(icon, ObjectValuePresentation(trimFunctionDescription(value)), true)
ValueType.ARRAY -> context.viewSupport.computeArrayPresentation(value, variable, context, node, icon)
ValueType.BOOLEAN, ValueType.NULL, ValueType.UNDEFINED -> node.setPresentation(icon, XKeywordValuePresentation(value.valueString!!), false)
ValueType.NUMBER -> node.setPresentation(icon, createNumberPresentation(value.valueString!!), false)
ValueType.STRING -> {
node.setPresentation(icon, XStringValuePresentation(value.valueString!!), false)
// isTruncated in terms of debugger backend, not in our terms (i.e. sometimes we cannot control truncation),
// so, even in case of StringValue, we check value string length
if ((value is StringValue && value.isTruncated) || value.valueString!!.length > XValueNode.MAX_VALUE_LENGTH) {
node.setFullValueEvaluator(MyFullValueEvaluator(value))
}
}
else -> node.setPresentation(icon, null, value.valueString!!, true)
}
}
override fun computeChildren(node: XCompositeNode) {
node.setAlreadySorted(true)
if (value !is ObjectValue) {
node.addChildren(XValueChildrenList.EMPTY, true)
return
}
val list = remainingChildren
if (list != null) {
val to = Math.min(remainingChildrenOffset + XCompositeNode.MAX_CHILDREN_TO_SHOW, list.size)
val isLast = to == list.size
node.addChildren(createVariablesList(list, remainingChildrenOffset, to, this, _memberFilter), isLast)
if (!isLast) {
node.tooManyChildren(list.size - to)
remainingChildrenOffset += XCompositeNode.MAX_CHILDREN_TO_SHOW
}
return
}
val objectValue = value as ObjectValue
val hasNamedProperties = objectValue.hasProperties() != ThreeState.NO
val hasIndexedProperties = objectValue.hasIndexedProperties() != ThreeState.NO
val promises = SmartList<Promise<*>>()
val additionalProperties = viewSupport.computeAdditionalObjectProperties(objectValue, variable, this, node)
if (additionalProperties != null) {
promises.add(additionalProperties)
}
// we don't support indexed properties if additional properties added - behavior is undefined if object has indexed properties and additional properties also specified
if (hasIndexedProperties) {
promises.add(computeIndexedProperties(objectValue as ArrayValue, node, !hasNamedProperties && additionalProperties == null))
}
if (hasNamedProperties) {
// named properties should be added after additional properties
if (additionalProperties == null || additionalProperties.state != Promise.State.PENDING) {
promises.add(computeNamedProperties(objectValue, node, !hasIndexedProperties && additionalProperties == null))
}
else {
promises.add(additionalProperties.thenAsync(node) { computeNamedProperties(objectValue, node, true) })
}
}
if (hasIndexedProperties == hasNamedProperties || additionalProperties != null) {
all(promises).processed(node) { node.addChildren(XValueChildrenList.EMPTY, true) }
}
}
abstract class ObsolescentIndexedVariablesConsumer(protected val node: XCompositeNode) : IndexedVariablesConsumer() {
override val isObsolete: Boolean
get() = node.isObsolete
}
private fun computeIndexedProperties(value: ArrayValue, node: XCompositeNode, isLastChildren: Boolean): Promise<*> {
return value.getIndexedProperties(0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, object : ObsolescentIndexedVariablesConsumer(node) {
override fun consumeRanges(ranges: IntArray?) {
if (ranges == null) {
val groupList = XValueChildrenList()
addGroups(value, ::lazyVariablesGroup, groupList, 0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, this@VariableView)
node.addChildren(groupList, isLastChildren)
}
else {
addRanges(value, ranges, node, this@VariableView, isLastChildren)
}
}
override fun consumeVariables(variables: List<Variable>) {
node.addChildren(createVariablesList(variables, this@VariableView, null), isLastChildren)
}
})
}
private fun computeNamedProperties(value: ObjectValue, node: XCompositeNode, isLastChildren: Boolean) = processVariables(this, value.properties, node) { memberFilter, variables ->
_memberFilter = memberFilter
if (value.type == ValueType.ARRAY && value !is ArrayValue) {
computeArrayRanges(variables, node)
return@processVariables
}
var functionValue = value as? FunctionValue
if (functionValue != null && functionValue.hasScopes() == ThreeState.NO) {
functionValue = null
}
remainingChildren = processNamedObjectProperties(variables, node, this@VariableView, memberFilter, XCompositeNode.MAX_CHILDREN_TO_SHOW, isLastChildren && functionValue == null)
if (remainingChildren != null) {
remainingChildrenOffset = XCompositeNode.MAX_CHILDREN_TO_SHOW
}
if (functionValue != null) {
// we pass context as variable context instead of this variable value - we cannot watch function scopes variables, so, this variable name doesn't matter
node.addChildren(XValueChildrenList.bottomGroup(FunctionScopesValueGroup(functionValue, context)), isLastChildren)
}
}
private fun computeArrayRanges(properties: List<Variable>, node: XCompositeNode) {
val variables = filterAndSort(properties, _memberFilter!!)
var count = variables.size
val bucketSize = XCompositeNode.MAX_CHILDREN_TO_SHOW
if (count <= bucketSize) {
node.addChildren(createVariablesList(variables, this, null), true)
return
}
while (count > 0) {
if (Character.isDigit(variables.get(count - 1).name[0])) {
break
}
count--
}
val groupList = XValueChildrenList()
if (count > 0) {
addGroups(variables, ::createArrayRangeGroup, groupList, 0, count, bucketSize, this)
}
var notGroupedVariablesOffset: Int
if ((variables.size - count) > bucketSize) {
notGroupedVariablesOffset = variables.size
while (notGroupedVariablesOffset > 0) {
if (!variables.get(notGroupedVariablesOffset - 1).name.startsWith("__")) {
break
}
notGroupedVariablesOffset--
}
if (notGroupedVariablesOffset > 0) {
addGroups(variables, ::createArrayRangeGroup, groupList, count, notGroupedVariablesOffset, bucketSize, this)
}
}
else {
notGroupedVariablesOffset = count
}
for (i in notGroupedVariablesOffset..variables.size - 1) {
val variable = variables.get(i)
groupList.add(VariableView(_memberFilter!!.rawNameToSource(variable), variable, this))
}
node.addChildren(groupList, true)
}
private val icon: Icon
get() = getIcon(value!!)
override fun getModifier(): XValueModifier? {
if (!variable.isMutable) {
return null
}
return object : XValueModifier() {
override fun getInitialValueEditorText(): String? {
if (value!!.type == ValueType.STRING) {
val string = value!!.valueString!!
val builder = StringBuilder(string.length)
builder.append('"')
StringUtil.escapeStringCharacters(string.length, string, builder)
builder.append('"')
return builder.toString()
}
else {
return if (value!!.type.isObjectType) null else value!!.valueString
}
}
override fun setValue(expression: String, callback: XValueModifier.XModificationCallback) {
variable.valueModifier!!.setValue(variable, expression, evaluateContext)
.doneRun {
value = null
callback.valueModified()
}
.rejected { callback.errorOccurred(it.message!!) }
}
}
}
fun getValue() = variable.value
override fun canNavigateToSource() = value is FunctionValue || viewSupport.canNavigateToSource(variable, context)
override fun computeSourcePosition(navigatable: XNavigatable) {
if (value is FunctionValue) {
(value as FunctionValue).resolve()
.done { function ->
vm!!.scriptManager.getScript(function)
.done {
navigatable.setSourcePosition(it?.let { viewSupport.getSourceInfo(null, it, function.openParenLine, function.openParenColumn) }?.let {
object : XSourcePositionWrapper(it) {
override fun createNavigatable(project: Project): Navigatable {
return PsiVisitors.visit(myPosition, project) { position, element, positionOffset, document ->
// element will be "open paren", but we should navigate to function name,
// we cannot use specific PSI type here (like JSFunction), so, we try to find reference expression (i.e. name expression)
var referenceCandidate: PsiElement? = element
var psiReference: PsiElement? = null
while (true) {
referenceCandidate = referenceCandidate?.prevSibling ?: break
if (referenceCandidate is PsiReference) {
psiReference = referenceCandidate
break
}
}
if (psiReference == null) {
referenceCandidate = element.parent
while (true) {
referenceCandidate = referenceCandidate?.prevSibling ?: break
if (referenceCandidate is PsiReference) {
psiReference = referenceCandidate
break
}
}
}
(if (psiReference == null) element.navigationElement else psiReference.navigationElement) as? Navigatable
} ?: super.createNavigatable(project)
}
}
})
}
}
}
else {
viewSupport.computeSourcePosition(variableName, value!!, variable, context, navigatable)
}
}
override fun computeInlineDebuggerData(callback: XInlineDebuggerDataCallback) = viewSupport.computeInlineDebuggerData(variableName, variable, context, callback)
override fun getEvaluationExpression(): String? {
if (!watchableAsEvaluationExpression()) {
return null
}
if (context.variableName == null) return variable.name // top level watch expression, may be call etc.
val list = SmartList<String>()
addVarName(list, parent, variable.name)
var parent: VariableContext? = context
while (parent != null && parent.variableName != null) {
addVarName(list, parent.parent, parent.variableName!!)
parent = parent.parent
}
return context.viewSupport.propertyNamesToString(list, false)
}
private fun addVarName(list: SmartList<String>, parent: VariableContext?, name: String) {
if (parent == null || parent.variableName != null) list.add(name)
else list.addAll(name.split(".").reversed())
}
private class MyFullValueEvaluator(private val value: Value) : XFullValueEvaluator(if (value is StringValue) value.length else value.valueString!!.length) {
override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) {
if (value !is StringValue || !value.isTruncated) {
callback.evaluated(value.valueString!!)
return
}
val evaluated = AtomicBoolean()
value.fullString
.done {
if (!callback.isObsolete && evaluated.compareAndSet(false, true)) {
callback.evaluated(value.valueString!!)
}
}
.rejected { callback.errorOccurred(it.message!!) }
}
}
companion object {
fun setObjectPresentation(value: ObjectValue, icon: Icon, node: XValueNode) {
node.setPresentation(icon, ObjectValuePresentation(getObjectValueDescription(value)), value.hasProperties() != ThreeState.NO)
}
fun setArrayPresentation(value: Value, context: VariableContext, icon: Icon, node: XValueNode) {
assert(value.type == ValueType.ARRAY)
if (value is ArrayValue) {
val length = value.length
node.setPresentation(icon, ArrayPresentation(length, value.className), length > 0)
return
}
val valueString = value.valueString
// only WIP reports normal description
if (valueString != null && valueString.endsWith("]") && ARRAY_DESCRIPTION_PATTERN.matcher(valueString).find()) {
node.setPresentation(icon, null, valueString, true)
}
else {
context.evaluateContext.evaluate("a.length", Collections.singletonMap<String, Any>("a", value), false)
.done(node) { node.setPresentation(icon, null, "Array[${it.value.valueString}]", true) }
.rejected(node) { node.setPresentation(icon, null, "Internal error: $it", false) }
}
}
fun getIcon(value: Value): Icon {
val type = value.type
return when (type) {
ValueType.FUNCTION -> AllIcons.Nodes.Function
ValueType.ARRAY -> AllIcons.Debugger.Db_array
else -> if (type.isObjectType) AllIcons.Debugger.Value else AllIcons.Debugger.Db_primitive
}
}
}
}
fun getClassName(value: ObjectValue): String {
val className = value.className
return if (className.isNullOrEmpty()) "Object" else className!!
}
fun getObjectValueDescription(value: ObjectValue): String {
val description = value.valueString
return if (description.isNullOrEmpty()) getClassName(value) else description!!
}
internal fun trimFunctionDescription(value: Value): String {
val presentableValue = value.valueString ?: return ""
var endIndex = 0
while (endIndex < presentableValue.length && !StringUtil.isLineBreak(presentableValue[endIndex])) {
endIndex++
}
while (endIndex > 0 && Character.isWhitespace(presentableValue[endIndex - 1])) {
endIndex--
}
return presentableValue.substring(0, endIndex)
}
private fun createNumberPresentation(value: String): XValuePresentation {
return if (value == PrimitiveValue.NA_N_VALUE || value == PrimitiveValue.INFINITY_VALUE) XKeywordValuePresentation(value) else XNumericValuePresentation(value)
}
private val ARRAY_DESCRIPTION_PATTERN = Pattern.compile("^[a-zA-Z\\d]+\\[\\d+\\]$")
private class ArrayPresentation(length: Int, className: String?) : XValuePresentation() {
private val length = Integer.toString(length)
private val className = if (className.isNullOrEmpty()) "Array" else className!!
override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) {
renderer.renderSpecialSymbol(className)
renderer.renderSpecialSymbol("[")
renderer.renderSpecialSymbol(length)
renderer.renderSpecialSymbol("]")
}
}
private val PROTOTYPE_PROP = "__proto__" | platform/script-debugger/debugger-ui/src/VariableView.kt | 2472403970 |
import kotlin.test.Test
import kotlin.test.assertEquals
class JsTestClient {
@Test
fun testGreet() {
assertEquals("world", greet())
}
}
| plugins/kotlin/idea/tests/testData/gradle/wasmSmokeTestProjects/checkWasmPlatformImported/src/jsTest/kotlin/Test.kt | 404835606 |
package jp.gr.aqua.vtextviewer
import android.app.AlertDialog
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.preference.*
class PreferenceFragment : PreferenceFragmentCompat() {
private var mListener: OnFragmentInteractionListener? = null
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
// Load the vtext_preferences from an XML resource
setPreferencesFromResource(R.xml.vtext_preferences, rootKey)
val pm = preferenceManager
val ps = pm.preferenceScreen
// 原稿用紙モード
val writingPaperModeEnabler : (value: Boolean)->Unit = { value->
ps.findPreference<Preference>(Preferences.KEY_FONT_SIZE)?.isEnabled = !value
ps.findPreference<Preference>(Preferences.KEY_CHAR_MAX_PORT)?.isEnabled = !value
ps.findPreference<Preference>(Preferences.KEY_CHAR_MAX_LAND)?.isEnabled = !value
}
writingPaperModeEnabler(Preferences(requireContext()).isWritingPaperMode())
ps.findPreference<Preference>(Preferences.KEY_WRITING_PAPER)
?.setOnPreferenceChangeListener { _, newValue -> if ( newValue is Boolean ) writingPaperModeEnabler(newValue)
true
}
// ダークモードを使う
ps.findPreference<Preference>(Preferences.KEY_USE_DARK_MODE)?.isEnabled=
( Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q )
// IPAフォントについて
ps.findPreference<Preference>(Preferences.KEY_IPA)
?.setOnPreferenceClickListener { showMessage(R.string.vtext_about_ipa_font, "IPA_Font_License_Agreement_v1.0.txt") }
// モリサワ BIZ UD明朝フォントについて
ps.findPreference<Preference>(Preferences.KEY_ABOUT_MORISAWA_MINCHO)
?.setOnPreferenceClickListener { showMessage(R.string.vtext_about_morisawa_mincho, "OFL_bizmincho.txt") }
// モリサワ BIZ UDゴシックフォントについて
ps.findPreference<Preference>(Preferences.KEY_ABOUT_MORISAWA_GOTHIC)
?.setOnPreferenceClickListener { showMessage(R.string.vtext_about_morisawa_gothic, "OFL_bizgothic.txt") }
// バージョン
ps.findPreference<Preference>(Preferences.KEY_ABOUT)
?.setSummary("version: ${versionName} (c)Aquamarine Networks.")
}
private val versionName: String
get() {
val pm = requireActivity().packageManager
var versionName = ""
try {
val packageInfo = pm.getPackageInfo(requireActivity().packageName, 0)
versionName = packageInfo.versionName
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return versionName
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnFragmentInteractionListener) {
mListener = context
} else {
throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
mListener = null
}
interface OnFragmentInteractionListener
private fun showMessage(titleResId: Int, assetText: String) : Boolean {
val message = requireContext().assets.open(assetText).reader(charset = Charsets.UTF_8).use{it.readText()}
AlertDialog.Builder(requireContext())
.setTitle(titleResId)
.setMessage(message)
.setPositiveButton(R.string.vtext_ok, null)
.show()
return false
}
}
| vtextview/src/main/java/jp/gr/aqua/vtextviewer/PreferenceFragment.kt | 2277111873 |
/**
<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>
*/
package slatekit.jobs
import slatekit.common.EnumLike
import slatekit.common.EnumSupport
/**
* General purpose priority Enum to be used for Queue to indicate
* that 1 queue has a higher/lower priority that another queue and
* therefore will be processed more often.
*/
enum class Priority(override val value: Int) : EnumLike {
Low(1),
Mid(2),
High(3);
companion object : EnumSupport() {
override fun all(): Array<EnumLike> {
return arrayOf(Low, Mid, High)
}
}
}
| src/lib/kotlin/slatekit-jobs/src/main/kotlin/slatekit/jobs/Priority.kt | 1621228817 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.annotator
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.util.InspectionMessage
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ArrayUtil
import org.jetbrains.plugins.groovy.GroovyBundle.message
import org.jetbrains.plugins.groovy.annotator.intentions.ConvertLambdaToClosureAction
import org.jetbrains.plugins.groovy.annotator.intentions.ReplaceDotFix
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.*
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.*
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrAssertStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.psi.util.isApplicationExpression
internal class GroovyAnnotatorPre30(private val holder: AnnotationHolder) : GroovyElementVisitor() {
private fun error(typeArgumentList: PsiElement, @InspectionMessage msg: String) {
holder.newAnnotation(HighlightSeverity.ERROR, msg).range(typeArgumentList).create()
}
override fun visitModifierList(modifierList: GrModifierList) {
val modifier = modifierList.getModifier(PsiModifier.DEFAULT) ?: return
error(modifier, message("default.modifier.in.old.versions"))
}
override fun visitDoWhileStatement(statement: GrDoWhileStatement) {
super.visitDoWhileStatement(statement)
error(statement.doKeyword, message("unsupported.do.while.statement"))
}
override fun visitVariableDeclaration(variableDeclaration: GrVariableDeclaration) {
super.visitVariableDeclaration(variableDeclaration)
if (variableDeclaration.parent is GrTraditionalForClause) {
if (variableDeclaration.isTuple) {
holder.newAnnotation(HighlightSeverity.ERROR, message("unsupported.tuple.declaration.in.for")).create()
}
else if (variableDeclaration.variables.size > 1) {
holder.newAnnotation(HighlightSeverity.ERROR, message("unsupported.multiple.variables.in.for")).create()
}
}
else if (variableDeclaration.isTuple) {
val initializer = variableDeclaration.tupleInitializer
if (initializer != null && initializer.isApplicationExpression()) {
error(initializer, message("unsupported.tuple.application.initializer"))
}
}
}
override fun visitExpressionList(expressionList: GrExpressionList) {
super.visitExpressionList(expressionList)
if (expressionList.expressions.size > 1) {
holder.newAnnotation(HighlightSeverity.ERROR, message("unsupported.expression.list.in.for.update")).create()
}
}
override fun visitTryResourceList(resourceList: GrTryResourceList) {
super.visitTryResourceList(resourceList)
error(resourceList.firstChild, message("unsupported.resource.list"))
}
override fun visitBinaryExpression(expression: GrBinaryExpression) {
super.visitBinaryExpression(expression)
val operator = expression.operationToken
val tokenType = operator.node.elementType
if (tokenType === T_ID || tokenType === T_NID) {
error(operator, message("operator.is.not.supported.in", tokenType))
}
}
override fun visitInExpression(expression: GrInExpression) {
super.visitInExpression(expression)
if (GrInExpression.isNegated(expression)) {
error(expression.operationToken, message("unsupported.negated.in"))
}
}
override fun visitInstanceofExpression(expression: GrInstanceOfExpression) {
super.visitInstanceofExpression(expression)
if (GrInstanceOfExpression.isNegated(expression)) {
error(expression.operationToken, message("unsupported.negated.instanceof"))
}
}
override fun visitAssignmentExpression(expression: GrAssignmentExpression) {
super.visitAssignmentExpression(expression)
val operator = expression.operationToken
if (operator.node.elementType === T_ELVIS_ASSIGN) {
error(operator, message("unsupported.elvis.assignment"))
}
}
override fun visitIndexProperty(expression: GrIndexProperty) {
super.visitIndexProperty(expression)
val safeAccessToken = expression.safeAccessToken
if (safeAccessToken != null) {
error(safeAccessToken, message("unsupported.safe.index.access"))
}
}
override fun visitReferenceExpression(expression: GrReferenceExpression) {
super.visitReferenceExpression(expression)
val dot = expression.dotToken ?: return
val tokenType = dot.node.elementType
if (tokenType === T_METHOD_REFERENCE) {
val fix = ReplaceDotFix(tokenType, T_METHOD_CLOSURE)
val message = message("operator.is.not.supported.in", tokenType)
val descriptor = InspectionManager.getInstance(expression.project).createProblemDescriptor(
dot, dot, message,
ProblemHighlightType.ERROR, true
)
holder.newAnnotation(HighlightSeverity.ERROR, message).range(dot)
.newLocalQuickFix(fix, descriptor).registerFix()
.create()
}
}
override fun visitArrayInitializer(arrayInitializer: GrArrayInitializer) {
super.visitArrayInitializer(arrayInitializer)
holder.newAnnotation(HighlightSeverity.ERROR, message("unsupported.array.initializers")).create()
}
override fun visitLambdaExpression(expression: GrLambdaExpression) {
super.visitLambdaExpression(expression)
holder.newAnnotation(HighlightSeverity.ERROR, message("unsupported.lambda")).range(expression.arrow)
.withFix(ConvertLambdaToClosureAction(expression))
.create()
}
override fun visitTypeDefinitionBody(typeDefinitionBody: GrTypeDefinitionBody) {
super.visitTypeDefinitionBody(typeDefinitionBody)
checkAmbiguousCodeBlockInDefinition(typeDefinitionBody)
}
private fun checkAmbiguousCodeBlockInDefinition(typeDefinitionBody: GrTypeDefinitionBody) {
val parent = typeDefinitionBody.parent as? GrAnonymousClassDefinition ?: return
val prev = typeDefinitionBody.prevSibling
if (!PsiUtil.isLineFeed(prev)) return
val newExpression = parent.parent as? GrNewExpression ?: return
val statementOwner = PsiTreeUtil.getParentOfType(newExpression, GrStatementOwner::class.java)
val parenthesizedExpression = PsiTreeUtil.getParentOfType(newExpression, GrParenthesizedExpression::class.java)
if (parenthesizedExpression != null && PsiTreeUtil.isAncestor(statementOwner, parenthesizedExpression, true)) return
val argumentList = PsiTreeUtil.getParentOfType(newExpression, GrArgumentList::class.java)
if (argumentList != null && argumentList !is GrCommandArgumentList) {
if (PsiTreeUtil.isAncestor(statementOwner, argumentList, true)) return
}
holder.newAnnotation(HighlightSeverity.ERROR, message("ambiguous.code.block")).create()
}
override fun visitBlockStatement(blockStatement: GrBlockStatement) {
super.visitBlockStatement(blockStatement)
if (blockStatement.parent is GrStatementOwner) {
holder.newAnnotation(HighlightSeverity.ERROR, message("ambiguous.code.block")).create()
}
}
override fun visitClosure(closure: GrClosableBlock) {
super.visitClosure(closure)
if (!closure.hasParametersSection() && !followsError(closure) && isClosureAmbiguous(closure)) {
holder.newAnnotation(HighlightSeverity.ERROR, message("ambiguous.code.block")).create()
}
}
/**
* for example if (!(a inst)) {}
* ^
* we are here
*/
private fun followsError(closure: GrClosableBlock): Boolean {
val prev = closure.prevSibling
return prev is PsiErrorElement || prev is PsiWhiteSpace && prev.getPrevSibling() is PsiErrorElement
}
private fun isClosureAmbiguous(closure: GrClosableBlock): Boolean {
if (mayBeAnonymousBody(closure)) return true
var place: PsiElement = closure
while (true) {
val parent = place.parent
if (parent == null || parent is GrUnAmbiguousClosureContainer) return false
if (PsiUtil.isExpressionStatement(place)) return true
if (parent.firstChild !== place) return false
place = parent
}
}
private fun mayBeAnonymousBody(closure: GrClosableBlock): Boolean {
val parent = closure.parent as? GrMethodCallExpression ?: return false
if (parent.invokedExpression !is GrNewExpression) {
return false
}
if (!ArrayUtil.contains(closure, *parent.closureArguments)) {
return false
}
var run: PsiElement? = parent.parent
while (run != null) {
if (run is GrParenthesizedExpression) return false
if (run is GrReturnStatement || run is GrAssertStatement || run is GrThrowStatement || run is GrCommandArgumentList) return true
run = run.parent
}
return false
}
override fun visitTypeElement(typeElement: GrTypeElement) {
typeElement.annotations.forEach {
error(it, message("unsupported.type.annotations"))
}
}
override fun visitCodeReferenceElement(refElement: GrCodeReferenceElement) {
refElement.annotations.forEach {
error(it, message("unsupported.type.annotations"))
}
}
override fun visitTupleAssignmentExpression(expression: GrTupleAssignmentExpression) {
val rValue = expression.rValue
if (rValue != null && rValue.isApplicationExpression()) {
error(rValue, message("unsupported.tuple.application.initializer"))
}
}
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotatorPre30.kt | 2340583973 |
/*
* Copyright 2017 Rod MacKenzie.
*
* 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.github.rodm.teamcity.gradle.scripts.server
import jetbrains.buildServer.controllers.ActionMessages
import jetbrains.buildServer.serverSide.ProjectManager
import jetbrains.buildServer.web.openapi.ControllerAction
import org.jdom.Element
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class DeleteScriptAction(controller: InitScriptsActionsController,
val projectManager: ProjectManager,
val scriptsManager: GradleScriptsManager) : ControllerAction
{
private val NAME = "deleteScript"
init {
controller.registerAction(this)
}
override fun canProcess(request: HttpServletRequest): Boolean {
return NAME == request.getParameter("action")
}
override fun process(request: HttpServletRequest, response: HttpServletResponse, ajaxResponse: Element?) {
val name = request.getParameter("name")
if (name != null) {
val projectId = request.getParameter("projectId")
val project = projectManager.findProjectById(projectId)
if (project != null) {
val deleted = scriptsManager.deleteScript(project, name)
val message = "Gradle init script $name ${if (deleted) "was deleted" else "cannot be deleted"}"
ActionMessages.getOrCreateMessages(request).addMessage("initScriptsMessage", message)
}
}
}
}
| server/src/main/kotlin/com/github/rodm/teamcity/gradle/scripts/server/DeleteScriptAction.kt | 1332301255 |
/*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.model
import com.vrem.util.EMPTY
import java.net.InetAddress
import java.nio.ByteOrder
import kotlin.math.abs
import kotlin.math.log10
import kotlin.math.pow
private const val DISTANCE_MHZ_M = 27.55
private const val MIN_RSSI = -100
private const val MAX_RSSI = -55
private const val QUOTE = "\""
fun calculateDistance(frequency: Int, level: Int): Double =
10.0.pow((DISTANCE_MHZ_M - 20 * log10(frequency.toDouble()) + abs(level)) / 20.0)
fun calculateSignalLevel(rssi: Int, numLevels: Int): Int = when {
rssi <= MIN_RSSI -> 0
rssi >= MAX_RSSI -> numLevels - 1
else -> (rssi - MIN_RSSI) * (numLevels - 1) / (MAX_RSSI - MIN_RSSI)
}
fun convertSSID(ssid: String): String = ssid.removePrefix(QUOTE).removeSuffix(QUOTE)
fun convertIpAddress(ipAddress: Int): String {
return try {
val value: Long = when (ByteOrder.LITTLE_ENDIAN) {
ByteOrder.nativeOrder() -> Integer.reverseBytes(ipAddress).toLong()
else -> ipAddress.toLong()
}
InetAddress.getByAddress(value.toBigInteger().toByteArray()).hostAddress
} catch (e: Exception) {
String.EMPTY
}
}
| app/src/main/kotlin/com/vrem/wifianalyzer/wifi/model/WiFiUtils.kt | 3095326847 |
package slatekit.apis.tools.code.builders
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
import kotlin.reflect.KProperty
import slatekit.apis.Verb
import slatekit.apis.routes.Action
import slatekit.apis.tools.code.CodeGenSettings
import slatekit.apis.tools.code.TypeInfo
import slatekit.common.newline
import slatekit.meta.KTypes
import slatekit.meta.Reflector
class JavaBuilder(val settings: CodeGenSettings) : CodeBuilder {
override val basicTypes = TypeInfo.basicTypes
override val mapTypeDecl = "HashMap<String, Object> postData = new HashMap<>();"
override fun buildModelInfo(cls: KClass<*>): String {
val props = Reflector.getProperties(cls)
val fields = props.foldIndexed("") { ndx: Int, acc: String, prop: KProperty<*> ->
val type = prop.returnType
val typeInfo = buildTypeName(type)
val field = "public " + typeInfo.targetType + " " + prop.name + ";" + newline
acc + (if (ndx > 0) "\t" else "") + field
}
return fields
}
override fun buildArg(parameter: KParameter): String {
return buildTargetName(parameter.type.classifier as KClass<*>) + " " + parameter.name
}
/**
* builds a string of parameters to put into the query string.
* e.g. queryParams.put("id", id);
*/
override fun buildQueryParams(action: Action): String {
return if (action.verb == Verb.Get) {
action.paramsUser.foldIndexed("") { ndx: Int, acc: String, param: KParameter ->
acc + (if (ndx > 0) "\t\t" else "") + "queryParams.put(\"" + param.name + "\", String.valueOf(" + param.name + "));" + newline
}
} else {
""
}
}
/**
* builds a string of the parameters to put into the entity/body of request
* e..g dataParams.put('id", id);
*/
override fun buildDataParams(action: Action): String {
return if (action.verb != Verb.Get) {
action.paramsUser.foldIndexed("") { ndx: Int, acc: String, param: KParameter ->
acc + (if (ndx > 0) "\t\t" else "") + "postData.put(\"" + param.name + "\", " + param.name + ");" + newline
}
} else {
""
}
}
override fun buildTargetName(cls:KClass<*>): String {
return when(cls) {
KTypes.KStringClass -> KTypes.KStringClass .java.simpleName
KTypes.KBoolClass -> KTypes.KBoolClass .java.simpleName
KTypes.KShortClass -> KTypes.KShortClass .java.simpleName
KTypes.KIntClass -> KTypes.KIntClass .java.simpleName
KTypes.KLongClass -> KTypes.KLongClass .java.simpleName
KTypes.KFloatClass -> KTypes.KFloatClass .java.simpleName
KTypes.KDoubleClass -> KTypes.KDoubleClass .java.simpleName
KTypes.KSmartValueClass -> KTypes.KSmartValueClass.java.simpleName
KTypes.KDecStringClass -> KTypes.KStringClass .java.simpleName
KTypes.KDecIntClass -> KTypes.KStringClass .java.simpleName
KTypes.KDecLongClass -> KTypes.KStringClass .java.simpleName
KTypes.KDecDoubleClass -> KTypes.KStringClass .java.simpleName
else -> KTypes.KStringClass .java.simpleName
}
}
override fun buildTypeLoader(): String = ".class"
}
| src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/tools/code/builders/JavaBuilder.kt | 1922633588 |
// FILE: 1.kt
// WITH_RUNTIME
package test
public interface MCloseable {
public open fun close()
}
public inline fun <T : MCloseable, R> T.muse(block: (T) -> R): R {
try {
return block(this)
} finally {
this.close()
}
}
// FILE: 2.kt
import test.*
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.fail
class MyException(message: String) : Exception(message)
class Holder(var value: String) {
operator fun plusAssign(s: String?) {
value += s
if (s != "closed") {
value += "->"
}
}
}
class Test() : MCloseable {
val status = Holder("")
private fun jobFun() {
status += "called"
}
fun nonLocalWithExceptionAndFinally(): Holder {
muse {
try {
jobFun()
throw MyException("exception")
}
catch (e: MyException) {
status += e.message
return status
}
finally {
status += "finally"
}
}
return Holder("fail")
}
override fun close() {
status += "closed"
throw MyException("error")
}
}
fun box() : String {
assertError(1, "called->exception->finally->closed") {
nonLocalWithExceptionAndFinally()
}
return "OK"
}
inline fun assertError(index: Int, expected: String, l: Test.()->Unit) {
val testLocal = Test()
try {
testLocal.l()
fail("fail $index: no error")
} catch (e: Exception) {
assertEquals(expected, testLocal.status.value, "failed on $index")
}
}
| backend.native/tests/external/codegen/boxInline/nonLocalReturns/tryFinally/exceptionTable/exceptionInFinally.kt | 1636834574 |
package codegen.`object`.fields1
import kotlin.test.*
class B(val a:Int, b:Int) {
constructor(pos:Int):this(1, pos) {}
val pos = b + 1
}
fun primaryConstructorCall(a:Int, b:Int) = B(a, b).pos
fun secondaryConstructorCall(a:Int) = B(a).pos
@Test fun runTest() {
if (primaryConstructorCall(0xdeadbeef.toInt(), 41) != 42) throw Error()
if (secondaryConstructorCall(41) != 42) throw Error()
} | backend.native/tests/codegen/object/fields1.kt | 3126031969 |
// Auto-generated by GeneratePrimitiveVsObjectEqualityTestData. Do not edit!
val nx: Any? = 0L
val nn: Any? = null
val x: Long = 0L
val y: Long = 1L
fun box(): String {
val ax: Any? = 0L
val an: Any? = null
val bx: Long = 0L
val by: Long = 1L
return when {
0L != nx -> "Fail 0"
1L == nx -> "Fail 1"
!(0L == nx) -> "Fail 2"
!(1L != nx) -> "Fail 3"
x != nx -> "Fail 4"
y == nx -> "Fail 5"
!(x == nx) -> "Fail 6"
!(y != nx) -> "Fail 7"
0L == nn -> "Fail 8"
!(0L != nn) -> "Fail 9"
x == nn -> "Fail 10"
!(x != nn) -> "Fail 11"
0L != ax -> "Fail 12"
1L == ax -> "Fail 13"
!(0L == ax) -> "Fail 14"
!(1L != ax) -> "Fail 15"
x != ax -> "Fail 16"
y == ax -> "Fail 17"
!(x == ax) -> "Fail 18"
!(y != ax) -> "Fail 19"
bx != ax -> "Fail 20"
by == ax -> "Fail 21"
!(bx == ax) -> "Fail 22"
!(by != ax) -> "Fail 23"
0L == an -> "Fail 24"
!(0L != an) -> "Fail 25"
x == an -> "Fail 26"
!(x != an) -> "Fail 27"
bx == an -> "Fail 28"
!(bx != an) -> "Fail 29"
else -> "OK"
}
}
| backend.native/tests/external/codegen/box/primitiveTypes/equalityWithObject/generated/primitiveEqObjectLong.kt | 1627368198 |
fun box(): String {
val a1: Any = 1.toByte().plus(1)
val a2: Any = 1.toShort().plus(1)
val a3: Any = 1.plus(1)
val a4: Any = 1L.plus(1)
val a5: Any = 1.0.plus(1)
val a6: Any = 1f.plus(1)
val a7: Any = 'A'.plus(1)
val a8: Any = 'B'.minus('A')
if (a1 !is Int || a1 != 2) return "fail 1"
if (a2 !is Int || a2 != 2) return "fail 2"
if (a3 !is Int || a3 != 2) return "fail 3"
if (a4 !is Long || a4 != 2L) return "fail 4"
if (a5 !is Double || a5 != 2.0) return "fail 5"
if (a6 !is Float || a6 != 2f) return "fail 6"
if (a7 !is Char || a7 != 'B') return "fail 7"
if (a8 !is Int || a8 != 1) return "fail 8"
return "OK"
} | backend.native/tests/external/codegen/box/binaryOp/callAny.kt | 3172074294 |
// IGNORE_BACKEND: JS
// WITH_RUNTIME
val DOUBLE_RANGE = 0.0 .. -0.0
val PZERO = 0.0 as Comparable<Any>
val NZERO = -0.0 as Comparable<Any>
val COMPARABLE_RANGE = PZERO .. NZERO
fun box(): String {
if (!(0.0 in DOUBLE_RANGE)) return "fail 1 in Double"
if (0.0 !in DOUBLE_RANGE) return "fail 1 !in Double"
if (!(-0.0 in DOUBLE_RANGE)) return "fail 2 in Double"
if (-0.0 !in DOUBLE_RANGE) return "fail 2 !in Double"
if (PZERO in COMPARABLE_RANGE) return "fail 3 in Comparable"
if (!(PZERO !in COMPARABLE_RANGE)) return "fail 3 !in Comparable"
if (NZERO in COMPARABLE_RANGE) return "fail 4 in Comparable"
if (!(NZERO !in COMPARABLE_RANGE)) return "fail 4a !in Comparable"
return "OK"
} | backend.native/tests/external/codegen/box/ranges/contains/inDoubleRangeLiteralVsComparableRangeLiteral.kt | 4078126653 |
package com.lush.view.holder
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import android.view.View
import com.lush.view.R
/**
* Base class for all view holders to be used in concrete implementations of [com.lush.lib.adapter.BaseListAdapter]
*/
abstract class BaseViewHolder<in T>(view: View?) : RecyclerView.ViewHolder(view)
{
abstract fun bind(model: T)
fun setOnClickListener(listener: View.OnClickListener)
{
itemView?.setOnClickListener(listener)
}
fun setPositionInList(position: Int)
{
itemView?.setBackgroundColor(if ((position % 2) == 0) Color.WHITE else itemView.resources.getColor(R.color.list_item_alternate))
}
/**
* Override this method to cancel any behaviour you don't want to continue after the view has been recycled
* This is most likely async behaviour
*/
open fun recycle() { }
} | views/src/main/java/com/lush/view/holder/BaseViewHolder.kt | 156604881 |
fun foo(b: Boolean) =
when (b) {
false -> 0
true -> 1
else -> 2
}
fun box(): String = if (foo(false) == 0 && foo(true) == 1) "OK" else "Fail"
| backend.native/tests/external/codegen/box/when/kt2466.kt | 2698001532 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.CompactChip
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.OutlinedChip
import androidx.wear.compose.material.OutlinedCompactChip
import androidx.wear.compose.material.Text
@Sampled
@Composable
fun ChipWithIconAndLabel() {
Chip(
onClick = { /* Do something */ },
enabled = true,
// When we have only primary label we can have up to 2 lines of text
label = {
Text(
text = "Main label can span over 2 lines",
maxLines = 2, overflow = TextOverflow.Ellipsis
)
},
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier.size(ChipDefaults.IconSize)
.wrapContentSize(align = Alignment.Center),
)
}
)
}
@Sampled
@Composable
fun OutlinedChipWithIconAndLabel() {
OutlinedChip(
onClick = { /* Do something */ },
enabled = true,
// When we have only primary label we can have up to 2 lines of text
label = {
Text(
text = "Main label can span over 2 lines",
maxLines = 2, overflow = TextOverflow.Ellipsis
)
},
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier.size(ChipDefaults.IconSize)
.wrapContentSize(align = Alignment.Center),
)
}
)
}
@Sampled
@Composable
fun ChipWithIconAndLabels() {
Chip(
onClick = { /* Do something */ },
enabled = true,
// When we have both label and secondary label present limit both to 1 line of text
label = { Text(text = "Main label", maxLines = 1, overflow = TextOverflow.Ellipsis) },
secondaryLabel = {
Text(text = "secondary label", maxLines = 1, overflow = TextOverflow.Ellipsis)
},
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier.size(ChipDefaults.IconSize)
.wrapContentSize(align = Alignment.Center),
)
}
)
}
@Sampled
@Composable
fun CompactChipWithIconAndLabel() {
CompactChip(
onClick = { /* Do something */ },
enabled = true,
// CompactChip label should be no more than 1 line of text
label = {
Text("Single line label", maxLines = 1, overflow = TextOverflow.Ellipsis)
},
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier.size(ChipDefaults.SmallIconSize),
)
},
)
}
@Sampled
@Composable
fun CompactChipWithLabel() {
CompactChip(
onClick = { /* Do something */ },
enabled = true,
// CompactChip label should be no more than 1 line of text
label = {
Text(
text = "Single line label",
maxLines = 1,
overflow = TextOverflow.Ellipsis,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
},
)
}
@Sampled
@Composable
fun CompactChipWithIcon() {
CompactChip(
onClick = { /* Do something */ },
enabled = true,
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier.size(ChipDefaults.IconSize)
)
},
)
}
@Sampled
@Composable
fun OutlinedCompactChipWithIconAndLabel() {
OutlinedCompactChip(
onClick = { /* Do something */ },
enabled = true,
// CompactChip label should be no more than 1 line of text
label = {
Text("Single line label", maxLines = 1, overflow = TextOverflow.Ellipsis)
},
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_airplanemode_active_24px),
contentDescription = "airplane",
modifier = Modifier.size(ChipDefaults.SmallIconSize),
)
},
)
}
| wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/ChipSample.kt | 3880356065 |
/*
* Copyright 2019 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.pyamsoft.padlock.lock
import com.pyamsoft.padlock.api.lockscreen.LockPassed
import com.pyamsoft.pydroid.core.threads.Enforcer
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
internal class LockPassedImpl @Inject internal constructor(
private val enforcer: Enforcer
) : LockPassed {
private val passedSet: MutableCollection<String> = LinkedHashSet()
override fun add(
packageName: String,
activityName: String
) {
enforcer.assertNotOnMainThread()
passedSet.add("$packageName$activityName")
}
override fun remove(
packageName: String,
activityName: String
) {
enforcer.assertNotOnMainThread()
passedSet.remove("$packageName$activityName")
}
override fun check(
packageName: String,
activityName: String
): Boolean {
enforcer.assertNotOnMainThread()
return passedSet.contains("$packageName$activityName")
}
}
| padlock-lock/src/main/java/com/pyamsoft/padlock/lock/LockPassedImpl.kt | 1166802662 |
package <%= appPackage %>
import <%= appPackage %>.data.ApiModule
import <%= appPackage %>.data.DataModule
import <%= appPackage %>.ui.PresenterModule
import <%= appPackage %>.ui.UiComponent
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(ApplicationModule::class, ApiModule::class, DataModule::class))
interface AppComponent {
fun inject(appApplication: AppApplication)
operator fun plus(presenterModule: PresenterModule): UiComponent
}
| app/templates/app_mvp/src/main/kotlin/AppComponent.kt | 3955389520 |
class KotlinClass {
fun <caret>a(): Int = extension()
}
fun test() {
KotlinClass().a()
}
fun KotlinClass.extension(): Int = 42
| plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/expressionBody/delegateToExtensionWithoutThis.kt | 1022393363 |
package one.two
fun read() {
val c = KotlinObject.Nested.variable
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/nestedObject/variable/Read.kt | 1863066234 |
package a
class A {
companion object Named {
val i: Int
}
}
fun main(args: Array<String>) {
A.Na<caret>med.i
}
// REF: companion object of (a).A | plugins/kotlin/idea/tests/testData/resolve/references/NamedClassObject.kt | 3542313759 |
// 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.
@file:Suppress("DeprecatedCallableAddReplaceWith")
package org.jetbrains.kotlin.idea.gradleTooling
import org.jetbrains.kotlin.idea.gradleTooling.arguments.AbstractCompilerArgumentsCacheAware
import org.jetbrains.kotlin.idea.projectModel.*
import org.jetbrains.plugins.gradle.model.ExternalDependency
import org.jetbrains.plugins.gradle.model.ModelFactory
import java.io.Serializable
typealias KotlinDependency = ExternalDependency
class KotlinDependencyMapper {
private var currentIndex: KotlinDependencyId = 0
private val idToDependency = HashMap<KotlinDependencyId, KotlinDependency>()
private val dependencyToId = HashMap<KotlinDependency, KotlinDependencyId>()
fun getDependency(id: KotlinDependencyId) = idToDependency[id]
fun getId(dependency: KotlinDependency): KotlinDependencyId {
return dependencyToId[dependency] ?: let {
currentIndex++
dependencyToId[dependency] = currentIndex
idToDependency[currentIndex] = dependency
return currentIndex
}
}
fun toDependencyMap(): Map<KotlinDependencyId, KotlinDependency> = idToDependency
}
fun KotlinDependency.deepCopy(cache: MutableMap<Any, Any>): KotlinDependency {
val cachedValue = cache[this] as? KotlinDependency
return if (cachedValue != null) {
cachedValue
} else {
val result = ModelFactory.createCopy(this)
cache[this] = result
result
}
}
interface KotlinMPPGradleModel : KotlinSourceSetContainer, Serializable {
val dependencyMap: Map<KotlinDependencyId, KotlinDependency>
val targets: Collection<KotlinTarget>
val extraFeatures: ExtraFeatures
val kotlinNativeHome: String
val partialCacheAware: CompilerArgumentsCacheAware
@Deprecated("Use 'sourceSetsByName' instead", ReplaceWith("sourceSetsByName"), DeprecationLevel.ERROR)
val sourceSets: Map<String, KotlinSourceSet>
get() = sourceSetsByName
override val sourceSetsByName: Map<String, KotlinSourceSet>
companion object {
const val NO_KOTLIN_NATIVE_HOME = ""
}
} | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinMPPGradleModel.kt | 4072063396 |
// PROBLEM: none
fun <T> doSomething(a: T) {}
fun test(n: Int): String {
var res: String
<caret>when (n) {
1 -> {
doSomething("***")
res = "one"
}
else -> {
res = "two"
doSomething("***")
}
}
return res
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/liftOut/whenToAssignment/simpleWhenWithoutTerminatingAssignment.kt | 3839296632 |
fun foo(): String? {
ret<caret>
}
// ELEMENT: "return null"
| plugins/kotlin/completion/tests/testData/handlers/keywords/ReturnNull.kt | 1665969471 |
package com.jetbrains.packagesearch.intellij.plugin.maven.configuration.ui
import com.intellij.openapi.project.Project
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ConfigurableContributor
internal class MavenConfigurableContributor(private val project: Project) : ConfigurableContributor {
override fun createDriver() = MavenConfigurableContributorDriver(project)
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/maven/configuration/ui/MavenConfigurableContributor.kt | 185113839 |
// !DIAGNOSTICS_NUMBER: 1
// !DIAGNOSTICS: UNSUPPORTED_FEATURE
// LANGUAGE_VERSION: 1.0
fun test() {
mapOf("1" to "2").forEach { (key, value) -> }
}
| plugins/kotlin/idea/tests/testData/diagnosticMessage/unsupportedFeature.kt | 2719566442 |
//ALLOW_AST_ACCESS
package test
typealias S = String
typealias SS = S
typealias SSS = SS
val x1: S = { "" }()
val x2: SS = { "" }()
val x3: SSS = { "" }()
val x4: S? = { "" }()
val x5: SS? = { "" }()
val x6: SSS? = { "" }()
| plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/typealias/Basic.kt | 2068256566 |
package com.example.unittesting
import android.content.res.Resources
import android.support.annotation.StringRes
class ResourceProvider(private var resources: Resources) {
fun getString(@StringRes stringResId: Int): String {
return resources.getString(stringResId)
}
}
| app/src/main/kotlin/com/example/unittesting/ResourceProvider.kt | 3003642247 |
package i_introduction._4_Lambdas
import util.*
fun example() {
val sum = { x: Int, y: Int -> x + y }
val square: (Int) -> Int = { x -> x * x }
sum(1, square(2)) == 5
}
fun todoTask4(collection: Collection<Int>): Nothing = TODO(
"""
Task 4.
Rewrite 'JavaCode4.task4()' in Kotlin using lambdas.
You can find the appropriate function to call on 'collection' through IntelliJ's code completion feature.
(Don't use the class 'Iterables').
""",
documentation = doc4(),
references = { JavaCode4().task4(collection) })
fun task4(collection: Collection<Int>): Boolean = todoTask4(collection)
| src/i_introduction/_4_Lambdas/Lambdas.kt | 4280570375 |
package com.habitrpg.android.habitica.ui.fragments.preferences
import android.content.SharedPreferences
import android.os.Bundle
import androidx.preference.CheckBoxPreference
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.user.User
import io.reactivex.functions.Consumer
class EmailNotificationsPreferencesFragment : BasePreferencesFragment(), SharedPreferences.OnSharedPreferenceChangeListener {
private var isInitialSet: Boolean = true
private var isSettingUser: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
HabiticaBaseApplication.userComponent?.inject(this)
super.onCreate(savedInstanceState)
}
override fun onResume() {
super.onResume()
preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
}
override fun setupPreferences() { /* no-on */ }
override fun setUser(user: User?) {
super.setUser(user)
isSettingUser = !isInitialSet
updatePreference("preference_email_you_won_challenge", user?.preferences?.emailNotifications?.wonChallenge)
updatePreference("preference_email_received_a_private_message", user?.preferences?.emailNotifications?.newPM)
updatePreference("preference_email_gifted_gems", user?.preferences?.emailNotifications?.giftedGems)
updatePreference("preference_email_gifted_subscription", user?.preferences?.emailNotifications?.giftedSubscription)
updatePreference("preference_email_invited_to_party", user?.preferences?.emailNotifications?.invitedParty)
updatePreference("preference_email_invited_to_guild", user?.preferences?.emailNotifications?.invitedGuild)
updatePreference("preference_email_your_quest_has_begun", user?.preferences?.emailNotifications?.questStarted)
updatePreference("preference_email_invited_to_quest", user?.preferences?.emailNotifications?.invitedQuest)
updatePreference("preference_email_important_announcements", user?.preferences?.emailNotifications?.majorUpdates)
updatePreference("preference_email_kicked_group", user?.preferences?.emailNotifications?.kickedGroup)
updatePreference("preference_email_onboarding", user?.preferences?.emailNotifications?.onboarding)
updatePreference("preference_email_subscription_reminders", user?.preferences?.emailNotifications?.subscriptionReminders)
isSettingUser = false
isInitialSet = false
}
private fun updatePreference(key: String, isChecked: Boolean?) {
val preference = (findPreference(key) as? CheckBoxPreference)
preference?.isChecked = isChecked == true
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (isSettingUser) {
return
}
val pathKey = when (key) {
"preference_email_you_won_challenge" -> "wonChallenge"
"preference_email_received_a_private_message" -> "newPM"
"preference_email_gifted_gems" -> "giftedGems"
"preference_email_gifted_subscription" -> "giftedSubscription"
"preference_email_invited_to_party" -> "invitedParty"
"preference_email_invited_to_guild" -> "invitedGuild"
"preference_email_your_quest_has_begun" -> "questStarted"
"preference_email_invited_to_quest" -> "invitedQuest"
"preference_email_important_announcements" -> "majorUpdates"
"preference_email_kicked_group" -> "kickedGroup"
"preference_email_onboarding" -> "onboarding"
"preference_email_subscription_reminders" -> "subscriptionReminders"
else -> null
}
if (pathKey != null) {
compositeSubscription.add(userRepository.updateUser(user, "preferences.emailNotifications.$pathKey", sharedPreferences.getBoolean(key, false)).subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
}
}
} | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/preferences/EmailNotificationsPreferencesFragment.kt | 496980772 |
package com.cn29.aac.datasource.api
import androidx.lifecycle.LiveData
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import java.lang.reflect.Type
import java.util.concurrent.atomic.AtomicBoolean
class LiveDataCallAdapter<R>(private val responseType: Type) : CallAdapter<R, LiveData<ApiResponse<R>>> {
override fun responseType(): Type {
return responseType
}
override fun adapt(call: Call<R>): LiveData<ApiResponse<R>> {
return object : LiveData<ApiResponse<R>>() {
var started = AtomicBoolean(false)
override fun onActive() {
super.onActive()
if (started.compareAndSet(false, true)) {
call.enqueue(object : Callback<R> {
override fun onResponse(call: Call<R>, response: Response<R>) {
postValue(ApiResponse(response))
}
override fun onFailure(call: Call<R>, throwable: Throwable) {
postValue(ApiResponse(throwable))
}
})
}
}
}
}
} | app/src/main/java/com/cn29/aac/datasource/api/LiveDataCallAdapter.kt | 2774191992 |
package com.cout970.modeler.util
import com.cout970.matrix.api.IMatrix4
import com.cout970.vector.api.IVector2
import com.cout970.vector.api.IVector3
import com.cout970.vector.extensions.Vector3
import com.cout970.vector.extensions.vec2Of
import org.joml.Matrix4d
import org.joml.Vector3d
/**
* Created by cout970 on 2017/03/26.
*/
object MatrixUtils {
fun createOrthoMatrix(size: IVector2): IMatrix4 {
val aspectRatio = (size.yd / size.xd)
return Matrix4d().setOrtho(-1.0 / aspectRatio, 1.0 / aspectRatio, -1.0, 1.0, 0.1, 10000.0).toIMatrix()
}
fun projectAxis(matrix: Matrix4d, dir: IVector3): Pair<IVector2, IVector2> {
val start = matrix.project(Vector3.ORIGIN.toJoml3d(), intArrayOf(-1, -1, 2, 2), Vector3d())
val end = matrix.project(dir.toJoml3d(), intArrayOf(-1, -1, 2, 2), Vector3d())
return vec2Of(start.x, start.y) to vec2Of(end.x, end.y)
}
} | src/main/kotlin/com/cout970/modeler/util/MatrixUtils.kt | 1189046929 |
package com.habitrpg.android.habitica.ui.fragments.support
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.databinding.FragmentSupportBugFixBinding
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.AppTestingLevel
import com.habitrpg.android.habitica.helpers.DeviceName
import com.habitrpg.android.habitica.modules.AppModule
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import io.reactivex.Completable
import javax.inject.Inject
import javax.inject.Named
class BugFixFragment: BaseMainFragment() {
private var deviceInfo: DeviceName.DeviceInfo? = null
private lateinit var binding: FragmentSupportBugFixBinding
@field:[Inject Named(AppModule.NAMED_USER_ID)]
lateinit var userId: String
@Inject
lateinit var appConfigManager: AppConfigManager
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
hidesToolbar = true
super.onCreateView(inflater, container, savedInstanceState)
binding = FragmentSupportBugFixBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
compositeSubscription.add(Completable.fromAction {
deviceInfo = DeviceName.getDeviceInfo(context)
}.subscribe())
binding.reportBugButton.setOnClickListener {
sendEmail("[Android] Bugreport")
}
}
private val versionName: String by lazy {
try {
@Suppress("DEPRECATION")
activity?.packageManager?.getPackageInfo(activity?.packageName, 0)?.versionName ?: ""
} catch (e: PackageManager.NameNotFoundException) {
""
}
}
private val versionCode: Int by lazy {
try {
@Suppress("DEPRECATION")
activity?.packageManager?.getPackageInfo(activity?.packageName, 0)?.versionCode ?: 0
} catch (e: PackageManager.NameNotFoundException) {
0
}
}
private fun sendEmail(subject: String) {
val version = Build.VERSION.SDK_INT
val deviceName = deviceInfo?.name ?: DeviceName.getDeviceName()
val manufacturer = deviceInfo?.manufacturer ?: Build.MANUFACTURER
var bodyOfEmail = "Device: $manufacturer $deviceName" +
" \nAndroid Version: $version"+
" \nAppVersion: " + getString(R.string.version_info, versionName, versionCode)
if (appConfigManager.testingLevel().name != AppTestingLevel.PRODUCTION.name) {
bodyOfEmail += " ${appConfigManager.testingLevel().name}"
}
bodyOfEmail += " \nUser ID: $userId"
val user = this.user
if (user != null) {
bodyOfEmail += " \nLevel: " + (user.stats?.lvl ?: 0) +
" \nClass: " + (if (user.preferences?.disableClasses == true) "Disabled" else (user.stats?.habitClass ?: "None")) +
" \nIs in Inn: " + (user.preferences?.sleep ?: false) +
" \nUses Costume: " + (user.preferences?.costume ?: false) +
" \nCustom Day Start: " + (user.preferences?.dayStart ?: 0) +
" \nTimezone Offset: " + (user.preferences?.timezoneOffset ?: 0)
}
bodyOfEmail += " \nDetails:\n"
activity?.let {
val emailIntent = Intent(Intent.ACTION_SENDTO)
val mailto = "mailto:" + appConfigManager.supportEmail() +
"&subject=" + Uri.encode(subject) +
"&body=" + Uri.encode(bodyOfEmail)
emailIntent.data = Uri.parse(mailto);
startActivity(Intent.createChooser(emailIntent, "Choose an Email client :"))
}
}
} | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/support/BugFixFragment.kt | 55781866 |
// Implementation
class ComplexSystemStore(val filePath: String) {
init {
println("Reading data from file: $filePath")
}
val store = HashMap<String, String>()
fun store(key: String, payload: String) {
store.put(key, payload)
}
fun read(key: String): String = store[key] ?: ""
fun commit() = println("Storing cached data: $store to file: $filePath")
}
data class User(val login: String)
class UserRepository {
val systemPreferences = ComplexSystemStore("/data/default.prefs")
fun save(user: User) {
systemPreferences.store("USER_KEY", user.login)
systemPreferences.commit()
}
fun findFirst(): User = User(systemPreferences.read("USER_KEY"))
}
// Usage
fun main(args: Array<String>) {
val userRepository = UserRepository()
val user = User("dbacinski")
userRepository.save(user)
val resultUser = userRepository.findFirst()
println("Found stored user: $resultUser")
} | Structural/Facade/Facade.kt | 2037520875 |
// WITH_RUNTIME
package org.apache.commons.logging
class Foo {
private val logger = LogFactory.getLog(<caret>Bar::class.java.name)
}
class Bar
object LogFactory {
fun getLog(clazz: Class<*>) {}
fun getLog(name: String?) {}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/logging/loggerInitializedWithForeignClass/commons/name.kt | 3702326924 |
class A() {
}
// SYMBOLS:
KtFirConstructorSymbol:
annotatedType: [] A
annotationClassIds: []
annotations: []
containingClassIdIfNonLocal: A
dispatchType: null
isPrimary: true
origin: SOURCE
symbolKind: MEMBER
typeParameters: []
valueParameters: []
visibility: PUBLIC
KtFirClassOrObjectSymbol:
annotationClassIds: []
annotations: []
classIdIfNonLocal: A
classKind: CLASS
companionObject: null
isData: false
isExternal: false
isFun: false
isInline: false
isInner: false
modality: FINAL
name: A
origin: SOURCE
superTypes: [[] kotlin/Any]
symbolKind: TOP_LEVEL
typeParameters: []
visibility: PUBLIC
| plugins/kotlin/frontend-fir/testData/symbolPointer/classPrimaryConstructor.kt | 18140972 |
/*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* econsim-tr01 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01
import org.joda.time.DateTime
/**
* Created by pisarenko on 05.04.2016.
*/
data class ResourceFlow (
val time: DateTime,
val src:ISometingIdentifiable,
val target:ISometingIdentifiable,
val res:String,
val amt:Double?) | src/main/java/cc/altruix/econsimtr01/ResourceFlow.kt | 3113893805 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.credentialStore
import com.intellij.testFramework.RuleChain
import com.intellij.testFramework.TemporaryDirectory
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import java.math.BigInteger
import java.util.*
// part of specific tests in the IcsCredentialTest
class FileCredentialStoreTest {
// we don't use in memory fs to check real file io
private val tempDirManager = TemporaryDirectory()
@Rule
@JvmField
val ruleChain = RuleChain(tempDirManager)
@Test
fun many() {
val baseDir = tempDirManager.newPath()
var provider = KeePassCredentialStore(baseDirectory = baseDir)
val serviceName = UUID.randomUUID().toString()
assertThat(baseDir).doesNotExist()
val random = Random()
for (i in 0..9) {
val accountName = BigInteger(8 * 16, random).toString()
provider.set(CredentialAttributes(serviceName, accountName), Credentials(accountName, BigInteger(8 * 16, random).toString()))
}
provider.save()
provider = KeePassCredentialStore(baseDirectory = baseDir)
provider.deleteFileStorage()
val pdbFile = baseDir.resolve("c.kdbx")
val pdbPwdFile = baseDir.resolve("pdb.pwd")
assertThat(pdbFile).doesNotExist()
assertThat(pdbPwdFile).doesNotExist()
}
@Test
fun test() {
val serviceName = UUID.randomUUID().toString()
val baseDir = tempDirManager.newPath()
var provider = KeePassCredentialStore(baseDirectory = baseDir)
assertThat(baseDir).doesNotExist()
val fooAttributes = CredentialAttributes(serviceName, "foo")
assertThat(provider.get(fooAttributes)).isNull()
provider.setPassword(fooAttributes, "pass")
assertThat(baseDir).doesNotExist()
val pdbFile = baseDir.resolve("c.kdbx")
val pdbPwdFile = baseDir.resolve("pdb.pwd")
provider.save()
assertThat(pdbFile).isRegularFile()
assertThat(pdbPwdFile).isRegularFile()
val amAttributes = CredentialAttributes(serviceName, "am")
provider.setPassword(amAttributes, "pass2")
assertThat(provider.getPassword(fooAttributes)).isNull()
assertThat(provider.getPassword(amAttributes)).isEqualTo("pass2")
provider.setPassword(fooAttributes, null)
assertThat(provider.get(fooAttributes)).isNull()
provider.save()
assertThat(pdbFile).isRegularFile()
assertThat(pdbPwdFile).isRegularFile()
provider = KeePassCredentialStore(baseDirectory = baseDir)
assertThat(provider.get(fooAttributes)).isNull()
assertThat(provider.getPassword(amAttributes)).isEqualTo("pass2")
provider.setPassword(amAttributes, null)
assertThat(provider.get(amAttributes)).isNull()
provider.save()
provider.deleteFileStorage()
assertThat(pdbFile).doesNotExist()
assertThat(pdbPwdFile).doesNotExist()
}
}
| platform/credential-store/test/KeePassCredentialStoreTest.kt | 2208091259 |
/**
* Hello darling
* @author DarkWing Duck
*/
val prop = 2
/**
* Hello darling var
* @author Megavolt
*/
var prop = 2
class outherClass {
/**
* Hello darling instance
* @author Morgana Macawber
*/
val instanceProp get() {
/**
* Hello darling local
* @author Launchpad McQuack
*/
val localProp get() {
if (true) {
/**
* Hello darling superLocal
* @author Reginald Bushroot
*/
val superLocalProp = 4
}
}
}
}
// RENDER: <div class='content'><p>Hello darling</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>DarkWing Duck</td></table>
// RENDER: <div class='content'><p>Hello darling var</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Megavolt</td></table>
// RENDER: <div class='content'><p>Hello darling instance</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Morgana Macawber</td></table>
// RENDER: <div class='content'><p>Hello darling local</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Launchpad McQuack</td></table>
// RENDER: <div class='content'><p>Hello darling superLocal</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Reginald Bushroot</td></table> | plugins/kotlin/idea/tests/testData/codeInsight/renderingKDoc/propertyRendering.kt | 996235921 |
class Bar {
operator fun plusAssign(arg: Bar) {}
}
fun foo(b: Bar) {
var a = Bar()
a <caret>+= b
}
| plugins/kotlin/idea/tests/testData/intentions/operatorToFunction/binaryPlusEquals.kt | 2184470476 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass
// OPTIONS: derivedInterfaces
interface <caret>X {
}
open class A: X {
}
interface Y: X {
}
| plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinTraitDerivedTraits.0.kt | 896128793 |
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin.text
//
// NOTE: THIS FILE IS AUTO-GENERATED by the GenerateUnicodeData.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
internal fun String.codePointAt(index: Int): Int {
val high = this[index]
if (high.isHighSurrogate() && index + 1 < this.length) {
val low = this[index + 1]
if (low.isLowSurrogate()) {
return Char.toCodePoint(high, low)
}
}
return high.toInt()
}
internal fun Int.charCount(): Int = if (this >= Char.MIN_SUPPLEMENTARY_CODE_POINT) 2 else 1
internal fun StringBuilder.appendCodePoint(codePoint: Int) {
if (codePoint < Char.MIN_SUPPLEMENTARY_CODE_POINT) {
append(codePoint.toChar())
} else {
append(Char.MIN_HIGH_SURROGATE + ((codePoint - 0x10000) shr 10))
append(Char.MIN_LOW_SURROGATE + (codePoint and 0x3ff))
}
}
internal fun String.uppercaseImpl(): String {
var unchangedIndex = 0
while (unchangedIndex < this.length) {
val codePoint = codePointAt(unchangedIndex)
if (this[unchangedIndex].oneToManyUppercase() != null || codePoint.uppercaseCodePoint() != codePoint) {
break
}
unchangedIndex += codePoint.charCount()
}
if (unchangedIndex == this.length) {
return this
}
val sb = StringBuilder(this.length)
sb.appendRange(this, 0, unchangedIndex)
var index = unchangedIndex
while (index < this.length) {
val specialCasing = this[index].oneToManyUppercase()
if (specialCasing != null) {
sb.append(specialCasing)
index++
continue
}
val codePoint = codePointAt(index)
val uppercaseCodePoint = codePoint.uppercaseCodePoint()
sb.appendCodePoint(uppercaseCodePoint)
index += codePoint.charCount()
}
return sb.toString()
}
| runtime/src/main/kotlin/generated/_StringUppercase.kt | 4048365942 |
package com.github.kerubistan.kerub.model.dynamic.gvinum
import com.fasterxml.jackson.annotation.JsonTypeName
@JsonTypeName("mirrored-configuration")
data class MirroredGvinumConfiguration(
val disks: List<String>
) : GvinumConfiguration {
override val diskNames: Collection<String> get() = disks
} | src/main/kotlin/com/github/kerubistan/kerub/model/dynamic/gvinum/MirroredGvinumConfiguration.kt | 3493382621 |
/*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* 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 org.ethereum.core
import org.ethereum.config.SystemProperties
import org.ethereum.crypto.ECKey
import org.ethereum.crypto.HashUtil
import org.ethereum.datasource.CountingBytesSource
import org.ethereum.datasource.JournalSource
import org.ethereum.datasource.Source
import org.ethereum.datasource.inmem.HashMapDB
import org.ethereum.db.ByteArrayWrapper
import org.ethereum.trie.SecureTrie
import org.ethereum.trie.TrieImpl
import org.ethereum.util.ByteUtil.intToBytes
import org.ethereum.util.FastByteComparisons
import org.ethereum.util.blockchain.EtherUtil.Unit.ETHER
import org.ethereum.util.blockchain.EtherUtil.convert
import org.ethereum.util.blockchain.StandaloneBlockchain
import org.junit.AfterClass
import org.junit.Assert
import org.junit.Assert.assertTrue
import org.junit.Ignore
import org.junit.Test
import org.spongycastle.util.encoders.Hex
import java.math.BigInteger
import java.util.*
class PruneTest {
@Test
@Throws(Exception::class)
fun testJournal1() {
val db = HashMapDB<ByteArray>()
val countDB = CountingBytesSource(db)
val journalDB = JournalSource(countDB)
put(journalDB, "11")
put(journalDB, "22")
put(journalDB, "33")
journalDB.commitUpdates(intToBytes(1))
checkKeys(db.storage, "11", "22", "33")
put(journalDB, "22")
delete(journalDB, "33")
put(journalDB, "44")
journalDB.commitUpdates(intToBytes(2))
checkKeys(db.storage, "11", "22", "33", "44")
journalDB.persistUpdate(intToBytes(1))
checkKeys(db.storage, "11", "22", "33", "44")
journalDB.revertUpdate(intToBytes(2))
checkKeys(db.storage, "11", "22", "33")
put(journalDB, "22")
delete(journalDB, "33")
put(journalDB, "44")
journalDB.commitUpdates(intToBytes(3))
checkKeys(db.storage, "11", "22", "33", "44")
delete(journalDB, "22")
put(journalDB, "33")
delete(journalDB, "44")
journalDB.commitUpdates(intToBytes(4))
checkKeys(db.storage, "11", "22", "33", "44")
journalDB.persistUpdate(intToBytes(3))
checkKeys(db.storage, "11", "22", "33", "44")
journalDB.persistUpdate(intToBytes(4))
checkKeys(db.storage, "11", "22", "33")
delete(journalDB, "22")
journalDB.commitUpdates(intToBytes(5))
checkKeys(db.storage, "11", "22", "33")
journalDB.persistUpdate(intToBytes(5))
checkKeys(db.storage, "11", "33")
}
@Test
@Throws(Exception::class)
fun simpleTest() {
val pruneCount = 3
SystemProperties.getDefault()!!.overrideParams(
"database.prune.enabled", "true",
"database.prune.maxDepth", "" + pruneCount,
"mine.startNonce", "0")
val bc = StandaloneBlockchain()
val alice = ECKey.fromPrivate(BigInteger.ZERO)
val bob = ECKey.fromPrivate(BigInteger.ONE)
// System.out.println("Gen root: " + Hex.toHexString(bc.getBlockchain().getBestBlock().getStateRoot()));
bc.createBlock()
val b0 = bc.blockchain.bestBlock
bc.sendEther(alice.address, convert(3, ETHER))
val b1_1 = bc.createBlock()
bc.sendEther(alice.address, convert(3, ETHER))
val b1_2 = bc.createForkBlock(b0)
bc.sendEther(alice.address, convert(3, ETHER))
val b1_3 = bc.createForkBlock(b0)
bc.sendEther(alice.address, convert(3, ETHER))
val b1_4 = bc.createForkBlock(b0)
bc.sendEther(bob.address, convert(5, ETHER))
bc.createBlock()
bc.sendEther(alice.address, convert(3, ETHER))
bc.createForkBlock(b1_2)
for (i in 0..8) {
bc.sendEther(alice.address, convert(3, ETHER))
bc.sendEther(bob.address, convert(5, ETHER))
bc.createBlock()
}
val roots = arrayOfNulls<ByteArray>(pruneCount + 1)
for (i in 0..pruneCount + 1 - 1) {
val bNum = bc.blockchain.bestBlock.number - i
val b = bc.blockchain.getBlockByNumber(bNum)
roots[i] = b.stateRoot
}
checkPruning(bc.stateDS, bc.pruningStateDS, *roots)
val bestBlockNum = bc.blockchain.bestBlock.number
Assert.assertEquals(convert(30, ETHER), bc.blockchain.repository.getBalance(alice.address))
Assert.assertEquals(convert(50, ETHER), bc.blockchain.repository.getBalance(bob.address))
run {
val b1 = bc.blockchain.getBlockByNumber(bestBlockNum - 1)
val r1 = bc.blockchain.repository.getSnapshotTo(b1.stateRoot)
Assert.assertEquals(convert((3 * 9).toLong(), ETHER), r1.getBalance(alice.address))
Assert.assertEquals(convert((5 * 9).toLong(), ETHER), r1.getBalance(bob.address))
}
run {
val b1 = bc.blockchain.getBlockByNumber(bestBlockNum - 2)
val r1 = bc.blockchain.repository.getSnapshotTo(b1.stateRoot)
Assert.assertEquals(convert((3 * 8).toLong(), ETHER), r1.getBalance(alice.address))
Assert.assertEquals(convert((5 * 8).toLong(), ETHER), r1.getBalance(bob.address))
}
run {
val b1 = bc.blockchain.getBlockByNumber(bestBlockNum - 3)
val r1 = bc.blockchain.repository.getSnapshotTo(b1.stateRoot)
Assert.assertEquals(convert((3 * 7).toLong(), ETHER), r1.getBalance(alice.address))
Assert.assertEquals(convert((5 * 7).toLong(), ETHER), r1.getBalance(bob.address))
}
run {
// this state should be pruned already
val b1 = bc.blockchain.getBlockByNumber(bestBlockNum - 4)
val r1 = bc.blockchain.repository.getSnapshotTo(b1.stateRoot)
Assert.assertEquals(BigInteger.ZERO, r1.getBalance(alice.address))
Assert.assertEquals(BigInteger.ZERO, r1.getBalance(bob.address))
}
}
@Test
@Throws(Exception::class)
fun contractTest() {
// checks that pruning doesn't delete the nodes which were 're-added' later
// e.g. when a contract variable assigned value V1 the trie acquires node with key K1
// then if the variable reassigned value V2 the trie acquires new node with key K2
// and the node K1 is not needed anymore and added to the prune list
// we should avoid situations when the value V1 is back, the node K1 is also back to the trie
// but erroneously deleted later as was in the prune list
val pruneCount = 3
SystemProperties.getDefault()!!.overrideParams(
"database.prune.enabled", "true",
"database.prune.maxDepth", "" + pruneCount)
val bc = StandaloneBlockchain()
val contr = bc.submitNewContract(
"contract Simple {" +
" uint public n;" +
" function set(uint _n) { n = _n; } " +
"}")
bc.createBlock()
// add/remove/add in the same block
contr.callFunction("set", 0xaaaaaaaaaaaaL)
contr.callFunction("set", 0xbbbbbbbbbbbbL)
contr.callFunction("set", 0xaaaaaaaaaaaaL)
bc.createBlock()
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr.callConstFunction("n")[0])
// force prune
bc.createBlock()
bc.createBlock()
bc.createBlock()
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr.callConstFunction("n")[0])
for (i in 1..3) {
for (j in 0..3) {
contr.callFunction("set", 0xbbbbbbbbbbbbL)
for (k in 0..j - 1) {
bc.createBlock()
}
if (j > 0)
Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr.callConstFunction("n")[0])
contr.callFunction("set", 0xaaaaaaaaaaaaL)
for (k in 0..i - 1) {
bc.createBlock()
}
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr.callConstFunction("n")[0])
}
}
val roots = arrayOfNulls<ByteArray>(pruneCount + 1)
for (i in 0..pruneCount + 1 - 1) {
val bNum = bc.blockchain.bestBlock.number - i
val b = bc.blockchain.getBlockByNumber(bNum)
roots[i] = b.stateRoot
}
checkPruning(bc.stateDS, bc.pruningStateDS, *roots)
}
@Test
@Throws(Exception::class)
fun twoContractsTest() {
val pruneCount = 3
SystemProperties.getDefault()!!.overrideParams(
"database.prune.enabled", "true",
"database.prune.maxDepth", "" + pruneCount)
val src = "contract Simple {" +
" uint public n;" +
" function set(uint _n) { n = _n; } " +
" function inc() { n++; } " +
"}"
val bc = StandaloneBlockchain()
val b0 = bc.blockchain.bestBlock
val contr1 = bc.submitNewContract(src)
val contr2 = bc.submitNewContract(src)
val b1 = bc.createBlock()
checkPruning(bc.stateDS, bc.pruningStateDS,
b1.stateRoot, b0.stateRoot)
// add/remove/add in the same block
contr1.callFunction("set", 0xaaaaaaaaaaaaL)
contr2.callFunction("set", 0xaaaaaaaaaaaaL)
val b2 = bc.createBlock()
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr1.callConstFunction("n")[0])
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr2.callConstFunction("n")[0])
checkPruning(bc.stateDS, bc.pruningStateDS,
b2.stateRoot, b1.stateRoot, b0.stateRoot)
contr2.callFunction("set", 0xbbbbbbbbbbbbL)
val b3 = bc.createBlock()
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr1.callConstFunction("n")[0])
Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr2.callConstFunction("n")[0])
checkPruning(bc.stateDS, bc.pruningStateDS,
b3.stateRoot, b2.stateRoot, b1.stateRoot, b0.stateRoot)
// force prune
val b4 = bc.createBlock()
checkPruning(bc.stateDS, bc.pruningStateDS,
b4.stateRoot, b3.stateRoot, b2.stateRoot, b1.stateRoot)
val b5 = bc.createBlock()
checkPruning(bc.stateDS, bc.pruningStateDS,
b5.stateRoot, b4.stateRoot, b3.stateRoot, b2.stateRoot)
val b6 = bc.createBlock()
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr1.callConstFunction("n")[0])
Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr2.callConstFunction("n")[0])
checkPruning(bc.stateDS, bc.pruningStateDS,
b6.stateRoot, b5.stateRoot, b4.stateRoot, b3.stateRoot)
contr1.callFunction("set", 0xaaaaaaaaaaaaL)
contr2.callFunction("set", 0xaaaaaaaaaaaaL)
val b7 = bc.createBlock()
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr1.callConstFunction("n")[0])
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr2.callConstFunction("n")[0])
checkPruning(bc.stateDS, bc.pruningStateDS,
b7.stateRoot, b6.stateRoot, b5.stateRoot, b4.stateRoot)
contr1.callFunction("set", 0xbbbbbbbbbbbbL)
val b8 = bc.createBlock()
Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr1.callConstFunction("n")[0])
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr2.callConstFunction("n")[0])
checkPruning(bc.stateDS, bc.pruningStateDS,
b8.stateRoot, b7.stateRoot, b6.stateRoot, b5.stateRoot)
contr2.callFunction("set", 0xbbbbbbbbbbbbL)
val b8_ = bc.createForkBlock(b7)
checkPruning(bc.stateDS, bc.pruningStateDS,
b8.stateRoot, b8_.stateRoot, b7.stateRoot, b6.stateRoot, b5.stateRoot)
val b9_ = bc.createForkBlock(b8_)
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr1.callConstFunction("n")[0])
Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr2.callConstFunction("n")[0])
checkPruning(bc.stateDS, bc.pruningStateDS,
b9_.stateRoot, b8.stateRoot, b8_.stateRoot, b7.stateRoot, b6.stateRoot)
val b9 = bc.createForkBlock(b8)
checkPruning(bc.stateDS, bc.pruningStateDS,
b9.stateRoot, b9_.stateRoot, b8.stateRoot, b8_.stateRoot, b7.stateRoot, b6.stateRoot)
val b10 = bc.createForkBlock(b9)
Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr1.callConstFunction("n")[0])
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr2.callConstFunction("n")[0])
checkPruning(bc.stateDS, bc.pruningStateDS,
b10.stateRoot, b9.stateRoot, b9_.stateRoot, b8.stateRoot, b8_.stateRoot, b7.stateRoot)
val b11 = bc.createForkBlock(b10)
Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr1.callConstFunction("n")[0])
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr2.callConstFunction("n")[0])
checkPruning(bc.stateDS, bc.pruningStateDS,
b11.stateRoot, b10.stateRoot, b9.stateRoot, /*b9_.getStateRoot(),*/ b8.stateRoot)
}
@Test
@Throws(Exception::class)
fun branchTest() {
val pruneCount = 3
SystemProperties.getDefault()!!.overrideParams(
"database.prune.enabled", "true",
"database.prune.maxDepth", "" + pruneCount)
val bc = StandaloneBlockchain()
val contr = bc.submitNewContract(
"contract Simple {" +
" uint public n;" +
" function set(uint _n) { n = _n; } " +
"}")
val b1 = bc.createBlock()
contr.callFunction("set", 0xaaaaaaaaaaaaL)
val b2 = bc.createBlock()
contr.callFunction("set", 0xbbbbbbbbbbbbL)
val b2_ = bc.createForkBlock(b1)
bc.createForkBlock(b2)
bc.createBlock()
bc.createBlock()
bc.createBlock()
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr.callConstFunction("n")[0])
}
@Test
@Throws(Exception::class)
fun storagePruneTest() {
val pruneCount = 3
SystemProperties.getDefault()!!.overrideParams(
"details.inmemory.storage.limit", "200",
"database.prune.enabled", "true",
"database.prune.maxDepth", "" + pruneCount)
val bc = StandaloneBlockchain()
val blockchain = bc.blockchain
// RepositoryImpl repository = (RepositoryImpl) blockchain.getRepository();
// HashMapDB storageDS = new HashMapDB();
// repository.getDetailsDataStore().setStorageDS(storageDS);
val contr = bc.submitNewContract(
"contract Simple {" +
" uint public n;" +
" mapping(uint => uint) largeMap;" +
" function set(uint _n) { n = _n; } " +
" function put(uint k, uint v) { largeMap[k] = v; }" +
"}")
val b1 = bc.createBlock()
val entriesForExtStorage = 100
for (i in 0..entriesForExtStorage - 1) {
contr.callFunction("put", i, i)
if (i % 100 == 0) bc.createBlock()
}
bc.createBlock()
blockchain.flush()
contr.callFunction("put", 1000000, 1)
bc.createBlock()
blockchain.flush()
for (i in 0..99) {
contr.callFunction("set", i)
bc.createBlock()
blockchain.flush()
println(bc.stateDS.storage.size.toString() + ", " + bc.stateDS.storage.size)
}
println("Done")
}
@Ignore
@Test
@Throws(Exception::class)
fun rewriteSameTrieNode() {
val pruneCount = 3
SystemProperties.getDefault()!!.overrideParams(
"database.prune.enabled", "true",
"database.prune.maxDepth", "" + pruneCount)
val bc = StandaloneBlockchain()
val receiver = Hex.decode("0000000000000000000000000000000000000000")
bc.sendEther(receiver, BigInteger.valueOf(0x77777777))
bc.createBlock()
for (i in 0..99) {
bc.sendEther(ECKey().address, BigInteger.valueOf(i.toLong()))
}
val contr = bc.submitNewContract(
"contract Stupid {" +
" function wrongAddress() { " +
" address addr = 0x0000000000000000000000000000000000000000; " +
" addr.call();" +
" } " +
"}")
val b1 = bc.createBlock()
contr.callFunction("wrongAddress")
val b2 = bc.createBlock()
contr.callFunction("wrongAddress")
val b3 = bc.createBlock()
Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr.callConstFunction("n")[0])
}
private fun checkPruning(stateDS: HashMapDB<ByteArray>, stateJournalDS: Source<ByteArray, ByteArray>, vararg roots: ByteArray?) {
println("Pruned storage size: " + stateDS.storage.size)
val allRefs = HashSet<ByteArrayWrapper>()
for (root in roots) {
val bRefs = getReferencedTrieNodes(stateJournalDS, true, root)
println("#" + Hex.toHexString(root).substring(0, 8) + " refs: ")
for (bRef in bRefs) {
println(" " + bRef.toString().substring(0, 8))
}
allRefs.addAll(bRefs)
}
println("Trie nodes closure size: " + allRefs.size)
if (allRefs.size != stateDS.storage.size) {
stateDS.storage.keys
.filterNot { allRefs.contains(ByteArrayWrapper(it)) }
.forEach { println("Extra node: " + Hex.toHexString(it)) }
// Assert.assertEquals(allRefs.size(), stateDS.getStorage().size());
}
for (key in stateDS.storage.keys) {
// Assert.assertTrue(allRefs.contains(new ByteArrayWrapper(key)));
}
}
private fun getReferencedTrieNodes(stateDS: Source<ByteArray, ByteArray>, includeAccounts: Boolean,
vararg roots: ByteArray?): Set<ByteArrayWrapper> {
val ret = HashSet<ByteArrayWrapper>()
roots
.map { SecureTrie(stateDS, it) }
.forEach {
it.scanTree(object : TrieImpl.ScanAction {
override fun doOnNode(hash: ByteArray, node: TrieImpl.Node) {
ret.add(ByteArrayWrapper(hash))
}
override fun doOnValue(nodeHash: ByteArray, node: TrieImpl.Node, key: ByteArray, value: ByteArray) {
if (includeAccounts) {
val accountState = AccountState(value)
if (!FastByteComparisons.equal(accountState.codeHash, HashUtil.EMPTY_DATA_HASH)) {
ret.add(ByteArrayWrapper(accountState.codeHash))
}
if (!FastByteComparisons.equal(accountState.stateRoot, HashUtil.EMPTY_TRIE_HASH)) {
ret.addAll(getReferencedTrieNodes(stateDS, false, accountState.stateRoot))
}
}
}
})
}
return ret
}
private fun dumpState(stateDS: Source<ByteArray, ByteArray>, includeAccounts: Boolean,
root: ByteArray): String {
val ret = StringBuilder()
val trie = SecureTrie(stateDS, root)
trie.scanTree(object : TrieImpl.ScanAction {
override fun doOnNode(hash: ByteArray, node: TrieImpl.Node) {}
override fun doOnValue(nodeHash: ByteArray, node: TrieImpl.Node, key: ByteArray, value: ByteArray) {
if (includeAccounts) {
val accountState = AccountState(value)
ret.append(Hex.toHexString(nodeHash)).append(": Account: ").append(Hex.toHexString(key)).append(", Nonce: ").append(accountState.nonce).append(", Balance: ").append(accountState.balance).append("\n")
if (!FastByteComparisons.equal(accountState.codeHash, HashUtil.EMPTY_DATA_HASH)) {
ret.append(" CodeHash: ").append(Hex.toHexString(accountState.codeHash)).append("\n")
}
if (!FastByteComparisons.equal(accountState.stateRoot, HashUtil.EMPTY_TRIE_HASH)) {
ret.append(dumpState(stateDS, false, accountState.stateRoot))
}
} else {
ret.append(" ").append(Hex.toHexString(nodeHash)).append(": ").append(Hex.toHexString(key)).append(" = ").append(Hex.toHexString(value)).append("\n")
}
}
})
return ret.toString()
}
companion object {
private val stateDS: HashMapDB<ByteArray>? = null
@AfterClass
fun cleanup() {
SystemProperties.resetToDefault()
}
private fun put(db: Source<ByteArray, ByteArray>, key: String) {
db.put(Hex.decode(key), Hex.decode(key))
}
private fun delete(db: Source<ByteArray, ByteArray>, key: String) {
db.delete(Hex.decode(key))
}
private fun checkKeys(map: Map<ByteArray, ByteArray>, vararg keys: String) {
Assert.assertEquals(keys.size.toLong(), map.size.toLong())
for (key in keys) {
assertTrue(map.containsKey(Hex.decode(key)))
}
}
internal fun getCount(hash: String): String {
val bytes = stateDS!![Hex.decode(hash)]
return if (bytes == null) "0" else "" + bytes[3]
}
}
}
| free-ethereum-core/src/test/java/org/ethereum/core/PruneTest.kt | 2430974610 |
/*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* 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 org.ethereum.config.net
import org.ethereum.config.blockchain.Eip150HFConfig
import org.ethereum.config.blockchain.Eip160HFConfig
import org.ethereum.config.blockchain.MordenConfig
class MordenNetConfig : BaseNetConfig() {
init {
add(0, MordenConfig.Frontier())
add(494000, MordenConfig.Homestead())
add(1783000, Eip150HFConfig(MordenConfig.Homestead()))
add(1885000, Eip160HFConfig(MordenConfig.Homestead()))
}
}
| free-ethereum-core/src/main/java/org/ethereum/config/net/MordenNetConfig.kt | 3883188445 |
// 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.application
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.testFramework.LoggedErrorProcessor
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.assertions.Assertions.assertThat
import kotlinx.coroutines.*
import org.apache.log4j.Logger
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.util.*
@RunWith(JUnit4::class)
class PooledCoroutineContextTest : UsefulTestCase() {
@Test
fun `log error`() = runBlocking<Unit> {
val errorMessage = "don't swallow me"
val loggedErrors = loggedErrorsAfterThrowingFromGlobalScope(RuntimeException(errorMessage))
assertThat(loggedErrors).anyMatch { errorMessage in it.message.orEmpty() }
}
@Test
fun `do not log ProcessCanceledException`() = runBlocking<Unit> {
val errorMessage = "ignore me"
val loggedErrors = loggedErrorsAfterThrowingFromGlobalScope(ProcessCanceledException(RuntimeException(errorMessage)))
assertThat(loggedErrors).noneMatch { errorMessage in it.cause?.message.orEmpty() }
}
private suspend fun loggedErrorsAfterThrowingFromGlobalScope(exception: Throwable): List<Throwable> {
// cannot use assertThatThrownBy here, because AssertJ doesn't support Kotlin coroutines
val loggedErrors = mutableListOf<Throwable>()
withLoggedErrorsRecorded(loggedErrors) {
GlobalScope.launch(Dispatchers.ApplicationThreadPool) {
throw exception
}.join()
}
return loggedErrors
}
private suspend fun <T> withLoggedErrorsRecorded(loggedErrors: List<Throwable>,
block: suspend () -> T): T {
val savedInstance = LoggedErrorProcessor.getInstance()
val synchronizedLoggedErrors = Collections.synchronizedList(loggedErrors)
LoggedErrorProcessor.setNewInstance(object : LoggedErrorProcessor() {
override fun processError(message: String, t: Throwable, details: Array<String>, logger: Logger) {
synchronizedLoggedErrors.add(t)
}
})
return try {
withNoopThreadUncaughtExceptionHandler { block() }
}
finally {
LoggedErrorProcessor.setNewInstance(savedInstance)
}
}
private suspend fun <T> withNoopThreadUncaughtExceptionHandler(block: suspend () -> T): T {
val savedHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { _, _ -> }
return try {
block()
}
finally {
Thread.setDefaultUncaughtExceptionHandler(savedHandler)
}
}
@Test
fun `error must be propagated to parent context if available`() = runBlocking {
class MyCustomException : RuntimeException()
try {
withContext(Dispatchers.ApplicationThreadPool) {
throw MyCustomException()
}
}
catch (ignored: MyCustomException) {
}
}
} | platform/platform-tests/testSrc/com/intellij/application/PooledCoroutineContextTest.kt | 1099009978 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material
import androidx.compose.animation.animateColor
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.core.Transition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Indication
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.runtime.State
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.min
import kotlin.math.sin
/**
* [Checkbox] provides an animated checkbox for use as a toggle control in
* [ToggleChip] or [SplitToggleChip].
*
* Example of a [SplitToggleChip] with [Checkbox] toggle control:
* @sample androidx.wear.compose.material.samples.SplitToggleChipWithCheckbox
*
* @param checked Boolean flag indicating whether this checkbox is currently checked.
* @param modifier Modifier to be applied to the checkbox. This can be used to provide a
* content description for accessibility.
* @param colors [CheckboxColors] from which the box and checkmark colors will be obtained.
* @param enabled Boolean flag indicating the enabled state of the [Checkbox] (affects
* the color).
* @param onCheckedChange Callback to be invoked when Checkbox is clicked. If null, then this is
* passive and relies entirely on a higher-level component to control the state
* (such as [ToggleChip] or [SplitToggleChip]).
* @param interactionSource When also providing [onCheckedChange], the [MutableInteractionSource]
* representing the stream of [Interaction]s for the "toggleable" tap area -
* can be used to customise the appearance / behavior of the Checkbox.
*/
@Composable
public fun Checkbox(
checked: Boolean,
modifier: Modifier = Modifier,
colors: CheckboxColors = CheckboxDefaults.colors(),
enabled: Boolean = true,
onCheckedChange: ((Boolean) -> Unit)? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
) {
val targetState = if (checked) ToggleStage.Checked else ToggleStage.Unchecked
val transition = updateTransition(targetState)
val tickProgress = animateProgress(transition, "Checkbox")
// For Checkbox, the color and alpha animations have the same duration and easing,
// so we don't need to explicitly animate alpha.
val boxColor = animateColor(
transition,
colorFn = { e, c -> colors.boxColor(enabled = e, checked = c) },
enabled = enabled
)
val checkColor = animateColor(
transition,
colorFn = { e, c -> colors.checkmarkColor(enabled = e, checked = c) },
enabled = enabled
)
Canvas(
modifier = modifier.maybeToggleable(
onCheckedChange, enabled, checked, interactionSource, rememberRipple(),
Role.Checkbox
)
) {
drawBox(color = boxColor.value)
if (targetState == ToggleStage.Checked) {
drawTick(
tickProgress = tickProgress.value,
tickColor = checkColor.value,
)
} else {
eraseTick(
tickProgress = tickProgress.value,
tickColor = checkColor.value,
)
}
}
}
/**
* [Switch] provides an animated switch for use as a toggle control in
* [ToggleChip] or [SplitToggleChip].
*
* Example of a [ToggleChip] with [Switch] toggle control:
* @sample androidx.wear.compose.material.samples.ToggleChipWithSwitch
*
* @param checked Boolean flag indicating whether this switch is currently toggled on.
* @param modifier Modifier to be applied to the switch. This can be used to provide a
* content description for accessibility.
* @param colors [SwitchColors] from which the colors of the thumb and track will be obtained.
* @param enabled Boolean flag indicating the enabled state of the [Switch] (affects
* the color).
* @param onCheckedChange Callback to be invoked when Switch is clicked. If null, then this is
* passive and relies entirely on a higher-level component to control the state
* (such as [ToggleChip] or [SplitToggleChip]).
* @param interactionSource When also providing [onCheckedChange], the [MutableInteractionSource]
* representing the stream of [Interaction]s for the "toggleable" tap area -
* can be used to customise the appearance / behavior of the Switch.
*/
@Composable
public fun Switch(
checked: Boolean,
modifier: Modifier = Modifier,
colors: SwitchColors = SwitchDefaults.colors(),
enabled: Boolean = true,
onCheckedChange: ((Boolean) -> Unit)? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
) {
val targetState = if (checked) ToggleStage.Checked else ToggleStage.Unchecked
val transition = updateTransition(targetState)
// For Switch, the color and alpha animations have the same duration and easing,
// so we don't need to explicitly animate alpha.
val thumbProgress = animateProgress(transition, "Switch")
val thumbColor = animateColor(
transition,
{ e, c -> colors.thumbColor(enabled = e, checked = c) },
enabled
)
val trackColor = animateColor(
transition,
{ e, c -> colors.trackColor(enabled = e, checked = c) },
enabled
)
Canvas(
modifier = modifier.maybeToggleable(
onCheckedChange, enabled, checked, interactionSource, rememberRipple(), Role.Switch
)
) {
val switchTrackLengthPx = SWITCH_TRACK_LENGTH.toPx()
val switchTrackHeightPx = SWITCH_TRACK_HEIGHT.toPx()
val switchThumbRadiusPx = SWITCH_THUMB_RADIUS.toPx()
val thumbProgressPx = lerp(
start = switchThumbRadiusPx,
stop = switchTrackLengthPx - switchThumbRadiusPx,
fraction = thumbProgress.value
)
drawTrack(trackColor.value, switchTrackLengthPx, switchTrackHeightPx)
// Use BlendMode.Src to overwrite overlapping pixels with the thumb color
// (by default, the track shows through any transparency).
drawCircle(
color = thumbColor.value,
radius = switchThumbRadiusPx,
center = Offset(thumbProgressPx, center.y),
blendMode = BlendMode.Src)
}
}
/**
* [RadioButton] provides an animated radio button for use as a toggle control in
* [ToggleChip] or [SplitToggleChip].
*
* Example of a [ToggleChip] with [RadioButton] toggle control:
* @sample androidx.wear.compose.material.samples.ToggleChipWithRadioButton
*
* @param selected Boolean flag indicating whether this radio button is currently toggled on.
* @param modifier Modifier to be applied to the radio button. This can be used to provide a
* content description for accessibility.
* @param colors [ToggleChipColors] from which the toggleControlColors will be obtained.
* @param enabled Boolean flag indicating the enabled state of the [RadioButton] (affects
* the color).
* @param onClick Callback to be invoked when RadioButton is clicked. If null, then this is
* passive and relies entirely on a higher-level component to control the state
* (such as [ToggleChip] or [SplitToggleChip]).
* @param interactionSource When also providing [onClick], the [MutableInteractionSource]
* representing the stream of [Interaction]s for the "toggleable" tap area -
* can be used to customise the appearance / behavior of the RadioButton.
*/
@Composable
public fun RadioButton(
selected: Boolean,
modifier: Modifier = Modifier,
colors: RadioButtonColors = RadioButtonDefaults.colors(),
enabled: Boolean = true,
onClick: (() -> Unit)? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
) {
val targetState = if (selected) ToggleStage.Checked else ToggleStage.Unchecked
val transition = updateTransition(targetState)
val circleColor = animateColor(
transition,
colorFn = { e, s -> colors.ringColor(enabled = e, selected = s) },
enabled
)
val dotRadiusProgress = animateProgress(
transition,
durationMillis = if (selected) QUICK else STANDARD,
label = "dot-radius"
)
val dotColor = animateColor(
transition,
colorFn = { e, s -> colors.dotColor(enabled = e, selected = s) },
enabled
)
// Animation of the dot alpha only happens when toggling On to Off.
val dotAlphaProgress =
if (targetState == ToggleStage.Unchecked)
animateProgress(
transition, durationMillis = RAPID, delayMillis = FLASH, label = "dot-alpha"
)
else
null
Canvas(
modifier = modifier.maybeSelectable(
onClick, enabled, selected, interactionSource, rememberRipple()
)
) {
// Outer circle has a constant radius.
drawCircle(
radius = RADIO_CIRCLE_RADIUS.toPx(),
color = circleColor.value,
center = center,
style = Stroke(RADIO_CIRCLE_STROKE.toPx()),
)
// Inner dot radius expands/shrinks.
drawCircle(
radius = dotRadiusProgress.value * RADIO_DOT_RADIUS.toPx(),
color = dotColor.value.copy(
alpha = (dotAlphaProgress?.value ?: 1f) * dotColor.value.alpha
),
center = center,
style = Fill,
)
}
}
/**
* Represents the content colors used in [Checkbox] in different states.
*/
@Stable
public interface CheckboxColors {
/**
* Represents the box color for this [Checkbox], depending on the [enabled] and [checked]
* properties.
*
* @param enabled Whether the [Checkbox] is enabled
* @param checked Whether the [Checkbox] is currently checked or unchecked
*/
@Composable
public fun boxColor(enabled: Boolean, checked: Boolean): State<Color>
/**
* Represents the checkmark color for this [Checkbox], depending on the [enabled] and [checked]
* properties.
*
* @param enabled Whether the [Checkbox] is enabled
* @param checked Whether the [Checkbox] is currently checked or unchecked
*/
@Composable
public fun checkmarkColor(enabled: Boolean, checked: Boolean): State<Color>
}
/**
* Represents the content colors used in [Switch] in different states.
*/
@Stable
public interface SwitchColors {
/**
* Represents the thumb color for this [Switch], depending on the [enabled] and [checked]
* properties.
*
* @param enabled Whether the [Switch] is enabled
* @param checked Whether the [Switch] is currently checked or unchecked
*/
@Composable
public fun thumbColor(enabled: Boolean, checked: Boolean): State<Color>
/**
* Represents the track color for this [Switch], depending on the [enabled] and [checked]
* properties.
*
* @param enabled Whether the [Switch] is enabled
* @param checked Whether the [Switch] is currently checked or unchecked
*/
@Composable
public fun trackColor(enabled: Boolean, checked: Boolean): State<Color>
}
/**
* Represents the content colors used in [RadioButton] in different states.
*/
@Stable
public interface RadioButtonColors {
/**
* Represents the outer ring color for this [RadioButton], depending on
* the [enabled] and [selected] properties.
*
* @param enabled Whether the [RadioButton] is enabled
* @param selected Whether the [RadioButton] is currently selected or unselected
*/
@Composable
public fun ringColor(enabled: Boolean, selected: Boolean): State<Color>
/**
* Represents the inner dot color for this [RadioButton], depending on
* the [enabled] and [selected] properties.
*
* @param enabled Whether the [RadioButton] is enabled
* @param selected Whether the [RadioButton] is currently selected or unselected
*/
@Composable
public fun dotColor(enabled: Boolean, selected: Boolean): State<Color>
}
/**
* Contains the default values used by [Checkbox].
*/
public object CheckboxDefaults {
/**
* Creates a [CheckboxColors] for use in a [Checkbox].
*
* @param checkedBoxColor The box color of this [Checkbox] when enabled and checked.
* @param uncheckedBoxColor The box color of this [Checkbox] when enabled and unchecked.
* @param checkedCheckmarkColor The check mark color of this [Checkbox] when enabled
* and checked.
* @param uncheckedCheckmarkColor The check mark color of this [Checkbox] when enabled
* and unchecked.
*/
@Composable
public fun colors(
checkedBoxColor: Color = MaterialTheme.colors.secondary,
checkedCheckmarkColor: Color = checkedBoxColor,
uncheckedBoxColor: Color = contentColorFor(
MaterialTheme.colors.primary.copy(alpha = 0.5f)
.compositeOver(MaterialTheme.colors.surface)
),
uncheckedCheckmarkColor: Color = uncheckedBoxColor,
): CheckboxColors {
return DefaultCheckboxColors(
checkedBoxColor = checkedBoxColor,
checkedCheckmarkColor = checkedCheckmarkColor,
uncheckedBoxColor = uncheckedBoxColor,
uncheckedCheckmarkColor = uncheckedCheckmarkColor,
disabledCheckedBoxColor =
checkedBoxColor.copy(alpha = ContentAlpha.disabled),
disabledCheckedCheckmarkColor =
checkedCheckmarkColor.copy(alpha = ContentAlpha.disabled),
disabledUncheckedBoxColor =
uncheckedBoxColor.copy(alpha = ContentAlpha.disabled),
disabledUncheckedCheckmarkColor =
uncheckedCheckmarkColor.copy(alpha = ContentAlpha.disabled),
)
}
}
/**
* Contains the default values used by [Switch].
*/
public object SwitchDefaults {
/**
* Creates a [SwitchColors] for use in a [Switch].
*
* @param checkedThumbColor The thumb color of this [Switch] when enabled and checked.
* @param checkedTrackColor The track color of this [Switch] when enabled and checked.
* @param uncheckedThumbColor The thumb color of this [Switch] when enabled and unchecked.
* @param uncheckedTrackColor The track color of this [Switch] when enabled and unchecked.
*/
@Composable
public fun colors(
checkedThumbColor: Color = MaterialTheme.colors.secondary,
checkedTrackColor: Color = checkedThumbColor.copy(alpha = ContentAlpha.disabled),
uncheckedThumbColor: Color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f),
uncheckedTrackColor: Color =
uncheckedThumbColor.copy(alpha = uncheckedThumbColor.alpha * ContentAlpha.disabled),
): SwitchColors {
return DefaultSwitchColors(
checkedThumbColor = checkedThumbColor,
checkedTrackColor = checkedTrackColor,
uncheckedThumbColor = uncheckedThumbColor,
uncheckedTrackColor = uncheckedTrackColor,
disabledCheckedThumbColor = checkedThumbColor.copy(alpha = ContentAlpha.disabled),
disabledCheckedTrackColor = checkedTrackColor.copy(
alpha = checkedTrackColor.alpha * ContentAlpha.disabled
),
disabledUncheckedThumbColor =
uncheckedThumbColor.copy(alpha = uncheckedThumbColor.alpha * ContentAlpha.disabled),
disabledUncheckedTrackColor =
uncheckedTrackColor.copy(alpha = uncheckedTrackColor.alpha * ContentAlpha.disabled),
)
}
}
/**
* Contains the default values used by [RadioButton].
*/
public object RadioButtonDefaults {
/**
* Creates a [RadioButtonColors] for use in a [RadioButton].
*
* @param selectedRingColor The outer ring color of this [RadioButton] when enabled
* and selected.
* @param selectedDotColor The inner dot color of this [RadioButton] when enabled
* and selected.
* @param unselectedRingColor The outer ring color of this [RadioButton] when enabled
* and unselected.
* @param unselectedDotColor The inner dot color of this [RadioButton] when enabled
* and unselected.
*/
@Composable
public fun colors(
selectedRingColor: Color = MaterialTheme.colors.secondary,
selectedDotColor: Color = MaterialTheme.colors.secondary,
unselectedRingColor: Color = contentColorFor(
MaterialTheme.colors.primary.copy(alpha = 0.5f)
.compositeOver(MaterialTheme.colors.surface)
),
unselectedDotColor: Color = contentColorFor(
MaterialTheme.colors.primary.copy(alpha = 0.5f)
.compositeOver(MaterialTheme.colors.surface)
),
): RadioButtonColors {
return DefaultRadioButtonColors(
selectedRingColor = selectedRingColor,
selectedDotColor = selectedDotColor,
unselectedRingColor = unselectedRingColor,
unselectedDotColor = unselectedDotColor,
disabledSelectedRingColor = selectedRingColor.copy(alpha = ContentAlpha.disabled),
disabledSelectedDotColor = selectedDotColor.copy(alpha = ContentAlpha.disabled),
disabledUnselectedRingColor =
unselectedRingColor.copy(alpha = ContentAlpha.disabled),
disabledUnselectedDotColor = unselectedDotColor.copy(alpha = ContentAlpha.disabled),
)
}
}
@Composable
private fun animateProgress(
transition: Transition<ToggleStage>,
label: String,
durationMillis: Int = QUICK,
delayMillis: Int = 0,
) =
transition.animateFloat(
transitionSpec = {
tween(durationMillis = durationMillis, delayMillis = delayMillis, easing = STANDARD_IN)
},
label = label
) {
// Return the tick progress as a Float in Px.
when (it) {
ToggleStage.Unchecked -> 0f
ToggleStage.Checked -> 1f
}
}
@Composable
private fun animateColor(
transition: Transition<ToggleStage>,
colorFn: @Composable (enabled: Boolean, checked: Boolean) -> State<Color>,
enabled: Boolean
): State<Color> =
transition.animateColor(
transitionSpec = { tween(durationMillis = QUICK, easing = STANDARD_IN) },
label = "content-color"
) {
colorFn(enabled, (it == ToggleStage.Checked)).value
}
private fun Modifier.maybeToggleable(
onCheckedChange: ((Boolean) -> Unit)?,
enabled: Boolean,
checked: Boolean,
interactionSource: MutableInteractionSource,
indication: Indication,
role: Role,
): Modifier {
val standardModifier = this
.wrapContentSize(Alignment.Center)
.requiredSize(24.dp)
return if (onCheckedChange == null) {
standardModifier
} else {
standardModifier.then(
Modifier.toggleable(
enabled = enabled,
value = checked,
onValueChange = onCheckedChange,
role = role,
indication = indication,
interactionSource = interactionSource
)
)
}
}
private fun Modifier.maybeSelectable(
onClick: (() -> Unit)?,
enabled: Boolean,
selected: Boolean,
interactionSource: MutableInteractionSource,
indication: Indication,
): Modifier {
val standardModifier = this
.wrapContentSize(Alignment.Center)
.requiredSize(24.dp)
return if (onClick == null) {
standardModifier
} else {
standardModifier.then(
Modifier.selectable(
selected = selected,
interactionSource = interactionSource,
indication = indication,
enabled = enabled,
role = Role.RadioButton,
onClick = onClick,
)
)
}
}
private fun DrawScope.drawBox(color: Color) {
val topCornerPx = BOX_CORNER.toPx()
val strokeWidthPx = BOX_STROKE.toPx()
val halfStrokeWidthPx = strokeWidthPx / 2.0f
val radiusPx = BOX_RADIUS.toPx()
val checkboxSizePx = BOX_SIZE.toPx()
drawRoundRect(
color,
topLeft = Offset(topCornerPx + halfStrokeWidthPx, topCornerPx + halfStrokeWidthPx),
size = Size(checkboxSizePx - strokeWidthPx, checkboxSizePx - strokeWidthPx),
cornerRadius = CornerRadius(radiusPx - halfStrokeWidthPx),
style = Stroke(strokeWidthPx)
)
}
private fun DrawScope.drawTick(tickColor: Color, tickProgress: Float) {
// Using tickProgress animating from zero to TICK_TOTAL_LENGTH,
// rotate the tick as we draw from 15 degrees to zero.
val tickBaseLength = TICK_BASE_LENGTH.toPx()
val tickStickLength = TICK_STICK_LENGTH.toPx()
val tickTotalLength = tickBaseLength + tickStickLength
val tickProgressPx = tickProgress * tickTotalLength
val center = Offset(12.dp.toPx(), 12.dp.toPx())
val angle = TICK_ROTATION - TICK_ROTATION / tickTotalLength * tickProgressPx
val angleRadians = angle.toRadians()
// Animate the base of the tick.
val baseStart = Offset(6.7f.dp.toPx(), 12.3f.dp.toPx())
val tickBaseProgress = min(tickProgressPx, tickBaseLength)
val path = Path()
path.moveTo(baseStart.rotate(angleRadians, center))
path.lineTo((baseStart + Offset(tickBaseProgress, tickBaseProgress))
.rotate(angleRadians, center))
if (tickProgressPx > tickBaseLength) {
val tickStickProgress = min(tickProgressPx - tickBaseLength, tickStickLength)
val stickStart = Offset(9.3f.dp.toPx(), 16.3f.dp.toPx())
// Move back to the start of the stick (without drawing)
path.moveTo(stickStart.rotate(angleRadians, center))
path.lineTo(
Offset(stickStart.x + tickStickProgress, stickStart.y - tickStickProgress)
.rotate(angleRadians, center))
}
// Use StrokeCap.Butt because Square adds an extension on the end of each line.
drawPath(path, tickColor, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Butt))
}
private fun DrawScope.eraseTick(tickColor: Color, tickProgress: Float) {
val tickBaseLength = TICK_BASE_LENGTH.toPx()
val tickStickLength = TICK_STICK_LENGTH.toPx()
val tickTotalLength = tickBaseLength + tickStickLength
val tickProgressPx = tickProgress * tickTotalLength
// Animate the stick of the tick, drawing down the stick from the top.
val stickStartX = 17.3f.dp.toPx()
val stickStartY = 8.3f.dp.toPx()
val tickStickProgress = min(tickProgressPx, tickStickLength)
val path = Path()
path.moveTo(stickStartX, stickStartY)
path.lineTo(stickStartX - tickStickProgress, stickStartY + tickStickProgress)
if (tickStickProgress > tickStickLength) {
// Animate the base of the tick, drawing up the base from bottom of the stick.
val tickBaseProgress = min(tickProgressPx - tickStickLength, tickBaseLength)
val baseStartX = 10.7f.dp.toPx()
val baseStartY = 16.3f.dp.toPx()
path.moveTo(baseStartX, baseStartY)
path.lineTo(baseStartX - tickBaseProgress, baseStartY - tickBaseProgress)
}
drawPath(path, tickColor, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Butt))
}
private fun DrawScope.drawTrack(
color: Color,
switchTrackLengthPx: Float,
switchTrackHeightPx: Float,
) {
val path = Path()
val strokeRadius = switchTrackHeightPx / 2f
path.moveTo(Offset(strokeRadius, center.y))
path.lineTo(Offset(switchTrackLengthPx - strokeRadius, center.y))
drawPath(
path = path,
color = color,
style = Stroke(width = switchTrackHeightPx, cap = StrokeCap.Round)
)
}
/**
* Default [CheckboxColors] implementation.
*/
@Immutable
private class DefaultCheckboxColors(
private val checkedBoxColor: Color,
private val checkedCheckmarkColor: Color,
private val uncheckedCheckmarkColor: Color,
private val uncheckedBoxColor: Color,
private val disabledCheckedBoxColor: Color,
private val disabledCheckedCheckmarkColor: Color,
private val disabledUncheckedBoxColor: Color,
private val disabledUncheckedCheckmarkColor: Color,
) : CheckboxColors {
@Composable
override fun boxColor(enabled: Boolean, checked: Boolean): State<Color> {
return rememberUpdatedState(
if (enabled) {
if (checked) checkedBoxColor else uncheckedBoxColor
} else {
if (checked) disabledCheckedBoxColor else disabledUncheckedBoxColor
}
)
}
@Composable
override fun checkmarkColor(enabled: Boolean, checked: Boolean): State<Color> {
return rememberUpdatedState(
if (enabled) {
if (checked) checkedCheckmarkColor else uncheckedCheckmarkColor
} else {
if (checked) disabledCheckedCheckmarkColor else disabledUncheckedCheckmarkColor
}
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null) return false
if (this::class != other::class) return false
other as DefaultCheckboxColors
if (checkedBoxColor != other.checkedBoxColor) return false
if (checkedCheckmarkColor != other.checkedCheckmarkColor) return false
if (uncheckedCheckmarkColor != other.uncheckedCheckmarkColor) return false
if (uncheckedBoxColor != other.uncheckedBoxColor) return false
if (disabledCheckedBoxColor != other.disabledCheckedBoxColor) return false
if (disabledCheckedCheckmarkColor != other.disabledCheckedCheckmarkColor) return false
if (disabledUncheckedBoxColor != other.disabledUncheckedBoxColor) return false
if (disabledUncheckedCheckmarkColor != other.disabledUncheckedCheckmarkColor) return false
return true
}
override fun hashCode(): Int {
var result = checkedBoxColor.hashCode()
result = 31 * result + checkedCheckmarkColor.hashCode()
result = 31 * result + uncheckedCheckmarkColor.hashCode()
result = 31 * result + uncheckedBoxColor.hashCode()
result = 31 * result + disabledCheckedBoxColor.hashCode()
result = 31 * result + disabledCheckedCheckmarkColor.hashCode()
result = 31 * result + disabledUncheckedBoxColor.hashCode()
result = 31 * result + disabledUncheckedCheckmarkColor.hashCode()
return result
}
}
/**
* Default [SwitchColors] implementation.
*/
@Immutable
private class DefaultSwitchColors(
private val checkedThumbColor: Color,
private val checkedTrackColor: Color,
private val uncheckedThumbColor: Color,
private val uncheckedTrackColor: Color,
private val disabledCheckedThumbColor: Color,
private val disabledCheckedTrackColor: Color,
private val disabledUncheckedThumbColor: Color,
private val disabledUncheckedTrackColor: Color,
) : SwitchColors {
@Composable
override fun thumbColor(enabled: Boolean, checked: Boolean): State<Color> {
return rememberUpdatedState(
if (enabled) {
if (checked) checkedThumbColor else uncheckedThumbColor
} else {
if (checked) disabledCheckedThumbColor else disabledUncheckedThumbColor
}
)
}
@Composable
override fun trackColor(enabled: Boolean, checked: Boolean): State<Color> {
return rememberUpdatedState(
if (enabled) {
if (checked) checkedTrackColor else uncheckedTrackColor
} else {
if (checked) disabledCheckedTrackColor else disabledUncheckedTrackColor
}
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null) return false
if (this::class != other::class) return false
other as DefaultSwitchColors
if (checkedThumbColor != other.checkedThumbColor) return false
if (checkedTrackColor != other.checkedTrackColor) return false
if (uncheckedThumbColor != other.uncheckedThumbColor) return false
if (uncheckedTrackColor != other.uncheckedTrackColor) return false
if (disabledCheckedThumbColor != other.disabledCheckedThumbColor) return false
if (disabledCheckedTrackColor != other.disabledCheckedTrackColor) return false
if (disabledUncheckedThumbColor != other.disabledUncheckedThumbColor) return false
if (disabledUncheckedTrackColor != other.disabledUncheckedTrackColor) return false
return true
}
override fun hashCode(): Int {
var result = checkedThumbColor.hashCode()
result = 31 * result + checkedTrackColor.hashCode()
result = 31 * result + uncheckedThumbColor.hashCode()
result = 31 * result + uncheckedTrackColor.hashCode()
result = 31 * result + disabledCheckedThumbColor.hashCode()
result = 31 * result + disabledCheckedTrackColor.hashCode()
result = 31 * result + disabledUncheckedThumbColor.hashCode()
result = 31 * result + disabledUncheckedTrackColor.hashCode()
return result
}
}
/**
* Default [SwitchColors] implementation.
*/
@Immutable
private class DefaultRadioButtonColors(
private val selectedRingColor: Color,
private val selectedDotColor: Color,
private val unselectedRingColor: Color,
private val unselectedDotColor: Color,
private val disabledSelectedRingColor: Color,
private val disabledSelectedDotColor: Color,
private val disabledUnselectedRingColor: Color,
private val disabledUnselectedDotColor: Color,
) : RadioButtonColors {
@Composable
override fun ringColor(enabled: Boolean, selected: Boolean): State<Color> {
return rememberUpdatedState(
if (enabled) {
if (selected) selectedRingColor else unselectedRingColor
} else {
if (selected) disabledSelectedRingColor else disabledUnselectedRingColor
}
)
}
@Composable
override fun dotColor(enabled: Boolean, selected: Boolean): State<Color> {
return rememberUpdatedState(
if (enabled) {
if (selected) selectedDotColor else unselectedDotColor
} else {
if (selected) disabledSelectedDotColor else disabledUnselectedDotColor
}
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null) return false
if (this::class != other::class) return false
other as DefaultRadioButtonColors
if (selectedRingColor != other.selectedRingColor) return false
if (selectedDotColor != other.selectedDotColor) return false
if (unselectedRingColor != other.unselectedRingColor) return false
if (unselectedDotColor != other.unselectedDotColor) return false
if (disabledSelectedRingColor != other.disabledSelectedRingColor) return false
if (disabledSelectedDotColor != other.disabledSelectedDotColor) return false
if (disabledUnselectedRingColor != other.disabledUnselectedRingColor) return false
if (disabledUnselectedDotColor != other.disabledUnselectedDotColor) return false
return true
}
override fun hashCode(): Int {
var result = selectedRingColor.hashCode()
result = 31 * result + selectedDotColor.hashCode()
result = 31 * result + unselectedRingColor.hashCode()
result = 31 * result + unselectedDotColor.hashCode()
result = 31 * result + disabledSelectedRingColor.hashCode()
result = 31 * result + disabledSelectedDotColor.hashCode()
result = 31 * result + disabledUnselectedRingColor.hashCode()
result = 31 * result + disabledUnselectedDotColor.hashCode()
return result
}
}
private fun Path.moveTo(offset: Offset) {
moveTo(offset.x, offset.y)
}
private fun Path.lineTo(offset: Offset) {
lineTo(offset.x, offset.y)
}
private fun Offset.rotate(angleRadians: Float): Offset {
val angledDirection = directionVector(angleRadians)
return angledDirection * x + angledDirection.rotate90() * y
}
private fun Offset.rotate(angleRadians: Float, center: Offset): Offset =
(this - center).rotate(angleRadians) + center
private fun directionVector(angleRadians: Float) = Offset(cos(angleRadians), sin(angleRadians))
private fun Offset.rotate90() = Offset(-y, x)
// This is duplicated from wear.compose.foundation/geometry.kt
// Any changes should be replicated there.
private fun Float.toRadians() = this * PI.toFloat() / 180f
private enum class ToggleStage {
Unchecked, Checked
}
private val BOX_CORNER = 3.dp
private val BOX_STROKE = 2.dp
private val BOX_RADIUS = 2.dp
private val BOX_SIZE = 18.dp
private val TICK_BASE_LENGTH = 4.dp
private val TICK_STICK_LENGTH = 8.dp
private const val TICK_ROTATION = 15f
private val SWITCH_TRACK_LENGTH = 24.dp
private val SWITCH_TRACK_HEIGHT = 10.dp
private val SWITCH_THUMB_RADIUS = 7.dp
private val RADIO_CIRCLE_RADIUS = 9.dp
private val RADIO_CIRCLE_STROKE = 2.dp
private val RADIO_DOT_RADIUS = 5.dp | wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/ToggleControl.kt | 3614571544 |
package com.sedsoftware.yaptalker.presentation.feature.posting.adapter
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.presentation.extensions.inflate
import com.sedsoftware.yaptalker.presentation.extensions.loadFromUrl
import com.sedsoftware.yaptalker.presentation.extensions.loadFromUrlWithGifSupport
import com.sedsoftware.yaptalker.presentation.model.base.EmojiModel
import kotlinx.android.synthetic.main.fragment_new_post_bottom_sheet_item.view.emoji_code
import kotlinx.android.synthetic.main.fragment_new_post_bottom_sheet_item.view.emoji_container
import kotlinx.android.synthetic.main.fragment_new_post_bottom_sheet_item.view.emoji_image
import java.util.ArrayList
import javax.inject.Inject
class EmojiAdapter @Inject constructor(
private val clickListener: EmojiClickListener
) : RecyclerView.Adapter<EmojiAdapter.EmojiViewHolder>() {
private var items: ArrayList<EmojiModel> = ArrayList()
init {
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = EmojiViewHolder(parent)
override fun onBindViewHolder(holder: EmojiViewHolder, position: Int) {
holder.bindTo(items[position])
}
override fun getItemId(position: Int): Long = position.toLong()
override fun getItemCount(): Int = items.size
fun addEmojiItem(item: EmojiModel) {
val insertPosition = items.size
items.add(item)
notifyItemInserted(insertPosition)
}
fun clearEmojiList() {
notifyItemRangeRemoved(0, items.size)
items.clear()
}
inner class EmojiViewHolder(parent: ViewGroup) :
RecyclerView.ViewHolder(parent.inflate(R.layout.fragment_new_post_bottom_sheet_item)) {
fun bindTo(emoji: EmojiModel) {
with(itemView) {
emoji_code.text = emoji.code
emoji_image.loadFromUrlWithGifSupport(emoji.link)
emoji_container.setOnClickListener { clickListener.onEmojiClicked(emoji.code) }
}
}
}
}
| app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/posting/adapter/EmojiAdapter.kt | 3428681548 |
// PROBLEM: Fewer arguments provided (2) than placeholders specified (3)
// FIX: none
package org.apache.logging.log4j
private val logger: Logger? = null
fun foo(a: Int, b: Int) {
logger?.warn("<caret>test {} {} {}", 1, 2)
}
interface Logger {
fun warn(format: String, param1: Any, param2: Any)
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/logging/placeholderCountMatchesArgumentCount/log4j/warn.kt | 936766346 |
// "Change to 'return@foo'" "true"
// ACTION: Change to 'return@forEach'
// ACTION: Introduce local variable
// WITH_RUNTIME
fun foo(f:()->Int){}
fun bar() {
foo {
listOf(1).forEach {
return<caret> 1
}
return@foo 1
}
} | plugins/kotlin/idea/tests/testData/quickfix/changeToLabeledReturn/multipleOuter.kt | 686862585 |
package com.intellij.settingsSync
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.wm.ToolWindowManager
import git4idea.GitVcs
import git4idea.log.showExternalGitLogInToolwindow
import java.util.function.Supplier
class SettingsSyncHistoryAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val settingsSyncStorage = SettingsSyncMain.getInstance().controls.settingsSyncStorage
val virtualFile = VfsUtil.findFile(settingsSyncStorage, true)
if (virtualFile == null) {
Messages.showErrorDialog(SettingsSyncBundle.message("history.error.message"), SettingsSyncBundle.message("history.dialog.title"))
return
}
val toolWindowId = "SettingsSync"
val toolWindowManager = ToolWindowManager.getInstance(project)
val toolWindow = toolWindowManager.getToolWindow(toolWindowId) ?: toolWindowManager.registerToolWindow(toolWindowId) {
stripeTitle = Supplier { SettingsSyncBundle.message("title.settings.sync") }
}
showExternalGitLogInToolwindow(project, toolWindow, GitVcs.getInstance(project), listOf(virtualFile),
SettingsSyncBundle.message("history.tab.name"), "")
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = e.project != null && isSettingsSyncEnabledByKey()
}
} | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncHistoryAction.kt | 1349679689 |
package com.automattic.android.tracks.crashlogging.performance
import io.sentry.SpanStatus
enum class TransactionStatus {
SUCCESSFUL, ABORTED
}
fun TransactionStatus.toSentrySpanStatus() =
when (this) {
TransactionStatus.SUCCESSFUL -> SpanStatus.OK
TransactionStatus.ABORTED -> SpanStatus.ABORTED
}
| AutomatticTracks/src/main/java/com/automattic/android/tracks/crashlogging/performance/TransactionStatus.kt | 1085649775 |
import A.Companion.run
open class Action<T> {
fun run(t: T){}
}
open class A {
companion object : Action<String>() {
}
}
class B : A() {
fun foo() {
run("")
}
} | plugins/kotlin/idea/tests/testData/editor/optimizeImports/jvm/FromCompanionObjectGeneric.kt | 1957106364 |
// 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.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ListEntityImpl(val dataSource: ListEntityData) : ListEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val data: List<String>
get() = dataSource.data
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ListEntityData?) : ModifiableWorkspaceEntityBase<ListEntity, ListEntityData>(result), ListEntity.Builder {
constructor() : this(ListEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ListEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field ListEntity#data should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override fun afterModification() {
val collection_data = getEntityData().data
if (collection_data is MutableWorkspaceList<*>) {
collection_data.cleanModificationUpdateAction()
}
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ListEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.data != dataSource.data) this.data = dataSource.data.toMutableList()
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
private val dataUpdater: (value: List<String>) -> Unit = { value ->
changedProperty.add("data")
}
override var data: MutableList<String>
get() {
val collection_data = getEntityData().data
if (collection_data !is MutableWorkspaceList) return collection_data
if (diff == null || modifiable.get()) {
collection_data.setModificationUpdateAction(dataUpdater)
}
else {
collection_data.cleanModificationUpdateAction()
}
return collection_data
}
set(value) {
checkModificationAllowed()
getEntityData(true).data = value
dataUpdater.invoke(value)
}
override fun getEntityClass(): Class<ListEntity> = ListEntity::class.java
}
}
class ListEntityData : WorkspaceEntityData<ListEntity>() {
lateinit var data: MutableList<String>
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ListEntity> {
val modifiable = ListEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ListEntity {
return getCached(snapshot) {
val entity = ListEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun clone(): ListEntityData {
val clonedEntity = super.clone()
clonedEntity as ListEntityData
clonedEntity.data = clonedEntity.data.toMutableWorkspaceList()
return clonedEntity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ListEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ListEntity(data, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ListEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ListEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.data?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ListEntityImpl.kt | 381266288 |
// 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.ui.dsl.builder
import com.intellij.ide.BrowserUtil
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.event.HyperlinkEvent
/**
* Component properties for UI DSL
*/
enum class DslComponentProperty {
/**
* A mark that component is a label of a row, see [Panel.row]
*
* Value: [Boolean]
*/
ROW_LABEL,
/**
* Custom visual paddings, which are used instead of [JComponent.getInsets]
*
* Value: [com.intellij.ui.dsl.gridLayout.Gaps]
*/
VISUAL_PADDINGS,
/**
* By default, almost every control have [SpacingConfiguration.verticalComponentGap] above and below it.
* This flag disables such gap below the control. Should be used in very rare situations (e.g. row with label **and** some additional
* label-kind controls above related to the label control), because most standard cases are covered by Kotlin UI DSL API
*
* Value: [Boolean]
*/
NO_BOTTOM_GAP,
/**
* By default, we're trying to assign [javax.swing.JLabel.setLabelFor] for the cell component itself.
* In some cases, a wrapper component needs to be used - and this property allows delegating this feature to a child component.
*
* Value: [JComponent]
*/
LABEL_FOR,
/**
* Some compound components can contain several components inside itself. [INTERACTIVE_COMPONENT] points to main interactive one,
* which is assigned to [JLabel.labelFor] and which is used as a component for data validation
*
* Value: [JComponent]
*/
INTERACTIVE_COMPONENT
}
/**
* Default comment width
*/
const val DEFAULT_COMMENT_WIDTH = 70
/**
* Text uses word wrap if there is no enough width
*/
const val MAX_LINE_LENGTH_WORD_WRAP = -1
/**
* Text is not wrapped and uses only html markup like <br>
*/
const val MAX_LINE_LENGTH_NO_WRAP = Int.MAX_VALUE
fun interface HyperlinkEventAction {
companion object {
/**
* Opens URL in a browser
*/
@JvmField
val HTML_HYPERLINK_INSTANCE = HyperlinkEventAction { e -> BrowserUtil.browse(e.url) }
}
fun hyperlinkActivated(e: HyperlinkEvent)
fun hyperlinkEntered(e: HyperlinkEvent) {
}
fun hyperlinkExited(e: HyperlinkEvent) {
}
}
| platform/platform-api/src/com/intellij/ui/dsl/builder/utils.kt | 628208248 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.ui.project.path
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemLocalSettings
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.getCanonicalPath
class ExternalSystemWorkingDirectoryInfo(project: Project, externalSystemId: ProjectSystemId) : WorkingDirectoryInfo {
private val readableName = externalSystemId.readableName
override val editorLabel: String = ExternalSystemBundle.message("run.configuration.project.path.label", readableName)
override val settingsName: String = ExternalSystemBundle.message("run.configuration.project.path.name", readableName)
override val fileChooserTitle: String = ExternalSystemBundle.message("settings.label.select.project", readableName)
override val fileChooserDescriptor: FileChooserDescriptor =
ExternalSystemApiUtil.getExternalProjectConfigDescriptor(externalSystemId)
override val emptyFieldError: String = ExternalSystemBundle.message("run.configuration.project.path.empty.error", readableName)
override val externalProjects: List<ExternalProject> by lazy {
ArrayList<ExternalProject>().apply {
val localSettings = ExternalSystemApiUtil.getLocalSettings<AbstractExternalSystemLocalSettings<*>>(project, externalSystemId)
val uiAware = ExternalSystemUiUtil.getUiAware(externalSystemId)
for ((parent, children) in localSettings.availableProjects) {
val parentPath = getCanonicalPath(parent.path)
val parentName = uiAware.getProjectRepresentationName(project, parentPath, null)
add(ExternalProject(parentName, parentPath))
for (child in children) {
val childPath = getCanonicalPath(child.path)
if (parentPath == childPath) continue
val childName = uiAware.getProjectRepresentationName(project, childPath, parentPath)
add(ExternalProject(childName, childPath))
}
}
}
}
} | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/project/path/ExternalSystemWorkingDirectoryInfo.kt | 2717477302 |
package inlineFun1
import inlineFun2.*
inline fun myFun1(f: () -> Int): Int = myFun2 { f() } | plugins/kotlin/idea/tests/testData/internal/toolWindow/inlineFunctionDeep2/inlineFun1.kt | 2400095021 |
package test
class A {
@JvmName("foo")
fun /*rename*/first() = 1
}
fun test() {
A().first()
} | plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinFunWithJvmName/before/test/test.kt | 1525889756 |
<warning descr="SSR">class MyClass</warning>
<warning descr="SSR">class MyClassTwo()</warning>
<warning descr="SSR">class MyClassThree constructor()</warning> | plugins/kotlin/idea/tests/testData/structuralsearch/class/classOptionalParam.kt | 2596066037 |
// "Create expected function in common module testModule_Common" "true"
// DISABLE-ERRORS
actual fun <caret>foo(my: My) {} | plugins/kotlin/idea/tests/testData/multiModuleQuickFix/createExpect/funWithAccessibleTypeFromCommon/jvm/foo.kt | 4040754460 |
// 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.internal.retype
import com.intellij.JavaTestUtil
import com.intellij.codeInsight.editorActions.CompletionAutoPopupHandler
import com.intellij.ide.IdeEventQueue
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.testFramework.TestModeFlags
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import com.intellij.testFramework.fixtures.TempDirTestFixture
import com.intellij.testFramework.fixtures.impl.TempDirTestFixtureImpl
class JavaRetypeTest : LightJavaCodeInsightFixtureTestCase() {
override fun getBasePath(): String = JavaTestUtil.getRelativeJavaTestDataPath()
override fun getTempDirFixture(): TempDirTestFixture {
return TempDirTestFixtureImpl()
}
fun testBraces() {
doTestWithoutLookup()
}
fun testImport() {
doTestWithLookup()
}
fun testClosingBracketAfterOpening() {
doTestWithoutLookup()
}
fun testMultilineFunction() {
doTestWithoutLookup()
}
fun testSuggestionBeforeNewLine() {
doTestWithLookup()
}
fun testEmptyClass() {
doTestWithLookup()
}
fun testBlockComment() {
doTestWithoutLookup()
}
fun testJavaDoc() {
doTestWithoutLookup()
}
fun testBrokenClass() {
doTestWithoutLookup()
}
private fun doTestWithLookup() {
val autopopupOldValue = TestModeFlags.set(CompletionAutoPopupHandler.ourTestingAutopopup, true)
val filePath = "retype/${getTestName(false)}.java"
myFixture.configureByFile(filePath)
RetypeSession(project, myFixture.editor as EditorImpl, 50, null, 0).start()
while (editor.getUserData(RETYPE_SESSION_KEY) != null) {
IdeEventQueue.getInstance().flushQueue()
}
myFixture.checkResultByFile(filePath)
TestModeFlags.set(CompletionAutoPopupHandler.ourTestingAutopopup, autopopupOldValue)
}
private fun doTestWithoutLookup() {
val filePath = "retype/${getTestName(false)}.java"
myFixture.configureByFile(filePath)
RetypeSession(project, myFixture.editor as EditorImpl, 50, null, 0).start()
while (editor.getUserData(RETYPE_SESSION_KEY) != null) {
IdeEventQueue.getInstance().flushQueue()
}
myFixture.checkResultByFile(filePath)
}
}
| java/java-tests/testSrc/com/intellij/internal/retype/JavaRetypeTest.kt | 2095042648 |
/*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.java.codeInsight.daemon.quickFix
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil
import com.intellij.codeInsight.daemon.impl.quickfix.CreateServiceClassFixBase
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiJavaFile
import junit.framework.TestCase
/**
* @author Pavel.Dolgov
*/
class CreateServiceImplementationClassTest : LightJava9ModulesCodeInsightFixtureTestCase() {
fun testExistingPackageAllQualified() {
addFile("foo/bar/MyService.java", "package foo.bar; public class MyService { }")
doAction("module foo.bar { provides foo.bar.MyService with foo.bar.<caret>MyServiceImpl; }",
"foo.bar.MyServiceImpl")
myFixture.checkResult("foo/bar/MyServiceImpl.java",
"package foo.bar;\n\n" +
"public class MyServiceImpl extends MyService {\n" +
"}", true)
}
fun testExistingPackageInterfaceImported() {
addFile("foo/bar/MyService.java", "package foo.bar; public class MyService { }")
doAction("import foo.bar.MyService; module foo.bar { provides MyService with foo.bar.<caret>MyServiceImpl; }",
"foo.bar.MyServiceImpl")
myFixture.checkResult("foo/bar/MyServiceImpl.java",
"package foo.bar;\n\n" +
"public class MyServiceImpl extends MyService {\n" +
"}", true)
}
fun testExistingPackageNested() {
addFile("foo/bar/MyService.java", "package foo.bar; public class MyService { }")
addFile("foo/bar/Outer.java", "package foo.bar;\n\n" +
"public class Outer {\n" +
" void aMethod() {}\n" +
"}")
doAction("module foo.bar { provides foo.bar.MyService with foo.bar.Outer.<caret>MyServiceImpl; }",
"foo.bar.Outer.MyServiceImpl")
myFixture.checkResult("foo/bar/Outer.java",
"package foo.bar;\n\n" +
"public class Outer {\n" +
" void aMethod() {}\n\n" +
" public static class MyServiceImpl extends MyService {\n" +
" }\n" +
"}", true)
}
fun testNonexistentPackage() {
addFile("foo/bar/MyService.java", "package foo.bar; public class MyService { }")
doAction("module foo.bar { provides foo.bar.MyService with foo.bar.<caret>baz.MyServiceImpl; }",
"foo.bar.baz.MyServiceImpl")
myFixture.checkResult("foo/bar/baz/MyServiceImpl.java",
"package foo.bar.baz;\n\n" +
"import foo.bar.MyService;\n" +
"\n" +
"public class MyServiceImpl extends MyService {\n" +
"}", true)
}
fun testNestedNonexistentPackage() {
addFile("foo/bar/MyService.java", "package foo.bar; public class MyService { }")
doAction("module foo.bar { provides foo.bar.MyService with foo.bar.<caret>baz.boo.MyServiceImpl; }",
"foo.bar.baz.boo.MyServiceImpl")
myFixture.checkResult("foo/bar/baz/boo/MyServiceImpl.java",
"package foo.bar.baz.boo;\n\n" +
"import foo.bar.MyService;\n" +
"\n" +
"public class MyServiceImpl extends MyService {\n" +
"}", true)
}
fun testNestedNonexistentPackageProviderMethod() {
addFile("foo/bar/MyService.java", "package foo.bar; public class MyService { }")
doAction("module foo.bar { provides foo.bar.MyService with foo.bar.<caret>baz.boo.MyServiceImpl; }",
"foo.bar.baz.boo.MyServiceImpl", isSubclass = false)
myFixture.checkResult("foo/bar/baz/boo/MyServiceImpl.java",
"package foo.bar.baz.boo;\n\n" +
"import foo.bar.MyService;\n" +
"\n" +
"public class MyServiceImpl {\n" +
" public static MyService provider() {\n" +
" return null;\n" +
" }\n" +
"}", true)
}
fun testMultipleImplementations() {
addFile("foo/bar/MyService.java", "package foo.bar; public class MyService { }")
addFile("foo/bar/other/MyServiceOther.java", "package foo.bar.other; import foo.bar.MyService; public class MyServiceOther extends MyService { }")
doAction("module foo.bar { provides foo.bar.MyService with foo.bar.<caret>MyServiceImpl, foo.bar.other.MyServiceOther; }",
"foo.bar.MyServiceImpl")
myFixture.checkResult("foo/bar/MyServiceImpl.java",
"package foo.bar;\n\n" +
"public class MyServiceImpl extends MyService {\n" +
"}", true)
}
fun testAbstractSuperclass() {
addFile("foo/bar/MyService.java", "package foo.bar; public abstract class MyService { public abstract void doWork(); }")
doAction("module foo.bar { provides foo.bar.MyService with foo.bar.<caret>MyServiceImpl; }",
"foo.bar.MyServiceImpl")
myFixture.checkResult("foo/bar/MyServiceImpl.java",
"package foo.bar;\n\n" +
"public class MyServiceImpl extends MyService {\n" +
"}", true)
}
fun testServiceInterface() {
addFile("foo/bar/MyService.java", "package foo.bar; public interface MyService { void doWork(); }")
doAction("module foo.bar { provides foo.bar.MyService with foo.bar.<caret>MyServiceImpl; }",
"foo.bar.MyServiceImpl")
myFixture.checkResult("foo/bar/MyServiceImpl.java",
"package foo.bar;\n\n" +
"public class MyServiceImpl implements MyService {\n" +
"}", true)
}
fun testServiceSuperclassFromOtherModule() {
moduleInfo("module foo.bar.other { exports foo.bar.other; }", OTHER)
addFile("foo/bar/other/MyService.java", "package foo.bar.other; public class MyService { }", OTHER)
doAction("module foo.bar.impl { requires foo.bar.other; provides foo.bar.other.MyService with foo.bar.<caret>impl.MyServiceImpl; }",
"foo.bar.impl.MyServiceImpl")
myFixture.checkResult("foo/bar/impl/MyServiceImpl.java",
"package foo.bar.impl;\n\n" +
"import foo.bar.other.MyService;\n" +
"\n" +
"public class MyServiceImpl extends MyService {\n" +
"}", true)
}
fun testServiceSuperclassFromNotReadableModule() {
moduleInfo("module foo.bar.other { exports foo.bar.other; }", OTHER)
addFile("foo/bar/other/MyService.java", "package foo.bar.other; public class MyService { }", OTHER)
doTestNoAction("module foo.bar.impl { provides foo.bar.other.MyService with foo.bar.impl.<caret>MyServiceImpl; }")
}
fun testExistingLibraryPackage() {
addFile("foo/bar/MyService.java", "package foo.bar; public class MyService { }")
doTestNoAction("module foo.bar { provides foo.bar.MyService with java.io.<caret>MyServiceImpl; }")
}
fun testExistingLibraryOuterClass() {
addFile("foo/bar/MyService.java", "package foo.bar; public class MyService { }")
doTestNoAction("module foo.bar { provides foo.bar.MyService with java.io.File.<caret>MyServiceImpl; }")
}
private fun doTestNoAction(text: String) {
myFixture.configureByText("module-info.java", text)
val filtered = myFixture.availableIntentions.filter { it.text.startsWith("Create class") }
TestCase.assertEquals(listOf<IntentionAction>(), filtered)
}
private fun doAction(moduleInfoText: String, implementationFQN: String,
rootDirectory: PsiDirectory? = null, isSubclass: Boolean = true) {
val moduleInfo = myFixture.configureByText("module-info.java", moduleInfoText) as PsiJavaFile
moduleInfo.putUserData(CreateServiceClassFixBase.SERVICE_ROOT_DIR, rootDirectory ?: moduleInfo.containingDirectory)
moduleInfo.putUserData(CreateServiceClassFixBase.SERVICE_IS_SUBCLASS, isSubclass)
val action = myFixture.findSingleIntention("Create class '$implementationFQN'")
myFixture.launchAction(action)
myFixture.checkHighlighting(false, false, false) // no error
val serviceImpl = myFixture.findClass(implementationFQN)
val javaModule = JavaModuleGraphUtil.findDescriptorByElement(serviceImpl)!!
assertEquals(moduleInfo.moduleDeclaration, javaModule)
}
private val OTHER = MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M2
} | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/quickFix/CreateServiceImplementationClassTest.kt | 3057242053 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass
// OPTIONS: derivedClasses
fun foo() {
open class Z : A() {
}
fun doSomething(x: A, y: A) {
}
doSomething(object : A() {}, object : Z() {})
fun bar() {
val x = object : Z() {
}
}
}
| plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinClassDerivedAnonymousObjects.1.kt | 2580713935 |
package zielu.gittoolbox
import com.google.common.util.concurrent.ThreadFactoryBuilder
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.util.messages.MessageBus
import zielu.gittoolbox.metrics.AppMetrics
import zielu.gittoolbox.util.AppUtil
import zielu.gittoolbox.util.ConcurrentUtil
import zielu.gittoolbox.util.ReschedulingExecutor
import zielu.intellij.concurrent.ZThreadFactory
import java.util.Collections
import java.util.Optional
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Supplier
internal class GitToolBoxApp : Disposable {
private val taskThreadFactory = ZThreadFactory("GitToolBox-task-group")
private val taskExecutor = ThreadPoolExecutor(
1,
1024,
60L,
TimeUnit.SECONDS,
SynchronousQueue(),
ThreadFactoryBuilder()
.setNameFormat("GitToolBox-task-%d")
.setDaemon(true)
.setThreadFactory(taskThreadFactory)
.build()
)
private val asyncThreadFactory = ZThreadFactory("GitToolBox-async-group")
private val asyncExecutor = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors(),
ThreadFactoryBuilder()
.setNameFormat("GitToolBox-async-%d")
.setDaemon(true)
.setThreadFactory(asyncThreadFactory)
.build()
)
private val scheduledThreadFactory = ZThreadFactory("GitToolBox-schedule-group")
private val scheduledExecutor = Executors.newSingleThreadScheduledExecutor(
ThreadFactoryBuilder()
.setNameFormat("GitToolBox-schedule-%d")
.setDaemon(true)
.setThreadFactory(scheduledThreadFactory)
.build()
)
private val active = AtomicBoolean(true)
init {
val metrics = AppMetrics.getInstance()
taskThreadFactory.exposeMetrics(metrics)
asyncThreadFactory.exposeMetrics(metrics)
scheduledThreadFactory.exposeMetrics(metrics)
runInBackground { AppMetrics.startReporting() }
}
override fun dispose() {
if (active.compareAndSet(true, false)) {
ConcurrentUtil.shutdown(scheduledExecutor)
ConcurrentUtil.shutdown(taskExecutor)
ConcurrentUtil.shutdown(asyncExecutor)
}
}
fun runInBackground(task: Runnable) {
if (active.get()) {
taskExecutor.submit(task)
}
}
fun <T> supplyAsyncList(supplier: Supplier<List<T>>): CompletableFuture<List<T>> {
return if (active.get()) {
CompletableFuture.supplyAsync(supplier, asyncExecutor)
} else {
CompletableFuture.completedFuture(Collections.emptyList())
}
}
fun <T> supplyAsync(supplier: Supplier<T>, fallbackSupplier: Supplier<T>): CompletableFuture<T> {
return if (active.get()) {
CompletableFuture.supplyAsync(supplier, asyncExecutor)
} else {
CompletableFuture.completedFuture(fallbackSupplier.get())
}
}
fun asyncExecutor(): Executor = asyncExecutor
fun schedule(task: Runnable, delay: Long, unit: TimeUnit): ScheduledFuture<*>? {
return if (active.get()) {
scheduledExecutor.schedule({ runInBackground(task) }, delay, unit)
} else {
null
}
}
fun publishSync(project: Project, publisher: (messageBus: MessageBus) -> Unit) {
if (active.get()) {
publisher.invoke(project.messageBus)
}
}
fun publishSync(publisher: (messageBus: MessageBus) -> Unit) {
if (active.get()) {
publisher.invoke(ApplicationManager.getApplication().messageBus)
}
}
companion object {
@JvmStatic
fun getInstance(): Optional<GitToolBoxApp> {
return AppUtil.getServiceInstanceSafe(GitToolBoxApp::class.java)
}
@JvmStatic
fun createReschedulingExecutor(): ReschedulingExecutor {
return ReschedulingExecutor(
{ task, duration ->
getInstance().flatMap {
val result: Optional<Future<*>> = Optional.ofNullable(
it.schedule(task, duration.toMillis(), TimeUnit.MILLISECONDS)
)
result
}
},
true
)
}
}
}
| src/main/kotlin/zielu/gittoolbox/GitToolBoxApp.kt | 2565052591 |
/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
package net.mediaarea.mediainfo
import kotlin.jvm.*
import java.io.File
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.Observer
import androidx.core.app.ActivityCompat
import androidx.appcompat.app.AppCompatDelegate
import android.os.Build
import android.os.Bundle
import android.os.AsyncTask
import android.os.Environment
import android.os.ParcelFileDescriptor
import android.net.Uri
import android.app.Activity
import android.content.Intent
import android.database.Cursor
import android.provider.OpenableColumns
import android.widget.FrameLayout
import android.widget.TextView
import android.content.Context
import android.widget.Toast
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.content.res.Resources
import android.view.*
import androidx.preference.PreferenceManager.getDefaultSharedPreferences
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_report_list.*
import kotlinx.android.synthetic.main.report_list_content.view.*
import kotlinx.android.synthetic.main.report_list.*
import kotlinx.android.synthetic.main.hello_layout.*
import com.github.angads25.filepicker.model.DialogConfigs
import com.github.angads25.filepicker.model.DialogProperties
import com.github.angads25.filepicker.view.FilePickerDialog
import com.yariksoffice.lingver.Lingver
import java.io.BufferedReader
import java.util.*
/**
* An activity representing a list of Pings. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a [ReportDetailActivity] representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
class ReportListActivity : AppCompatActivity(), ReportActivityListener {
private lateinit var subscriptionManager: SubscriptionManager
private lateinit var reportModel: ReportViewModel
private var disposable: CompositeDisposable = CompositeDisposable()
private var twoPane: Boolean = false
private var reports: List<Report> = listOf()
private var pendingFileUris: MutableList<Uri> = mutableListOf()
inner class AddFile: AsyncTask<Uri, Int, Boolean>() {
override fun onPreExecute() {
super.onPreExecute()
add_button.hide()
val rootLayout: FrameLayout = findViewById(R.id.frame_layout)
var found = false
for (i: Int in rootLayout.childCount downTo 1) {
if (rootLayout.getChildAt(i - 1).id == R.id.spinner_layout)
found = true
}
if (!found)
View.inflate(this@ReportListActivity, R.layout.spinner_layout, rootLayout)
}
override fun onPostExecute(result: Boolean?) {
super.onPostExecute(result)
add_button.show()
val rootLayout: FrameLayout = findViewById(R.id.frame_layout)
for (i: Int in rootLayout.childCount downTo 1) {
if (rootLayout.getChildAt(i - 1).id == R.id.spinner_layout)
rootLayout.removeViewAt(i - 1)
}
}
override fun doInBackground(vararg params: Uri?): Boolean {
for (uri: Uri? in params) {
if (uri == null) {
continue
}
var fd: ParcelFileDescriptor? = null
var displayName = ""
when (uri.scheme) {
"content" -> {
if (Build.VERSION.SDK_INT >= 19) {
try {
val cursor: Cursor? = contentResolver.query(uri, null, null, null, null, null)
// moveToFirst() returns false if the cursor has 0 rows
if (cursor != null && cursor.moveToFirst()) {
// DISPLAY_NAME is provider-specific, and might not be the file name
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
cursor.close()
}
} catch (e: Exception) {
}
try {
fd = contentResolver.openFileDescriptor(uri, "r")
} catch (e: Exception) {}
}
}
"file" -> {
val file = File(uri.path.orEmpty())
try {
fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
} catch (e: Exception) {}
displayName = uri.lastPathSegment.orEmpty()
}
}
if (fd == null) {
continue
}
val report: ByteArray = Core.createReport(fd.detachFd(), displayName)
disposable.add(reportModel.insertReport(Report(0, displayName, report, Core.version))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnComplete {
// Don't go to report view when opening multiples files
if (params.size == 1) {
disposable.add(reportModel.getLastId()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess {
showReport(it)
}.subscribe())
}
}.subscribe())
}
return true
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
READ_EXTERNAL_STORAGE_PERMISSION_REQUEST -> {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
AddFile().execute(*(pendingFileUris.toTypedArray()))
pendingFileUris.clear()
} else {
// Abort all pending request
pendingFileUris.clear()
}
}
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleIntent(intent)
}
private fun handleUri(uri: Uri) {
if (uri.scheme == "file") {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
pendingFileUris.add(uri)
ActivityCompat.requestPermissions(this@ReportListActivity,
arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),
READ_EXTERNAL_STORAGE_PERMISSION_REQUEST)
return
}
}
}
AddFile().execute(uri)
}
private fun handleIntent(intent: Intent) {
if (intent.action != null) {
val action: String? = intent.action
if (action == Intent.ACTION_VIEW) {
val uri: Uri? = intent.data
if (uri != null) {
handleUri(uri)
}
} else if (action == Intent.ACTION_SEND) {
val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
if (uri != null) {
handleUri(uri)
} else if (action == Intent.ACTION_SEND_MULTIPLE) {
val uriList = intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)
if (uriList != null) {
for (i in uriList) {
handleUri(i)
}
}
}
}
}
}
private fun updatePreferences() {
val sharedPreferences = getDefaultSharedPreferences(this)
val key = getString(R.string.preferences_uimode_key)
when (sharedPreferences?.contains(key)) {
false -> {
val oldSharedPreferences = getSharedPreferences(getString(R.string.preferences_key), Context.MODE_PRIVATE)
if (oldSharedPreferences?.contains(key) == true) {
oldSharedPreferences.getString(key, "").let {
when (it) {
"ON" -> {
oldSharedPreferences.edit()?.remove(key)
sharedPreferences.edit()?.putString(key, "on")?.apply()
}
"OFF" -> {
oldSharedPreferences.edit()?.remove(key)
sharedPreferences.edit()?.putString(key, "off")?.apply()
}
else -> {
}
}
}
}
}
true -> {
try {
sharedPreferences.getBoolean(key, false).let {
when (it) {
false -> {
sharedPreferences.edit()?.remove(key)
sharedPreferences.edit()?.putString(key, "off")?.apply()
}
true -> {
sharedPreferences.edit()?.remove(key)
sharedPreferences.edit()?.putString(key, "on")?.apply()
}
}
}
}
catch(_: ClassCastException) {}
}
}
}
private fun applyUiMode() {
val sharedPreferences = getDefaultSharedPreferences(this)
val key = getString(R.string.preferences_uimode_key)
sharedPreferences?.getString(getString(R.string.preferences_uimode_key), "system").let {
when (it) {
"off" -> {
if (AppCompatDelegate.getDefaultNightMode()!=AppCompatDelegate.MODE_NIGHT_NO) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
recreate()
}
}
"on" -> {
if (AppCompatDelegate.getDefaultNightMode()!=AppCompatDelegate.MODE_NIGHT_YES) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
recreate()
}
}
"system" -> {
if (AppCompatDelegate.getDefaultNightMode()!=AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
recreate()
}
}
}
}
}
private fun setLocale() {
try {
val stream = applicationContext.resources.openRawResource(R.raw.lang)
val content = stream.bufferedReader().use(BufferedReader::readText)
Core.setLocale(content)
}
catch (error: Exception) {
}
}
private fun setPrefLocale() {
val sharedPreferences: SharedPreferences? = getDefaultSharedPreferences(this)
sharedPreferences?.getBoolean(getString(R.string.preferences_report_translate_key), false).let {
when (it) {
false -> {
Core.setLocale("")
}
true -> {
setLocale()
}
}
}
sharedPreferences?.getString(getString(R.string.preferences_locale_key), "system").let {
val locale: Locale =
if (it == null || it == "system") {
if (Build.VERSION.SDK_INT >= 24) {
Resources.getSystem().configuration.locales.get(0)
} else {
@Suppress("DEPRECATION")
Resources.getSystem().configuration.locale
}
} else {
val language = it.split("-r")
if (language.size > 1) {
Locale(language[0], language[1])
} else {
Locale(language[0])
}
}
Locale.setDefault(locale)
if (Lingver.getInstance().getLocale() != locale) {
Lingver.getInstance().setLocale(this, locale)
recreate()
}
}
}
fun showReport(id: Int) {
intent.putExtra(Core.ARG_REPORT_ID, id)
if (twoPane) {
val fragment: ReportDetailFragment = ReportDetailFragment().apply {
arguments = Bundle().apply {
putInt(Core.ARG_REPORT_ID, id)
}
}
supportFragmentManager
.beginTransaction()
.replace(R.id.report_detail_container, fragment)
.commit()
disposable.add(reportModel.getReport(id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess {
title = it.filename
}.subscribe())
} else {
val intent = Intent(this@ReportListActivity, ReportDetailActivity::class.java)
intent.putExtra(Core.ARG_REPORT_ID, id)
startActivityForResult(intent, SHOW_REPORT_REQUEST)
}
}
fun deleteReport(id: Int) {
disposable.add(reportModel
.deleteReport(id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe())
if (intent.getIntExtra(Core.ARG_REPORT_ID, -1)==id) {
intent.putExtra(Core.ARG_REPORT_ID, -1)
}
if (twoPane) {
val fragment = supportFragmentManager.findFragmentById(R.id.report_detail_container)
if (fragment != null && (fragment as ReportDetailFragment).id == id) {
supportFragmentManager
.beginTransaction()
.detach(fragment)
.commit()
title = getString(R.string.app_name)
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
menu?.findItem(R.id.action_subscribe)?.isEnabled=false
subscriptionManager.ready.observe(this, Observer {
if (subscriptionManager.subscribed.value == false) {
menu?.findItem(R.id.action_subscribe)?.isEnabled = it
}
})
subscriptionManager.subscribed.observe(this, Observer {
if (it) {
if (subscriptionManager.isLifetime.value == true) {
menu?.findItem(R.id.action_subscribe).let { item ->
item?.title = getString(R.string.subscribe_text)
item?.isVisible = false
}
} else {
menu?.findItem(R.id.action_subscribe).let { item ->
item?.isEnabled = true
item?.title = getString(R.string.subscribed_text)
item?.setOnMenuItemClickListener { _ ->
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(getString(R.string.subscription_manage_url).replace('|', '&'))
startActivity(intent)
true
}
}
}
} else {
menu?.findItem(R.id.action_subscribe).let { item ->
item?.title = getString(R.string.subscribe_text)
item?.setOnMenuItemClickListener { _ ->
val intent = Intent(this, SubscribeActivity::class.java)
startActivityForResult(intent, SUBSCRIBE_REQUEST)
true
}
}
}
})
menu?.findItem(R.id.action_about).let {
it?.setOnMenuItemClickListener {
val intent = Intent(this, AboutActivity::class.java)
startActivity(intent)
true
}
}
menu?.findItem(R.id.action_settings).let {
it?.setOnMenuItemClickListener {
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
true
}
}
return super.onCreateOptionsMenu(menu)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
OPEN_FILE_REQUEST -> {
if (Build.VERSION.SDK_INT >= 19) {
if (resultData == null)
return
val clipData = resultData.clipData
if (clipData != null) {
val uris: Array<Uri> = Array(clipData.itemCount) {
clipData.getItemAt(it).uri
}
AddFile().execute(*(uris))
} else if (resultData.data != null) {
AddFile().execute(resultData.data)
}
}
}
SUBSCRIBE_REQUEST -> {
Toast.makeText(applicationContext, R.string.thanks_text, Toast.LENGTH_SHORT).show()
}
SHOW_REPORT_REQUEST -> {
if (resultData!=null) {
val id = resultData.getIntExtra(Core.ARG_REPORT_ID, -1)
if (id!=-1 && twoPane) {
showReport(id)
}
}
}
}
}
}
override fun getReportViewModel(): ReportViewModel {
return reportModel
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_report_list)
setSupportActionBar(tool_bar)
tool_bar.title = title
updatePreferences()
subscriptionManager = SubscriptionManager.getInstance(application)
lifecycle.addObserver(subscriptionManager)
setLocale()
subscriptionManager.subscribed.observe(this, Observer {
if (it==true) {
applyUiMode()
setPrefLocale()
}
})
val viewModelFactory = Injection.provideViewModelFactory(this)
reportModel = ViewModelProvider(this, viewModelFactory).get(ReportViewModel::class.java)
add_button.setOnClickListener {
if (Build.VERSION.SDK_INT >= 19) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
startActivityForResult(intent, OPEN_FILE_REQUEST)
} else {
if (Environment.getExternalStorageState() in setOf(Environment.MEDIA_MOUNTED, Environment.MEDIA_MOUNTED_READ_ONLY)) {
val properties = DialogProperties()
properties.selection_mode = DialogConfigs.MULTI_MODE
properties.selection_type = DialogConfigs.FILE_SELECT
properties.root = File(DialogConfigs.DEFAULT_DIR)
properties.error_dir = File(DialogConfigs.DEFAULT_DIR)
properties.offset = File(DialogConfigs.DEFAULT_DIR)
properties.extensions = null
val dialog = FilePickerDialog(this, properties)
dialog.setTitle(R.string.open_title)
dialog.setDialogSelectionListener { files: Array<String> ->
var uris: Array<Uri> = arrayOf()
files.forEach { uri: String ->
uris += Uri.parse("file://$uri")
}
AddFile().execute(*(uris))
}
dialog.show()
} else {
val toast = Toast.makeText(applicationContext, R.string.media_error_text, Toast.LENGTH_LONG)
toast.show()
}
}
}
clear_btn.setOnClickListener {
disposable.add(reportModel.deleteAllReports()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
intent.putExtra(Core.ARG_REPORT_ID, -1)
if (twoPane) {
val fragment = supportFragmentManager.findFragmentById(R.id.report_detail_container)
if (fragment != null) {
supportFragmentManager
.beginTransaction()
.detach(fragment)
.commit()
title = getString(R.string.app_name)
}
}
})
}
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
if (report_detail_container != null)
twoPane = true
setupRecyclerView(report_list)
onNewIntent(intent)
}
override fun onStart() {
super.onStart()
disposable.add(reportModel.getAllReports()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
reports = it
setupRecyclerView(report_list)
val rootLayout: FrameLayout = findViewById(R.id.frame_layout)
if (reports.isEmpty()) {
var found = false
for (i: Int in rootLayout.childCount downTo 1) {
if (rootLayout.getChildAt(i - 1).id == R.id.hello_layout)
found = true
}
if (!found)
View.inflate(this, R.layout.hello_layout, rootLayout)
clear_btn.visibility = View.INVISIBLE
} else {
for (i: Int in rootLayout.childCount downTo 1) {
if (rootLayout.getChildAt(i - 1).id == R.id.hello_layout)
rootLayout.removeViewAt(i - 1)
}
rootLayout.removeView(hello_layout)
clear_btn.visibility = View.VISIBLE
}
})
if (twoPane && intent.getIntExtra(Core.ARG_REPORT_ID, -1)!=-1) {
showReport(intent.getIntExtra(Core.ARG_REPORT_ID, -1))
}
}
override fun onStop() {
super.onStop()
// clear all the subscription
disposable.clear()
}
private fun setupRecyclerView(recyclerView: RecyclerView) {
recyclerView.adapter = ItemRecyclerViewAdapter()
recyclerView.isNestedScrollingEnabled = false
}
inner class ItemRecyclerViewAdapter : RecyclerView.Adapter<ItemRecyclerViewAdapter.ViewHolder>() {
private val onClickListener: View.OnClickListener
init {
onClickListener = View.OnClickListener {
val report: Report = it.tag as Report
showReport(report.id)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.report_list_content, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val report: Report = reports[position]
holder.name.text = report.filename
holder.id = report.id
with(holder.itemView) {
tag = report
setOnClickListener(onClickListener)
}
}
override fun getItemCount(): Int = reports.size
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val name: TextView = view.name_text
var id: Int = -1
init {
view.delete_button.setOnClickListener {
if (id != -1)
deleteReport(id)
}
}
}
}
companion object {
const val SHOW_REPORT_REQUEST = 20
const val SUBSCRIBE_REQUEST = 30
const val OPEN_FILE_REQUEST = 40
const val READ_EXTERNAL_STORAGE_PERMISSION_REQUEST = 50
}
}
| Source/GUI/Android/app/src/main/java/net/mediaarea/mediainfo/ReportListActivity.kt | 491255550 |
// GENERATED
package com.fkorotkov.kubernetes.extensions
import io.fabric8.kubernetes.api.model.PodTemplateSpec as model_PodTemplateSpec
import io.fabric8.kubernetes.api.model.extensions.DaemonSetSpec as extensions_DaemonSetSpec
import io.fabric8.kubernetes.api.model.extensions.DeploymentSpec as extensions_DeploymentSpec
import io.fabric8.kubernetes.api.model.extensions.ReplicaSetSpec as extensions_ReplicaSetSpec
fun extensions_DaemonSetSpec.`template`(block: model_PodTemplateSpec.() -> Unit = {}) {
if(this.`template` == null) {
this.`template` = model_PodTemplateSpec()
}
this.`template`.block()
}
fun extensions_DeploymentSpec.`template`(block: model_PodTemplateSpec.() -> Unit = {}) {
if(this.`template` == null) {
this.`template` = model_PodTemplateSpec()
}
this.`template`.block()
}
fun extensions_ReplicaSetSpec.`template`(block: model_PodTemplateSpec.() -> Unit = {}) {
if(this.`template` == null) {
this.`template` = model_PodTemplateSpec()
}
this.`template`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/extensions/template.kt | 497548387 |
package io.heapy.coverage
import io.heapy.Extensions.defaultRepositories
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.getValue
import org.gradle.kotlin.dsl.provideDelegate
import org.gradle.kotlin.dsl.registering
import org.gradle.testing.jacoco.plugins.JacocoPluginExtension
import org.gradle.testing.jacoco.tasks.JacocoMerge
import org.gradle.testing.jacoco.tasks.JacocoReport
/**
* Plugin which setups defaults in jvm based komodo modules
*
* @author Ruslan Ibragimov
* @since 1.0
*/
class RootCoveragePlugin : Plugin<Project> {
override fun apply(project: Project) {
project.defaultRepositories()
project.config()
}
private fun Project.config() {
plugins.apply("jacoco")
extensions.getByType(JacocoPluginExtension::class.java).apply {
toolVersion = "0.8.5"
}
val jacocoMerge by tasks.registering(JacocoMerge::class) {
group = "jacoco"
description = "JaCoCo merge subprojects results into root one"
destinationFile = file("$buildDir/jacoco/rootTestsCoverage.exec")
executionData = files(subprojects.mapNotNull {
val exec = file("${it.buildDir}/jacoco/module.exec")
if (exec.exists()) exec else null
})
}
@Suppress("UNUSED_VARIABLE")
val jacocoRootReport by tasks.registering(JacocoReport::class) {
group = "jacoco"
description = "Generate Jacoco coverage reports after running tests."
dependsOn(jacocoMerge)
reports {
xml.apply {
isEnabled = true
destination = file("${buildDir}/reports/jacoco/report.xml")
}
html.isEnabled = true
}
val mainSourceSets = subprojects.mapNotNull {
val sourceSets: SourceSetContainer? by it
sourceSets?.get("main")
}
sourceDirectories.from(files(mainSourceSets.map { it.allSource.srcDirs }))
classDirectories.from(files(mainSourceSets.map { it.output }))
executionData.from(jacocoMerge.get().destinationFile)
}
}
}
| buildSrc/src/main/kotlin/io/heapy/coverage/RootCoveragePlugin.kt | 4294530849 |
package com.twbarber.register.public
import com.twbarber.register.public.cli.CashRegisterCliRunner
import com.twbarber.register.public.data.Balance
import junit.framework.TestCase.assertFalse
import junit.framework.TestCase.assertTrue
import org.junit.Assert.assertEquals
import org.junit.Test
class CashRegisterCliRunnerTest {
val cli = CashRegisterCliRunner()
@Test
fun matchPutRegex() {
val input = "put 1 1 1 1 1"
assertTrue(input.matches(Regex(cli.PUT_REGEX)))
}
@Test
fun badPutRegex_NotEnoughBills() {
val input = "put 1 1 1 1"
assertFalse(input.matches(Regex(cli.PUT_REGEX)))
}
@Test
fun matchTakeRegex() {
val input = "take 1 1 1 1 1"
assertTrue(input.matches(Regex(cli.TAKE_REGEX)))
}
@Test
fun badTakeRegex_NotEnoughBills() {
val input = "take 1 1 1 1"
assertFalse(input.matches(Regex(cli.TAKE_REGEX)))
}
@Test
fun matchShowRegex() {
val input = "show"
assertTrue(input.matches(Regex(cli.SHOW_REGEX)))
}
@Test
fun matchChangeRegex() {
val input = "change 13"
assertTrue(input.matches(Regex(cli.CHANGE_REGEX)))
}
@Test
fun matchQuitRegex() {
val input = "quit"
assertTrue(input.matches(Regex(cli.QUIT_REGEX)))
}
@Test
fun emptyInput() {
val input = ""
assertTrue(!input.matches(Regex(cli.TAKE_REGEX)))
assertTrue(!input.matches(Regex(cli.PUT_REGEX)))
assertTrue(!input.matches(Regex(cli.CHANGE_REGEX)))
assertTrue(!input.matches(Regex(cli.SHOW_REGEX)))
}
@Test
fun parsePutTransaction() {
val input = "put 1 1 1 1 1"
assertEquals(Balance(1, 1, 1, 1, 1), cli.parseTransaction(input))
}
@Test
fun parseTakeTransaction() {
val input = "take 1 1 1 1 1"
assertEquals(Balance(1, 1, 1, 1, 1), cli.parseTransaction(input))
}
@Test
fun parseExcessTransactionString() {
val input = "take 1 1 1 1 1 EXTRA"
assertEquals(Balance(1, 1, 1, 1, 1), cli.parseTransaction(input))
}
@Test
fun parseChange() {
val input = "change 3"
assertEquals(3, cli.parseChange(input))
}
} | cash-register-public/src/test/kotlin/com/twbarber/register/public/CashRegisterCliRunnerTest.kt | 220291031 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.