content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.habitrpg.android.habitica.ui.views.promo import android.content.Context import android.util.AttributeSet import android.widget.Button import android.widget.RelativeLayout import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.helpers.MainNavigationController class SubscriptionBuyGemsPromoView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RelativeLayout(context, attrs, defStyleAttr) { init { inflate(R.layout.promo_subscription_buy_gems, true) setBackgroundColor(ContextCompat.getColor(context, R.color.window_background)) clipToPadding = false clipChildren = false clipToOutline = false findViewById<Button>(R.id.button).setOnClickListener { MainNavigationController.navigate(R.id.gemPurchaseActivity, bundleOf(Pair("openSubscription", true))) } } }
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/promo/SubscriptionBuyGemsPromoView.kt
1457297204
/* * Copyright (C) 2020 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xslt.ast.xslt import com.intellij.psi.PsiElement /** * An XSLT 1.0 `xsl:text` node in the XSLT AST. */ interface XsltText : PsiElement
src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/ast/xslt/XsltText.kt
979280953
package com.habitrpg.android.habitica.ui.fragments.social.party import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayoutMediator import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.databinding.FragmentViewpagerBinding import com.habitrpg.android.habitica.models.social.Group import com.habitrpg.android.habitica.ui.activities.GroupFormActivity import com.habitrpg.android.habitica.ui.activities.GroupInviteActivity import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.fragments.social.ChatFragment import com.habitrpg.android.habitica.ui.viewmodels.GroupViewType import com.habitrpg.android.habitica.ui.viewmodels.PartyViewModel class PartyFragment : BaseMainFragment<FragmentViewpagerBinding>() { private var detailFragment: PartyDetailFragment? = null private var chatFragment: ChatFragment? = null private var viewPagerAdapter: FragmentStateAdapter? = null internal val viewModel: PartyViewModel by viewModels() override var binding: FragmentViewpagerBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentViewpagerBinding { return FragmentViewpagerBinding.inflate(inflater, container, false) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { this.usesTabLayout = true this.hidesToolbar = true return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.groupViewType = GroupViewType.PARTY viewModel.getGroupData().observe( viewLifecycleOwner, { updateGroupUI(it) } ) binding?.viewPager?.currentItem = 0 setViewPagerAdapter() arguments?.let { val args = PartyFragmentArgs.fromBundle(it) binding?.viewPager?.currentItem = args.tabToOpen if (args.partyID?.isNotBlank() == true) { viewModel.setGroupID(args.partyID ?: "") } } viewModel.loadPartyID() this.tutorialStepIdentifier = "party" this.tutorialTexts = listOf(getString(R.string.tutorial_party)) viewModel.retrieveGroup {} } override fun injectFragment(component: UserComponent) { component.inject(this) } private fun updateGroupUI(group: Group?) { viewPagerAdapter?.notifyDataSetChanged() if (group == null) { tabLayout?.visibility = View.GONE return } else { tabLayout?.visibility = View.VISIBLE } this.activity?.invalidateOptionsMenu() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) val group = viewModel.getGroupData().value if (viewModel.isLeader) { inflater.inflate(R.menu.menu_party_admin, menu) menu.findItem(R.id.menu_guild_leave).isVisible = group?.memberCount != 1 } else { inflater.inflate(R.menu.menu_party, menu) } } @Suppress("ReturnCount") override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_invite_item -> { val intent = Intent(activity, GroupInviteActivity::class.java) intent.putExtra("groupType", "party") sendInvitesResult.launch(intent) return true } R.id.menu_guild_edit -> { this.displayEditForm() return true } R.id.menu_guild_leave -> { detailFragment?.leaveParty() return true } R.id.menu_guild_refresh -> { viewModel.retrieveGroup { } return true } } return super.onOptionsItemSelected(item) } private fun displayEditForm() { val bundle = Bundle() val group = viewModel.getGroupData().value bundle.putString("groupID", group?.id) bundle.putString("name", group?.name) bundle.putString("groupType", group?.type) bundle.putString("description", group?.description) bundle.putString("leader", group?.leaderID) bundle.putBoolean("leaderCreateChallenge", group?.leaderOnlyChallenges ?: false) val intent = Intent(activity, GroupFormActivity::class.java) intent.putExtras(bundle) intent.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT groupFormResult.launch(intent) } private val groupFormResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == Activity.RESULT_OK) { viewModel.updateOrCreateGroup(it.data?.extras) } } private val sendInvitesResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == Activity.RESULT_OK) { val inviteData = HashMap<String, Any>() inviteData["inviter"] = viewModel.user.value?.profile?.name ?: "" val emails = it.data?.getStringArrayExtra(GroupInviteActivity.EMAILS_KEY) if (emails != null && emails.isNotEmpty()) { val invites = ArrayList<HashMap<String, String>>() emails.forEach { email -> val invite = HashMap<String, String>() invite["name"] = "" invite["email"] = email invites.add(invite) } inviteData["emails"] = invites } val userIDs = it.data?.getStringArrayExtra(GroupInviteActivity.USER_IDS_KEY) if (userIDs != null && userIDs.isNotEmpty()) { val invites = ArrayList<String>() userIDs.forEach { invites.add(it) } inviteData["usernames"] = invites } viewModel.inviteToGroup(inviteData) } } private fun setViewPagerAdapter() { val fragmentManager = childFragmentManager viewPagerAdapter = object : FragmentStateAdapter(fragmentManager, lifecycle) { override fun createFragment(position: Int): Fragment { return when (position) { 0 -> { detailFragment = PartyDetailFragment() detailFragment?.viewModel = viewModel detailFragment } 1 -> { chatFragment = ChatFragment() chatFragment?.viewModel = viewModel chatFragment } else -> Fragment() } ?: Fragment() } override fun getItemCount(): Int { return 2 } } binding?.viewPager?.adapter = viewPagerAdapter binding?.viewPager?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { if (position == 1) { chatFragment?.setNavigatedToFragment() } } override fun onPageSelected(position: Int) { if (position == 1) { chatFragment?.setNavigatedToFragment() } } }) tabLayout?.let { binding?.viewPager?.let { it1 -> TabLayoutMediator(it, it1) { tab, position -> tab.text = when (position) { 0 -> context?.getString(R.string.party) 1 -> context?.getString(R.string.chat) else -> "" } }.attach() } } } }
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/party/PartyFragment.kt
7677800
operator fun ArrayList<String>.get(index1: Int, index2: Int) = this[index1 + index2] operator fun ArrayList<String>.set(index1: Int, index2: Int, elem: String) { this[index1 + index2] = elem } fun box(): String { val s = ArrayList<String>(1) s.add("") s[1, -1] = "O" s[2, -2] += "K" return s[2, -2] }
backend.native/tests/external/codegen/box/arrays/collectionAssignGetMultiIndex.kt
2895364331
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME fun box(): String { var obj = "0" as java.lang.Object val result = synchronized (obj) { 239 } if (result != 239) return "Fail: $result" return "OK" }
backend.native/tests/external/codegen/box/synchronized/value.kt
3441230297
package org.stepik.android.presentation.wishlist import ru.nobird.android.presentation.redux.container.ReduxViewContainer import ru.nobird.android.view.redux.viewmodel.ReduxViewModel class WishlistViewModel( reduxViewContainer: ReduxViewContainer<WishlistFeature.State, WishlistFeature.Message, WishlistFeature.Action.ViewAction> ) : ReduxViewModel<WishlistFeature.State, WishlistFeature.Message, WishlistFeature.Action.ViewAction>(reduxViewContainer)
app/src/main/java/org/stepik/android/presentation/wishlist/WishlistViewModel.kt
1891926348
/* * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * 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. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.endpoints import com.cognifide.apm.core.endpoints.params.RequestParameter import org.apache.sling.api.SlingHttpServletRequest import org.apache.sling.models.annotations.Model import javax.inject.Inject @Model(adaptables = [SlingHttpServletRequest::class]) class ScriptMoveForm @Inject constructor( @param:RequestParameter("path") val path: String, @param:RequestParameter("dest") val dest: String, @param:RequestParameter("rename") val rename: String )
app/aem/core/src/main/kotlin/com/cognifide/apm/core/endpoints/ScriptMoveForm.kt
3518728121
package com.ucsoftworks.leafdb.serializer /** * Created by Pasenchuk Victor on 27/08/2017 */ enum class NullMergeStrategy { TAKE_DESTINATION, KEEP_SOURCE, TAKE_NULL, TAKE_NON_NULL }
leafdb-core/src/main/java/com/ucsoftworks/leafdb/serializer/NullMergeStrategy.kt
2296842556
package com.jdiazcano.modulartd import com.badlogic.gdx.scenes.scene2d.ui.Table import com.badlogic.gdx.scenes.scene2d.ui.Value import com.jdiazcano.modulartd.tabs.* import com.jdiazcano.modulartd.ui.widgets.HorizontalToggleTabbedPane import com.jdiazcano.modulartd.utils.addListener import com.kotcrab.vis.ui.widget.VisTable class MainScreenUI(parentActor: Table) : VisTable() { private val creatorsTabbedPane = HorizontalToggleTabbedPane() private val creatorsTable = VisTable() private val game = VisTable() init { creatorsTabbedPane.addListener { creatorsTable.clearChildren() creatorsTable.add(it.contentTable).expand().fill() } creatorsTabbedPane.add(GameTab()) creatorsTabbedPane.add(TileTab()) creatorsTabbedPane.add(TurretTab()) creatorsTabbedPane.add(LevelTab()) creatorsTabbedPane.add(UnitTab()) val leftSide = VisTable() leftSide.add(creatorsTabbedPane.table).center().expandX().fillX().padBottom(5F).row() leftSide.add(creatorsTable).expand().fill() add(leftSide).expandY().fillY().width(Value.percentWidth(0.35F, parentActor)) add(game).expand().fill() } }
editor/core/src/main/kotlin/com/jdiazcano/modulartd/MainScreenUI.kt
1144763643
/* * Copyright 2017 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nomic.app import com.sun.org.apache.xml.internal.security.utils.XalanXPathAPI.isInstalled import nomic.app.config.TypesafeConfig import nomic.compiler.Compiler import nomic.core.* import nomic.core.exception.BoxAlreadyInstalledException import nomic.core.exception.WtfException import nomic.core.fact.ModuleFact import nomic.core.fact.RequireFact import nomic.db.AvroDb import nomic.db.NomicDb import nomic.hdfs.HdfsPlugin import nomic.hdfs.adapter.HdfsAdapter import nomic.hive.HivePlugin import nomic.oozie.OoziePlugin /** * @author [email protected] */ class NomicApp : NomicInstance { //------------------------------------------------------------------------------------------------- // properties & construction //------------------------------------------------------------------------------------------------- override val config: NomicConfig private val compiler: Compiler private val plugins: List<Plugin> private val hdfs: HdfsAdapter private val db: NomicDb constructor(config: NomicConfig, plugins: List<Plugin>) { this.plugins = plugins this.hdfs = plugins.filterIsInstance(HdfsPlugin::class.java).firstOrNull()?.hdfs ?: throw WtfException() this.db = AvroDb( hdfs = hdfs, nomicHome = config.hdfsRepositoryDir ) this.config = this.Config(config) this.compiler = Compiler( user = config.user, homeDir = config.hdfsHomeDir, appDir = config.hdfsAppDir, expos = plugins.filterIsInstance(Exposable::class.java).toList() ) } companion object { @JvmStatic fun createDefault(): NomicApp = createDefault(TypesafeConfig.loadDefaultConfiguration()) @JvmStatic fun createDefault(config:NomicConfig): NomicApp { val config = TypesafeConfig.loadDefaultConfiguration() val hdfsPlugin = HdfsPlugin.init(config) val hivePlugin = HivePlugin(config) val ooziePlugin = OoziePlugin.init(config, hdfsPlugin.hdfs) return NomicApp(config, listOf(hdfsPlugin, hivePlugin, ooziePlugin)) } } //------------------------------------------------------------------------------------------------- // inner classes //------------------------------------------------------------------------------------------------- private inner class Config(private val parent: NomicConfig): NomicConfig() { override fun get(name: String): String? { if (name == "nomic.hdfs.home") { return hdfs.homeDirectory } else { return parent[name] } } } //------------------------------------------------------------------------------------------------- // implemented methods //------------------------------------------------------------------------------------------------- /** * open the bundle and compile it's root 'nomic.box' into [BundledBox] with facts */ override fun compile(bundle: Bundle): ApplicationBox = compileAll(bundle) .filterIsInstance(ApplicationBox::class.java) .first() /** * This function compile the bundle's box and all submodules. * * @see NomicInstance.compileAll */ override fun compileAll(bundle: Bundle): List<BundledBox> { val facts = compiler.compile(bundle.script) val appBox = ApplicationBox(bundle, facts) val dependenciesFacts = mutableListOf<RequireFact>() return facts.findFactsType(ModuleFact::class.java) .flatMap { moduleFact -> // compile child module and child's submodules (recursion) val childModuleBundle = NestedBundle(appBox, moduleFact.name) val childModuleBoxes = compileAll(childModuleBundle) // find the root, create require fact val r = childModuleBoxes.filterIsInstance(ApplicationBox::class.java).first() dependenciesFacts += RequireFact(box = r.ref()) childModuleBoxes } .map { box -> // make all nested boxes as MOduleBox-es (only one root might exist) if (box is ApplicationBox) { box.toModuleBox() } else { box } } .toList() + ApplicationBox(appBox, facts + dependenciesFacts) } /** * compile the bundle and install it if it's not installed yet. * * @param force if it set to true, the bundle will be installed * even if box is already present. It's good for * fixing bad installations. * * @return references to all installed boxes from bundle in order how * they was installed. */ override fun install(bundle: Bundle, force: Boolean): List<BoxRef> { // compile bundle into boxes and do topology sort of them val boxes = compileAll(bundle) val sortedBoxes = boxes.topologySort() // install the boxes in right order val installedRefs = sortedBoxes.map { box -> install(box as BundledBox, force) } return installedRefs } /** * install once concrete [BundledBox] */ fun install(box: BundledBox, force: Boolean): BoxRef { if (!canInstall(box, force)) { throw BoxAlreadyInstalledException(box) } // send all facts into plugins for commit for(fact in box.facts) { commitFact(box, fact) } //TODO: replace emptyList() by all require facts db.insertOrUpdate(box) return box.ref() } /** * uninstall the box by reference */ override fun uninstall(ref: BoxRef, force: Boolean) { val installedBox = details(ref) if (installedBox != null) { uninstall(installedBox, force) } } /** * uninstall the [InstalledBox] */ fun uninstall(box: InstalledBox, force: Boolean) { // first uninstall all dependencies box.dependencies.forEach { dep -> uninstall(dep, force) } // send all facts in reverse order into plugins for rollback box.facts .reversed() .forEach { fact -> rollbackFact(box, fact) } db.delete(box.ref()) } /** * compile the bundle and upgrade it, or install if it's not * present */ override fun upgrade(bundle: Bundle) = upgrade(compile(bundle)) /** * upgrade the box or install if it's not * present */ fun upgrade(box: BundledBox) { if (isAlreadyInstalled(box)) { uninstall(box.ref(), false) } install(box, false) } /** * return list of boxes installed/available in system */ override fun installedBoxes(): List<BoxRef> = db.loadAll().map(Box::ref) /** * return concrete box with facts if it's present, otherwise * returns null. */ override fun details(info: BoxRef): InstalledBox? = db.load(info)?.compileWith(compiler) //------------------------------------------------------------------------------------------------- // private methods //------------------------------------------------------------------------------------------------- private fun canUninstall(box: Box, force: Boolean): Boolean = isAlreadyInstalled(box) || force private fun canInstall(box:Box, force: Boolean): Boolean = isNotInstalled(box) || force private fun isAlreadyInstalled(box: Box): Boolean = !isNotInstalled(box) private fun isNotInstalled(box: Box): Boolean = db.load(box.ref()) == null private fun commitFact(box: BundledBox, fact: Fact) { plugins.asSequence() .forEach { p -> p.commit(box, fact) } } private fun rollbackFact(box: InstalledBox, fact: Fact) { plugins.asSequence() .forEach { p -> p.rollback(box, fact) } } }
nomic-app/src/main/kotlin/nomic/app/NomicApp.kt
3622900794
package com.jdiazcano.modulartd.beans /** * Determines if a MapObject can have sounds or not */ interface Sounded<T> { val sounds: MutableMap<T, Resource> }
editor/core/src/main/kotlin/com/jdiazcano/modulartd/beans/Sounded.kt
1866143863
package pl.droidsonroids.gradle.ci import org.gradle.api.tasks.Internal open class DeviceSetupTask : DeviceActionTask() { init { description = "Setups device before instrumentation tests" } @Internal override val worker = DeviceSetuper() }
plugin/src/main/kotlin/pl/droidsonroids/gradle/ci/DeviceSetupTask.kt
886126918
package info.nightscout.androidaps.plugins.iob.iobCobCalculator
app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/InMemoryGlucoseValue.kt
1474411512
package io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.notification import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.Toast import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.WykopApp import io.github.feelfreelinux.wykopmobilny.models.dataclass.Notification import io.github.feelfreelinux.wykopmobilny.models.fragments.DataFragment import io.github.feelfreelinux.wykopmobilny.models.fragments.PagedDataModel import io.github.feelfreelinux.wykopmobilny.models.fragments.getDataFragmentInstance import io.github.feelfreelinux.wykopmobilny.models.fragments.removeDataFragment import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.BaseNotificationsListActivity import io.github.feelfreelinux.wykopmobilny.utils.isVisible import kotlinx.android.synthetic.main.activity_notifications_list.* import javax.inject.Inject fun Context.startNotificationsListActivity() { val intent = Intent(this, NotificationsListActivity::class.java) startActivity(intent) } class NotificationsListActivity : BaseNotificationsListActivity() { private lateinit var entryFragmentData : DataFragment<PagedDataModel<List<Notification>>> companion object { val DATA_FRAGMENT_TAG = "NOTIFICATIONS_LIST_ACTIVITY" } override fun loadMore() { presenter.loadData(false) } override fun onRefresh() { presenter.loadData(true) } @Inject lateinit var presenter : NotificationsListPresenter override fun onCreate(savedInstanceState: Bundle?) { WykopApp.uiInjector.inject(this) presenter.subscribe(this) super.onCreate(savedInstanceState) supportActionBar?.setTitle(R.string.notifications_title) entryFragmentData = supportFragmentManager.getDataFragmentInstance(DATA_FRAGMENT_TAG) if (entryFragmentData.data != null && entryFragmentData.data!!.model.isNotEmpty()) { loadingView.isVisible = false presenter.page = entryFragmentData.data!!.page notificationAdapter.addData(entryFragmentData.data!!.model, true) } else { loadingView.isVisible = true onRefresh() } } override fun markAsRead() { presenter.readNotifications() } override fun onDestroy() { super.onDestroy() presenter.unsubscribe() } override fun onPause() { super.onPause() if (isFinishing) supportFragmentManager.removeDataFragment(entryFragmentData) } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) entryFragmentData.data = PagedDataModel(presenter.page, notificationAdapter.data) } }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/notificationslist/notification/NotificationsListActivity.kt
349470810
package expo.interfaces.devmenu.items import com.facebook.react.bridge.ReadableMap interface DevMenuCallableProvider { fun registerCallable(): DevMenuExportedCallable? } sealed class DevMenuExportedCallable(val id: String) class DevMenuExportedFunction( id: String, val function: (ReadableMap?) -> Unit ) : DevMenuExportedCallable(id) { fun call(args: ReadableMap?) { function(args) } } class DevMenuExportedAction( id: String, val action: () -> Unit ) : DevMenuExportedCallable(id) { var keyCommand: KeyCommand? = null var isAvailable = { true } fun registerKeyCommand(keyCommand: KeyCommand?) { this.keyCommand = keyCommand } fun call() { action() } }
packages/expo-dev-menu-interface/android/src/main/java/expo/interfaces/devmenu/items/DevMenuExportedCallable.kt
3112158165
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import java.util.* import javax.inject.Inject import javax.inject.Singleton /** * Created by andy on 16/05/2018. */ @Singleton class RileyLinkServiceData @Inject constructor() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rileyLinkUtil: RileyLinkUtil @Inject lateinit var rxBus: RxBus var tuneUpDone = false var rileyLinkError: RileyLinkError? = null var rileyLinkServiceState: RileyLinkServiceState = RileyLinkServiceState.NotStarted private set var lastServiceStateChange = 0L private set // here we have "compatibility level" version @JvmField var firmwareVersion: RileyLinkFirmwareVersion? = null @JvmField var rileyLinkTargetFrequency: RileyLinkTargetFrequency? = null @JvmField var rileyLinkAddress: String? = null @JvmField var rileyLinkName: String? = null @JvmField var batteryLevel: Int? = null var showBatteryLevel = false var lastTuneUpTime = 0L var lastGoodFrequency: Double? = null // bt version var versionBLE113: String? = null // radio version @JvmField var versionCC110: String? = null // orangeLink var isOrange = false var versionOrangeFirmware: String? = null var versionOrangeHardware: String? = null @JvmField var targetDevice: RileyLinkTargetDevice? = null // Medtronic Pump var pumpID: String? = null var pumpIDBytes: ByteArray = byteArrayOf(0, 0, 0) fun setPumpID(pumpId: String?, pumpIdBytes: ByteArray) { pumpID = pumpId pumpIDBytes = pumpIdBytes } @Synchronized fun setServiceState(newState: RileyLinkServiceState, errorCode: RileyLinkError? = null) { rileyLinkServiceState = newState lastServiceStateChange = System.currentTimeMillis() rileyLinkError = errorCode aapsLogger.info(LTag.PUMP, String.format(Locale.ENGLISH, "RileyLink State Changed: $newState - Error State: ${errorCode?.name}")) rileyLinkUtil.rileyLinkHistory.add(RLHistoryItem(rileyLinkServiceState, errorCode, targetDevice)) rxBus.send(EventRileyLinkDeviceStatusChange(targetDevice!!, newState, errorCode)) } }
rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkServiceData.kt
573093095
package info.nightscout.androidaps.events class EventTherapyEventChange : Event()
app/src/main/java/info/nightscout/androidaps/events/EventTherapyEventChange.kt
1862111395
package info.nightscout.androidaps.events class EventProfileSwitchChanged : Event()
core/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChanged.kt
2411701510
package com.cherryperry.amiami.model.currency import com.cherryperry.amiami.model.lastmodified.LastModifiedValue import com.cherryperry.amiami.util.readProperty import org.apache.logging.log4j.LogManager import org.springframework.stereotype.Repository import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.locks.ReentrantLock @Repository class CurrencyRepositoryImpl : CurrencyRepository { companion object { private const val CURRENCY_JPY = "JPY" private const val CURRENCY_EUR = "EUR" private const val PROPERTIES_FILE = "secure.properties" private const val PROPERTIES_KEY = "fixer.key" private val INTERNAL_ERROR_RESPONSE = CurrencyResponse(success = false, error = CurrencyErrorResponse(0, "Internal error")) } private val log = LogManager.getLogger(CurrencyRepositoryImpl::class.java) private val accessKey: String = readProperty(PROPERTIES_FILE) { if (!containsKey(PROPERTIES_KEY)) { throw IllegalStateException("No $PROPERTIES_KEY in $PROPERTIES_FILE found!") } getProperty(PROPERTIES_KEY) } private val cachedResult = AtomicReference<CurrencyResponse?>() private val lock = ReentrantLock() private val lastModifiedValue = LastModifiedValue() private val currencyRestClient = CurrencyRestClient() override val lastModified: Long get() = lastModifiedValue.value @Suppress("ReturnCount") override fun get(): CurrencyResponse { log.trace("get") try { lock.lock() val cached = cachedResult.get() log.info("cached $cached") if (cached != null && cached.isUpToDate(TimeUnit.DAYS, 1)) { log.info("cache is valid") return cached } log.info("cache is invalid") val result = currencyRestClient.currency(accessKey) if (result.success) { val jpyRate = result.rates?.get(CURRENCY_JPY) if (result.base != CURRENCY_EUR || jpyRate == null) { log.error("invalid response $result") return INTERNAL_ERROR_RESPONSE } log.info("valid response $result") val newRates = result.rates.mapValues { it.value / jpyRate } val newResult = CurrencyResponse( success = true, timestamp = result.timestamp, date = result.date, base = CURRENCY_JPY, rates = newRates, ) log.info("calculated response $newResult") cachedResult.set(newResult) lastModifiedValue.update() return newResult } else { log.info("currency api returns error $result") return cached ?: result } } catch (expected: Exception) { log.error("currency api throws exception", expected) val cached = cachedResult.get() return cached ?: INTERNAL_ERROR_RESPONSE } finally { lock.unlock() } } }
src/main/kotlin/com/cherryperry/amiami/model/currency/CurrencyRepositoryImpl.kt
3699985435
package me.elsiff.morefish.command import co.aikar.commands.BaseCommand import co.aikar.commands.annotation.CommandAlias import co.aikar.commands.annotation.CommandPermission import co.aikar.commands.annotation.Default import co.aikar.commands.annotation.Subcommand import me.elsiff.morefish.MoreFish import me.elsiff.morefish.configuration.Config import me.elsiff.morefish.configuration.Lang import me.elsiff.morefish.fishing.competition.FishingCompetition import me.elsiff.morefish.fishing.competition.FishingCompetitionHost import me.elsiff.morefish.shop.FishShop import org.bukkit.ChatColor import org.bukkit.command.CommandSender import org.bukkit.entity.Player import org.bukkit.plugin.PluginDescriptionFile /** * Created by elsiff on 2018-12-26. */ @CommandAlias("morefish|mf|fish") class MainCommand( private val moreFish: MoreFish, private val competitionHost: FishingCompetitionHost, private val fishShop: FishShop ) : BaseCommand() { private val pluginInfo: PluginDescriptionFile = moreFish.description private val competition: FishingCompetition = competitionHost.competition @Default @Subcommand("help") @CommandPermission("morefish.help") fun help(sender: CommandSender) { val pluginName = pluginInfo.name val prefix = "${ChatColor.AQUA}[$pluginName]${ChatColor.RESET} " sender.sendMessage( prefix + "${ChatColor.DARK_AQUA}> ===== " + "${ChatColor.AQUA}${ChatColor.BOLD}$pluginName ${ChatColor.AQUA}v${pluginInfo.version}" + "${ChatColor.DARK_AQUA} ===== <" ) val label = execCommandLabel sender.sendMessage("$prefix/$label help") sender.sendMessage("$prefix/$label begin [runningTime(sec)]") sender.sendMessage("$prefix/$label suspend") sender.sendMessage("$prefix/$label end") sender.sendMessage("$prefix/$label rewards") sender.sendMessage("$prefix/$label clear") sender.sendMessage("$prefix/$label reload") sender.sendMessage("$prefix/$label top") sender.sendMessage("$prefix/$label shop [player]") } @Subcommand("begin|start") @CommandPermission("morefish.admin") fun begin(sender: CommandSender, args: Array<String>) { if (!competition.isEnabled()) { if (args.size == 1) { try { val runningTime = args[0].toLong() if (runningTime < 0) { sender.sendMessage(Lang.text("not-positive")) } else { competitionHost.openCompetitionFor(runningTime * 20) if (!Config.standard.boolean("messages.broadcast-start")) { val msg = Lang.format("contest-start-timer") .replace("%time%" to Lang.time(runningTime)).output() sender.sendMessage(msg) } } } catch (e: NumberFormatException) { val msg = Lang.format("not-number").replace("%s" to args[0]).output() sender.sendMessage(msg) } } else { competitionHost.openCompetition() if (!Config.standard.boolean("messages.broadcast-start")) { sender.sendMessage(Lang.text("contest-start")) } } } else { sender.sendMessage(Lang.text("already-ongoing")) } } @Subcommand("suspend") @CommandPermission("morefish.admin") fun suspend(sender: CommandSender) { if (!competition.isDisabled()) { competitionHost.closeCompetition(suspend = true) if (!Config.standard.boolean("messages.broadcast-stop")) { sender.sendMessage(Lang.text("contest-stop")) } } else { sender.sendMessage(Lang.text("already-stopped")) } } @Subcommand("end") @CommandPermission("morefish.admin") fun end(sender: CommandSender) { if (!competition.isDisabled()) { competitionHost.closeCompetition() if (!Config.standard.boolean("messages.broadcast-stop")) { sender.sendMessage(Lang.text("contest-stop")) } } else { sender.sendMessage(Lang.text("already-stopped")) } } @Subcommand("top|ranking") @CommandPermission("morefish.top") fun top(sender: CommandSender) { competitionHost.informAboutRanking(sender) } @Subcommand("clear") @CommandPermission("morefish.admin") fun clear(sender: CommandSender) { competition.clearRecords() sender.sendMessage(Lang.text("clear-records")) } @Subcommand("reload") @CommandPermission("morefish.admin") fun reload(sender: CommandSender) { try { moreFish.applyConfig() sender.sendMessage(Lang.text("reload-config")) } catch (e: Exception) { e.printStackTrace() sender.sendMessage(Lang.text("failed-to-reload")) } } @Subcommand("shop") fun shop(sender: CommandSender, args: Array<String>) { val guiUser: Player = if (args.size == 1) { if (!sender.hasPermission("morefish.admin")) { sender.sendMessage(Lang.text("no-permission")) return } val target = sender.server.getPlayerExact(args[0]) ?: null if (target == null) { val msg = Lang.format("player-not-found").replace("%s" to args[0]).output() sender.sendMessage(msg) return } else { target } } else { if (!sender.hasPermission("morefish.shop")) { sender.sendMessage(Lang.text("no-permission")) return } if (sender !is Player) { sender.sendMessage(Lang.text("in-game-command")) return } sender } if (!fishShop.enabled) { sender.sendMessage(Lang.text("shop-disabled")) } else { fishShop.openGuiTo(guiUser) if (guiUser != sender) { val msg = Lang.format("forced-player-to-shop").replace("%s" to guiUser.name).output() sender.sendMessage(msg) } } } }
src/main/kotlin/me/elsiff/morefish/command/MainCommand.kt
2828271611
/* * Copyright (C) 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.test.espresso.device.controller.emulator import io.grpc.CallCredentials import io.grpc.Metadata import java.util.concurrent.Executor /** Call credentials that will inject the given header into the outgoing gRPC call. */ internal class HeaderCallCredentials constructor( private val header: String, private val value: String, ) : CallCredentials() { override fun applyRequestMetadata( requestInfo: CallCredentials.RequestInfo, appExecutor: Executor, applier: CallCredentials.MetadataApplier ) { appExecutor.execute { var headers: Metadata = Metadata() headers.put(Metadata.Key.of(header, Metadata.ASCII_STRING_MARSHALLER), value) applier.apply(headers) } } override fun thisUsesUnstableApi() {} }
espresso/device/java/androidx/test/espresso/device/controller/emulator/HeaderCallCredentials.kt
1688811840
/* * Easy Auth0 Java Library * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>. */ package it.simonerenzo.easyauth0.helpers import it.simonerenzo.easyauth0.models.Credentials import it.simonerenzo.easyauth0.models.User interface IAuth0Helper { fun login(authHeader: String): Credentials fun logout(authHeader: String): Boolean fun authorize(authHeader: String): Boolean fun refresh(authHeader: String): Credentials? fun reset(email: String): Boolean fun mails(audience: String): MutableList<User> }
src/main/kotlin/it/simonerenzo/easyauth0/helpers/IAuth0Helper.kt
2357010032
package biz.eventually.atpl.di.module import android.arch.persistence.room.Database import android.arch.persistence.room.RoomDatabase import android.arch.persistence.room.TypeConverters import biz.eventually.atpl.data.AtplTypeConverter import biz.eventually.atpl.data.dao.* import biz.eventually.atpl.data.db.* /** * Created by Thibault de Lambilly on 17/10/17. */ @Database(entities = [ Source::class, Subject::class, Topic::class, Question::class, Answer::class, LastCall::class ], version = 2) @TypeConverters(AtplTypeConverter::class) abstract class AppDatabase : RoomDatabase() { abstract fun sourceDao() : SourceDao abstract fun subjectDao() : SubjectDao abstract fun topicDao() : TopicDao abstract fun questionDao() : QuestionDao abstract fun lastCallDao() : LastCallDao }
app/src/main/java/biz/eventually/atpl/di/module/AppDatabase.kt
3775922014
/** * This file is part of lavagna. * lavagna is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * lavagna is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with lavagna. If not, see //www.gnu.org/licenses/>. */ package io.lavagna.model import ch.digitalfondue.npjt.ConstructorAnnotationRowMapper.Column class ProjectWithEventCounts(@Column("PROJECT_ID") projectId: Int, @Column("PROJECT_NAME") projectName: String, @Column("PROJECT_SHORT_NAME") projectShortName: String, @Column("PROJECT_DESCRIPTION") projectDescription: String?, @Column("PROJECT_ARCHIVED") projectArchived: Boolean, // @Column("EVENTS") val events: Long) { val project: Project init { this.project = Project(projectId, projectName, projectShortName, projectDescription, projectArchived) } }
src/main/java/io/lavagna/model/ProjectWithEventCounts.kt
667508500
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package org.jetbrains.plugins.ideavim.option import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.command.VimStateMachine import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.options.OptionScope import org.jetbrains.plugins.ideavim.SkipNeovimReason import org.jetbrains.plugins.ideavim.TestWithoutNeovim import org.jetbrains.plugins.ideavim.VimTestCase /** * @author Alex Plate */ // TODO: 2019-06-18 VimOptionsTestCase class DigraphTest : VimTestCase() { @TestWithoutNeovim(SkipNeovimReason.UNCLEAR, "backspace works strange") fun `test digraph`() { VimPlugin.getOptionService().setOption(OptionScope.GLOBAL, OptionConstants.digraphName) doTest( "i B<BS>B", """ A Discovery I found it$c in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it ¦$c in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.UNCLEAR, "backspace works strange") fun `test digraph stops`() { VimPlugin.getOptionService().setOption(OptionScope.GLOBAL, OptionConstants.digraphName) doTest( "i B<BS>BHello", """ A Discovery I found it$c in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it ¦Hello$c in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.UNCLEAR, "backspace works strange") fun `test digraph double backspace`() { VimPlugin.getOptionService().setOption(OptionScope.GLOBAL, OptionConstants.digraphName) doTest( "i B<BS><BS>B", """ A Discovery I found it$c in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found itB$c in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.UNCLEAR, "backspace works strange") fun `test digraph backspace digraph`() { VimPlugin.getOptionService().setOption(OptionScope.GLOBAL, OptionConstants.digraphName) doTest( "i B<BS>B<BS>B", """ A Discovery I found it$c in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it B$c in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } }
src/test/java/org/jetbrains/plugins/ideavim/option/DigraphTest.kt
1147932620
package com.github.kpavlov.jreactive8583 /** * Default read/write idle timeout in seconds (ping interval) = 30 sec. * * @see .getIdleTimeout */ private const val DEFAULT_IDLE_TIMEOUT_SECONDS = 30 /** * Default [.maxFrameLength] (max message length) = 8192 * * @see .getMaxFrameLength */ private const val DEFAULT_MAX_FRAME_LENGTH = 8192 /** * Default [.frameLengthFieldLength] (length of TCP Frame length) = 2 * * @see .getFrameLengthFieldLength */ private const val DEFAULT_FRAME_LENGTH_FIELD_LENGTH = 2 /** * Default [.frameLengthFieldAdjust] (compensation value to add to the value of the length field) = 0 * * @see .getFrameLengthFieldAdjust */ private const val DEFAULT_FRAME_LENGTH_FIELD_ADJUST = 0 /** * Default [.frameLengthFieldOffset] (the offset of the length field) = 0 * * @see .getFrameLengthFieldOffset */ private const val DEFAULT_FRAME_LENGTH_FIELD_OFFSET = 0 public abstract class ConnectorConfiguration protected constructor(b: Builder<*>) { public val addEchoMessageListener: Boolean /** * The maximum length of the frame. */ public val maxFrameLength: Int /** * Set channel read/write idle timeout in seconds. * * If no message was received/sent during specified time interval then `Echo` message will be sent. * * @return timeout in seconds */ public val idleTimeout: Int /** * Returns number of threads in worker [EventLoopGroup]. * * * Default value is `Runtime.getRuntime().availableProcessors() * 16`. * * @return Number of Netty worker threads */ public val workerThreadsCount: Int public val replyOnError: Boolean public val addLoggingHandler: Boolean public val logSensitiveData: Boolean /** * Returns field numbers to be treated as sensitive data. * Use `null` to use default ones * * Array of ISO8583 sensitive field numbers to be masked, or `null` to use default fields. * @see IsoMessageLoggingHandler */ public val sensitiveDataFields: IntArray public val logFieldDescription: Boolean /** * Returns length of TCP frame length field. * * * Default value is `2`. * * @return Length of TCP frame length field. * @see LengthFieldBasedFrameDecoder */ public val frameLengthFieldLength: Int /** * Returns the offset of the length field. * * Default value is `0`. * @see LengthFieldBasedFrameDecoder * * @return The offset of the length field. */ public val frameLengthFieldOffset: Int /** * Returns the compensation value to add to the value of the length field. * * * Default value is `0`. * * @return The compensation value to add to the value of the length field * @see LengthFieldBasedFrameDecoder */ public val frameLengthFieldAdjust: Int /** * If <code>true</code> then the length header is to be encoded as a String, as opposed to the default binary */ public val encodeFrameLengthAsString: Boolean /** * Allows to add default echo message listener to [AbstractIso8583Connector]. * * @return true if [EchoMessageListener] should be added to [CompositeIsoMessageHandler] */ public fun shouldAddEchoMessageListener(): Boolean { return addEchoMessageListener } /** * Returns true is [IsoMessageLoggingHandler] * * Allows to disable adding default logging handler to [ChannelPipeline]. * * @return true if [IsoMessageLoggingHandler] should be added. */ public fun addLoggingHandler(): Boolean { return addLoggingHandler } /** * Whether to reply with administrative message in case of message syntax errors. Default value is `false.` * * @return true if reply message should be sent in case of error parsing the message. */ public fun replyOnError(): Boolean { return replyOnError } /** * Returns `true` if sensitive information like PAN, CVV/CVV2, and Track2 should be printed to log. * * * Default value is `true` (sensitive data is printed). * * * @return `true` if sensitive data should be printed to log */ public fun logSensitiveData(): Boolean { return logSensitiveData } public fun logFieldDescription(): Boolean { return logFieldDescription } /** * Returns <code>true</code> if the length header is to be encoded as a String, * as opposed to the default binary * * Default value is <code>false</code> (frame length header is binary encoded). * * Used with @link frameLengthFieldLength, [#frameLengthFieldOffset] * and [#frameLengthFieldAdjust] * * @return <code>true</code> if frame length header is string-encoded * @return Number of Netty worker threads */ public fun encodeFrameLengthAsString(): Boolean = this.encodeFrameLengthAsString init { this.addEchoMessageListener = b.addEchoMessageListener this.addLoggingHandler = b.addLoggingHandler this.encodeFrameLengthAsString = b.encodeFrameLengthAsString this.frameLengthFieldAdjust = b.frameLengthFieldAdjust this.frameLengthFieldLength = b.frameLengthFieldLength this.frameLengthFieldOffset = b.frameLengthFieldOffset this.idleTimeout = b.idleTimeout this.logFieldDescription = b.logFieldDescription this.logSensitiveData = b.logSensitiveData this.maxFrameLength = b.maxFrameLength this.replyOnError = b.replyOnError this.sensitiveDataFields = b.sensitiveDataFields this.workerThreadsCount = b.workerThreadsCount } @Suppress("UNCHECKED_CAST") public open class Builder<B : Builder<B>> { internal var addLoggingHandler = false internal var addEchoMessageListener = false internal var logFieldDescription = true internal var logSensitiveData = true internal var replyOnError = false internal var idleTimeout = DEFAULT_IDLE_TIMEOUT_SECONDS internal var maxFrameLength = DEFAULT_MAX_FRAME_LENGTH internal var workerThreadsCount = 0 // use netty default internal var sensitiveDataFields: IntArray = IntArray(0) internal var frameLengthFieldLength = DEFAULT_FRAME_LENGTH_FIELD_LENGTH internal var frameLengthFieldOffset = DEFAULT_FRAME_LENGTH_FIELD_OFFSET internal var frameLengthFieldAdjust = DEFAULT_FRAME_LENGTH_FIELD_ADJUST internal var encodeFrameLengthAsString = false /** * @param shouldAddEchoMessageListener `true` to add echo message handler. */ public fun addEchoMessageListener(shouldAddEchoMessageListener: Boolean = true): B = apply { addEchoMessageListener = shouldAddEchoMessageListener } as B /** * @param length Maximum frame length. */ public fun maxFrameLength(length: Int): B = apply { maxFrameLength = length } as B public fun idleTimeout(timeout: Int): B = apply { idleTimeout = timeout } as B public fun replyOnError(doReply: Boolean = true): B = apply { replyOnError = doReply } as B /** * @param addLoggingHandler `true` if [IsoMessageLoggingHandler] should be added to Netty pipeline. */ public fun addLoggingHandler(value: Boolean = true): B = apply { addLoggingHandler = value } as B /** * Should log sensitive data (unmasked) or not. * * * **Don't use on production!** * * @param logSensitiveData `true` to log sensitive data via logger */ public fun logSensitiveData(logSensitiveData: Boolean = true): B = apply { this.logSensitiveData = logSensitiveData } as B /** * @param logFieldDescription `true` to print ISO field descriptions in the log */ public fun describeFieldsInLog(shouldDescribe: Boolean = true): B = apply { logFieldDescription = shouldDescribe } as B /** * @param sensitiveDataFields Array of sensitive fields */ public fun sensitiveDataFields(vararg sensitiveDataFields: Int): B = apply { this.sensitiveDataFields = sensitiveDataFields } as B public fun frameLengthFieldLength(frameLengthFieldLength: Int): B = apply { this.frameLengthFieldLength = frameLengthFieldLength } as B public fun frameLengthFieldOffset(frameLengthFieldOffset: Int): B = apply { this.frameLengthFieldOffset = frameLengthFieldOffset } as B public fun frameLengthFieldAdjust(frameLengthFieldAdjust: Int): B = apply { this.frameLengthFieldAdjust = frameLengthFieldAdjust } as B public fun encodeFrameLengthAsString(encodeFrameLengthAsString: Boolean): B = apply { this.encodeFrameLengthAsString = encodeFrameLengthAsString } as B public fun workerThreadsCount(numberOfThreads: Int): B = apply { workerThreadsCount = numberOfThreads } as B } }
src/main/kotlin/com/github/kpavlov/jreactive8583/ConnectorConfiguration.kt
1552437776
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.core.stackFrame import com.intellij.debugger.impl.descriptors.data.DescriptorData import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl import com.sun.jdi.Field import com.sun.jdi.ObjectReference import com.sun.jdi.Value import org.jetbrains.kotlin.codegen.AsmUtil import org.jetbrains.kotlin.idea.debugger.base.util.safeFields import java.util.* private sealed class PendingValue { class Ordinary(val name: String, val field: Field, val container: Container) : PendingValue() { override fun addTo(existingVariables: ExistingVariables): CapturedValueData? { if (!existingVariables.add(ExistingVariable.Ordinary(name))) { return null } return CapturedValueData(name, container.value, field) } } class This(val label: String, val value: Value?) : PendingValue() { override fun addTo(existingVariables: ExistingVariables): DescriptorData<out ValueDescriptorImpl>? { val thisName = if (existingVariables.hasThisVariables) { if (!existingVariables.add(ExistingVariable.LabeledThis(label))) { // Avoid item duplication return null } getThisName(label) } else { if (!existingVariables.add(ExistingVariable.LabeledThis(label))) { return null } AsmUtil.THIS } return LabeledThisData(label, thisName, value) } } class Container(val value: ObjectReference) : PendingValue() { fun getChildren(): List<PendingValue> { return value.referenceType().safeFields() .filter { it.isApplicable() } .mapNotNull { createPendingValue(this, it) } } private fun Field.isApplicable(): Boolean { val name = name() return name.startsWith(AsmUtil.CAPTURED_PREFIX) || name == AsmUtil.CAPTURED_THIS_FIELD } override fun addTo(existingVariables: ExistingVariables): DescriptorData<out ValueDescriptorImpl>? { throw IllegalStateException("Should not be called on a container") } } abstract fun addTo(existingVariables: ExistingVariables): DescriptorData<out ValueDescriptorImpl>? } internal fun attachCapturedValues( containerValue: ObjectReference, existingVariables: ExistingVariables, collector: (DescriptorData<out ValueDescriptorImpl>) -> Unit ) { val values = collectPendingValues(PendingValue.Container(containerValue)) for (value in values) { val descriptorData = value.addTo(existingVariables) ?: continue collector(descriptorData) } } private fun collectPendingValues(container: PendingValue.Container): List<PendingValue> { val queue = ArrayDeque<PendingValue>() queue.offer(container) val values = mutableListOf<PendingValue>() collectValuesBfs(queue, values) return values } private tailrec fun collectValuesBfs(queue: Deque<PendingValue>, consumer: MutableList<PendingValue>) { val deeperValues = ArrayDeque<PendingValue>() while (queue.isNotEmpty()) { val value = queue.removeFirst() ?: break if (value is PendingValue.Container) { val children = value.getChildren() deeperValues.addAll(children) continue } consumer += value } if (deeperValues.isNotEmpty()) { collectValuesBfs(deeperValues, consumer) } } private fun createPendingValue(container: PendingValue.Container, field: Field): PendingValue? { val name = field.name() if (name == AsmUtil.CAPTURED_THIS_FIELD) { /* * Captured entities. * In case of captured lambda, we just add values captured to the lambda to the list. * In case of captured this (outer this, for example), we add the 'this' value. */ val value = container.value.getValue(field) as? ObjectReference ?: return null return when (val label = getThisValueLabel(value)) { null -> PendingValue.Container(value) else -> PendingValue.This(label, value) } } else if (name.startsWith(AsmUtil.CAPTURED_LABELED_THIS_FIELD)) { // Extension receivers for a new scheme ($this_<label>) val value = container.value.getValue(field) val label = name.drop(AsmUtil.CAPTURED_LABELED_THIS_FIELD.length).takeIf { it.isNotEmpty() } ?: return null return PendingValue.This(label, value) } // Ordinary values (everything but 'this') assert(name.startsWith(AsmUtil.CAPTURED_PREFIX)) val capturedValueName = name.drop(1).takeIf { it.isNotEmpty() } ?: return null return PendingValue.Ordinary(capturedValueName, field, container) }
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/stackFrame/CapturedValuesSearcher.kt
2615519324
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.psi.callExpressionVisitor import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class UnusedDataClassCopyResultInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(call) { val callee = call.calleeExpression ?: return if (callee.text != "copy") return val context = call.analyze(BodyResolveMode.PARTIAL_WITH_CFA) val descriptor = call.getResolvedCall(context)?.resultingDescriptor ?: return val receiver = descriptor.dispatchReceiverParameter ?: descriptor.extensionReceiverParameter ?: return if ((receiver.value as? ImplicitClassReceiver)?.classDescriptor?.isData != true) return if (call.getQualifiedExpressionForSelectorOrThis().isUsedAsExpression(context)) return holder.registerProblem(callee, KotlinBundle.message("inspection.unused.result.of.data.class.copy")) }) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedDataClassCopyResultInspection.kt
3625816508
package io.philippeboisney.material.animation import android.animation.* import android.content.Context import android.util.AttributeSet import android.annotation.TargetApi import android.graphics.drawable.Animatable import android.os.Build import android.view.View import androidx.core.view.forEach import com.google.android.material.bottomappbar.BottomAppBar import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat import androidx.core.view.get import io.philippeboisney.material.R @TargetApi(Build.VERSION_CODES.LOLLIPOP) class BottomAppBarAnimatableTransition(context: Context, attrs: AttributeSet) : BaseForcedTransition(context, attrs) { private var onAppear: Boolean = false init { val a = context.obtainStyledAttributes(attrs, R.styleable.BottomAppBarAnimatable) onAppear = a.getBoolean(R.styleable.BottomAppBarAnimatable_onAppear, onAppear) a.recycle() } override fun getAnimator(view: View): Animator = createAnimation(view) // --- private fun createAnimation(view: View): ValueAnimator { val bottomAppBar = view as BottomAppBar val context = bottomAppBar.context if (onAppear) { bottomAppBar.menu[2].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_search_to_more) bottomAppBar.menu[1].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_delete_scale_up) bottomAppBar.menu[0].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_star_scale_up) } else { bottomAppBar.menu[2].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_more_to_search) bottomAppBar.menu[1].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_delete_scale_down) bottomAppBar.menu[0].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_star_scale_down) } val transition = ValueAnimator.ofInt(0, 1) transition.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { bottomAppBar.menu.forEach { (it.icon as? Animatable)?.start() } } }) return transition!! } }
app/src/main/java/io/philippeboisney/material/animation/BottomAppBarAnimatableTransition.kt
3509125457
// 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.intellij.plugins.markdown.extensions.common.highlighter import com.intellij.icons.AllIcons import com.intellij.lang.LangBundle import com.intellij.openapi.application.invokeLater import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.WindowManager import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension import org.intellij.plugins.markdown.extensions.MarkdownExtensionsUtil import org.intellij.plugins.markdown.ui.preview.BrowserPipe import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel import org.intellij.plugins.markdown.ui.preview.ResourceProvider import java.awt.datatransfer.StringSelection import javax.swing.Icon internal class CodeFenceCopyButtonBrowserExtension(panel: MarkdownHtmlPanel, browserPipe: BrowserPipe): MarkdownBrowserPreviewExtension, ResourceProvider { init { browserPipe.subscribe("copy-button/copy") { CopyPasteManager.getInstance().setContents(StringSelection(it)) val project = panel.project ?: return@subscribe invokeLater { val statusBar = WindowManager.getInstance().getStatusBar(project) val text = StringUtil.shortenTextWithEllipsis(it, 32, 0) statusBar?.info = LangBundle.message("status.bar.text.reference.has.been.copied", "'$text'") } } } override val resourceProvider = this override val styles = listOf(STYLE_NAME) override val scripts = listOf(SCRIPT_NAME) override fun canProvide(resourceName: String): Boolean { return resourceName in resources } override fun loadResource(resourceName: String): ResourceProvider.Resource? { return when (resourceName) { STYLE_NAME -> ResourceProvider.loadInternalResource<CodeFenceCopyButtonBrowserExtension>(STYLE_NAME) SCRIPT_NAME -> ResourceProvider.loadInternalResource<CodeFenceCopyButtonBrowserExtension>(SCRIPT_NAME) COPY_ICON_NAME -> loadIconAsResource(AllIcons.General.InlineCopy) COPY_ICON_HOVERED_NAME -> loadIconAsResource(AllIcons.General.InlineCopyHover) else -> null } } override fun dispose() = Unit class Provider: MarkdownBrowserPreviewExtension.Provider { override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension? { return panel.browserPipe?.let { CodeFenceCopyButtonBrowserExtension(panel, it) } } } companion object { private const val STYLE_NAME = "copy-button.css" private const val SCRIPT_NAME = "copy-button.js" private const val COPY_ICON_NAME = "copy-button-copy-icon.png" private const val COPY_ICON_HOVERED_NAME = "copy-button-copy-icon-hovered.png" private val resources = listOf( STYLE_NAME, SCRIPT_NAME, COPY_ICON_NAME, COPY_ICON_HOVERED_NAME ) private fun loadIconAsResource(icon: Icon): ResourceProvider.Resource { return ResourceProvider.Resource(MarkdownExtensionsUtil.loadIcon(icon, "png")) } } }
plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/highlighter/CodeFenceCopyButtonBrowserExtension.kt
3308935128
package rs.emulate.legacy.map /** * A 3-dimensional 64x64 area of the map. * * @param planes The [MapPlane]s. */ class MapFile(planes: Array<MapPlane>) { val planes: Array<MapPlane> = planes.clone() get() = field.clone() /** * Gets the [MapPlane] with the specified level. */ fun getPlane(plane: Int): MapPlane { require(plane < planes.size) { "Plane index out of bounds, must be [0, ${planes.size})." } return planes[plane] } companion object { /** * The amount of planes in a MapFile. */ const val PLANES = 4 /** * The width of a MapFile, in [Tile]s. */ const val WIDTH = 64 } }
legacy/src/main/kotlin/rs/emulate/legacy/map/MapFile.kt
3820168680
/* * SeqGoData.kt * * Copyright 2015-2016 Michael Farrell <[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 au.id.micolous.metrodroid.transit.seq_go import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.multi.StringResource import au.id.micolous.metrodroid.multi.VisibleForTesting /** * Constants used in Go card */ object SeqGoData { const val SEQ_GO_STR = "seq_go" internal const val VEHICLE_RAIL = 5 internal const val VEHICLE_GLINK = 32 /* Airtrain */ @VisibleForTesting internal const val DOMESTIC_AIRPORT = 9 private const val INTERNATIONAL_AIRPORT = 10 internal val AIRPORT_STATIONS = listOf(DOMESTIC_AIRPORT, INTERNATIONAL_AIRPORT) // https://github.com/micolous/metrodroid/wiki/Go-(SEQ)#ticket-types // TODO: Discover child and seniors card type. internal val TICKET_TYPES = mapOf( // Adult Go seeQ (2019), comes up as "Adult Explore" on TVMs 0xf to TicketType.ADULT_EXPLORE, // Adult (2011) 0x0801 to TicketType.ADULT, // Adult (2016) 0x0c01 to TicketType.ADULT, // Concession (2016) 0x08a5 to TicketType.CONCESSION) enum class TicketType constructor(val description: StringResource) { UNKNOWN(R.string.unknown), ADULT(R.string.seqgo_ticket_type_adult), ADULT_EXPLORE(R.string.seqgo_ticket_type_adult_explore), CHILD(R.string.seqgo_ticket_type_child), CONCESSION(R.string.seqgo_ticket_type_concession), SENIOR(R.string.seqgo_ticket_type_senior) } }
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/seq_go/SeqGoData.kt
960164671
package com.emberjs.configuration.serve import com.emberjs.icons.EmberIcons import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ConfigurationTypeBase class EmberServeConfigurationType : ConfigurationTypeBase( "EMBER_SERVE_CONFIGURATION", "Ember Serve", "Ember Serve Configuration", EmberIcons.ICON_16 ) { override fun getConfigurationFactories(): Array<ConfigurationFactory> { return arrayOf(EmberServeConfigurationFactory(this)) } }
src/main/kotlin/com/emberjs/configuration/serve/EmberServeConfigurationType.kt
364603862
package siarhei.luskanau.iot.doorbell.ui.imagelist import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.paging.LoadState import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.items import coil.compose.rememberAsyncImagePainter import coil.request.ImageRequest import siarhei.luskanau.iot.doorbell.data.model.ImageData import siarhei.luskanau.iot.doorbell.ui.common.BaseFragment import siarhei.luskanau.iot.doorbell.ui.common.ErrorItem import siarhei.luskanau.iot.doorbell.ui.common.LoadingItem import siarhei.luskanau.iot.doorbell.ui.common.R import siarhei.luskanau.iot.doorbell.ui.imagelist.databinding.FragmentImageListBinding class ImageListFragment( presenterProvider: (fragment: Fragment) -> ImageListPresenter ) : BaseFragment<ImageListPresenter>(presenterProvider) { private lateinit var fragmentBinding: FragmentImageListBinding private lateinit var normalStateCompose: ComposeView private val camerasAdapter = CameraAdapter() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { fragmentBinding = FragmentImageListBinding.inflate( inflater, container, false ) normalStateCompose = ComposeView(inflater.context).apply { setContent { MaterialTheme { ImageListComposable( items = presenter.doorbellListFlow.collectAsLazyPagingItems(), onItemClickListener = { imageData -> imageData?.let { presenter.onImageClicked(it) } } ) } } } fragmentBinding.containerContent.addView(normalStateCompose) return fragmentBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fragmentBinding.camerasRecyclerView.adapter = camerasAdapter camerasAdapter.onItemClickListener = { _, _, position -> presenter.onCameraClicked(camerasAdapter.getItem(position)) } } override fun observeDataSources() { super.observeDataSources() viewLifecycleOwner.lifecycleScope.launchWhenStarted { camerasAdapter.submitList(presenter.getCameraList()) } } } @Composable @Suppress("FunctionNaming", "EmptyFunctionBlock", "UnusedPrivateMember") fun ImageListComposable( items: LazyPagingItems<ImageData>, onItemClickListener: (ImageData?) -> Unit ) { LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(all = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { items( items = items, key = { imageData -> imageData.imageId } ) { imageData -> imageData?.let { ImageDataItem( imageData = imageData, onItemClickListener = onItemClickListener ) } } when (val loadState = items.loadState.append) { is LoadState.Error -> item { ErrorItem(loadState.error.message ?: "error") } LoadState.Loading -> item { LoadingItem() } is LoadState.NotLoading -> item { if (items.itemCount <= 0) { Text(text = "no data") } } } when (val loadState = items.loadState.refresh) { is LoadState.Error -> item { ErrorItem(loadState.error.message ?: "error") } LoadState.Loading -> item { LoadingItem() } is LoadState.NotLoading -> Unit } } } @Composable @Suppress("FunctionNaming") fun ImageDataItem( imageData: ImageData, onItemClickListener: (ImageData?) -> Unit ) { val painter = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current) .data(imageData.imageUri) .crossfade(durationMillis = 1000) .error(R.drawable.ic_error_outline) .placeholder(R.drawable.ic_image) .build() ) Surface( shape = MaterialTheme.shapes.medium, modifier = Modifier .padding(vertical = 4.dp, horizontal = 8.dp) .clickable { onItemClickListener.invoke(imageData) }, color = MaterialTheme.colors.background, elevation = 2.dp, border = if (MaterialTheme.colors.isLight) { null } else { BorderStroke(1.dp, MaterialTheme.colors.surface) } ) { Image( modifier = Modifier.fillMaxSize(), painter = painter, contentDescription = "Unsplash Image", contentScale = ContentScale.Crop ) } }
ui/ui_image_list/src/main/kotlin/siarhei/luskanau/iot/doorbell/ui/imagelist/ImageListFragment.kt
3335162150
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.idea.refactoring.replaceListPsiAndKeepDelimiters import org.jetbrains.kotlin.psi.KtDestructuringDeclaration import org.jetbrains.kotlin.psi.KtDestructuringDeclarationEntry import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.buildDestructuringDeclaration import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.utils.ifEmpty class KotlinComponentUsageInDestructuring(element: KtDestructuringDeclarationEntry) : KotlinUsageInfo<KtDestructuringDeclarationEntry>(element) { override fun processUsage( changeInfo: KotlinChangeInfo, element: KtDestructuringDeclarationEntry, allUsages: Array<out UsageInfo> ): Boolean { if (!changeInfo.isParameterSetOrOrderChanged) return true val declaration = element.parent as KtDestructuringDeclaration val currentEntries = declaration.entries val newParameterInfos = changeInfo.getNonReceiverParameters() val newDestructuring = KtPsiFactory(element).buildDestructuringDeclaration { val lastIndex = newParameterInfos.indexOfLast { it.oldIndex in currentEntries.indices } val nameValidator = CollectingNameValidator( filter = Fe10KotlinNewDeclarationNameValidator( declaration.parent.parent, null, KotlinNameSuggestionProvider.ValidatorTarget.VARIABLE ) ) appendFixedText("val (") for (i in 0..lastIndex) { if (i > 0) { appendFixedText(", ") } val paramInfo = newParameterInfos[i] val oldIndex = paramInfo.oldIndex if (oldIndex >= 0 && oldIndex < currentEntries.size) { appendChildRange(PsiChildRange.singleElement(currentEntries[oldIndex])) } else { appendFixedText(Fe10KotlinNameSuggester.suggestNameByName(paramInfo.name, nameValidator)) } } appendFixedText(")") } replaceListPsiAndKeepDelimiters( changeInfo, declaration, newDestructuring, { apply { val oldEntries = entries.ifEmpty { return@apply } val firstOldEntry = oldEntries.first() val lastOldEntry = oldEntries.last() val newEntries = it.entries if (newEntries.isNotEmpty()) { addRangeBefore(newEntries.first(), newEntries.last(), firstOldEntry) } deleteChildRange(firstOldEntry, lastOldEntry) } }, { entries } ) return true } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinComponentUsageInDestructuring.kt
3685983402
/* * Copyright 2017 Lloyd Ramey <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lloydramey.cfn.model.aws import com.lloydramey.cfn.model.aws.autoscaling.AdjustmentType import com.lloydramey.cfn.model.aws.autoscaling.BlockDeviceMapping import com.lloydramey.cfn.model.aws.autoscaling.MetricsCollection import com.lloydramey.cfn.model.aws.autoscaling.NotificationConfigurations import com.lloydramey.cfn.model.aws.autoscaling.StepAdjustment import com.lloydramey.cfn.model.aws.autoscaling.Tag import com.lloydramey.cfn.model.functions.AwsTemplateValue import com.lloydramey.cfn.model.resources.Required import com.lloydramey.cfn.model.resources.ResourceProperties @Suppress("unused") class AutoScaling { class AutoScalingGroup : ResourceProperties("AWS::AutoScaling::AutoScalingGroup") { @Required var maxSize: AwsTemplateValue? = null @Required var minSize: AwsTemplateValue? = null var availabilityZones: MutableList<AwsTemplateValue> = mutableListOf() var cooldown: AwsTemplateValue? = null var desiredCapacity: AwsTemplateValue? = null var healthCheckGracePeriod: AwsTemplateValue? = null var healthCheckType: AwsTemplateValue? = null var instanceId: AwsTemplateValue? = null var launchConfigurationName: AwsTemplateValue? = null var loadBalancerNames: MutableList<AwsTemplateValue> = mutableListOf() var metricsCollection: MutableList<MetricsCollection> = mutableListOf() var notificationConfigurations: MutableList<NotificationConfigurations> = mutableListOf() var placementGroup: AwsTemplateValue? = null var tags: MutableList<Tag> = mutableListOf() var targetGroupARNs: MutableList<AwsTemplateValue> = mutableListOf() var terminationPolicies: MutableList<AwsTemplateValue> = mutableListOf() var vPCZoneIdentifier: MutableList<AwsTemplateValue> = mutableListOf() } class LaunchConfiguration : ResourceProperties("AWS::AutoScaling::LaunchConfiguration") { var associatePublicIpAddress: AwsTemplateValue? = null var blockDeviceMappings: MutableList<BlockDeviceMapping>? = mutableListOf() var classicLinkVPCId: AwsTemplateValue? = null var classicLinkVPCSecurityGroups: MutableList<AwsTemplateValue> = mutableListOf() var ebsOptimized: AwsTemplateValue? = null var iamInstanceProfile: AwsTemplateValue? = null @Required var imageId: AwsTemplateValue? = null var instanceId: AwsTemplateValue? = null var instanceMonitoring: AwsTemplateValue? = null @Required var instanceType: AwsTemplateValue? = null var kernelId: AwsTemplateValue? = null var keyName: AwsTemplateValue? = null var placementTenancy: AwsTemplateValue? = null var ramDiskId: AwsTemplateValue? = null var securityGroups: AwsTemplateValue? = null var spotPrice: AwsTemplateValue? = null var userData: AwsTemplateValue? = null } class LifecycleHook : ResourceProperties("AWS::AutoScaling::LifecycleHook") { @Required var autoScalingGroupName: AwsTemplateValue? = null var defaultResult: AwsTemplateValue? = null var heartbeatTimeout: AwsTemplateValue? = null @Required var lifecycleTransition: AwsTemplateValue? = null var notificationMetadata: AwsTemplateValue? = null @Required var notificationTargetARN: AwsTemplateValue? = null @Required var roleARN: AwsTemplateValue? = null } class ScalingPolicy : ResourceProperties("AWS::AutoScaling::ScalingPolicy") { @Required var adjustmentType: AdjustmentType? = null @Required var autoScalingGroupName: AwsTemplateValue? = null var cooldown: AwsTemplateValue? = null var estimatedInstanceWarmup: AwsTemplateValue? = null var metricAggregationType: AwsTemplateValue? = null var minAdjustmentMagnitude: AwsTemplateValue? = null var policyType: AwsTemplateValue? = null var scalingAdjustment: AwsTemplateValue? = null var stepAdjustments: MutableList<StepAdjustment> = mutableListOf() } class ScheduledAction : ResourceProperties("AWS::AutoScaling::ScheduledAction") { @Required var autoScalingGroupName: AwsTemplateValue? = null var desiredCapacity: AwsTemplateValue? = null var endTime: AwsTemplateValue? = null var maxSize: AwsTemplateValue? = null var minSize: AwsTemplateValue? = null var recurrence: AwsTemplateValue? = null var startTime: AwsTemplateValue? = null } }
aws/src/main/kotlin/com/lloydramey/cfn/model/aws/AutoScaling.kt
807020103
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.base.util import kotlin.coroutines.Continuation import org.jetbrains.org.objectweb.asm.Type as AsmType val CONTINUATION_TYPE: AsmType = AsmType.getType(Continuation::class.java) val SUSPEND_LAMBDA_CLASSES: List<String> = listOf( "kotlin.coroutines.jvm.internal.SuspendLambda", "kotlin.coroutines.jvm.internal.RestrictedSuspendLambda" )
plugins/kotlin/jvm-debugger/base/util/src/org/jetbrains/kotlin/idea/debugger/base/util/CoroutineUtils.kt
3946958891
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.execution.wsl import com.intellij.execution.target.TargetEnvironment import com.intellij.util.PathMappingSettings import java.nio.file.Path import kotlin.io.path.pathString /** * Win drives -> /mnt */ val WSLDistribution.rootMappings: List<PathMappingSettings.PathMapping> get() = listWindowsRoots().map { PathMappingSettings.PathMapping(it.pathString, getWslPath(it.pathString)) } + listOf( PathMappingSettings.PathMapping(getWindowsPath("/"), "/") ) /** * Same as [rootMappings] but with [TargetEnvironment.SynchronizedVolume] */ val WSLDistribution.synchronizedVolumes get() = rootMappings.map { TargetEnvironment.SynchronizedVolume(Path.of(it.localRoot), it.remoteRoot) }
platform/execution-impl/src/com/intellij/execution/wsl/WslDistributionEx.kt
3726255944
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring import com.intellij.util.messages.Topic interface KotlinRefactoringEventListener { companion object { val EVENT_TOPIC = Topic.create("KOTLIN_REFACTORING_EVENT_TOPIC", KotlinRefactoringEventListener::class.java) } fun onRefactoringExit(refactoringId: String) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/RefactoringEventListenerEx.kt
2408447223
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("Topics") package com.intellij.application import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.util.messages.Topic // disposable is not an optional param to force pass `null` explicitly /** * Subscribes given handler to the application message bus. * * Use this shortcut method only if you need to subscribe to the one topic, otherwise you should reuse message bus connection. */ fun <L : Any> Topic<L>.subscribe(disposable: Disposable?, handler: L) { val messageBus = ApplicationManager.getApplication().messageBus (if (disposable == null) messageBus.connect() else messageBus.connect(disposable)).subscribe(this, handler) }
platform/util-ex/src/com/intellij/application/Topics.kt
4068482498
/* * Copyright 2022, TeamDev. All rights reserved. * * 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 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.io import java.io.File import java.nio.file.Files.exists import java.nio.file.Path import java.nio.file.Paths import java.util.function.Predicate import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir class `'ResourceDirectory' should` { private lateinit var directory: ResourceDirectory private lateinit var target: Path private companion object { const val resourceName = "directory" val allFiles = listOf( ".dot-file", "file1.txt", "subdir/.dot-file", "subdir/file1.txt", "subdir/file2.txt", "subdir/sub-sub-dir/.dot-file", "subdir/sub-sub-dir/file1.txt", "subdir/sub-sub-dir/file2.txt", "subdir/sub-sub-dir/file3.txt", ) val dotNamed: Predicate<String> = Predicate { s -> s.contains(File.separator + ".dot") } val noSubSub: Predicate<String> = Predicate { s -> !s.contains("-sub-") } } @BeforeEach fun obtainDirectory(@TempDir tempDir: Path) { directory = ResourceDirectory.get(resourceName, javaClass.classLoader) target = tempDir } @Test fun `copy all content to a target directory`() { directory.copyContentTo(target) allFiles.forEach { p -> assertExists(p) } } @Test fun `copy content matching a predicate`() { val condition = dotNamed.and(noSubSub) directory.copyContentTo(target) { path -> condition.test(path.toString()) } allFiles .filter { name -> condition.test(name) } .forEach { p -> assertExists(p) } val reverse = dotNamed.negate().and(noSubSub.negate()) allFiles .filter { name -> reverse.test(name) } .forEach { p -> assertNotExists(p) } } @Test fun `copy the directory to file system`() { directory.copyTo(target) assertExists(resourceName) allFiles.forEach { p -> assertExists(nestedPath(p)) } } @Test fun `copy the directory with filtering`() { val condition = dotNamed.and(noSubSub) directory.copyTo(target) { path -> condition.test(path.toString()) } assertExists(resourceName) allFiles .filter { name -> condition.test(name) } .forEach { p -> assertExists(nestedPath(p)) } val reverse = dotNamed.negate().and(noSubSub.negate()) allFiles .filter { name -> reverse.test(name) } .forEach { p -> assertNotExists(nestedPath(p)) } } private fun nestedPath(p: String) = Paths.get(resourceName, p).toString() private fun assertExists(relativePath: String) { val fullPath = target.resolve(relativePath) assertTrue(exists(fullPath), "Expected to exist: `${fullPath}`.") } private fun assertNotExists(relativePath: String) { val fullPath = target.resolve(relativePath) assertFalse(exists(fullPath), "Expected to NOT exist: `${fullPath}`.") } }
base/src/test/kotlin/io/spine/io/ResourceDirectoryTest.kt
2407903007
package com.kondroid.sampleproject.dto /** * Created by kondo on 2017/10/01. */ data class TokenDto(val token: String?, val expiredAt: Long?)
app/src/main/java/com/kondroid/sampleproject/dto/TokenDto.kt
2515722450
/* * Copyright (C) 2021 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.functional.assisted.kotlin import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import javax.inject.Inject class Dep @Inject constructor() class AssistedDep /** Assisted injection for a kotlin class. */ class Foo @AssistedInject constructor(val dep: Dep, @Assisted val assistedDep: AssistedDep) /** Assisted injection for a kotlin data class. */ data class FooData @AssistedInject constructor(val dep: Dep, @Assisted val assistedDep: AssistedDep) /** Assisted factory for a kotlin class */ @AssistedFactory interface FooFactory { fun create(assistedDep: AssistedDep): Foo } /** Assisted factory for a kotlin data class */ @AssistedFactory interface FooDataFactory { fun create(assistedDep: AssistedDep): FooData } /** Kotlin classes for regression test of https://github.com/google/dagger/issues/3065. */ class BarManager @AssistedInject internal constructor(@Assisted val bar: Bar, @Assisted val name: String) { @AssistedFactory interface Factory { operator fun Bar.invoke(name: String): BarManager } } class Bar
javatests/dagger/functional/assisted/kotlin/KotlinAssistedInjectionClasses.kt
93368777
package com.aswiatek.pricecomparator.events import com.aswiatek.pricecomparator.adapters.CardsViewHolder import com.aswiatek.pricecomparator.buisinesslogic.Mode data class ScreenValueChanged( val viewHolder: CardsViewHolder, val mode: Mode, val value: String)
PriceComparator/app/src/main/java/com/aswiatek/pricecomparator/events/ScreenValueChanged.kt
1431634786
@file:Suppress("UNCHECKED_CAST") package me.camdenorrb.minibus.listener.table import me.camdenorrb.kcommons.ext.isGenericSupertypeOf import me.camdenorrb.minibus.listener.ListenerAction import me.camdenorrb.minibus.listener.ListenerAction.Lambda import me.camdenorrb.minibus.listener.ListenerEntry import me.camdenorrb.minibus.listener.ListenerPriority import me.camdenorrb.minibus.listener.ListenerPriority.NORMAL import java.util.concurrent.ConcurrentSkipListSet import kotlin.reflect.KCallable import kotlin.reflect.KFunction import kotlin.reflect.KType import kotlin.reflect.typeOf //private typealias ListenerMapEntry = Map.Entry<KClass<out Any>, TreeMap<ListenerPriority, MutableList<ListenerAction<Any>>>> class ListenerTable { val map = mutableMapOf<KType, ConcurrentSkipListSet<ListenerEntry<Any>>>() inline fun <reified T> find(): List<ListenerEntry<Any>>? { val type = typeOf<T>() return map.filterKeys { it == type || it.isGenericSupertypeOf(type) }.values.flatten() } inline fun <reified T : Any> entries(): Set<ListenerEntry<Any>>? { return map[typeOf<T>()] } inline fun <reified T : Any> entries(priority: ListenerPriority): List<ListenerEntry<Any>>? { return entries<T>()?.filter { it.priority == priority } } inline fun <reified T> get(): Set<ListenerEntry<Any>>? { return map[typeOf<T>()] } inline fun <reified T> get(priority: ListenerPriority): List<ListenerEntry<Any>>? { return map[typeOf<T>()]?.filter { it.priority == priority } } //inline operator fun <reified T> get() = map[typeOf<T>()] inline fun <reified T> call(event: Any) { /*map.forEach { println("${it.key} [${it.value.joinToString { it.action.callable.toString() }}]") } println("----")*/ find<T>()?.forEach { it.action(event) } //println() } inline fun <reified T> remove(): Set<ListenerEntry<Any>>? { return map.remove(typeOf<T>()) } inline fun <reified T> remove(priority: ListenerPriority): Boolean? { return map[typeOf<T>()]?.removeIf { it.priority == priority } } fun remove(action: ListenerAction<*>) = map.values.removeIf { value -> value.removeIf { it.action == action } value.isEmpty() } fun remove(callable: KCallable<*>) = map.values.removeIf { value -> value.removeIf { it.action.callable == callable } value.isEmpty() } inline fun <reified T : Any> add(action: ListenerAction<T>, priority: ListenerPriority = NORMAL) { this.add(typeOf<T>(), action as ListenerAction<Any>, priority) } inline fun <reified T : Any> add(instance: Any, function: KFunction<Any>, priority: ListenerPriority = NORMAL) { this.add<T>(ListenerAction.Function(instance, function), priority) } inline fun <reified T : Any> add(priority: ListenerPriority = NORMAL, noinline block: Lambda<T>.(T) -> Unit) { this.add<T>(Lambda(block) as Lambda<Any>, priority) } fun add(type: KType, instance: Any, function: KFunction<Any>, priority: ListenerPriority = NORMAL) { this.add(type, ListenerAction.Function(instance, function), priority) } fun add(type: KType, action: ListenerAction<Any>, priority: ListenerPriority = NORMAL) { map.getOrPut(type) { ConcurrentSkipListSet() }.add(ListenerEntry(priority, action)) } }
src/main/kotlin/me/camdenorrb/minibus/listener/table/ListenerTable.kt
3530790216
package graphics.scenery.primitives import graphics.scenery.BufferUtils import graphics.scenery.Mesh import graphics.scenery.OrientedBoundingBox import graphics.scenery.ShaderMaterial import graphics.scenery.geometry.GeometryType import org.joml.Vector3f import java.nio.FloatBuffer import java.nio.file.FileSystems import java.nio.file.Files /** * Constructs a point cloud, with a given base [pointRadius]. * * @author Kyle Harrington <[email protected]> * @author Ulrik Günther <[email protected]> */ open class PointCloud(var pointRadius: Float = 1.0f, override var name: String = "PointCloud") : Mesh(name) { init { geometry { /** [PointCloud]s are rendered as point geometry. */ geometryType = GeometryType.POINTS } renderable { // PointClouds do not get billboarded. isBillboard = false // we are going to use shader files whose name is derived from the class name. // -> PointCloud.vert, PointCloud.frag } setMaterial(ShaderMaterial.fromClass(this::class.java)) { blending.transparent = true } } /** * Sets up normal and texcoord buffers from the vertex buffers. */ fun setupPointCloud() { geometry { if( this.texcoords.limit() == 0 ) {// Only preinitialize if texcoords has not been preinialized this.texcoords = BufferUtils.allocateFloat(vertices.limit() / 3 * 2) var i = 0 while (i < this.texcoords.limit() - 1) { this.texcoords.put(i, pointRadius) this.texcoords.put(i + 1, pointRadius) i += 2 } } if( this.normals.limit() == 0 ) {// Only preinitialize if need be this.normals = BufferUtils.allocateFloatAndPut(FloatArray(vertices.limit(), { 1.0f })) } } } /** * Reads the [PointCloud] from [filename], assuming the ThunderSTORM format. * See http://www.neurocytolab.org/tscolumns/ for format documentation. * * This function automatically determines the used separator char, and supports * comma (,), semicolon (;), and tab as separators. */ fun readFromPALM(filename: String) { geometry { val count = Files.lines(FileSystems.getDefault().getPath(filename)).count() this.vertices = BufferUtils.allocateFloat(count.toInt() * 3) this.normals = BufferUtils.allocateFloat(count.toInt() * 3) this.texcoords = BufferUtils.allocateFloat(count.toInt() * 2) logger.info("Reading ${count/3} locations from $filename...") val boundingBoxCoords = floatArrayOf(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f) var separator = "" Files.lines(FileSystems.getDefault().getPath(filename)).forEach { // try to figure out separator char if(separator == "") { separator = when { it.split(",").size >= 6 -> "," it.split("\t").size >= 6 -> "\t" it.split(";").size >= 6 -> ";" else -> throw IllegalStateException("Could not determine separator char for file $filename.") } logger.debug("Determined <$separator> as separator char for $filename.") } val arr = it.split(separator) if (!arr[0].startsWith("\"")) { this.vertices.put(arr[1].toFloat()) this.vertices.put(arr[2].toFloat()) this.vertices.put(arr[3].toFloat()) boundingBoxCoords[0] = minOf(arr[1].toFloat(), boundingBoxCoords[0]) boundingBoxCoords[2] = minOf(arr[2].toFloat(), boundingBoxCoords[2]) boundingBoxCoords[4] = minOf(arr[3].toFloat(), boundingBoxCoords[4]) boundingBoxCoords[1] = maxOf(arr[1].toFloat(), boundingBoxCoords[1]) boundingBoxCoords[3] = maxOf(arr[2].toFloat(), boundingBoxCoords[3]) boundingBoxCoords[5] = maxOf(arr[3].toFloat(), boundingBoxCoords[5]) this.normals.put(arr[1].toFloat()) this.normals.put(arr[2].toFloat()) this.normals.put(arr[3].toFloat()) this.texcoords.put(arr[4].toFloat()) this.texcoords.put(arr[5].toFloat()) } } logger.info("Finished reading. Found ${vertices.capacity()/3} locations.") this.vertices.flip() this.normals.flip() this.texcoords.flip() boundingBox = OrientedBoundingBox(this@PointCloud, boundingBoxCoords) } } /** * Sets the [color] for all vertices. */ fun setColor(color: Vector3f) { val colorBuffer = FloatBuffer.allocate(geometry().vertices.capacity()) while(colorBuffer.hasRemaining()) { color.get(colorBuffer) } } companion object { /** * Creates a point cloud from an [array] of floats. */ fun fromArray(array: FloatArray): PointCloud { val p = PointCloud() p.geometry().vertices = FloatBuffer.wrap(array) p.setupPointCloud() return p } /** * Creates a point cloud from a [buffer] of floats. */ fun fromBuffer(buffer: FloatBuffer): PointCloud { val p = PointCloud() p.geometry().vertices = buffer.duplicate() p.setupPointCloud() return p } } }
src/main/kotlin/graphics/scenery/primitives/PointCloud.kt
2585348913
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengles.templates import org.lwjgl.generator.* import opengles.* val OES_sample_shading = "OESSampleShading".nativeClassGLES("OES_sample_shading", postfix = OES) { documentation = """ Native bindings to the $registryLink extension. In standard multisample rendering, an implementation is allowed to assign the same sets of fragment shader input values to each sample. This can cause aliasing where the fragment shader input values are used to generate a result that doesn't antialias itself, for example with alpha-tested transparency. This extension adds the ability to explicitly request that an implementation use a minimum number of unique set of fragment computation inputs when multisampling a pixel. Specifying such a requirement can reduce aliasing that results from evaluating the fragment computations too few times per pixel. This extension adds new global state that controls the minimum number of samples for which attribute data is independently interpolated. When enabled, all fragment-shading operations are executed independently on each sample. Requires ${GLES30.core}. """ IntConstant( """ Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetInteger64v. """, "SAMPLE_SHADING_OES"..0x8C36 ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetInteger64v, and GetFloatv.", "MIN_SAMPLE_SHADING_VALUE_OES"..0x8C37 ) void( "MinSampleShadingOES", "", GLfloat("value", "") ) }
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/OES_sample_shading.kt
3727599727
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.tests.community import com.intellij.openapi.application.ApplicationManager import com.intellij.testGuiFramework.fixtures.IdeFrameFixture import com.intellij.testGuiFramework.framework.GuiTestUtil import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.impl.* import com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitUntil import com.intellij.testGuiFramework.launcher.system.SystemInfo import com.intellij.testGuiFramework.launcher.system.SystemInfo.isMac import com.intellij.testGuiFramework.launcher.system.SystemInfo.isUnix import com.intellij.testGuiFramework.launcher.system.SystemInfo.isWin import com.intellij.testGuiFramework.util.Key.* import com.intellij.testGuiFramework.util.Modifier.* import com.intellij.testGuiFramework.util.plus import org.fest.swing.exception.WaitTimedOutError import org.fest.swing.timing.Timeout import org.junit.Test import java.io.File import java.nio.file.Paths import java.util.concurrent.TimeUnit import javax.swing.JButton import kotlin.test.assertEquals //test for issue (GUI-167) class SaveFilesOnFrameDeactivationGuiTest : GuiTestCase() { private val textToWrite = """new text in editor""" @Test fun testSwitchBetweenIdeFrames() { ensureSaveFilesOnFrameDeactivation() val ideFrame1 = CommunityProjectCreator.importProject("command-line-app") .let { IdeFrameFixture.find(robot(), it, null, Timeouts.seconds10) } ideFrame1.prepare() val ideFrame2File = CommunityProjectCreator.importProject("command-line-app2") openProjectInNewWindow() val ideFrame2 = IdeFrameFixture.find(robot(), ideFrame2File, null, Timeouts.seconds10) ideFrame2.prepare() val filePath = getCurrentEditorFilePath(ideFrame2) ideFrame2.pasteTextToEditor(textToWrite) //modify ideFrame2 main file ideFrame1.switchFrameTo() //check ideFrame2 content val fileSystemText = waitFileToBeSynced(textToWrite, filePath) ideFrame1.closeProject(false) ideFrame2.closeProject(false) assertEquals(textToWrite, fileSystemText) } @Test fun testSwitchIdeFrameToApp() { val ideFrame = CommunityProjectCreator.importProject("command-line-app") .let { IdeFrameFixture.find(robot(), it, null, Timeouts.seconds10) } ideFrame.prepare() val filePath = getCurrentEditorFilePath(ideFrame) ideFrame.pasteTextToEditor(textToWrite) val processBuilder = dummyUiApp() val process = processBuilder.start() process.waitFor(3, TimeUnit.SECONDS) process.destroyForcibly() val fileSystemText = waitFileToBeSynced(textToWrite, filePath) ideFrame.closeProject(false) assertEquals(textToWrite, fileSystemText) } @Test fun testSwitchIdeFrameToAppBlockedByModal() { val ideFrame = CommunityProjectCreator.importProject("command-line-app") .let { IdeFrameFixture.find(robot(), it, null, Timeouts.seconds10) } ideFrame.prepare() val filePath = getCurrentEditorFilePath(ideFrame) val originalTextFromEditor = File(filePath).readText() ideFrame.pasteTextToEditor(textToWrite) openSettings() val processBuilder = dummyUiApp() val process = processBuilder.start() process.waitFor(3, TimeUnit.SECONDS) process.destroyForcibly() val fileSystemText = waitFileToBeSynced(textToWrite, filePath) dialog(if (SystemInfo.isMac()) "Preferences" else "Settings") { button("Cancel").click() } ideFrame.closeProject(false) assertEquals(originalTextFromEditor, fileSystemText) } private fun openSettings() { shortcut(CONTROL + ALT + S, META + COMMA) } private fun getCurrentEditorFilePath(ideFrame2: IdeFrameFixture) = ApplicationManager.getApplication().runReadAction<String> { ideFrame2.let { it.editor.currentFile!!.path } } private fun IdeFrameFixture.pasteTextToEditor(text: String) { editor { shortcut(CONTROL + A, META + A) typeText(text) } waitUntil("text in editor will match entered text", Timeouts.seconds05) { editor.getCurrentFileContents(false) == text } } private fun dummyUiApp(): ProcessBuilder { val dummyUIAppClassStr: String = DummyUIApp::class.java.name.replace(".", "/") + ".class" val cl = this.javaClass.classLoader.getResource(dummyUIAppClassStr) val classpath = File(cl.toURI()).path.dropLast(dummyUIAppClassStr.length) val javaPath = System.getenv("JAVA_HOME") ?: System.getProperty("java.home") ?: throw Exception("Unable to locate java") val javaFilePath = Paths.get(javaPath, "bin", "java").toFile().path return ProcessBuilder(javaFilePath, "-classpath", classpath, DummyUIApp::class.java.name).apply { inheritIO() } } private fun ensureSaveFilesOnFrameDeactivation() { val preferences = if (SystemInfo.isMac()) "Preferences" else "Settings" welcomeFrame { actionLink("Configure").click() popupMenu(preferences).clickSearchedItem() dialog("$preferences for New Projects") { jTree("Appearance & Behavior", "System Settings").clickPath() checkbox("Save files on frame deactivation").apply { if (!isSelected) click() } button("OK").click() } } } private fun waitFileToBeSynced(textInEditor: String, filePath: String?, timeout: Timeout = Timeouts.seconds30): String { var textFromFile: String = "" try { waitUntil("File content and editor's content will be synced", timeout) { textFromFile = File(filePath).readText() textInEditor == textFromFile } } catch (e: WaitTimedOutError) { System.err.println(e.message) } return textFromFile } private fun IdeFrameFixture.switchFrameTo() { if (this.target().isActive) return when { isWin() -> shortcut(CONTROL + ALT + OPEN_BRACKET) isMac() -> shortcut(META + BACK_QUOTE) isUnix() -> shortcut(ALT + BACK_QUOTE) } GuiTestUtilKt.waitUntil("IdeFrame[${this.projectPath}] will be activated", Timeouts.seconds02) { this.target().isActive } } private fun IdeFrameFixture.prepare() { this.apply { waitForStartingIndexing(10) waitForBackgroundTasksToFinish() projectView { path(project.name, "src", "com.company", "Main").doubleClick() waitForBackgroundTasksToFinish() } } } private fun GuiTestCase.openProjectInNewWindow() { val button = GuiTestUtil.waitUntilFound(this.robot(), null, GuiTestUtilKt.typeMatcher(JButton::class.java) { it.text == "New Window" }) this.robot().click(button) } }
community-guitests/testSrc/com/intellij/testGuiFramework/tests/community/SaveFilesOnFrameDeactivationGuiTest.kt
2743953697
package sen.yuan.dao.gluttony_realm import io.realm.RealmObject import io.realm.RealmQuery import io.realm.RealmResults import io.realm.Sort import kotlin.reflect.declaredMemberProperties /** * Created by Administrator on 2016/11/24. */ inline fun <reified T : RealmObject> T.findOneByKey(propertyValue: Any): T? { val mClass = this.javaClass.kotlin val name = "${mClass.simpleName}" var propertyName: String? = null mClass.declaredMemberProperties.forEach { if (it.annotations.map { it.annotationClass }.contains(GluttonyPrimaryKey::class)) { propertyName = it.name } } if (propertyName == null) { throw Exception("$name 类没有设置PrimaryKey") } return Gluttony.realm.where(this.javaClass) .apply { when (propertyValue) { is String -> equalTo(propertyName, propertyValue) is Int -> equalTo(propertyName, propertyValue) is Byte -> equalTo(propertyName, propertyValue) is Short -> equalTo(propertyName, propertyValue) is Long -> equalTo(propertyName, propertyValue) else -> throw Exception("$name 类设置了错误的PrimaryKey的类型") } } .findFirst() } // ///** // * 对单例模式数据的支持:寻找 // * // * 注意:必须有@Singleton注解的Int字段 // * */ //inline fun <reified T : RealmObject> T.findSingleton(): T? { // val mClass = this.javaClass.kotlin // val name = "${mClass.simpleName}" // var propertyName: String? = null // mClass.declaredMemberProperties.forEach { // if (it.annotations.map { it.annotationClass }.contains(Singleton::class)) { // propertyName = it.name // } // } // if (propertyName == null) { // throw Exception("$name 类没有设置 @Singleton 注解的 Int 字段") // } // // return Gluttony.realm.where(this.javaClass) // .apply { // equalTo(propertyName, 1) // } // .findFirst() //} inline fun <reified T : RealmObject> T.findOne(optionFunctor: RealmFinder.() -> Unit): T? { val realmFinder = RealmFinder().apply { optionFunctor() } return Gluttony.realm.where([email protected]) .apply { realmFinder.conditionFunctor?.invoke(this) }.findFirst() } inline fun <reified T : RealmObject> T.findAll(optionFunctor: RealmFinder.() -> Unit): RealmResults<T> { val realmFinder = RealmFinder().apply { optionFunctor() } return Gluttony.realm.where([email protected]) .apply { realmFinder.conditionFunctor?.invoke(this) }.findAll() .let { it.apply { realmFinder.orderFunctor?.invoke(this) } } } class RealmFinder() { var orderFunctor: (RealmResults<*>.() -> RealmResults<*>)? = null var conditionFunctor: (RealmQuery<*>.() -> Unit)? = null inline fun condition(crossinline functor: RealmCondition.() -> RealmCondition): RealmFinder { conditionFunctor = { RealmCondition().apply { functor().functorArray.forEach { it() } } } return this } inline fun <reified T : RealmObject> RealmResults<T>.orderBy(propertyName: String, orderMode: OrderMode): RealmResults<T> { orderFunctor = { sort(propertyName, when (orderMode) { OrderMode.ASC -> Sort.ASCENDING OrderMode.DESC -> Sort.DESCENDING }) } return this } }
gluttony-realm/src/main/java/sen/yuan/dao/gluttony_realm/realm_find.kt
2605742052
package com.stanfy.helium.handler.codegen.objectivec.entity.builder import com.stanfy.helium.handler.codegen.objectivec.entity.ObjCEntitiesOptions import com.stanfy.helium.handler.codegen.objectivec.entity.classtree.ObjCProjectClassesTree import com.stanfy.helium.handler.codegen.objectivec.entity.filetree.ObjCHeaderFile import com.stanfy.helium.handler.codegen.objectivec.entity.filetree.ObjCImplementationFile import com.stanfy.helium.handler.codegen.objectivec.entity.filetree.ObjCProjectFilesStructure /** * Created by paultaykalo on 12/17/15. * Transforms classes tree to the structure of source files */ class ObjCDefaultFileStructureBuilder : ObjCBuilder<ObjCProjectClassesTree, ObjCProjectFilesStructure> { override fun build(from: ObjCProjectClassesTree, options: ObjCEntitiesOptions?): ObjCProjectFilesStructure { val result = ObjCProjectFilesStructure() result.addFiles( from.classes.flatMap { objcClass -> val headerBuilder = ObjCHeaderFileBuilder() val headerFile = ObjCHeaderFile(objcClass.name, headerBuilder.build(objcClass, options)) val implementationFile = ObjCImplementationFile(objcClass.name, objcClass.implementation.asString()) listOf(headerFile, implementationFile) } ) result.addFiles( from.pregeneratedClasses .filter { objClass -> objClass.header != null } .map { objcClass -> ObjCHeaderFile(objcClass.name, objcClass.header!!) } ) result.addFiles( from.pregeneratedClasses .filter { objClass -> objClass.implementation != null } .map { objcClass -> ObjCImplementationFile(objcClass.name, objcClass.implementation!!) } ) return result } }
codegen/objc/objc-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/objectivec/entity/builder/ObjCDefaultFileStructureBuilder.kt
2576454676
package org.wikipedia.feed.view import android.content.Context import android.graphics.LinearGradient import android.graphics.Shader.TileMode import android.graphics.drawable.GradientDrawable import android.util.AttributeSet import android.view.LayoutInflater import android.widget.FrameLayout import androidx.core.content.ContextCompat import org.wikipedia.R import org.wikipedia.databinding.ViewGradientCircleNumberBinding import org.wikipedia.util.ResourceUtil class GradientCircleNumberView constructor(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) { private val binding = ViewGradientCircleNumberBinding.inflate(LayoutInflater.from(context), this) private val gradientColor1 = ResourceUtil.getThemedColor(context, R.attr.colorAccent) private val gradientColor2 = ContextCompat.getColor(context, R.color.green50) private fun applyGradient() { val textShader = LinearGradient(0f, 0f, 0f, binding.numberView.textSize, intArrayOf(gradientColor2, gradientColor1, gradientColor2), floatArrayOf(0f, 0.5f, 1f), TileMode.CLAMP) val gradientDrawable = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(gradientColor1, gradientColor2)) gradientDrawable.cornerRadius = 90f binding.numberView.paint.shader = textShader binding.baseNumberView.background = gradientDrawable } fun setNumber(number: Int) { binding.numberView.text = number.toString() applyGradient() } }
app/src/main/java/org/wikipedia/feed/view/GradientCircleNumberView.kt
4054270843
package com.ashish.movieguide.data.models import com.squareup.moshi.Json /** * Created by Ashish on Dec 31. */ data class Results<out I>( val page: Int = 1, val results: List<I>? = null, @Json(name = "total_pages") val totalPages: Int = 0 )
app/src/main/kotlin/com/ashish/movieguide/data/models/Results.kt
826346288
package com.tungnui.dalatlaptop.ux import android.app.Activity import android.app.ProgressDialog import android.content.Intent import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import android.view.View import com.facebook.appevents.AppEventsLogger import com.tungnui.dalatlaptop.MyApplication import com.tungnui.dalatlaptop.R import com.tungnui.dalatlaptop.libraryhelper.Utils import kotlinx.android.synthetic.main.activity_splash.* import timber.log.Timber class SplashActivity : AppCompatActivity() { private var activity: Activity? = null private lateinit var progressDialog: ProgressDialog private var layoutCreated = false private var windowDetached = false public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Timber.tag(TAG) activity = this // init loading dialog progressDialog = Utils.generateProgressDialog(this, false) init() } private fun init() { // Check if data connected. if (MyApplication.instance?.isDataConnected == false) { progressDialog.hide() initSplashLayout() splash_content.visibility = View.VISIBLE splash_intro_screen.visibility = View.GONE splash_content_no_connection.visibility = View.VISIBLE } else { progressDialog.hide() startMainActivity(null) } } private fun initSplashLayout() { if (!layoutCreated) { setContentView(R.layout.activity_splash) splash_re_run_btn.setOnClickListener { progressDialog.show() Handler().postDelayed({ init() }, 600) } layoutCreated=true } else { Timber.d("%s screen is already created.", this.javaClass.simpleName) } } private fun startMainActivity(bundle: Bundle?) { val mainIntent = Intent(this@SplashActivity, MainActivity::class.java) startActivity(mainIntent) finish() } override fun onResume() { super.onResume() AppEventsLogger.activateApp(this) } override fun onPause() { super.onPause() AppEventsLogger.deactivateApp(this) } override fun onStop() { progressDialog.cancel() splash_intro_screen.visibility = View.GONE splash_content.visibility = View.VISIBLE super.onStop() } override fun onAttachedToWindow() { windowDetached = false super.onAttachedToWindow() } override fun onDetachedFromWindow() { windowDetached = true super.onDetachedFromWindow() } companion object { val REFERRER = "referrer" private val TAG = SplashActivity::class.java.simpleName } }
app/src/main/java/com/tungnui/dalatlaptop/ux/SplashActivity.kt
4162495559
package katas.kotlin.leetcode.wildcard_matching.v4 import datsok.shouldEqual import org.junit.Test typealias Matcher = (String) -> Set<String> fun char(char: Char): Matcher = { s -> if (s.firstOrNull() == char) setOf(s.drop(1)) else emptySet() } fun anyChar(): Matcher = { s -> if (s.isNotEmpty()) setOf(s.drop(1)) else emptySet() } fun anyChars(): Matcher = { s -> (0..s.length).mapTo(HashSet()) { s.drop(it) } } fun isMatch(s: String, pattern: String): Boolean { val matchers = pattern.map { when (it) { '?' -> anyChar() '*' -> anyChars() else -> char(it) } } return matchers .fold(setOf(s)) { outputs, matcher -> outputs.flatMapTo(HashSet()) { matcher(it) } } .any { output -> output.isEmpty() } } // ✅ class WildcardMatching { @Test fun `some examples`() { isMatch("a", "a") shouldEqual true isMatch("a", "b") shouldEqual false isMatch("aa", "aa") shouldEqual true isMatch("aa", "a") shouldEqual false isMatch("a", "aa") shouldEqual false isMatch("", "*") shouldEqual true isMatch("a", "*") shouldEqual true isMatch("aa", "*") shouldEqual true isMatch("aa", "**") shouldEqual true isMatch("aa", "***") shouldEqual true isMatch("aa", "*a") shouldEqual true isMatch("aa", "a*") shouldEqual true isMatch("aa", "*aa") shouldEqual true isMatch("aa", "a*a") shouldEqual true isMatch("aa", "aa*") shouldEqual true isMatch("aa", "*b") shouldEqual false isMatch("aa", "b*") shouldEqual false isMatch("adceb", "*a*b") shouldEqual true isMatch("a", "?") shouldEqual true isMatch("cb", "?a") shouldEqual false isMatch("acdcb", "a*c?b") shouldEqual false } }
kotlin/src/katas/kotlin/leetcode/wildcard_matching/v4/WildcardMatching.kt
2931065855
// FIR_IDENTICAL open class A { open fun Int.foo(): Int { return 0 } } class B: A() { <caret> }
plugins/kotlin/idea/tests/testData/codeInsight/overrideImplement/overrideExtensionFunction.kt
1596668684
package com.theah64.mock_api.servlets import com.theah64.mock_api.utils.APIResponse import com.theah64.webengine.utils.PathInfo import com.theah64.webengine.utils.Request import com.thedeanda.lorem.Lorem import com.thedeanda.lorem.LoremIpsum import org.json.JSONException import javax.servlet.annotation.WebServlet import java.io.IOException import java.sql.SQLException @WebServlet(urlPatterns = ["/v1/get_random"]) class GetRandomServlet : AdvancedBaseServlet() { override val isSecureServlet: Boolean get() = false override val requiredParameters: Array<String>? @Throws(Request.RequestException::class) get() = arrayOf(KEY_RANDOM_WHAT, KEY_COUNT) @Throws(Request.RequestException::class, IOException::class, JSONException::class, SQLException::class, PathInfo.PathInfoException::class) override fun doAdvancedPost() { val randomWhat = getStringParameter(KEY_RANDOM_WHAT) val count = getIntParameter(KEY_COUNT, 1) val output: String val lorem = LoremIpsum.getInstance() when (randomWhat) { TYPE_WORDS -> output = capitalize(lorem.getWords(count, count)) TYPE_PARAGRAPHS -> output = lorem.getParagraphs(count, count) TYPE_NAME -> output = lorem.name TYPE_PHONE -> output = lorem.phone TYPE_CITY -> output = lorem.city TYPE_STATE -> output = lorem.stateFull TYPE_COUNTRY -> output = lorem.country TYPE_MALE_NAME -> output = lorem.nameMale TYPE_FEMALE_NAME -> output = lorem.nameFemale TYPE_FIRST_NAME -> output = lorem.firstName TYPE_LAST_NAME -> output = lorem.lastName else -> throw Request.RequestException("Invalid randomWhat: $randomWhat") } writer!!.write(APIResponse("Done", "random_output", output).response) } private fun capitalize(line: String): String { return Character.toUpperCase(line[0]) + line.substring(1) } companion object { private val KEY_RANDOM_WHAT = "random_what" private val KEY_COUNT = "count" private val TYPE_WORDS = "words" private val TYPE_PARAGRAPHS = "paragraphs" private val TYPE_NAME = "name" private val TYPE_PHONE = "phone" private val TYPE_CITY = "city" private val TYPE_STATE = "state" private val TYPE_COUNTRY = "country" private val TYPE_MALE_NAME = "male_name" private val TYPE_FEMALE_NAME = "female_name" private val TYPE_FIRST_NAME = "first_name" private val TYPE_LAST_NAME = "last_name" } }
src/com/theah64/mock_api/servlets/GetRandomServlet.kt
2948106136
package com.intellij.codeInspection.tests import com.intellij.codeInspection.InspectionProfileEntry import com.intellij.codeInspection.InspectionsBundle import com.intellij.openapi.application.PathManager import com.intellij.openapi.roots.LanguageLevelProjectExtension import com.intellij.pom.java.LanguageLevel import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.InspectionTestUtil import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase import java.io.File abstract class UastInspectionTestBase : LightJavaCodeInsightFixtureTestCase() { override fun getTestDataPath(): String = PathManager.getCommunityHomePath().replace(File.separatorChar, '/') + basePath abstract val inspection: InspectionProfileEntry open val languageLevel = LanguageLevel.JDK_11 open val sdkLevel = LanguageLevel.JDK_11 override fun setUp() { super.setUp() myFixture.enableInspections(inspection) LanguageLevelProjectExtension.getInstance(project).languageLevel = languageLevel } override fun getProjectDescriptor(): LightProjectDescriptor = ProjectDescriptor(sdkLevel) protected fun JavaCodeInsightTestFixture.setLanguageLevel(languageLevel: LanguageLevel) { LanguageLevelProjectExtension.getInstance(project).languageLevel = languageLevel IdeaTestUtil.setModuleLanguageLevel(myFixture.module, languageLevel, testRootDisposable) } protected fun JavaCodeInsightTestFixture.testHighlighting( lang: ULanguage, text: String, fileName: String = generateFileName() ) { configureByText("$fileName${lang.ext}", text) checkHighlighting() } protected fun JavaCodeInsightTestFixture.testQuickFix( lang: ULanguage, before: String, after: String, vararg hints: String = arrayOf(InspectionsBundle.message( "fix.all.inspection.problems.in.file", InspectionTestUtil.instantiateTool(inspection.javaClass).displayName )), fileName: String = generateFileName() ) { configureByText("$fileName${lang.ext}", before) hints.forEach { runQuickFix(it) } checkResult(after) } protected fun JavaCodeInsightTestFixture.testQuickFix(file: String, hint: String = InspectionsBundle.message( "fix.all.inspection.problems.in.file", InspectionTestUtil.instantiateTool(inspection.javaClass).displayName )) { configureByFile(file) runQuickFix(hint) checkResultByFile(file.replace(".", ".after.")) } private fun JavaCodeInsightTestFixture.runQuickFix(hint: String) { val action = getAvailableIntention(hint) ?: throw AssertionError("Quickfix '$hint' is not available.") launchAction(action) } protected fun JavaCodeInsightTestFixture.testQuickFixUnavailable( lang: ULanguage, text: String, hint: String = InspectionsBundle.message( "fix.all.inspection.problems.in.file", InspectionTestUtil.instantiateTool(inspection.javaClass).displayName ), fileName: String = generateFileName() ) { configureByText("$fileName${lang.ext}", text) assertEmpty("Quickfix '$hint' is available but should not.", myFixture.filterAvailableIntentions(hint)) } protected fun JavaCodeInsightTestFixture.testQuickFixUnavailable(file: String, hint: String = InspectionsBundle.message( "fix.all.inspection.problems.in.file", InspectionTestUtil.instantiateTool(inspection.javaClass).displayName )) { configureByFile(file) assertEmpty("Quickfix '$hint' is available but should not.", myFixture.filterAvailableIntentions(hint)) } private fun generateFileName() = getTestName(false).replace("[^a-zA-Z0-9\\.\\-]", "_") override fun tearDown() { try { myFixture.disableInspections(inspection) } finally { super.tearDown() } } }
jvm/jvm-analysis-tests/src/com/intellij/codeInspection/tests/UastInspectionTestBase.kt
1351281041
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.test.kt import com.github.jonathanxd.kores.Types import com.github.jonathanxd.kores.base.ClassDeclaration import com.github.jonathanxd.kores.base.KoresModifier import com.github.jonathanxd.kores.base.ConstructorDeclaration import com.github.jonathanxd.kores.base.TypeDeclaration import com.github.jonathanxd.kores.factory.source import com.github.jonathanxd.kores.factory.variable import com.github.jonathanxd.kores.literal.* import com.github.jonathanxd.kores.util.conversion.toLiteral import org.junit.Test class LiteralTest_ { fun `$`(): TypeDeclaration { return ClassDeclaration.Builder.builder() .modifiers(KoresModifier.PUBLIC) .qualifiedName("test." + LiteralTest_::class.java.simpleName) .constructors(ConstructorDeclaration.Builder.builder() .modifiers(KoresModifier.PUBLIC) .body(source( variable(Types.BOOLEAN, "bool", falseLiteral()), variable(Types.CHAR, "char", char('c')), variable(Types.BYTE, "byte", byte(0)), variable(Types.SHORT, "short", short(0)), variable(Types.INT, "int", int(0)), variable(Types.FLOAT, "float", float(1.0F)), variable(Types.DOUBLE, "double", double(0.0009)), variable(Types.LONG, "long", long(10000000000L)), variable(Types.CLASS, "class", type(String::class.java)), variable(Types.STRING, "string", string("Hello")), variable(Types.STRING, "string2", "Hello".toLiteral()) )) .build()) .build() } @Test fun test() { `$`() } }
src/test/kotlin/com/github/jonathanxd/kores/test/kt/LiteralTest_.kt
3400461391
package com.becypress.android.demo import org.junit.Assert.assertEquals import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
yframework-android/app/src/test/java/com/becypress/android/demo/ExampleUnitTest.kt
192157923
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jem.crawler import jclp.KeyedService import jclp.ServiceManager import jclp.setting.Settings import jem.Book import jem.Chapter import jem.epm.EpmFactory import jem.epm.Parser import jem.epm.ParserException import java.io.InterruptedIOException import java.net.URL import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime const val ATTR_CHAPTER_UPDATE_TIME = "updateTime" const val ATTR_CHAPTER_SOURCE_URL = "sourceUrl" const val EXT_CRAWLER_BOOK_ID = "jem.ext.crawler.bookId" const val EXT_CRAWLER_SOURCE_URL = "jem.ext.crawler.sourceUrl" const val EXT_CRAWLER_SOURCE_SITE = "jem.ext.crawler.sourceSite" const val EXT_CRAWLER_LAST_CHAPTER = "jem.ext.crawler.lastChapter" const val EXT_CRAWLER_UPDATE_TIME = "jem.ext.crawler.updateTime" val Book.crawlerTime: LocalDateTime? get() = extensions[EXT_CRAWLER_UPDATE_TIME]?.let { when (it) { is LocalDateTime -> it is LocalDate -> it.atTime(8, 0) is LocalTime -> it.atDate(LocalDate.now()) else -> throw IllegalStateException("Invalid value for $EXT_CRAWLER_UPDATE_TIME") } } interface Crawler { fun getBook(url: String, settings: Settings?): Book fun getText(url: String, settings: Settings?): String { throw NotImplementedError() } } interface CrawlerFactory : KeyedService { fun getCrawler(): Crawler } object CrawlerManager : ServiceManager<CrawlerFactory>(CrawlerFactory::class.java) { fun getCrawler(host: String) = get(host)?.getCrawler() fun fetchBook(url: String, settings: Settings?) = getCrawler(URL(url).host)?.getBook(url, settings) } abstract class ReusableCrawler : Crawler, CrawlerFactory { override fun getCrawler(): Crawler = this protected fun Chapter.setText(url: String, settings: Settings?) { text = CrawlerText(url, this, this@ReusableCrawler, settings) this[ATTR_CHAPTER_SOURCE_URL] = url } protected open fun fetchPage(page: Int, arg: Any): Int { throw NotImplementedError() } protected fun fetchContents(arg: Any) { for (i in 2 until fetchPage(1, arg)) { if (Thread.interrupted()) throw InterruptedIOException() fetchPage(i, arg) } } } class CrawlerParser : Parser, EpmFactory { override val name = "Book Crawler" override val keys = setOf("crawler", "net") override val hasParser = true override val parser = this override fun parse(input: String, arguments: Settings?): Book { return CrawlerManager.fetchBook(input, arguments) ?: throw ParserException(M.tr("err.crawler.unsupported", input)) } }
jem-crawler/src/main/kotlin/jem/crawler/CrawlerSpec.kt
337705757
package i_introduction._9_Extension_Functions import org.junit.Assert import org.junit.Test class _08_Extension_Functions() { @Test fun testIntExtension() { Assert.assertEquals("Rational number creation error: ", RationalNumber(4, 1), 4.r()) } @Test fun testPairExtension() { Assert.assertEquals("Rational number creation error: ", RationalNumber(2, 3), Pair(2, 3).r()) } }
test/i_introduction/_9_Extension_Functions/_08_Extension_Functions.kt
638277288
import java.awt.Polygon import java.awt.Rectangle import kotlin.experimental.* fun topLevelMethod(x: Int, y: Int, byx: Byte, byy: Byte, sx: Short, sy: Short, lx: Long, ly: Long, dx: Double, dy: Double, fx: Float, fy: Float, ): Int { val i1 = 1 val i2 = x + y val i3 = x - y val i4 = x / y val i5 = x % y val i6 = x shl y val i7 = x shr y val i8 = x ushr y val i9 = x and y val i10 = x or y val i11 = x xor y val i12 = x.inv() val i13 = x == y val i14 = x != y val i15 = x < y val i16 = x <= y val i17 = x > y val i18 = x >= y val i19 = x === y val i20 = x !== y val i21 = x in x .. y val i22 = x !in x .. y val by1 = 1.0 val by2 = byx + byy val by3 = byx - byy val by4 = byx / byy val by5 = byx % byy val by6 = byx == byy val by7 = byx != byy val by8 = byx < byy val by9 = byx <= byy val by10 = byx > byy val by11 = byx >= byy val by12 = byx === byy val by13 = byx !== byy val by14 = byx or byy val by15 = byx and byy val by16 = byx xor byy val s1 = 1.0 val s2 = sx + sy val s3 = sx - sy val s4 = sx / sy val s5 = sx % sy val s6 = sx == sy val s7 = sx != sy val s8 = sx < sy val s9 = sx <= sy val s10 = sx > sy val s11 = sx >= sy val s12 = sx === sy val s13 = sx !== sy val s14 = sx or sy val s15 = sx and sy val s16 = sx xor sy val l1 = 1.0 val l2 = lx + ly val l3 = lx - ly val l4 = lx / ly val l5 = lx % ly val l6 = lx shl y val l7 = lx shr y val l8 = lx ushr y val l9 = lx and ly val l10 = lx or ly val l11 = lx xor ly val l12 = lx.inv() val l13 = lx == ly val l14 = lx != ly val l15 = lx < ly val l16 = lx <= ly val l17 = lx > ly val l18 = lx >= ly val l19 = lx === ly val l20 = lx !== ly val d1 = 1.0 val d2 = dx + dy val d3 = dx - dy val d4 = dx / dy val d5 = dx % dy val d6 = dx == dy val d7 = dx != dy val d8 = dx < dy val d9 = dx <= dy val d10 = dx > dy val d11 = dx >= dy val d12 = dx === dy val d13 = dx !== dy val f1 = 1.0 val f2 = fx + fy val f3 = fx - fy val f4 = fx / fy val f5 = fx % fy val f6 = fx == fy val f7 = fx != fy val f8 = fx < fy val f9 = fx <= fy val f10 = fx > fy val f11 = fx >= fy val f12 = fx === fy val f13 = fx !== fy val b1 = true val b2 = false val b3 = b1 && b2 val b4 = b1 || b2 val b5 = !b1 val c = 'x' val str = "string lit" val strWithQuote = "string \" lit" val b6 = i1 is Int val b7 = i1 !is Int val b8 = b7 as Boolean val str1: String = "string lit" val str2: String? = "string lit" val str3: String? = null val str4: String = "foo $str1 bar $str2 baz" val str5: String = "foo ${str1 + str2} bar ${str2 + str1} baz" val str6 = str1 + str2 var variable = 10 while (variable > 0) { variable-- } return 123 + 456 } fun getClass() { val d = true::class } class C(val n: Int) { fun foo(): C { return C(42) } } open class Root {} class Subclass1: Root() {} class Subclass2: Root() {} fun typeTests(x: Root, y: Subclass1) { if(x is Subclass1) { val x1: Subclass1 = x } val y1: Subclass1 = if (x is Subclass1) { x } else { y } var q = 1 if (x is Subclass1) { q = 2 } else { q = 3 } } fun foo(p: Polygon) { val r = p.getBounds() if(r != null) { val r2: Rectangle = r val height = r2.height r2.height = 3 } } enum class Direction { NORTH, SOUTH, WEST, EAST } enum class Color(val rgb: Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF) } fun enums() { val south = Direction.SOUTH val green = Color.GREEN } interface Interface1 {} class Class1 { val a1 = 1 private fun getObject() : Any { val a2 = 2 return object : Interface1 { val a3: String = (a1 + a2).toString() } } } fun notNullAssertion(x: Any?) { val y: Any = x!! } class Class2 { fun x(aa: Any?, s: String?) { val a = aa.toString() val b0 = s.plus(5) val b1 = s + 5 val b2 = s!!.plus(5) val b3 = s!! + 5 val c0 = enumValues<Color>() val c1 = Color.values() val d0 = enumValueOf<Color>("GREEN") val d1 = Color.valueOf("GREEN") } } fun todo() { TODO() } class SomeClass1 {} fun fnClassRef() { val x = SomeClass1::class } fun equalityTests(notNullPrimitive: Int, nullablePrimitive: Int?, notNullReftype: String, nullableReftype: String?) { val b1 = notNullPrimitive == notNullPrimitive val b2 = notNullPrimitive == nullablePrimitive val b3 = nullablePrimitive == nullablePrimitive val b4 = notNullReftype == notNullReftype val b5 = notNullReftype == nullableReftype val b6 = nullableReftype == nullableReftype val b7 = notNullPrimitive != notNullPrimitive val b8 = notNullPrimitive != nullablePrimitive val b9 = nullablePrimitive != nullablePrimitive val b10 = notNullReftype != notNullReftype val b11 = notNullReftype != nullableReftype val b12 = nullableReftype != nullableReftype val b13 = notNullPrimitive == null val b14 = nullablePrimitive == null val b15 = notNullReftype == null val b16 = nullableReftype == null val b17 = notNullPrimitive != null val b18 = nullablePrimitive != null val b19 = notNullReftype != null val b20 = nullableReftype != null } fun mulOperators(x: Int, y: Int, byx: Byte, byy: Byte, sx: Short, sy: Short, lx: Long, ly: Long, dx: Double, dy: Double, fx: Float, fy: Float) { val i = x * y val b = byx * byy val l = lx * ly val d = dx * dy val f = fx * fy } fun inPlaceOperators() { var updated = 0 updated += 1 updated -= 1 updated *= 1 updated /= 1 updated %= 1 } inline fun <reified T : Enum<T>> getEnumValues() = enumValues<T>() fun callToEnumValues() { enumValues<Color>() getEnumValues<Color>() } fun unaryExprs(i: Int, d: Double, b: Byte, s: Short, l: Long, f: Float) { -i +i -d +d var i0 = 1 val i1 = 1 i0++ ++i0 i0-- --i0 i0.inc() i0.dec() i1.inc() i1.dec() i.inv() -b +b var b0: Byte = 1 val b1: Byte = 1 b0++ ++b0 b0-- --b0 b0.inc() b0.dec() b1.inc() b1.dec() b.inv() -s +s var s0: Short = 1 val s1: Short = 1 s0++ ++s0 s0-- --s0 s0.inc() s0.dec() s1.inc() s1.dec() s.inv() -l +l var l0: Long = 1 val l1: Long = 1 l0++ ++l0 l0-- --l0 l0.inc() l0.dec() l1.inc() l1.dec() l.inv() +f -f } // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Byte.dec in java.lang.Byte % // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Byte.inc in java.lang.Byte % // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Byte.toInt in java.lang.Byte % // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Int.dec in java.lang.Integer % // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Int.inc in java.lang.Integer % // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Int.rangeTo in java.lang.Integer % // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Short.inc in java.lang.Short % // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Short.dec in java.lang.Short % // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Short.toInt in java.lang.Short % // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Long.dec in java.lang.Long % // Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Long.inc in java.lang.Long %
java/ql/test/kotlin/library-tests/exprs/exprs.kt
3978116637
package net.nemerosa.ontrack.repository.support.store import net.nemerosa.ontrack.model.structure.ProjectEntity import java.time.LocalDateTime class EntityDataStoreFilter @JvmOverloads constructor( val entity: ProjectEntity? = null, val category: String? = null, val name: String? = null, val group: String? = null, val beforeTime: LocalDateTime? = null, val offset: Int = 0, val count: Int = 20 ) { fun withEntity(entity: ProjectEntity?) = EntityDataStoreFilter( entity, category, name, group, beforeTime, offset, count ) fun withCategory(category: String?) = EntityDataStoreFilter( entity, category, name, group, beforeTime, offset, count ) fun withName(name: String?) = EntityDataStoreFilter( entity, category, name, group, beforeTime, offset, count ) fun withGroup(group: String?) = EntityDataStoreFilter( entity, category, name, group, beforeTime, offset, count ) fun withBeforeTime(beforeTime: LocalDateTime?) = EntityDataStoreFilter( entity, category, name, group, beforeTime, offset, count ) fun withOffset(offset: Int) = EntityDataStoreFilter( entity, category, name, group, beforeTime, offset, count ) fun withCount(count: Int) = EntityDataStoreFilter( entity, category, name, group, beforeTime, offset, count ) }
ontrack-repository-support/src/main/java/net/nemerosa/ontrack/repository/support/store/EntityDataStoreFilter.kt
2938023600
package com.octtoplus.proj.recorda import org.json.JSONObject class JSON private constructor() { companion object { fun create(block: JSONBuilder.() -> Unit) = JSONBuilder(block).build() } class JSONBuilder private constructor() { constructor(init: JSONBuilder.() -> Unit) : this() { init() } var addedCount: Int? = null var beforeText: CharSequence? = null var className: CharSequence? = null var contentDescription: CharSequence? = null var currentItemIndex: Int? = null var eventText: CharSequence? = null var eventTime: Long? = null var eventType: CharSequence? = null var resourceIdName: CharSequence? = null var fromIndex: Int? = null var isChecked: Boolean? = null var isEnable: Boolean? = null var isPassword: Boolean? = null var itemCount: Int? = null var packageName: CharSequence? = null var scrollX: Int? = null var scrollY: Int? = null var toIndex: Int? = null var removedCount: Int? = null var resource_id: CharSequence? = null fun className(block: JSONBuilder.() -> CharSequence) = apply { className = block() } fun contentDescription(block: JSONBuilder.() -> CharSequence) = apply { contentDescription = block() } fun eventTime(block: JSONBuilder.() -> Long) = apply { eventTime = block() } fun eventType(block: JSONBuilder.() -> CharSequence) = apply { eventType = block() } fun resourceIdName(block: JSONBuilder.() -> CharSequence) = apply { resourceIdName = block() } fun build() = JSONObject().build(this) /* put("className", event.className) put("contentDescription", event.contentDescription) put("eventText", getEventText(event)) put("eventTime", java.lang.Long.toString(event.eventTime)) put("eventType", AccessibilityEvent.eventTypeToString(event.eventType)) put("fromIndex", event.fromIndex) put("isChecked", event.isChecked) put("isEnable", event.isEnabled) put("isPassword", event.isPassword) put("itemCount", event.itemCount) put("packageName", event.packageName) put("toIndex", event.toIndex) put("resource-id", event.source.viewIdResourceName) */ } } fun JSONObject.build(builder: JSON.JSONBuilder): JSONObject { apply { builder.addedCount?.let { put("addedCount", it.toString()) } builder.beforeText?.let { put("beforeText", it.toString()) } builder.className?.let { put("className", it.toString()) } builder.contentDescription?.let { put("contentDescription", it.toString()) } builder.currentItemIndex?.let { put("currentItemIndex", it.toString()) } builder.eventText?.let { put("eventText", it.toString()) } builder.eventTime?.let { put("eventTime", it.toString()) } builder.eventType?.let { put("eventType", it.toString()) } builder.resourceIdName?.let { put("resource-id", it.toString()) } builder.fromIndex?.let { put("fromIndex", it.toString()) } builder.isChecked?.let { put("isChecked", it.toString()) } builder.isEnable?.let { put("isEnable", it.toString()) } builder.isPassword?.let { put("isPassword", it.toString()) } builder.itemCount?.let { put("itemCount", it.toString()) } builder.packageName?.let { put("packageName", it.toString()) } builder.scrollX?.let { put("scrollX", it.toString()) } builder.scrollY.let { put("scrollY", it.toString()) } builder.toIndex?.let{ put("toIndex", it.toString()) } builder.removedCount?.let { put("removedCount", it.toString()) } builder.resource_id?.let { put("resource-id", it.toString()) } } return this }
app/src/main/kotlin/com/octtoplus/proj/recorda/JSONBuilder.kt
2830006853
package org.craftsmenlabs.socketoutlet.core import mockit.Tested import org.assertj.core.api.Assertions.assertThat import org.junit.Test class OutletRegistryTest { @Tested lateinit var outletRegistry: OutletRegistry private var outlet1 = TestOutlet<TestData1>(TestData1::class.java) private var outlet2 = TestOutlet<TestData2>(TestData2::class.java) data class TestData1(val message: String) data class TestData2(val message: String) @Test fun shouldGetClassByName() { val expectedClazz1 = TestData1::class.java val expectedClazz2 = TestData2::class.java outletRegistry.register(outlet1) outletRegistry.register(outlet2) val actualClazz1 = outletRegistry.getClazz(expectedClazz1.simpleName) val actualClazz2 = outletRegistry.getClazz(expectedClazz2.simpleName) assertThat(actualClazz1).isSameAs(expectedClazz1) assertThat(actualClazz2).isSameAs(expectedClazz2) } @Test fun shouldGetOutletByName() { val expectedClazz1 = TestData1::class.java val expectedClazz2 = TestData2::class.java outletRegistry.register(outlet1) outletRegistry.register(outlet2) val actualOutlet1 = outletRegistry.getOutlet(expectedClazz1.simpleName) val actualOutlet2 = outletRegistry.getOutlet(expectedClazz2.simpleName) assertThat(actualOutlet1).isSameAs(outlet1) assertThat(actualOutlet2).isSameAs(outlet2) } class TestOutlet<T>(clazz: Class<T>) : Outlet<T>(clazz) { var message: T? = null override fun onMessage(message: T, egress: Egress) { this.message = message } } }
core/src/test/java/org/craftsmenlabs/socketoutlet/core/OutletRegistryTest.kt
667147878
package net.nemerosa.ontrack.extension.git.branching import net.nemerosa.ontrack.model.support.NameValue class BranchingModelProperty( val patterns: List<NameValue> )
ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/branching/BranchingModelProperty.kt
3135857415
package net.nemerosa.ontrack.extension.api /** * Provides some caches which can be configured. */ interface CacheConfigExtension { /** * List of configurable caches. * * Returns a map whose key is the cache name, and the value is a * `com.github.benmanes.caffeine.cache.CaffeineSpec` string specification. */ val caches: Map<String, String> }
ontrack-extension-api/src/main/java/net/nemerosa/ontrack/extension/api/CacheConfigExtension.kt
1505098202
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.statistics import com.intellij.internal.statistic.beans.ConvertUsagesUtil import com.intellij.internal.statistic.beans.UsageDescriptor import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.internal.statistic.utils.getBooleanUsage import com.intellij.internal.statistic.utils.getEnumUsage import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.SdkType import org.jetbrains.plugins.gradle.service.settings.GradleSettingsService import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.settings.GradleSettings class GradleSettingsCollector : ProjectUsagesCollector() { override fun getGroupId() = "build.gradle.state" override fun getUsages(project: Project): Set<UsageDescriptor> { val gradleSettings = GradleSettings.getInstance(project) val projectsSettings = gradleSettings.linkedProjectsSettings if (projectsSettings.isEmpty()) { return emptySet() } val usages = mutableSetOf<UsageDescriptor>() // global settings usages.add(getBooleanUsage("offlineWork", gradleSettings.isOfflineWork)) usages.add(getBooleanUsage("showSelectiveImportDialogOnInitialImport", gradleSettings.showSelectiveImportDialogOnInitialImport())) val settingsService = GradleSettingsService.getInstance(project) // project settings for (setting in gradleSettings.linkedProjectsSettings) { val projectPath = setting.externalProjectPath usages.add(getYesNoUsage("isCompositeBuilds", setting.compositeBuild != null)) usages.add(getEnumUsage("distributionType", setting.distributionType)) usages.add(getEnumUsage("storeProjectFilesExternally", setting.storeProjectFilesExternally)) usages.add(getBooleanUsage("disableWrapperSourceDistributionNotification", setting.isDisableWrapperSourceDistributionNotification)) usages.add(getBooleanUsage("createModulePerSourceSet", setting.isResolveModulePerSourceSet)) usages.add(UsageDescriptor("gradleJvm." + ConvertUsagesUtil.escapeDescriptorName(getGradleJvmName(setting, project) ?: "empty"), 1)) val gradleVersion = setting.resolveGradleVersion() if(gradleVersion.isSnapshot) { usages.add(UsageDescriptor("gradleVersion." + gradleVersion.baseVersion.version + ".SNAPSHOT", 1)) } else { usages.add(UsageDescriptor("gradleVersion." + gradleVersion.version, 1)) } usages.add(getBooleanUsage("delegateBuildRun", settingsService.isDelegatedBuildEnabled(projectPath))) usages.add(getEnumUsage("preferredTestRunner", settingsService.getTestRunner(projectPath))) } return usages } private fun getGradleJvmName(setting: GradleProjectSettings, project: Project): String? { val jdk = ExternalSystemJdkUtil.getJdk(project, setting.gradleJvm) val sdkType = jdk?.sdkType return if (sdkType is SdkType) { sdkType.suggestSdkName(null, jdk.homePath) } else setting.gradleJvm } private fun getYesNoUsage(key: String, value: Boolean): UsageDescriptor { return UsageDescriptor(key + if (value) ".yes" else ".no", 1) } }
plugins/gradle/src/org/jetbrains/plugins/gradle/statistics/GradleSettingsCollector.kt
1742066374
package backend.view.challenge import backend.converter.MoneySerializer import backend.view.SponsorTeamProfileView import com.fasterxml.jackson.databind.annotation.JsonSerialize class ChallengeTeamProfileView( val id: Long?, @JsonSerialize(using = MoneySerializer::class) val amount: org.javamoney.moneta.Money, val description: String, val status: String, val fulfilledCount: Int, val maximumCount: Int?, val sponsor: SponsorTeamProfileView?)
src/main/java/backend/view/challenge/ChallengeTeamProfileView.kt
3492717042
package hm.orz.chaos114.android.slideviewer.infra.repository import android.content.Context import com.j256.ormlite.dao.Dao import hm.orz.chaos114.android.slideviewer.infra.dao.TalkDao import hm.orz.chaos114.android.slideviewer.infra.model.Slide import hm.orz.chaos114.android.slideviewer.infra.model.Talk import hm.orz.chaos114.android.slideviewer.infra.model.TalkMetaData import hm.orz.chaos114.android.slideviewer.infra.util.DatabaseHelper import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.Maybe import io.reactivex.MaybeOnSubscribe import java.io.IOException import java.sql.SQLException import java.util.* class TalkRepository(private val mContext: Context) { fun findByUrl(url: String): Maybe<Talk> { return Maybe.create(MaybeOnSubscribe { emitter -> val helper = DatabaseHelper(mContext) try { val dao = helper.getDao<Dao<Talk, Int>, Talk>(Talk::class.java) val talks = dao.queryForEq("url", url) if (talks.isEmpty()) { emitter.onComplete() return@MaybeOnSubscribe } val talk = talks[0] setTalkInfo(talk) emitter.onSuccess(talk) emitter.onComplete() } catch (e: SQLException) { throw RuntimeException(e) } finally { helper.close() } }) } fun list(): Flowable<List<Talk>> { return Flowable.create({ emitter -> val helper = DatabaseHelper(mContext) try { val dao = helper.getDao<Dao<Talk, Int>, Talk>(Talk::class.java) val talks = dao.query(dao.queryBuilder().orderBy("id", false).limit(50L).prepare()) for (talk in talks) { setTalkInfo(talk) } emitter.onNext(talks) } catch (e: SQLException) { throw RuntimeException(e) } finally { helper.close() } }, BackpressureStrategy.LATEST) } fun count(): Long { val helper = DatabaseHelper(mContext) try { val dao = helper.getDao<Dao<Talk, Int>, Talk>(Talk::class.java) return dao.countOf() } catch (e: SQLException) { throw RuntimeException(e) } finally { helper.close() } } fun deleteByUrl(url: String) { val dao = TalkDao(mContext) dao.deleteByUrl(url) } fun findMetaData(talk: Talk): TalkMetaData? { val dao = TalkDao(mContext) return dao.findMetaData(talk) } fun saveIfNotExists(talk: Talk, slides: List<Slide>, talkMetaData: TalkMetaData) { val dao = TalkDao(mContext) dao.saveIfNotExists(talk, slides, talkMetaData) } private fun setTalkInfo(talk: Talk) { val iterator = talk.slideCollection!!.closeableIterator() try { val slides = ArrayList<Slide>() while (iterator.hasNext()) { val slide = iterator.next() slides.add(slide) } talk.slides = slides } finally { try { iterator.close() } catch (e: IOException) { // no-op } } } }
modules/infra/src/main/java/hm/orz/chaos114/android/slideviewer/infra/repository/TalkRepository.kt
4216808197
package com.cv4j.app.fragment import android.content.res.Resources import android.graphics.* 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.app.BaseFragment import com.cv4j.core.datamodel.CV4JImage import com.cv4j.core.datamodel.Point import com.cv4j.core.tpl.TemplateMatch import com.cv4j.image.util.Tools import kotlinx.android.synthetic.main.fragment_template_match.* /** * * @FileName: * com.cv4j.app.fragment.TemplateMatchFragment * @author: Tony Shen * @date: 2020-05-04 13:12 * @version: V1.0 <描述当前版本功能> */ class TemplateMatchFragment : BaseFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_template_match, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initData() } private fun initData() { val res: Resources = resources val bitmap1 = BitmapFactory.decodeResource(res, R.drawable.test_tpl_target) target_image.setImageBitmap(bitmap1) val bitmap2 = BitmapFactory.decodeResource(res, R.drawable.tpl) template_image.setImageBitmap(bitmap2) val targetCV4J = CV4JImage(bitmap1) val targetImageProcessor = targetCV4J.convert2Gray().processor val templateCV4J = CV4JImage(bitmap2) val templateProcessor = templateCV4J.convert2Gray().processor val match = TemplateMatch() val floatProcessor = match.match(targetImageProcessor, templateProcessor, TemplateMatch.TM_CCORR_NORMED) val points = Tools.getMinMaxLoc(floatProcessor.gray, floatProcessor.width, floatProcessor.height) var resultPoint: Point? = null if (points != null) { resultPoint = points[0] val resultBitmap = bitmap1.copy(Bitmap.Config.ARGB_8888, true) val canvas = Canvas(resultBitmap) val rect = Rect() val sx = resultPoint.x + templateProcessor.width / 2 val sy = resultPoint.y - templateProcessor.height / 2 rect[sx, sy, sx + templateProcessor.width] = sy + templateProcessor.height val paint = Paint() paint.style = Paint.Style.STROKE paint.strokeWidth = 4.0.toFloat() paint.color = Color.RED canvas.drawRect(rect, paint) result.setImageBitmap(resultBitmap) } } }
app/src/main/java/com/cv4j/app/fragment/TemplateMatchFragment.kt
657348650
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.lang.java.actions import com.intellij.codeInsight.completion.JavaLookupElementBuilder import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.codeInsight.template.Expression import com.intellij.codeInsight.template.ExpressionContext import com.intellij.codeInsight.template.Result import com.intellij.codeInsight.template.TextResult import com.intellij.icons.AllIcons import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.util.createSmartPointer import com.intellij.ui.LayeredIcon import javax.swing.Icon internal class FieldExpression( project: Project, target: PsiClass, private val fieldName: String, private val typeText: () -> String ) : Expression() { companion object { private val newFieldIcon: Icon = LayeredIcon.create(AllIcons.Nodes.Field, AllIcons.Actions.New) } private val myClassPointer = target.createSmartPointer(project) private val myFactory = JavaPsiFacade.getElementFactory(project) override fun calculateResult(context: ExpressionContext): Result? = TextResult(fieldName) override fun calculateQuickResult(context: ExpressionContext): Result? = calculateResult(context) override fun calculateLookupItems(context: ExpressionContext): Array<LookupElement> { val psiClass = myClassPointer.element ?: return LookupElement.EMPTY_ARRAY val userType = myFactory.createTypeFromText(typeText(), psiClass) val result = LinkedHashSet<LookupElement>() if (psiClass.findFieldByName(fieldName, false) == null) { result += LookupElementBuilder.create(fieldName).withIcon(newFieldIcon).withTypeText(userType.presentableText) } for (field in psiClass.fields) { val fieldType = field.type if (userType == fieldType) { result += JavaLookupElementBuilder.forField(field).withTypeText(fieldType.presentableText) } } return if (result.size < 2) LookupElement.EMPTY_ARRAY else result.toTypedArray() } }
java/java-impl/src/com/intellij/lang/java/actions/FieldExpression.kt
2308664045
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.at.psi import com.demonwav.mcdev.platform.mcp.at.AtLanguage import com.intellij.psi.tree.IElementType import org.jetbrains.annotations.NonNls class AtTokenType(@NonNls debugName: String) : IElementType(debugName, AtLanguage)
src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/psi/AtTokenType.kt
1132770486
// 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.jetbrains.python.psi.types import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.codeInsight.typing.TDFields import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyBuiltinCache import com.jetbrains.python.psi.impl.PyPsiUtils import java.util.* class PyTypedDictType @JvmOverloads constructor(private val name: String, val fields: LinkedHashMap<String, FieldTypeAndTotality>, private val inferred: Boolean, private val dictClass: PyClass, private val definitionLevel: DefinitionLevel, private val ancestors: List<PyTypedDictType>, private val declaration: PyQualifiedNameOwner? = null) : PyClassTypeImpl(dictClass, definitionLevel != DefinitionLevel.INSTANCE), PyCollectionType { override fun getElementTypes(): List<PyType?> { return listOf(if (!inferred || fields.isNotEmpty()) PyBuiltinCache.getInstance(dictClass).strType else null, getValuesType()) } override fun getIteratedItemType(): PyType? { return PyBuiltinCache.getInstance(dictClass).strType } private fun getValuesType(): PyType? { return PyUnionType.union(fields.map { it.value.type }) } fun getElementType(key: String): PyType? { return fields[key]?.type } override fun getCallType(context: TypeEvalContext, callSite: PyCallSiteExpression): PyType? { if (definitionLevel == DefinitionLevel.NEW_TYPE) { return toInstance() } return null } override fun isDefinition(): Boolean { return definitionLevel == DefinitionLevel.NEW_TYPE } override fun toInstance(): PyClassType { return if (definitionLevel == DefinitionLevel.NEW_TYPE) PyTypedDictType(name, fields, inferred, dictClass, DefinitionLevel.INSTANCE, ancestors, declaration) else this } override fun toClass(): PyClassLikeType { return if (definitionLevel == DefinitionLevel.INSTANCE) PyTypedDictType(name, fields, inferred, dictClass, DefinitionLevel.NEW_TYPE, ancestors, declaration) else this } override fun getName(): String { return name } override fun isBuiltin(): Boolean { return inferred // if TD is inferred then it's a dict with str-only keys } override fun isCallable(): Boolean { return definitionLevel != DefinitionLevel.INSTANCE } override fun getParameters(context: TypeEvalContext): List<PyCallableParameter>? { return if (isCallable) if (fields.isEmpty()) emptyList() else { val elementGenerator = PyElementGenerator.getInstance(dictClass.project) val singleStarParameter = PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter()) val ellipsis = elementGenerator.createEllipsis() listOf(singleStarParameter) + fields.map { if (it.value.isRequired) PyCallableParameterImpl.nonPsi(it.key, it.value.type) else PyCallableParameterImpl.nonPsi(it.key, it.value.type, ellipsis) } } else null } fun getKeysToValueTypes(): Map<String, PyType?> { return fields.mapValues { it.value.type } } fun getKeysToValuesWithTypes(): Map<String, Pair<PyExpression?, PyType?>> { return fields.mapValues { Pair(it.value.value, it.value.type) } } override fun toString(): String { return "PyTypedDictType: $name" } override fun equals(other: Any?): Boolean { if (other === this) return true if (other == null || javaClass != other.javaClass) return false val otherTypedDict = other as? PyTypedDictType ?: return false return name == otherTypedDict.name && fields == otherTypedDict.fields && inferred == otherTypedDict.inferred && definitionLevel == otherTypedDict.definitionLevel && ancestors == otherTypedDict.ancestors && declaration == otherTypedDict.declaration } override fun hashCode(): Int { return Objects.hash(super.hashCode(), name, fields, inferred, definitionLevel, ancestors, declaration) } enum class DefinitionLevel { NEW_TYPE, INSTANCE } /** * Checks whether this is an actual TypedDict type or [PyDictLiteralExpression] with all str keys */ fun isInferred(): Boolean { return inferred } override fun getDeclarationElement(): PyQualifiedNameOwner = declaration ?: super<PyClassTypeImpl>.getDeclarationElement() class FieldTypeAndTotality @JvmOverloads constructor(val value: PyExpression?, val type: PyType?, val isRequired: Boolean = true) companion object { const val TYPED_DICT_NAME_PARAMETER = "name" const val TYPED_DICT_FIELDS_PARAMETER = "fields" const val TYPED_DICT_TOTAL_PARAMETER = "total" fun createFromKeysToValueTypes(anchor: PsiElement, keysToValueTypes: Map<String, Pair<PyExpression?, PyType?>>): PyTypedDictType? { val dict = PyBuiltinCache.getInstance(anchor).dictType?.pyClass return if (dict != null) { val fields = TDFields(keysToValueTypes.entries.associate { it.key to FieldTypeAndTotality(it.value.first, it.value.second) }) PyTypedDictType("TypedDict", fields, true, dict, DefinitionLevel.INSTANCE, emptyList()) } else null } /** * [actual] matches [expected] if: * * all required keys from [expected] are present in [actual] * * all keys from [actual] are present in [expected] * * each key has the same value type in [expected] and [actual] */ fun checkTypes(expected: PyType, actual: PyTypedDictType, context: TypeEvalContext, value: PyExpression?): TypeCheckingResult? { if (!actual.isInferred()) { val match = checkStructuralCompatibility(expected, actual, context) if (match != null) { return match } } if (expected !is PyTypedDictType) return null val mandatoryArguments = expected.fields.filterValues { it.isRequired }.mapValues { Pair(it.value.value, it.value.type) } val actualArguments = actual.getKeysToValuesWithTypes() val expectedArguments = expected.getKeysToValuesWithTypes() return match(mandatoryArguments, expectedArguments, actualArguments, context, value, expected.name) } private fun match(mandatoryArguments: Map<String, Pair<PyExpression?, PyType?>>, expectedArguments: Map<String, Pair<PyExpression?, PyType?>>, actualArguments: Map<String, Pair<PyExpression?, PyType?>>, context: TypeEvalContext, actualTypedDict: PyExpression?, expectedTypedDictName: String): TypeCheckingResult { val valueTypeErrors = mutableListOf<ValueTypeError>() val missingKeys = mutableListOf<MissingKeysError>() val extraKeys = mutableListOf<ExtraKeyError>() var match = true val containedExpression = PyPsiUtils.flattenParens( if (actualTypedDict is PyKeywordArgument) actualTypedDict.valueExpression else actualTypedDict) val typedDictInstanceCreation = containedExpression is PyDictLiteralExpression || containedExpression is PyCallExpression && containedExpression.callee?.textMatches( PyNames.DICT) ?: false actualArguments.forEach { val actualValue = it.value.first val key = it.key if (!expectedArguments.containsKey(key)) { if (typedDictInstanceCreation) { val extraKeyToHighlight = PsiTreeUtil.getParentOfType(actualValue, PyKeyValueExpression::class.java) ?: PsiTreeUtil.getParentOfType(actualValue, PyKeywordArgument::class.java) ?: actualValue extraKeys.add(ExtraKeyError(extraKeyToHighlight, expectedTypedDictName, key)) match = false } else { return TypeCheckingResult(false, emptyList(), emptyList(), emptyList()) } } val expectedType = expectedArguments[key]?.second val actualType = it.value.second if (expectedType is PyTypedDictType && actualType is PyTypedDictType) { val res = checkTypes(expectedType, actualType, context, actualValue) if (res != null && !res.match) { val (innerMatch, innerValueTypeErrors, innerMissingKeys, innerExtraKeys) = res if (typedDictInstanceCreation) { if (!innerMatch && innerExtraKeys.isEmpty() && innerMissingKeys.isEmpty() && innerValueTypeErrors.isEmpty()) { match = false valueTypeErrors.add(ValueTypeError(actualValue, expectedType, actualType)) // inner TypedDict didn't match, but it's not a dict definition } match = false valueTypeErrors.addAll(innerValueTypeErrors) extraKeys.addAll(innerExtraKeys) missingKeys.addAll(innerMissingKeys) } else if (!innerMatch) { return TypeCheckingResult(false, emptyList(), emptyList(), emptyList()) } } } val matchResult: Boolean = strictUnionMatch( expectedType, if (actualValue != null) PyLiteralType.promoteToLiteral(actualValue, expectedType, context, null) ?: context.getType(actualValue) else it.value.second, context ) if (!matchResult && (expectedType !is PyTypedDictType || actualType !is PyTypedDictType)) { if (typedDictInstanceCreation) { valueTypeErrors.add( ValueTypeError(actualValue, expectedType, it.value.second)) match = false } else { return TypeCheckingResult(false, emptyList(), emptyList(), emptyList()) } } } if (!actualArguments.keys.containsAll(mandatoryArguments.keys)) { if (typedDictInstanceCreation) { missingKeys.add(MissingKeysError(actualTypedDict, expectedTypedDictName, mandatoryArguments.keys.filter { !actualArguments.containsKey(it) })) match = false } else { return TypeCheckingResult(false, emptyList(), emptyList(), emptyList()) } } return if (typedDictInstanceCreation) TypeCheckingResult(match, valueTypeErrors, missingKeys, extraKeys) else TypeCheckingResult(true, emptyList(), emptyList(), emptyList()) } private fun strictUnionMatch(expected: PyType?, actual: PyType?, context: TypeEvalContext): Boolean { return PyTypeUtil.toStream(actual).allMatch { type -> PyTypeChecker.match(expected, type, context) } } /** * Rules for type-checking TypedDicts are described in PEP-589 * @see <a href=https://www.python.org/dev/peps/pep-0589/#type-consistency>PEP-589</a> */ fun checkStructuralCompatibility(expected: PyType?, actual: PyTypedDictType, context: TypeEvalContext): TypeCheckingResult? { if (expected is PyCollectionType && PyTypingTypeProvider.MAPPING == expected.classQName) { val builtinCache = PyBuiltinCache.getInstance(actual.dictClass) val elementTypes = expected.elementTypes return TypeCheckingResult(elementTypes.size == 2 && builtinCache.strType == elementTypes[0] && (elementTypes[1] == null || PyNames.OBJECT == elementTypes[1].name), emptyList(), emptyList(), emptyList()) } if (expected !is PyTypedDictType) return null expected.fields.forEach { val expectedTypeAndTotality = it.value val actualTypeAndTotality = actual.fields[it.key] if (actualTypeAndTotality == null || !strictUnionMatch(expectedTypeAndTotality.type, actualTypeAndTotality.type, context) || !strictUnionMatch(actualTypeAndTotality.type, expectedTypeAndTotality.type, context) || expectedTypeAndTotality.isRequired.xor(actualTypeAndTotality.isRequired)) { return TypeCheckingResult(false, emptyList(), emptyList(), emptyList()) } if (!actual.fields.containsKey(it.key)) { return TypeCheckingResult(false, emptyList(), emptyList(), emptyList()) } } return TypeCheckingResult(true, emptyList(), emptyList(), emptyList()) } } data class MissingKeysError(val actualExpression: PyExpression?, val expectedTypedDictName: String, val missingKeys: List<String>) data class ExtraKeyError(val actualExpression: PyExpression?, val expectedTypedDictName: String, val key: String) data class ValueTypeError(val actualExpression: PyExpression?, val expectedType: PyType?, val actualType: PyType?) data class TypeCheckingResult(val match: Boolean, val valueTypeErrors: List<ValueTypeError>, val missingKeys: List<MissingKeysError>, val extraKeys: List<ExtraKeyError>) }
python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypedDictType.kt
342142820
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight.gradle import org.jetbrains.kotlin.tooling.core.KotlinToolingVersion import org.jetbrains.kotlin.tooling.core.isStable object KotlinGradlePluginVersions { val V_1_4_32 = KotlinToolingVersion(1, 4, 32, null) val V_1_5_32 = KotlinToolingVersion(1, 5, 32, null) val V_1_6_21 = KotlinToolingVersion(1, 6, 21, null) val latest = KotlinToolingVersion("1.8.0-dev-2023") val all = listOf( V_1_4_32, V_1_5_32, V_1_6_21, latest ) val allStable = all.filter { it.isStable } val lastStable = allStable.max() }
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/KotlinGradlePluginVersions.kt
1052630705
// MODE: function_return fun foo(x: String?): Int? = x?.let{ it.length<# [: [jar://kotlin-stdlib-sources.jar!/kotlin/Primitives.kt:28460]Int] #> }
plugins/kotlin/idea/tests/testData/codeInsight/hints/types/SingleLineLambda.kt
651148878
/* * Copyright (C) 2015 Antonio Leiva * * 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.antonioleiva.bandhookkotlin.data.lastfm.model import com.google.gson.annotations.SerializedName class LastFmTracklist ( SerializedName("track") val tracks: List<LastFmTrack> )
data/src/main/java/com/antonioleiva/bandhookkotlin/data/lastfm/model/LastFmTracklist.kt
927130399
package codesample.kotlin.sandbox.classes typealias StringSet = Set<String> fun printSetOfString(setOfStrings: Set<String>) { setOfStrings.forEach { println(it) } } /** Everything is Kotlin is final by default, so we have to declare class as open for inheritance */ open class TheSuper(val name: String) { constructor() : this("default_name") /* The same goes for methods */ open fun printName() { println(name) } class InnerStatic { private val innerStaticName: String = "Static Blah-blah" fun printInnerStatic() { println(innerStaticName) } } inner class Inner { private val innerName: String = "Inner Blah-blah" fun printInner() { println(innerName) } } } class TheSub : TheSuper(), Runnnnable { override var myVar: String = "initialized!" override fun printName() { println("The sub calls for you, $name") } override fun run() { println("TheSub si running!") } } class Other(str: String) { var str: String = str get() = field.toUpperCase() set(value) { field = value.toLowerCase() } } interface Runnnnable { fun run() var myVar: String // Kotlin properties may also be defined and initialized in subclasses } // Properties not defined in primary constructor in data classes will not be in toString() data class Person(val name: String) { var age: Int = 0 constructor(name: String, age: Int): this(name) { this.age = age } } fun main(args: Array<String>) { val innerStatic = TheSuper.InnerStatic() innerStatic.printInnerStatic() val inner = TheSuper().Inner() inner.printInner() val human: Runnnnable = object : Runnnnable { override var myVar = "topkek" override fun run() { println("I RUN LIKE A HUMAN") } } human.run() /* Kotlin supports type aliases. It also supports passing named parameters to function */ val strSet: StringSet = setOf("one", "two", "three") printSetOfString(setOfStrings = strSet) val superb = TheSuper("My name is IVAAAAAn") superb.printName() val sub = TheSub() sub.printName() sub.run() with(Other("aaa")) { println(str) str = "bbb" println(str) } // Will only print name becase only primary constructor parameters for data class are printed in Kotlin val person = Person("privet", 1) println(person.toString()) }
code-sample-kotlin/code-sample-kotlin-basics/src/main/kotlin/codesample/kotlin/sandbox/classes/Classes.kt
2434217470
package org.stepik.android.model.adaptive enum class Reaction(val value: Int) { SOLVED(2), INTERESTING(1), MAYBE_LATER(0), NEVER_AGAIN(-1) }
model/src/main/java/org/stepik/android/model/adaptive/Reaction.kt
1149926755
package io.github.chrislo27.rhre3.editor.stage import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.utils.Align import io.github.chrislo27.rhre3.RHRE3 import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.screen.EditorScreen import io.github.chrislo27.rhre3.track.Remix import io.github.chrislo27.rhre3.util.Swing import io.github.chrislo27.toolboks.ui.* import io.github.chrislo27.toolboks.util.gdxutils.drawRect import io.github.chrislo27.toolboks.util.gdxutils.fillRect import kotlin.math.max import kotlin.properties.Delegates class PresentationModeStage(val editor: Editor, val palette: UIPalette, parent: EditorStage, camera: OrthographicCamera) : Stage<EditorScreen>(parent, camera) { private val backgroundPane = ColourPane(this, this).apply { this.location.set(0f, 0f, 1f, 1f) } private val remix: Remix get() = editor.remix private val themePalette: UIPalette = palette.copy(textColor = Color(palette.textColor)) private val infoTextPalette: UIPalette = palette.copy(textColor = Color(palette.textColor)) private val progressBar: UIElement<EditorScreen> private val timeLabel: TextLabel<EditorScreen> private val durationLabel: TextLabel<EditorScreen> private val bpmLabel: TextLabel<EditorScreen> private var progress = 0f init { // this.elements += backgroundPane this.elements += ColourPane(this, this).apply { this.colour.set(Editor.TRANSLUCENT_BLACK) this.location.set(0f, 0f, 1f, 1f) this.visible = false } val fontScale = 0.8f this.elements += TextLabel(infoTextPalette, this, this).apply { this.location.set(screenHeight = 0.125f, screenY = 0.0f) this.textWrapping = false this.isLocalizationKey = false this.textAlign = Align.center this.text = RHRE3.GITHUB_SHORTLINK this.fontScaleMultiplier = fontScale } this.elements += TextLabel(infoTextPalette, this, this).apply { this.location.set(screenHeight = 0.125f, screenY = 0.125f) this.textWrapping = false this.isLocalizationKey = false this.textAlign = Align.center this.text = "Made with the Rhythm Heaven Remix Editor, which is licensed under GPL-3.0" this.fontScaleMultiplier = fontScale } val aboveText = 0.125f + 0.125f progressBar = object : UIElement<EditorScreen>(this, this) { override fun render(screen: EditorScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) { val oldColor = batch.packedColor batch.color = themePalette.textColor val line = 3f val lineX = line * Gdx.graphics.width / RHRE3.WIDTH val lineY = line * Gdx.graphics.height / RHRE3.HEIGHT batch.drawRect(location.realX, location.realY, location.realWidth, location.realHeight, lineX, lineY) batch.fillRect(location.realX + lineX * 2, location.realY + lineY * 2, (location.realWidth - lineX * 4) * progress.coerceIn(0f, 1f), location.realHeight - lineY * 4) batch.packedColor = oldColor } }.apply { this.location.set(screenX = 0.25f, screenY = aboveText + 0.05f, screenWidth = 0.5f, screenHeight = 0.15f) } this.elements += progressBar timeLabel = TextLabel(themePalette, this, this).apply { this.textWrapping = false this.isLocalizationKey = false this.textAlign = Align.right this.text = "0:00" this.location.set(screenX = 0f, screenY = progressBar.location.screenY, screenWidth = progressBar.location.screenX - 0.0125f, screenHeight = progressBar.location.screenHeight) } this.elements += timeLabel durationLabel = TextLabel(themePalette, this, this).apply { this.textWrapping = false this.isLocalizationKey = false this.textAlign = Align.left this.text = "0:00" this.location.set(screenX = progressBar.location.screenX + progressBar.location.screenWidth + 0.0125f, screenY = progressBar.location.screenY, screenHeight = progressBar.location.screenHeight) this.location.set(screenWidth = 1f - (this.location.screenX)) } this.elements += durationLabel val gameDisplay = object : GameDisplayStage(editor, themePalette, this@PresentationModeStage, [email protected]) { override fun getFont(): BitmapFont { return themePalette.font } }.apply { [email protected]() this.location.set(screenX = progressBar.location.screenX, screenY = progressBar.location.screenY + progressBar.location.screenHeight + 0.0125f, screenHeight = progressBar.location.screenHeight * 1.5f) this.location.set(screenWidth = 1 / 3f) this.updatePositions() } this.elements += gameDisplay bpmLabel = object : TextLabel<EditorScreen>(themePalette, this, this) { // override fun getFont(): BitmapFont { // return editor.main.defaultBorderedFont // } }.apply { this.textWrapping = false this.isLocalizationKey = false this.textAlign = Align.right this.text = "X BPM" this.fontScaleMultiplier = GameDisplayStage.FONT_SCALE this.location.set(screenX = gameDisplay.location.screenX + gameDisplay.location.screenWidth, screenY = gameDisplay.location.screenY, screenHeight = gameDisplay.location.screenHeight) this.location.set( screenWidth = (progressBar.location.screenX + progressBar.location.screenWidth) - (this.location.screenX)) } this.elements += bpmLabel this.updatePositions() } private fun secondsToText(seconds: Int): String { val sec = seconds % 60 return "${seconds / 60}:${if (sec < 10) "0" else ""}${max(0, sec)}" } private var timeSeconds: Int by Delegates.observable(0) { _, old, new -> if (new != old) { timeLabel.text = secondsToText(new) } } private var durationSeconds: Int by Delegates.observable(0) { _, old, new -> if (new != old) { durationLabel.text = secondsToText(new) } } private var bpm: Float by Delegates.observable(Float.NEGATIVE_INFINITY) { _, old, new -> if (new != old) { setBpmLabelText() } } private var swing: Swing by Delegates.observable(Swing.STRAIGHT) { _, old, new -> if (new != old) { setBpmLabelText() } } private fun setBpmLabelText() { bpmLabel.text = (if (swing != Swing.STRAIGHT) "${swing.getNoteSymbol()} ${swing.getSwingName()}\n" else "") + "${String.format("%.1f", bpm)} BPM" } override fun render(screen: EditorScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) { backgroundPane.colour.set(screen.editor.theme.background) backgroundPane.colour.a = 1f themePalette.textColor.set(editor.theme.trackLine) infoTextPalette.textColor.set(themePalette.textColor) infoTextPalette.textColor.a = 0.75f timeSeconds = remix.tempos.beatsToSeconds(remix.beat).toInt() durationSeconds = remix.tempos.beatsToSeconds(remix.lastPoint).toInt() bpm = remix.tempos.tempoAt(remix.beat) swing = remix.tempos.swingAt(remix.beat) progress = (remix.seconds / remix.tempos.beatsToSeconds(remix.lastPoint)).coerceIn(0f, 1f) super.render(screen, batch, shapeRenderer) } }
core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/PresentationModeStage.kt
2497835359
package com.aemtools.lang.htl.psi.pattern import com.aemtools.common.util.findParentByType import com.aemtools.lang.util.isInsideOf import com.aemtools.lang.htl.psi.HtlHtlEl import com.intellij.patterns.PatternCondition import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext /** * Pattern that matches htl expression inside of given htl attribute. * * @author Dmytro Troynikov */ class HtlTemplatePattern(val name: String) : PatternCondition<PsiElement?>(name) { override fun accepts(element: PsiElement, context: ProcessingContext?): Boolean { return element.findParentByType(HtlHtlEl::class.java) ?.isInsideOf(name) ?: false } }
lang/src/main/kotlin/com/aemtools/lang/htl/psi/pattern/HtlTemplatePattern.kt
1394617125
package cn.imrhj.sharetoqrcode.util import android.graphics.Bitmap import android.media.Image import android.net.Uri import android.provider.MediaStore import cn.imrhj.sharetoqrcode.App import java.io.File import java.io.FileOutputStream /** * Created by rhj on 2017/9/12. */ fun save(src: Bitmap, file: File): Boolean { if (isEmptyBitmap(src) || !createOrExistsFile(file)) { return false } var ret = false FileOutputStream(file).use { ret = src.compress(Bitmap.CompressFormat.JPEG, 100, it) it.flush() it.close() } return ret } fun file2bitmap(src: File): Bitmap? { if (src.exists()) { return MediaStore.Images.Media.getBitmap(App.instance().contentResolver, Uri.fromFile(src)) } return null } fun isEmptyBitmap(src: Bitmap?): Boolean = src == null || src.width == 0 || src.height == 0 fun saveTmpBitmap(src: Bitmap): Boolean { val file = File(App.instance().externalCacheDir, "${System.currentTimeMillis()}.jpg") return save(src, file) } fun image2bitmap(image: Image): Bitmap { val width = image.width val height = image.height val planes = image.planes val buffer = planes[0].buffer val pixelStride = planes[0].pixelStride val rowStride = planes[0].rowStride val rowPadding = rowStride - pixelStride * width; var bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888) bitmap.copyPixelsFromBuffer(buffer) bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height) saveTmpBitmap(bitmap) image.close() return bitmap }
app/src/main/java/cn/imrhj/sharetoqrcode/util/ImageUtils.kt
4060396543
package com.aemtools.test.reference import com.aemtools.test.base.BaseLightTest import com.aemtools.test.fixture.JdkProjectDescriptor import com.aemtools.test.reference.model.IReferenceTestFixture import com.aemtools.test.reference.model.ReferenceTestFixture import com.intellij.testFramework.LightProjectDescriptor /** * @author Dmytro Troynikov */ abstract class BaseReferenceTest(withAemUberJar: Boolean = false) : BaseLightTest(withAemUberJar) { fun testReference(unit: IReferenceTestFixture.() -> Unit) { val fixture = ReferenceTestFixture(fixture = myFixture).apply { unit() } fixture.init() fixture.test() } override fun getProjectDescriptor(): LightProjectDescriptor = JdkProjectDescriptor() }
test-framework/src/main/kotlin/com/aemtools/test/reference/BaseReferenceTest.kt
2462979087
package com.intellij.grazie.ide.ui.proofreading import com.intellij.grazie.GrazieConfig import com.intellij.grazie.ide.ui.components.dsl.msg import com.intellij.openapi.components.service import com.intellij.openapi.options.ConfigurableBase class ProofreadConfigurable : ConfigurableBase<ProofreadSettingsPanel, GrazieConfig>("proofread", msg("grazie.group.name"), "reference.settings.ide.settings.proofreading") { private val ui by lazy { ProofreadSettingsPanel() } override fun getSettings() = service<GrazieConfig>() override fun createUi() = ui }
plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/ui/proofreading/ProofreadConfigurable.kt
2245456569
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.execution.test.runner import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.actions.ConfigurationFromContextImpl import com.intellij.execution.actions.RunConfigurationProducer import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import org.jetbrains.plugins.gradle.importing.GradleBuildScriptBuilderEx import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase import org.jetbrains.plugins.gradle.util.* import org.junit.runners.Parameterized import java.io.File import java.util.function.Consumer abstract class GradleTestRunConfigurationProducerTestCase : GradleImportingTestCase() { protected fun getContextByLocation(vararg elements: PsiElement): ConfigurationContext { assertTrue(elements.isNotEmpty()) return object : ConfigurationContext(elements[0]) { override fun getDataContext() = SimpleDataContext.getSimpleContext(LangDataKeys.PSI_ELEMENT_ARRAY, elements, super.getDataContext()) override fun containsMultipleSelection() = elements.size > 1 } } protected fun getConfigurationFromContext(context: ConfigurationContext): ConfigurationFromContextImpl { val fromContexts = context.configurationsFromContext val fromContext = fromContexts?.firstOrNull() assertNotNull("Gradle configuration from context not found", fromContext) return fromContext as ConfigurationFromContextImpl } protected inline fun <reified P : GradleTestRunConfigurationProducer> getConfigurationProducer(): P { return RunConfigurationProducer.getInstance(P::class.java) } protected fun assertProducersFromContext( element: PsiElement, vararg producerTypes: String ) = runReadActionAndWait { val context = getContextByLocation(element) val producers = context.configurationsFromContext!! .map { it as ConfigurationFromContextImpl } .map { it.configurationProducer } assertEquals(producerTypes.size, producers.size) for ((producer, producerType) in producers.zip(producerTypes)) { assertEquals(producerType, producer::class.java.simpleName) } } protected inline fun <reified P : GradleTestRunConfigurationProducer> assertConfigurationFromContext( expectedSettings: String, vararg elements: PsiElement, noinline testTasksFilter: (TestName) -> Boolean = { true } ) = runReadActionAndWait { val context = getContextByLocation(*elements) val configurationFromContext = getConfigurationFromContext(context) val producer = configurationFromContext.configurationProducer as P producer.setTestTasksChooser(testTasksFilter) val configuration = configurationFromContext.configuration as ExternalSystemRunConfiguration assertTrue(producer.setupConfigurationFromContext(configuration, context, Ref(context.psiLocation))) if (producer !is PatternGradleConfigurationProducer) { assertTrue(producer.isConfigurationFromContext(configuration, context)) } producer.onFirstRun(configurationFromContext, context, Runnable {}) assertEquals(expectedSettings, configuration.settings.toString().trim()) } protected fun GradleTestRunConfigurationProducer.setTestTasksChooser(testTasksFilter: (TestName) -> Boolean) { testTasksChooser = object : TestTasksChooser() { override fun chooseTestTasks(project: Project, context: DataContext, testTasks: Map<TestName, Map<SourcePath, TasksToRun>>, consumer: Consumer<List<Map<SourcePath, TestTasks>>>) { consumer.accept(testTasks.filterKeys(testTasksFilter).values.toList()) } } } protected fun GradleTestRunConfigurationProducer.createTemplateConfiguration(): ExternalSystemRunConfiguration { return configurationFactory.createTemplateConfiguration(myProject) as ExternalSystemRunConfiguration } protected fun generateAndImportTemplateProject(): ProjectData { val testCaseFile = createProjectSubFile("src/test/java/TestCase.java", """ import org.junit.Test; public class TestCase extends AbstractTestCase { @Test public void test1() {} @Test public void test2() {} @Test public void test3() {} } """.trimIndent()) val packageTestCaseFile = createProjectSubFile("src/test/java/pkg/TestCase.java", """ package pkg; import org.junit.Test; public class TestCase extends AbstractTestCase { @Test public void test1() {} @Test public void test2() {} @Test public void test3() {} } """.trimIndent()) val automationTestCaseFile = createProjectSubFile("automation/AutomationTestCase.java", """ import org.junit.Test; public class AutomationTestCase extends AbstractTestCase { @Test public void test1() {} @Test public void test2() {} @Test public void test3() {} } """.trimIndent()) val abstractTestCaseFile = createProjectSubFile("src/test/java/AbstractTestCase.java", """ import org.junit.Test; public abstract class AbstractTestCase { @Test public void test() {} } """.trimIndent()) val moduleTestCaseFile = createProjectSubFile("module/src/test/java/ModuleTestCase.java", """ import org.junit.Test; public class ModuleTestCase extends AbstractTestCase { @Test public void test1() {} @Test public void test2() {} @Test public void test3() {} } """.trimIndent()) val groovyTestCaseFile = createProjectSubFile("src/test/groovy/GroovyTestCase.groovy", """ import org.junit.Test; public class GroovyTestCase extends AbstractTestCase { @Test public void 'Don\\\'t use single . quo\\"tes'() {} @Test public void test1() {} @Test public void test2() {} @Test public void test3() {} } """.trimIndent()) val myModuleTestCaseFile = createProjectSubFile("my module/src/test/groovy/MyModuleTestCase.groovy", """ import org.junit.Test; public class MyModuleTestCase extends AbstractTestCase { @Test public void test1() {} @Test public void test2() {} @Test public void test3() {} } """.trimIndent()) val buildScript = GradleBuildScriptBuilderEx() .withJavaPlugin() .withIdeaPlugin() .withJUnit("4.12") .withGroovyPlugin("2.4.14") .addPrefix(""" idea.module { testSourceDirs += file('automation') } sourceSets { automation.java.srcDirs = ['automation'] automation.compileClasspath += sourceSets.test.runtimeClasspath } task autoTest(type: Test) { testClassesDirs = sourceSets.automation.output.classesDirs } task automationTest(type: Test) { testClassesDirs = sourceSets.automation.output.classesDirs } """.trimIndent()) .addPrefix(""" task myTestsJar(type: Jar, dependsOn: testClasses) { baseName = "test-${'$'}{project.archivesBaseName}" from sourceSets.automation.output } configurations { testArtifacts } artifacts { testArtifacts myTestsJar } """.trimIndent()) val moduleBuildScript = GradleBuildScriptBuilderEx() .withJavaPlugin() .withJUnit("4.12") .withGroovyPlugin("2.4.14") .addDependency("testCompile project(path: ':', configuration: 'testArtifacts')") createSettingsFile(""" rootProject.name = 'project' include 'module', 'my module' """.trimIndent()) createProjectSubFile("module/build.gradle", moduleBuildScript.generate()) createProjectSubFile("my module/build.gradle", moduleBuildScript.generate()) importProject(buildScript.generate()) assertModulesContains("project", "project.module", "project.my_module") val automationTestCase = extractJavaClassData(automationTestCaseFile) val testCase = extractJavaClassData(testCaseFile) val abstractTestCase = extractJavaClassData(abstractTestCaseFile) val moduleTestCase = extractJavaClassData(moduleTestCaseFile) val packageTestCase = extractJavaClassData(packageTestCaseFile) val groovyTestCase = extractGroovyClassData(groovyTestCaseFile) val myModuleTestCase = extractGroovyClassData(myModuleTestCaseFile) val projectDir = findPsiDirectory(".") val moduleDir = findPsiDirectory("module") val myModuleDir = findPsiDirectory("my module") return ProjectData( ModuleData("project", projectDir, testCase, packageTestCase, automationTestCase, abstractTestCase, groovyTestCase), ModuleData("module", moduleDir, moduleTestCase), ModuleData("my module", myModuleDir, myModuleTestCase) ) } private fun findPsiDirectory(relativePath: String) = runReadActionAndWait { val virtualFile = VfsUtil.findFileByIoFile(File(projectPath, relativePath), false)!! val psiManager = PsiManager.getInstance(myProject) psiManager.findDirectory(virtualFile)!! } private fun extractJavaClassData(file: VirtualFile) = runReadActionAndWait { val psiManager = PsiManager.getInstance(myProject) val psiFile = psiManager.findFile(file)!! val psiClass = psiFile.findChildByType<PsiClass>() val psiMethods = psiClass.findChildrenByType<PsiMethod>() val methods = psiMethods.map { MethodData(it.name, it) } ClassData(psiClass.qualifiedName!!, psiClass, methods) } private fun extractGroovyClassData(file: VirtualFile) = runReadActionAndWait { val psiManager = PsiManager.getInstance(myProject) val psiFile = psiManager.findFile(file)!! val psiClass = psiFile.findChildByType<PsiClass>() val classBody = psiClass.findChildByElementType("CLASS_BODY") val psiMethods = classBody.findChildrenByType<PsiMethod>() val methods = psiMethods.map { MethodData(it.name, it) } ClassData(psiClass.qualifiedName!!, psiClass, methods) } protected open class Mapping<D>(val data: Map<String, D>) { operator fun get(key: String): D = data.getValue(key) } protected class ProjectData( vararg modules: ModuleData ) : Mapping<ModuleData>(modules.map { it.name to it }.toMap()) protected class ModuleData( val name: String, val root: PsiDirectory, vararg classes: ClassData ) : Mapping<ClassData>(classes.map { it.name to it }.toMap()) protected class ClassData( val name: String, val element: PsiClass, methods: List<MethodData> ) : Mapping<MethodData>(methods.map { it.name to it }.toMap()) protected class MethodData( val name: String, val element: PsiMethod ) protected fun PsiDirectory.subDirectory(vararg names: String) = runReadActionAndWait { var directory = this for (name in names) { directory = directory.findSubdirectory(name)!! } directory } companion object { /** * It's sufficient to run the test against one gradle version */ @Parameterized.Parameters(name = "with Gradle-{0}") @JvmStatic fun tests(): Collection<Array<out String>> = arrayListOf(arrayOf(GradleImportingTestCase.BASE_GRADLE_VERSION)) } }
plugins/gradle/java/testSources/execution/test/runner/GradleTestRunConfigurationProducerTestCase.kt
1956436128
package ch.difty.scipamato.core.sync.jobs.newsletter import ch.difty.scipamato.core.sync.PublicNewsletter import ch.difty.scipamato.core.sync.jobs.AbstractItemWriterTest import org.jooq.DSLContext internal class NewsletterItemWriterTest : AbstractItemWriterTest<PublicNewsletter, NewsletterItemWriter>() { override fun newWriter(dslContextMock: DSLContext) = NewsletterItemWriter(dslContextMock) }
core/core-sync/src/test/kotlin/ch/difty/scipamato/core/sync/jobs/newsletter/NewsletterItemWriterTest.kt
3399281767
package nu.peg.demo.controller import nu.peg.demo.service.account.AccountService import nu.peg.demo.data.account.Account import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/api/admin") class AdminController @Autowired constructor(val accountService: AccountService) { @GetMapping("/account/{id}/load/{amount}") fun loadAccount(@PathVariable id: Long, @PathVariable amount: Double): Account? { return accountService.loadAccount(id, amount) } }
src/main/kotlin/nu/peg/demo/controller/AdminController.kt
1866691113
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.history import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.VcsLogDataPack import com.intellij.vcs.log.history.FileHistoryPaths.filePaths import com.intellij.vcs.log.ui.VcsLogColorManager import com.intellij.vcs.log.ui.VcsLogColorManagerImpl import com.intellij.vcsUtil.VcsFileUtil import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenCustomHashSet import java.awt.Color internal class FileHistoryColorManager(private val root: VirtualFile, private val path: FilePath) : VcsLogColorManager { private var baseColorManager = VcsLogColorManagerImpl(setOf(path)) override fun getPathColor(path: FilePath): Color { return baseColorManager.getPathColor(path) } fun update(pack: VcsLogDataPack) { val pathsFromPack = pack.filePaths() if (pathsFromPack.isEmpty()) { baseColorManager = VcsLogColorManagerImpl(setOf(path)) } else { val newPaths = ObjectLinkedOpenCustomHashSet(baseColorManager.paths, FILE_PATH_HASHING_STRATEGY) newPaths.retainAll(pathsFromPack) newPaths.addAll(pathsFromPack) baseColorManager = VcsLogColorManagerImpl(newPaths) } } override fun getPaths(): Collection<FilePath> { return baseColorManager.paths } override fun getLongName(path: FilePath): String { return VcsFileUtil.relativePath(root, path) } }
platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryColorManager.kt
2442676929
/* * 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 git4idea.branch import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.vcs.VcsNotifier import git4idea.GitNotificationIdsHolder.Companion.BRANCH_CREATE_ROLLBACK_ERROR import git4idea.GitNotificationIdsHolder.Companion.BRANCH_CREATE_ROLLBACK_SUCCESS import git4idea.commands.Git import git4idea.commands.GitCompoundResult import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.util.GitUIUtil.bold import git4idea.util.GitUIUtil.code import org.jetbrains.annotations.Nls internal class GitCreateBranchOperation( project: Project, git: Git, uiHandler: GitBranchUiHandler, private val branchName: String, private val startPoints: Map<GitRepository, String>, private val force: Boolean) : GitBranchOperation(project, git, uiHandler, startPoints.keys) { public override fun execute() { var fatalErrorHappened = false while (hasMoreRepositories() && !fatalErrorHappened) { val repository = next() val result = myGit.branchCreate(repository, branchName, startPoints[repository]!!, force) if (result.success()) { repository.update() markSuccessful(repository) } else { fatalError(GitBundle.message("create.branch.operation.could.not.create.new.branch", branchName), result.errorOutputAsJoinedString) fatalErrorHappened = true } } if (!fatalErrorHappened) { notifySuccess() updateRecentBranch() } } override fun rollback() { val repositories = successfulRepositories val deleteResult = GitCompoundResult(myProject) for (repository in repositories) { deleteResult.append(repository, myGit.branchDelete(repository, branchName, false)) repository.update() } val vcsNotifier = VcsNotifier.getInstance(myProject) if (deleteResult.totalSuccess()) { vcsNotifier.notifySuccess(BRANCH_CREATE_ROLLBACK_SUCCESS, GitBundle.message("create.branch.operation.rollback.successful"), GitBundle.message("create.branch.operation.deleted.branch", branchName)) } else { vcsNotifier.notifyError(BRANCH_CREATE_ROLLBACK_ERROR, GitBundle.message("create.branch.operation.error.during.rollback"), deleteResult.errorOutputWithReposIndication, true) } } override fun getSuccessMessage(): String = GitBundle.message("create.branch.operation.branch.created", bold(code(branchName))) override fun getRollbackProposal(): String = HtmlBuilder() .append(GitBundle.message("create.branch.operation.however.the.branch.was.created.in.the.following.repositories", successfulRepositories.size)) .br() .appendRaw(successfulRepositoriesJoined()) .br() .append(GitBundle.message("create.branch.operation.you.may.rollback.not.to.let.branches.diverge", branchName)) .toString() override fun getOperationName(): @Nls String = GitBundle.message("create.branch.operation.name") }
plugins/git4idea/src/git4idea/branch/GitCreateBranchOperation.kt
4002505669
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ import kotlinx.coroutines.* import kotlinx.coroutines.test.* import kotlin.concurrent.* import kotlin.coroutines.* import kotlin.test.* class MultithreadingTest { @Test fun incorrectlyCalledRunBlocking_doesNotHaveSameInterceptor() = runBlockingTest { // this code is an error as a production test, please do not use this as an example // this test exists to document this error condition, if it's possible to make this code work please update val outerInterceptor = coroutineContext[ContinuationInterceptor] // runBlocking always requires an argument to pass the context in tests runBlocking { assertNotSame(coroutineContext[ContinuationInterceptor], outerInterceptor) } } @Test fun testSingleThreadExecutor() = runBlocking { val mainThread = Thread.currentThread() Dispatchers.setMain(Dispatchers.Unconfined) newSingleThreadContext("testSingleThread").use { threadPool -> withContext(Dispatchers.Main) { assertSame(mainThread, Thread.currentThread()) } Dispatchers.setMain(threadPool) withContext(Dispatchers.Main) { assertNotSame(mainThread, Thread.currentThread()) } assertSame(mainThread, Thread.currentThread()) withContext(Dispatchers.Main.immediate) { assertNotSame(mainThread, Thread.currentThread()) } assertSame(mainThread, Thread.currentThread()) Dispatchers.setMain(Dispatchers.Unconfined) withContext(Dispatchers.Main.immediate) { assertSame(mainThread, Thread.currentThread()) } assertSame(mainThread, Thread.currentThread()) } } @Test fun whenDispatchCalled_runsOnCurrentThread() { val currentThread = Thread.currentThread() val subject = TestCoroutineDispatcher() val scope = TestCoroutineScope(subject) val deferred = scope.async(Dispatchers.Default) { withContext(subject) { assertNotSame(currentThread, Thread.currentThread()) 3 } } runBlocking { // just to ensure the above code terminates assertEquals(3, deferred.await()) } } @Test fun whenAllDispatchersMocked_runsOnSameThread() { val currentThread = Thread.currentThread() val subject = TestCoroutineDispatcher() val scope = TestCoroutineScope(subject) val deferred = scope.async(subject) { withContext(subject) { assertSame(currentThread, Thread.currentThread()) 3 } } runBlocking { // just to ensure the above code terminates assertEquals(3, deferred.await()) } } /** Tests that resuming the coroutine of [runTest] asynchronously in reasonable time succeeds. */ @Test fun testResumingFromAnotherThread() = runTest { suspendCancellableCoroutine<Unit> { cont -> thread { Thread.sleep(10) cont.resume(Unit) } } } /** Tests that [StandardTestDispatcher] is confined to the thread that interacts with the scheduler. */ @Test fun testStandardTestDispatcherIsConfined() = runTest { val initialThread = Thread.currentThread() withContext(Dispatchers.IO) { val ioThread = Thread.currentThread() assertNotSame(initialThread, ioThread) } assertEquals(initialThread, Thread.currentThread()) } }
kotlinx-coroutines-test/jvm/test/MultithreadingTest.kt
3230655658
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.roots.ui.configuration import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.service import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkTypeId import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.Condition import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.ui.AnActionButton import com.intellij.ui.awt.RelativePoint import com.intellij.ui.popup.list.ComboBoxPopup import java.awt.Component import java.awt.Point import java.awt.Window import java.util.function.Consumer import javax.swing.JComponent import javax.swing.JFrame import javax.swing.JPanel private data class SdkPopupBuilderImpl( val project: Project? = null, val projectSdksModel: ProjectSdksModel? = null, val sdkListModelBuilder: SdkListModelBuilder? = null, val sdkTypeFilter: Condition<SdkTypeId>? = null, val sdkTypeCreateFilter: Condition<SdkTypeId>? = null, val sdkFilter: Condition<Sdk>? = null, val registerNewSdk : Boolean = false, val updateProjectSdk : Boolean = false, val updateSdkForVirtualFile: VirtualFile? = null, val updateSdkForPsiFile: PsiFile? = null, val onItemSelected: Consumer<SdkListItem>? = null, val onSdkSelected: Consumer<Sdk>? = null, val onPopupClosed: Runnable? = null ) : SdkPopupBuilder { override fun registerNewSdk() = copy(registerNewSdk = true) override fun updateProjectSdkFromSelection() = copy(updateProjectSdk = true) override fun updateSdkForFile(file: PsiFile) = copy(updateSdkForPsiFile = file) override fun updateSdkForFile(file: VirtualFile) = copy(updateSdkForVirtualFile = file) override fun withProject(project: Project?) = copy(project = project) override fun withProjectSdksModel(projectSdksModel: ProjectSdksModel) = copy(projectSdksModel = projectSdksModel) override fun withSdkListModelBuilder(sdkListModelBuilder: SdkListModelBuilder) = copy(sdkListModelBuilder = sdkListModelBuilder) override fun withSdkType(type: SdkTypeId) = withSdkTypeFilter(Condition { sdk -> sdk == type }) override fun withSdkTypeFilter(filter: Condition<SdkTypeId>) = copy(sdkTypeFilter = filter) override fun withSdkTypeCreateFilter(filter: Condition<SdkTypeId>) = copy(sdkTypeCreateFilter = filter) override fun withSdkFilter(filter: Condition<Sdk>) = copy(sdkFilter = filter) override fun onItemSelected(onItemSelected: Consumer<SdkListItem>) = copy(onItemSelected = onItemSelected) override fun onPopupClosed(onClosed: Runnable) = copy(onPopupClosed = onClosed) override fun onSdkSelected(onSdkSelected: Consumer<Sdk>) = copy(onSdkSelected = onSdkSelected) override fun buildPopup() = service<SdkPopupFactory>().createPopup(copy()) } private interface SdkPopupListener { fun onClosed() /** * Executed when a new item was created via a user action * and added to the model, called after model is refreshed */ fun onNewItemAddedAndSelected(item: SdkListItem) /** * Executed when an existing selectable item was selected * in the popup, it does mean no new items were created * by a user */ fun onExistingItemSelected(item: SdkListItem) } internal class PlatformSdkPopupFactory : SdkPopupFactory { override fun createBuilder(): SdkPopupBuilder = SdkPopupBuilderImpl() override fun createPopup(builder: SdkPopupBuilder): SdkPopup = (builder as SdkPopupBuilderImpl).copy().run { val (sdksModel, ownsModel) = if (projectSdksModel != null) { projectSdksModel to false } else { ProjectSdksModel() to true } val modelBuilder = if (sdkListModelBuilder != null) { require(sdkTypeFilter == null) { "sdkListModelBuilder was set explicitly via " + ::withSdkListModelBuilder.name } require(sdkTypeCreateFilter == null) { "sdkListModelBuilder was set explicitly via " + ::withSdkListModelBuilder.name } require(sdkFilter == null) { "sdkListModelBuilder was set explicitly via " + ::withSdkListModelBuilder.name } sdkListModelBuilder } else { SdkListModelBuilder( project, sdksModel, sdkTypeFilter, sdkTypeCreateFilter, sdkFilter ) } if (updateProjectSdk && project == null) { require(false) { "Cannot update project SDK when project was not set" } } val popupListener = object : SdkPopupListener { override fun onNewItemAddedAndSelected(item: SdkListItem) { val addToJdkTable = registerNewSdk || updateProjectSdk || updateSdkForPsiFile != null || updateSdkForVirtualFile != null if (addToJdkTable && item is SdkListItem.SdkItem) { val sdk = item.sdk runWriteAction { val jdkTable = ProjectJdkTable.getInstance() if (jdkTable.findJdk(sdk.name) == null) { jdkTable.addJdk(sdk) } } } onItemSelected(item) } override fun onExistingItemSelected(item: SdkListItem) { onItemSelected(item) } private fun onItemSelected(item: SdkListItem) { onItemSelected?.accept(item) if (item is SdkListItem.SdkItem) { onSdkSelected(item.sdk) } } private fun onSdkSelected(sdk: Sdk) { onSdkSelected?.accept(sdk) if (updateProjectSdk) { runWriteAction { requireNotNull(project) { "project must be set to use " + SdkPopupBuilder::updateProjectSdkFromSelection.name } ProjectRootManager.getInstance(project).projectSdk = sdk } } if (updateSdkForPsiFile != null || updateSdkForVirtualFile != null) { requireNotNull(project) { "project must be set to use " + ::updateProjectSdkFromSelection.name } runWriteAction { val moduleToUpdateSdk = when { updateSdkForVirtualFile != null -> ModuleUtilCore.findModuleForFile(updateSdkForVirtualFile, project) updateSdkForPsiFile != null -> ModuleUtilCore.findModuleForFile(updateSdkForPsiFile) else -> null } if (moduleToUpdateSdk != null) { val roots = ModuleRootManager.getInstance(moduleToUpdateSdk) if (!roots.isSdkInherited) { roots.modifiableModel.also { it.sdk = sdk it.commit() } return@runWriteAction } } ProjectRootManager.getInstance(project).projectSdk = sdk } } } override fun onClosed() { onPopupClosed?.run() } } return createSdkPopup(project, sdksModel, ownsModel, modelBuilder, popupListener) } private fun createSdkPopup( project: Project?, projectSdksModel: ProjectSdksModel, ownsProjectSdksModel: Boolean, myModelBuilder: SdkListModelBuilder, listener: SdkPopupListener ): SdkPopup { lateinit var popup: SdkPopupImpl val context = SdkListItemContext(project) val onItemSelected = Consumer<SdkListItem> { value -> myModelBuilder.processSelectedElement(popup.popupOwner, value, listener::onNewItemAddedAndSelected, listener::onExistingItemSelected ) } popup = SdkPopupImpl(context, onItemSelected) val modelListener: SdkListModelBuilder.ModelListener = object : SdkListModelBuilder.ModelListener { override fun syncModel(model: SdkListModel) { context.myModel = model popup.syncWithModelChange() } } myModelBuilder.addModelListener(modelListener) popup.addListener(object : JBPopupListener { override fun beforeShown(event: LightweightWindowEvent) { if (ownsProjectSdksModel) { projectSdksModel.reset(project) } myModelBuilder.reloadActions() myModelBuilder.detectItems(popup.list, popup) myModelBuilder.reloadSdks() } override fun onClosed(event: LightweightWindowEvent) { myModelBuilder.removeListener(modelListener) listener.onClosed() } }) return popup } } private class SdkPopupImpl( context: SdkListItemContext, onItemSelected: Consumer<SdkListItem> ) : ComboBoxPopup<SdkListItem>(context, null, onItemSelected), SdkPopup { val popupOwner: JComponent get() { val owner = myOwner if (owner is JComponent) { return owner } if (owner is JFrame) { owner.rootPane?.let { return it } } if (owner is Window) { owner.components.first { it is JComponent }?.let { return it as JComponent } } return JPanel() } override fun showPopup(e: AnActionEvent) { if (e is AnActionButton.AnActionEventWrapper) { e.showPopup(this) } else { showInBestPositionFor(e.dataContext) } } override fun showUnderneathToTheRightOf(component: Component) { val popupWidth = list.preferredSize.width show(RelativePoint(component, Point(component.width - popupWidth, component.height))) } } private class SdkListItemContext( private val myProject: Project? ) : ComboBoxPopup.Context<SdkListItem> { var myModel = SdkListModel.emptyModel() private val myRenderer = SdkListPresenter { myModel } override fun getProject() = myProject override fun getMaximumRowCount() = 30 override fun getModel() = myModel override fun getRenderer() = myRenderer }
platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/SdkPopupFactoryImpl.kt
4165502683
// 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. @file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty") package com.intellij.openapi.project.impl import com.intellij.conversion.ConversionResult import com.intellij.conversion.ConversionService import com.intellij.diagnostic.Activity import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.diagnostic.runActivity import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector import com.intellij.ide.AppLifecycleListener import com.intellij.ide.GeneralSettings import com.intellij.ide.IdeEventQueue import com.intellij.ide.SaveAndSyncHandler import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.impl.setTrusted import com.intellij.ide.lightEdit.LightEditCompatible import com.intellij.ide.startup.impl.StartupManagerImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.components.ComponentManagerEx import com.intellij.openapi.components.StorageScheme import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.getProjectDataPathRoot import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame import com.intellij.platform.PlatformProjectOpenProcessor import com.intellij.project.ProjectStoreOwner import com.intellij.projectImport.ProjectAttachProcessor import com.intellij.projectImport.ProjectOpenedCallback import com.intellij.ui.GuiUtils import com.intellij.ui.IdeUICustomization import com.intellij.util.io.delete import org.jetbrains.annotations.ApiStatus import java.awt.event.InvocationEvent import java.io.IOException import java.nio.file.* import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import java.util.function.BiFunction @ApiStatus.Internal open class ProjectManagerExImpl : ProjectManagerImpl() { final override fun createProject(name: String?, path: String): Project? { return newProject(toCanonicalName(path), OpenProjectTask(isNewProject = true, runConfigurators = false, projectName = name)) } final override fun newProject(projectName: String?, path: String, useDefaultProjectAsTemplate: Boolean, isDummy: Boolean): Project? { return newProject(toCanonicalName(path), OpenProjectTask(isNewProject = true, useDefaultProjectAsTemplate = useDefaultProjectAsTemplate, projectName = projectName)) } final override fun loadAndOpenProject(originalFilePath: String): Project? { return openProject(toCanonicalName(originalFilePath), OpenProjectTask()) } final override fun openProject(projectStoreBaseDir: Path, options: OpenProjectTask): Project? { return openProjectAsync(projectStoreBaseDir, options).get(30, TimeUnit.MINUTES) } final override fun openProjectAsync(projectStoreBaseDir: Path, options: OpenProjectTask): CompletableFuture<Project?> { if (LOG.isDebugEnabled && !ApplicationManager.getApplication().isUnitTestMode) { LOG.debug("open project: $options", Exception()) } if (options.project != null && isProjectOpened(options.project)) { return CompletableFuture.completedFuture(null) } val activity = StartUpMeasurer.startActivity("project opening preparation") if (!options.forceOpenInNewFrame) { val openProjects = openProjects if (!openProjects.isEmpty()) { var projectToClose = options.projectToClose if (projectToClose == null) { // if several projects are opened, ask to reuse not last opened project frame, but last focused (to avoid focus switching) val lastFocusedFrame = IdeFocusManager.getGlobalInstance().lastFocusedFrame projectToClose = lastFocusedFrame?.project if (projectToClose == null || projectToClose is LightEditCompatible) { projectToClose = openProjects.last() } } // this null assertion is required to overcome bug in new version of KT compiler: KT-40034 @Suppress("UNNECESSARY_NOT_NULL_ASSERTION") if (checkExistingProjectOnOpen(projectToClose!!, options.callback, projectStoreBaseDir, this)) { return CompletableFuture.completedFuture(null) } } } return doOpenAsync(options, projectStoreBaseDir, activity) } private fun doOpenAsync(options: OpenProjectTask, projectStoreBaseDir: Path, activity: Activity): CompletableFuture<Project?> { val frameAllocator = if (ApplicationManager.getApplication().isHeadlessEnvironment) ProjectFrameAllocator(options) else ProjectUiFrameAllocator(options, projectStoreBaseDir) val disableAutoSaveToken = SaveAndSyncHandler.getInstance().disableAutoSave() return frameAllocator.run { indicator -> activity.end() val result: PrepareProjectResult if (options.project == null) { result = prepareProject(options, projectStoreBaseDir) ?: return@run null } else { result = PrepareProjectResult(options.project, null) } val project = result.project if (!addToOpened(project)) { return@run null } frameAllocator.projectLoaded(project) try { openProject(project, indicator, isRunStartUpActivitiesEnabled(project)).join() } catch (e: ProcessCanceledException) { ApplicationManager.getApplication().invokeAndWait { closeProject(project, /* saveProject = */false, /* dispose = */true, /* checkCanClose = */false) } ApplicationManager.getApplication().messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed() return@run null } frameAllocator.projectOpened(project) result } .handle(BiFunction { result, error -> disableAutoSaveToken.finish() if (error != null) { throw error } if (result == null) { frameAllocator.projectNotLoaded(error = null) if (options.showWelcomeScreen) { WelcomeFrame.showIfNoProjectOpened() } return@BiFunction null } val project = result.project if (options.callback != null) { options.callback!!.projectOpened(project, result.module ?: ModuleManager.getInstance(project).modules[0]) } project }) } override fun openProject(project: Project): Boolean { val store = if (project is ProjectStoreOwner) (project as ProjectStoreOwner).componentStore else null if (store != null) { val projectFilePath = if (store.storageScheme == StorageScheme.DIRECTORY_BASED) store.directoryStorePath!! else store.projectFilePath for (p in openProjects) { if (ProjectUtil.isSameProject(projectFilePath, p)) { GuiUtils.invokeLaterIfNeeded({ ProjectUtil.focusProjectWindow(p, false) }, ModalityState.NON_MODAL) return false } } } if (!addToOpened(project)) { return false } val app = ApplicationManager.getApplication() if (!app.isUnitTestMode && app.isDispatchThread) { LOG.warn("Do not open project in EDT") } try { openProject(project, ProgressManager.getInstance().progressIndicator, isRunStartUpActivitiesEnabled(project)).join() } catch (e: ProcessCanceledException) { app.invokeAndWait { closeProject(project, /* saveProject = */false, /* dispose = */true, /* checkCanClose = */false) } app.messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed() if (!app.isUnitTestMode) { WelcomeFrame.showIfNoProjectOpened() } return false } return true } override fun newProject(projectFile: Path, options: OpenProjectTask): Project? { removeProjectConfigurationAndCaches(projectFile) val project = instantiateProject(projectFile, options) try { val template = if (options.useDefaultProjectAsTemplate) defaultProject else null initProject(projectFile, project, options.isRefreshVfsNeeded, options.preloadServices, template, ProgressManager.getInstance().progressIndicator) project.setTrusted(true) return project } catch (t: Throwable) { handleErrorOnNewProject(t) return null } } protected open fun handleErrorOnNewProject(t: Throwable) { LOG.warn(t) try { val errorMessage = message(t) ApplicationManager.getApplication().invokeAndWait { Messages.showErrorDialog(errorMessage, ProjectBundle.message("project.load.default.error")) } } catch (e: NoClassDefFoundError) { // error icon not loaded LOG.info(e) } } protected open fun instantiateProject(projectStoreBaseDir: Path, options: OpenProjectTask): ProjectImpl { val activity = StartUpMeasurer.startActivity("project instantiation") val project = ProjectExImpl(projectStoreBaseDir, options.projectName) activity.end() options.beforeInit?.invoke(project) return project } private fun prepareProject(options: OpenProjectTask, projectStoreBaseDir: Path): PrepareProjectResult? { val project: Project? val indicator = ProgressManager.getInstance().progressIndicator if (options.isNewProject) { removeProjectConfigurationAndCaches(projectStoreBaseDir) project = instantiateProject(projectStoreBaseDir, options) val template = if (options.useDefaultProjectAsTemplate) defaultProject else null initProject(projectStoreBaseDir, project, options.isRefreshVfsNeeded, options.preloadServices, template, indicator) } else { var conversionResult: ConversionResult? = null if (options.runConversionBeforeOpen) { val conversionService = ConversionService.getInstance() if (conversionService != null) { indicator?.text = IdeUICustomization.getInstance().projectMessage("progress.text.project.checking.configuration") conversionResult = runActivity("project conversion") { conversionService.convert(projectStoreBaseDir) } if (conversionResult.openingIsCanceled()) { return null } indicator?.text = "" } } project = instantiateProject(projectStoreBaseDir, options) // template as null here because it is not a new project initProject(projectStoreBaseDir, project, options.isRefreshVfsNeeded, options.preloadServices, null, indicator) if (conversionResult != null && !conversionResult.conversionNotNeeded()) { StartupManager.getInstance(project).runAfterOpened { conversionResult.postStartupActivity(project) } } } @Suppress("UNNECESSARY_NOT_NULL_ASSERTION") if (options.beforeOpen != null && !options.beforeOpen!!(project)) { return null } if (options.runConfigurators && (options.isNewProject || ModuleManager.getInstance(project).modules.isEmpty())) { val module = PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(projectStoreBaseDir, project, options.isProjectCreatedWithWizard) options.preparedToOpen?.invoke(module) return PrepareProjectResult(project, module) } else { return PrepareProjectResult(project, module = null) } } protected open fun isRunStartUpActivitiesEnabled(project: Project): Boolean = true } @NlsSafe private fun message(e: Throwable): String { var message = e.message ?: e.localizedMessage if (message != null) { return message } message = e.toString() val causeMessage = message(e.cause ?: return message) return "$message (cause: $causeMessage)" } private fun checkExistingProjectOnOpen(projectToClose: Project, callback: ProjectOpenedCallback?, projectDir: Path?, projectManager: ProjectManagerExImpl): Boolean { val settings = GeneralSettings.getInstance() val isValidProject = projectDir != null && ProjectUtil.isValidProjectPath(projectDir) var result = false // modality per thread, it means that we cannot use invokeLater, because after getting result from EDT, we MUST continue execution // in ORIGINAL thread ApplicationManager.getApplication().invokeAndWait task@{ if (projectDir != null && ProjectAttachProcessor.canAttachToProject() && (!isValidProject || settings.confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK)) { val exitCode = ProjectUtil.confirmOpenOrAttachProject() if (exitCode == -1) { result = true return@task } else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) { if (!projectManager.closeAndDispose(projectToClose)) { result = true return@task } } else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) { if (PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, callback)) { result = true return@task } } // process all pending events that can interrupt focus flow // todo this can be removed after taming the focus beast IdeEventQueue.getInstance().flushQueue() } else { val exitCode = ProjectUtil.confirmOpenNewProject(false) if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) { if (!projectManager.closeAndDispose(projectToClose)) { result = true return@task } } else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) { // not in a new window result = true return@task } } result = false } return result } private fun openProject(project: Project, indicator: ProgressIndicator?, runStartUpActivities: Boolean): CompletableFuture<*> { val waitEdtActivity = StartUpMeasurer.startActivity("placing calling projectOpened on event queue") if (indicator != null) { indicator.text = if (ApplicationManager.getApplication().isInternal) "Waiting on event queue..." // NON-NLS (internal mode) else ProjectBundle.message("project.preparing.workspace") indicator.isIndeterminate = true } // invokeLater cannot be used for now ApplicationManager.getApplication().invokeAndWait { waitEdtActivity.end() if (indicator != null && ApplicationManager.getApplication().isInternal) { indicator.text = "Running project opened tasks..." // NON-NLS (internal mode) } ProjectManagerImpl.LOG.debug("projectOpened") LifecycleUsageTriggerCollector.onProjectOpened(project) val activity = StartUpMeasurer.startActivity("project opened callbacks") runActivity("projectOpened event executing") { ApplicationManager.getApplication().messageBus.syncPublisher(ProjectManager.TOPIC).projectOpened(project) } @Suppress("DEPRECATION") (project as ComponentManagerEx) .processInitializedComponents(com.intellij.openapi.components.ProjectComponent::class.java) { component, pluginDescriptor -> ProgressManager.checkCanceled() try { val componentActivity = StartUpMeasurer.startActivity(component.javaClass.name, ActivityCategory.PROJECT_OPEN_HANDLER, pluginDescriptor.pluginId.idString) component.projectOpened() componentActivity.end() } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { ProjectManagerImpl.LOG.error(e) } } activity.end() ProjectImpl.ourClassesAreLoaded = true } if (runStartUpActivities) { (StartupManager.getInstance(project) as StartupManagerImpl).projectOpened(indicator) } return CompletableFuture.completedFuture(null) } // allow `invokeAndWait` inside startup activities internal fun waitAndProcessInvocationEventsInIdeEventQueue(startupManager: StartupManagerImpl) { val eventQueue = IdeEventQueue.getInstance() while (true) { // getNextEvent() will block until an event has been posted by another thread, so, // peekEvent() is used to check that there is already some event in the queue if (eventQueue.peekEvent() == null) { if (startupManager.postStartupActivityPassed()) { break } else { continue } } val event = eventQueue.nextEvent if (event is InvocationEvent) { eventQueue.dispatchEvent(event) } } } private data class PrepareProjectResult(val project: Project, val module: Module?) private fun toCanonicalName(filePath: String): Path { val file = Paths.get(filePath) try { if (SystemInfoRt.isWindows && FileUtil.containsWindowsShortName(filePath)) { return file.toRealPath(LinkOption.NOFOLLOW_LINKS) } } catch (e: InvalidPathException) { } catch (e: IOException) { // OK. File does not yet exist, so its canonical path will be equal to its original path. } return file } private fun removeProjectConfigurationAndCaches(projectFile: Path) { try { if (Files.isRegularFile(projectFile)) { Files.deleteIfExists(projectFile) } else { Files.newDirectoryStream(projectFile.resolve(Project.DIRECTORY_STORE_FOLDER)).use { directoryStream -> for (file in directoryStream) { file!!.delete() } } } } catch (ignored: IOException) { } try { getProjectDataPathRoot(projectFile).delete() } catch (ignored: IOException) { } }
platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerExImpl.kt
2086223751
package io.codekvast.intake.file_import.impl import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.whenever import io.codekvast.common.lock.LockTemplate import io.codekvast.common.messaging.EventService import io.codekvast.intake.metrics.IntakeMetricsService import io.codekvast.intake.model.PublicationType.CODEBASE import io.codekvast.javaagent.model.v2.CommonPublicationData2 import io.codekvast.javaagent.model.v3.CodeBaseEntry3 import io.codekvast.javaagent.model.v3.CodeBasePublication3 import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.Mockito.verify import org.mockito.MockitoAnnotations import java.time.Clock import java.time.Duration import java.time.Instant import java.util.concurrent.Callable /** @author [email protected] */ class CodeBaseImporterImplTest { @Mock private lateinit var clock: Clock @Mock private lateinit var syntheticSignatureService: SyntheticSignatureService @Mock private lateinit var lockTemplate: LockTemplate @Mock private lateinit var metricsService: IntakeMetricsService @Mock private lateinit var commonImporter: CommonImporter @Mock private lateinit var importDAO: ImportDAO @Mock private lateinit var eventService: EventService @InjectMocks private lateinit var codeBaseImporter: CodeBaseImporterImpl @BeforeEach fun beforeTest() { MockitoAnnotations.openMocks(this) whenever(clock.instant()).thenReturn(Instant.now()) } @Test fun should_ignore_synthetic_signatures() { // given val syntheticSignature = "customer1.FooConfig..EnhancerBySpringCGLIB..96aac875.CGLIB\$BIND_CALLBACKS(java.lang.Object)" val publication = CodeBasePublication3.builder() .commonData(CommonPublicationData2.sampleCommonPublicationData()) .entries( listOf( CodeBaseEntry3.sampleCodeBaseEntry(), CodeBaseEntry3.sampleCodeBaseEntry().toBuilder() .signature(syntheticSignature) .build() ) ) .build() whenever(syntheticSignatureService.isSyntheticMethod(syntheticSignature)).thenReturn(true) whenever(lockTemplate.doWithLockOrThrow(any(), any<Callable<Any>>())) .thenReturn(Duration.ofSeconds(1)) // when codeBaseImporter.importPublication(publication) // then verify(metricsService).recordImportedPublication(CODEBASE, 1, 1, Duration.ofSeconds(1)) } }
product/server/intake/src/test/kotlin/io/codekvast/intake/file_import/impl/CodeBaseImporterImplTest.kt
2592389247
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.execution.build import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.impl.DefaultJavaProgramRunner import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ProgramRunner import com.intellij.execution.runners.RunContentBuilder import com.intellij.execution.ui.RunContentDescriptor internal class DelegateBuildRunner : DefaultJavaProgramRunner() { override fun getRunnerId() = ID override fun doExecute(state: RunProfileState, environment: ExecutionEnvironment): RunContentDescriptor? { val executionResult = state.execute(environment.executor, this) ?: return null val runContentBuilder = RunContentBuilder(executionResult, environment) val runContentDescriptor = runContentBuilder.showRunContent(environment.contentToReuse) ?: return null val descriptor = object : RunContentDescriptor(runContentDescriptor.executionConsole, runContentDescriptor.processHandler, runContentDescriptor.component, runContentDescriptor.displayName, runContentDescriptor.icon, null, runContentDescriptor.restartActions) { override fun isHiddenContent() = true } descriptor.runnerLayoutUi = runContentDescriptor.runnerLayoutUi return descriptor } companion object { private const val ID = "MAVEN_DELEGATE_BUILD_RUNNER" @JvmStatic fun getDelegateRunner(): ProgramRunner<*>? = ProgramRunner.findRunnerById(ID) } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/build/DelegateBuildRunner.kt
695005125
// IGNORE_BACKEND: NATIVE import kotlin.test.* import kotlin.test.assertTrue import kotlin.comparisons.* import kotlin.test.assertEquals private fun <T : Comparable<T>> totalOrderMinOf2(f2t: (T, T) -> T, function: String) { @Suppress("UNCHECKED_CAST") with(Double) { assertEquals<Any>(0.0, f2t(0.0 as T, NaN as T), "$function(0, NaN)") assertEquals<Any>(0.0, f2t(NaN as T, 0.0 as T), "$function(NaN, 0)") } } fun box() { totalOrderMinOf2<Comparable<Any>>({ a, b -> sequenceOf(a, b).min()!! }, "sequenceOf().min()") }
backend.native/tests/external/stdlib/numbers/NaNPropagationTest/sequenceTMin.kt
3409333704
import kotlin.reflect.KProperty class Delegate<T>(var inner: T) { operator fun getValue(t: Any?, p: KProperty<*>): T = inner operator fun setValue(t: Any?, p: KProperty<*>, i: T) { inner = i } } class A { inner class B { var prop: Int by Delegate(1) } } fun box(): String { val c = A().B() if(c.prop != 1) return "fail get" c.prop = 2 if (c.prop != 2) return "fail set" return "OK" }
backend.native/tests/external/codegen/box/delegatedProperty/genericDelegate.kt
2449014559
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package engine import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.net.VpnService import android.os.IBinder import kotlinx.coroutines.CompletableDeferred import model.BlokadaException import model.Dns import model.TunnelStatus import service.ContextService import ui.utils.cause import utils.Logger import java.net.DatagramSocket import java.net.Socket object SystemTunnelService { private val log = Logger("SystemTunnel") private val context = ContextService private var connection: SystemTunnelConnection? = null @Synchronized get @Synchronized set var onConfigureTunnel: (vpn: VpnService.Builder) -> Unit = {} var onTunnelClosed = { ex: BlokadaException? -> } private var tunnel: SystemTunnel? = null fun setup() { log.v("Starting SystemTunnel service") val ctx = context.requireAppContext() val intent = Intent(ctx, SystemTunnel::class.java) ctx.startService(intent) } suspend fun getStatus(): Boolean { return try { val hasFileDescriptor = getConnection().binder.tunnel.queryConfig() != null hasFileDescriptor } catch (ex: Exception) { log.e("Could not get tunnel status".cause(ex)) false } } suspend fun open(): SystemTunnelConfig { log.v("Received a request to open tunnel") try { return getConnection().binder.tunnel.turnOn() } catch (ex: Exception) { log.w("Could not turn on, unbinding to rebind on next attempt: ${ex.message}") unbind() throw ex } } suspend fun close() { log.v("Received a request to close tunnel") getConnection().binder.tunnel.turnOff() } suspend fun getTunnelConfig(): SystemTunnelConfig { return getConnection().binder.tunnel.queryConfig() ?: throw BlokadaException("No system tunnel started") } fun protectSocket(socket: DatagramSocket) { tunnel?.protect(socket) ?: log.w("No tunnel reference while called protectSocket()") } fun protectSocket(socket: Socket) { tunnel?.protect(socket) ?: log.w("No tunnel reference while called protectSocket()") } private suspend fun getConnection(): SystemTunnelConnection { return connection ?: run { val deferred = CompletableDeferred<SystemTunnelBinder>() val connection = bind(deferred) deferred.await() log.v("Bound SystemTunnel") this.connection = connection this.tunnel = connection.binder.tunnel connection } } private suspend fun bind(deferred: ConnectDeferred): SystemTunnelConnection { log.v("Binding SystemTunnel") val ctx = context.requireAppContext() val intent = Intent(ctx, SystemTunnel::class.java).apply { action = SYSTEM_TUNNEL_BINDER_ACTION } val connection = SystemTunnelConnection(deferred, { onConfigureTunnel(it) }, onTunnelClosed = { log.w("Tunnel got closed, unbinding (if bound)") unbind() this.onTunnelClosed(it) }, onConnectionClosed = { this.connection = null }) if (!ctx.bindService(intent, connection, Context.BIND_AUTO_CREATE or Context.BIND_ABOVE_CLIENT or Context.BIND_IMPORTANT )) { deferred.completeExceptionally(BlokadaException("Could not bindService()")) } else { // delay(3000) // if (!deferred.isCompleted) deferred.completeExceptionally( // BlokadaException("Timeout waiting for bindService()") // ) } return connection } fun unbind() { connection?.let { log.v("Unbinding SystemTunnel") try { val ctx = context.requireAppContext() ctx.unbindService(it) log.v("unbindService called") } catch (ex: Exception) { log.w("unbindService failed: ${ex.message}") } } connection = null } } private class SystemTunnelConnection( private val deferred: ConnectDeferred, var onConfigureTunnel: (vpn: VpnService.Builder) -> Unit, var onTunnelClosed: (exception: BlokadaException?) -> Unit, val onConnectionClosed: () -> Unit ): ServiceConnection { private val log = Logger("SystemTunnel") lateinit var binder: SystemTunnelBinder override fun onServiceConnected(name: ComponentName, binder: IBinder) { this.binder = binder as SystemTunnelBinder binder.onConfigureTunnel = onConfigureTunnel binder.onTunnelClosed = onTunnelClosed deferred.complete(this.binder) } override fun onServiceDisconnected(name: ComponentName?) { log.w("onServiceDisconnected") onConnectionClosed() } } private typealias ConnectDeferred = CompletableDeferred<SystemTunnelBinder>
android5/app/src/engine/kotlin/engine/SystemTunnelService.kt
536620689
// TARGET_BACKEND: JVM // IGNORE_LIGHT_ANALYSIS // WITH_RUNTIME // KOTLIN_CONFIGURATION_FLAGS: +JVM.INHERIT_MULTIFILE_PARTS // FILE: box.kt import a.* fun box(): String = OK().ok // FILE: part1.kt @file:[JvmName("MultifileClass") JvmMultifileClass] package a private val reallyOk = run { "OK" } class OK() { val ok = reallyOk }
backend.native/tests/external/codegen/box/multifileClasses/optimized/valWithAccessor.kt
3336394336
/* * Copyright (C) 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.health.connect.client.changes import androidx.health.connect.client.records.Record /** * A [Change] with inserted or updated [Record]. * * @property record Updated or inserted record. */ class UpsertionChange internal constructor(public val record: Record) : Change
health/connect/connect-client/src/main/java/androidx/health/connect/client/changes/UpsertionChange.kt
1120349879
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.caches.resolve import com.intellij.openapi.module.Module import com.intellij.testFramework.IdeaTestUtil import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR import org.jetbrains.kotlin.test.KotlinCompilerStandalone import org.jetbrains.kotlin.test.KotlinTestUtils import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith import java.io.File @RunWith(JUnit38ClassRunner::class) class Java9MultiModuleHighlightingTest : AbstractMultiModuleHighlightingTest() { override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("multiModuleHighlighting/java9") private fun module(name: String): Module = super.module(name, false) { IdeaTestUtil.getMockJdk9() } fun testSimpleModuleExportsPackage() { module("main").addDependency(module("dependency")) checkHighlightingInProject() } fun testSimpleLibraryExportsPackage() { val sources = listOf(File(testDataPath, getTestName(true) + "/library")) // -Xallow-kotlin-package to avoid "require kotlin.stdlib" in module-info.java val extraOptions = listOf("-jdk-home", KotlinTestUtils.getAtLeastJdk9Home().path, "-Xallow-kotlin-package") val libraryJar = KotlinCompilerStandalone( sources, platform = KotlinCompilerStandalone.Platform.Jvm(JvmTarget.JVM_9), options = extraOptions ).compile() module("main").addLibrary(libraryJar, "library") checkHighlightingInProject() } fun testNamedDependsOnUnnamed() { module("main").addDependency(module("dependency")) checkHighlightingInProject() } fun testUnnamedDependsOnNamed() { module("main").addDependency(module("dependency")) checkHighlightingInProject() } fun testDeclarationKinds() { module("main").addDependency(module("dependency")) checkHighlightingInProject() } fun testExportsTo() { val d = module("dependency") module("first").addDependency(d) module("second").addDependency(d) module("unnamed").addDependency(d) checkHighlightingInProject() } fun testExportedPackageIsInaccessibleWithoutRequires() { module("main").addDependency(module("dependency")) checkHighlightingInProject() } fun testTypealiasToUnexported() { module("main").addDependency(module("dependency")) checkHighlightingInProject() } fun testCyclicDependency() { val a = module("moduleA") val b = module("moduleB") val c = module("moduleC") module("main").addDependency(a).addDependency(b).addDependency(c) checkHighlightingInProject() } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/caches/resolve/Java9MultiModuleHighlightingTest.kt
357707944