content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package co.smartreceipts.android.identity.apis.organizations data class OrganizationModel( val organization: Organization, val userRole: OrganizationUser.UserRole, val settingsMatch: Boolean )
app/src/main/java/co/smartreceipts/android/identity/apis/organizations/OrganizationModel.kt
4261063390
/* * Copyright 2016, 2017 Thomas Harning Jr. <[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 us.eharning.atomun.core.ec.internal import org.bouncycastle.asn1.ASN1Integer import org.bouncycastle.asn1.ASN1Sequence import org.bouncycastle.asn1.DERSequenceGenerator import org.bouncycastle.crypto.digests.SHA256Digest import org.bouncycastle.crypto.params.ECPrivateKeyParameters import org.bouncycastle.crypto.params.ECPublicKeyParameters import org.bouncycastle.crypto.signers.ECDSASigner import org.bouncycastle.math.ec.ECPoint import us.eharning.atomun.core.ec.ECDSA import us.eharning.atomun.core.ec.ECKey import us.eharning.atomun.core.ec.internal.BouncyCastleECKeyConstants.CURVE import us.eharning.atomun.core.ec.internal.BouncyCastleECKeyConstants.DOMAIN import java.io.ByteArrayOutputStream import java.io.IOException import java.math.BigInteger import javax.annotation.concurrent.Immutable /** * Signature implementation using exposed secret exponent / public ECPoint. */ @Immutable internal class BouncyCastleECSigner /** * Construct a signature operation with the given key material. * * @param privateExponent * Private exponent from EC key - if present, signatures are allowed. * @param publicPoint * Public point on the Elliptical Curve, verification is dependent on this. * @param canonicalize * If true, then the signature point is canonicalized. */ @JvmOverloads constructor( private val privateExponent: BigInteger?, private val publicPoint: ECPoint, private val canonicalize: Boolean = true ) : ECDSA { /** * Obtain an ECDSA instance with the given canonicalization bit set. * * @param canonicalize * If true, then the signature point is canonicalized. * * @return * ECDSA instance with canonicalization set to the given value. */ fun withCanonicalize(canonicalize: Boolean): BouncyCastleECSigner { if (this.canonicalize == canonicalize) { return this } return BouncyCastleECSigner(privateExponent, publicPoint, canonicalize) } /** * Perform an ECDSA signature using the private key. * * @param hash * byte array to sign. * * @return ASN.1 representation of the signature. */ override fun sign(hash: ByteArray): ByteArray { if (null == privateExponent) { throw UnsupportedOperationException("Cannot sign with public key") } /* The HMacDSAKCalculator is what makes this signer RFC 6979 compliant. */ val signer = ECDSASigner(RFC6979KCalculator(SHA256Digest())) signer.init(true, ECPrivateKeyParameters(privateExponent, DOMAIN)) val signature = signer.generateSignature(hash) /* Need to canonicalize signature up front ... */ if (canonicalize && signature[1] > HALF_CURVE_ORDER) { /* BOP does not do this */ signature[1] = CURVE.n - signature[1] } return calculateSignature(signature) } /** * Convert the DSA signature-parts into a byte array. * * @param signature * ECDSA signature to convert. * * @return * byte[] for of signature. */ @Throws(IOException::class) fun calculateSignature(signature: Array<BigInteger>): ByteArray { val stream = ByteArrayOutputStream() val seq = DERSequenceGenerator(stream) seq.addObject(ASN1Integer(signature[0])) seq.addObject(ASN1Integer(signature[1])) seq.close() return stream.toByteArray() } /** * Verify an ECDSA signature using the public key. * * @param hash * byte array of the hash to verify. * @param signature * ASN.1 representation of the signature to verify hash with. * * @return true if the signature matches, else false. */ @SuppressWarnings("checkstyle:localvariablename") override fun verify(hash: ByteArray, signature: ByteArray): Boolean { try { val signer = ECDSASigner() signer.init(false, ECPublicKeyParameters(publicPoint, DOMAIN)) val seq = ASN1Sequence.getInstance(signature) val r = seq.getObjectAt(0) val s = seq.getObjectAt(1) if (r !is ASN1Integer || s !is ASN1Integer) { return false } return signer.verifySignature(hash, r.positiveValue, s.positiveValue) } catch (e: Throwable) { // treat format errors as invalid signatures return false } } companion object { private val HALF_CURVE_ORDER = CURVE.n.shiftRight(1) /** * Obtain a signer given a private key - specifically a BouncyCastleECKeyPair. * * @param privateKey * Key instance to collect data for signing from. * * @return * ECDSA instance capable of signature and verification. */ @JvmStatic fun fromPrivateKey(privateKey: ECKey): BouncyCastleECSigner { assert(privateKey is BouncyCastleECKeyPair) val publicPoint = CURVE.curve.decodePoint(privateKey.exportPublic()) val privateExponent = (privateKey as BouncyCastleECKeyPair).privateExponent return BouncyCastleECSigner(privateExponent, publicPoint) } /** * Obtain a signer given any public key. * * @param publicKey * Key instance to collect data for verification from. * * @return * ECDSA instance capable of verification. */ @JvmStatic fun fromPublicKey(publicKey: ECKey): BouncyCastleECSigner { val publicPoint = CURVE.curve.decodePoint(publicKey.exportPublic()) return BouncyCastleECSigner(null, publicPoint) } } }
src/main/kotlin/us/eharning/atomun/core/ec/internal/BouncyCastleECSigner.kt
3751454613
package ua.com.lavi.komock.http.handler.response import ua.com.lavi.komock.model.Request import ua.com.lavi.komock.model.Response /** * Created by Oleksandr Loushkin */ class EmptyResponseHandler : ResponseHandler { override fun handle(request: Request, response: Response) { // nothing to do } }
komock-core/src/main/kotlin/ua/com/lavi/komock/http/handler/response/EmptyResponseHandler.kt
3203787136
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.updates import com.intellij.ide.startup.StartupActionScriptManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.io.IoTestUtil import com.intellij.testFramework.fixtures.BareTestFixtureTestCase import com.intellij.testFramework.rules.TempDirectory import com.intellij.util.io.createDirectories import com.intellij.util.io.delete import com.intellij.util.io.exists import com.intellij.util.io.outputStream import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import java.io.File import java.io.ObjectOutputStream import java.nio.file.Path import java.nio.file.Paths class StartupActionScriptManagerTest : BareTestFixtureTestCase() { @Rule @JvmField val tempDir = TempDirectory() private lateinit var scriptFile: Path @Before fun setUp() { scriptFile = Paths.get(PathManager.getPluginTempPath(), StartupActionScriptManager.ACTION_SCRIPT_FILE) scriptFile.parent.createDirectories() } @After fun tearDown() { scriptFile.delete() } @Test fun `reading and writing empty file`() { StartupActionScriptManager.addActionCommands(listOf()) assertTrue(scriptFile.exists()) StartupActionScriptManager.executeActionScript() assertFalse(scriptFile.exists()) } @Test fun `reading empty file in old format`() { ObjectOutputStream(scriptFile.outputStream()).use { it.writeObject(ArrayList<StartupActionScriptManager.ActionCommand>()) } assertTrue(scriptFile.exists()) StartupActionScriptManager.executeActionScript() assertFalse(scriptFile.exists()) } @Test fun `executing "copy" command`() { val source = tempDir.newFile("source.txt") val destination = File(tempDir.root, "destination.txt") assertTrue(source.exists()) assertFalse(destination.exists()) StartupActionScriptManager.addActionCommand(StartupActionScriptManager.CopyCommand(source, destination)) StartupActionScriptManager.executeActionScript() assertTrue(destination.exists()) assertTrue(source.exists()) assertFalse(scriptFile.exists()) } @Test fun `executing "unzip" command`() { val source = IoTestUtil.createTestJar(tempDir.newFile("source.zip"), "zip/file.txt", "") val destination = tempDir.newFolder("dir") val unpacked = File(destination, "zip/file.txt") assertTrue(source.exists()) assertFalse(unpacked.exists()) StartupActionScriptManager.addActionCommand(StartupActionScriptManager.UnzipCommand(source, destination)) StartupActionScriptManager.executeActionScript() assertTrue(unpacked.exists()) assertTrue(source.exists()) assertFalse(scriptFile.exists()) } @Test fun `executing "delete" command`() { val tempFile = tempDir.newFile("temp.txt") assertTrue(tempFile.exists()) StartupActionScriptManager.addActionCommand(StartupActionScriptManager.DeleteCommand(tempFile)) StartupActionScriptManager.executeActionScript() assertFalse(tempFile.exists()) assertFalse(scriptFile.exists()) } @Test fun `executing commands with path mapping`() { val oldTarget = tempDir.newFolder("old/plugins") val newTarget = tempDir.newFolder("new/plugins") val copySource = tempDir.newFile("source.txt") val copyDestinationInOld = File(oldTarget, "destination.txt") val copyDestinationInNew = File(newTarget, "destination.txt") val unzipSource = IoTestUtil.createTestJar(tempDir.newFile("source.zip"), "zip/file.txt", "") val unpackedInOld = File(oldTarget, "zip/file.txt") val unpackedInNew = File(newTarget, "zip/file.txt") val deleteInOld = tempDir.newFile("old/plugins/to_delete.txt") val deleteInNew = tempDir.newFile("new/plugins/to_delete.txt") StartupActionScriptManager.addActionCommands(listOf( StartupActionScriptManager.CopyCommand(copySource, copyDestinationInOld), StartupActionScriptManager.UnzipCommand(unzipSource, oldTarget), StartupActionScriptManager.DeleteCommand(deleteInOld))) StartupActionScriptManager.executeActionScript(scriptFile, oldTarget.toPath(), newTarget) assertFalse(copyDestinationInOld.exists()) assertTrue(copyDestinationInNew.exists()) assertFalse(unpackedInOld.exists()) assertTrue(unpackedInNew.exists()) assertTrue(deleteInOld.exists()) assertFalse(deleteInNew.exists()) assertTrue(scriptFile.exists()) } }
platform/platform-tests/testSrc/com/intellij/ide/updates/StartupActionScriptManagerTest.kt
2695121298
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.colors import com.demonwav.mcdev.nbt.lang.NbttLexerAdapter import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.psi.tree.IElementType class NbttSyntaxHighlighter : SyntaxHighlighterBase() { override fun getHighlightingLexer() = NbttLexerAdapter() override fun getTokenHighlights(tokenType: IElementType): Array<TextAttributesKey> { return when (tokenType) { NbttTypes.BYTES, NbttTypes.INTS, NbttTypes.LONGS -> KEYWORD_KEYS NbttTypes.STRING_LITERAL -> STRING_KEYS NbttTypes.UNQUOTED_STRING_LITERAL -> UNQUOTED_STRING_KEYS NbttTypes.BYTE_LITERAL -> BYTE_KEYS NbttTypes.SHORT_LITERAL -> SHORT_KEYS NbttTypes.INT_LITERAL -> INT_KEYS NbttTypes.LONG_LITERAL -> LONG_KEYS NbttTypes.FLOAT_LITERAL -> FLOAT_KEYS NbttTypes.DOUBLE_LITERAL -> DOUBLE_KEYS else -> EMPTY_KEYS } } companion object { val KEYWORD = TextAttributesKey.createTextAttributesKey("NBTT_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD) val STRING = TextAttributesKey.createTextAttributesKey("NBTT_STRING", DefaultLanguageHighlighterColors.STRING) val UNQUOTED_STRING = TextAttributesKey.createTextAttributesKey("NBTT_UNQUOTED_STRING", STRING) val STRING_NAME = TextAttributesKey.createTextAttributesKey("NBTT_STRING_NAME", STRING) val UNQUOTED_STRING_NAME = TextAttributesKey.createTextAttributesKey("NBTT_UNQUOTED_STRING_NAME", STRING_NAME) val BYTE = TextAttributesKey.createTextAttributesKey("NBTT_BYTE", DefaultLanguageHighlighterColors.NUMBER) val SHORT = TextAttributesKey.createTextAttributesKey("NBTT_SHORT", DefaultLanguageHighlighterColors.NUMBER) val INT = TextAttributesKey.createTextAttributesKey("NBTT_INT", DefaultLanguageHighlighterColors.NUMBER) val LONG = TextAttributesKey.createTextAttributesKey("NBTT_LONG", DefaultLanguageHighlighterColors.NUMBER) val FLOAT = TextAttributesKey.createTextAttributesKey("NBTT_FLOAT", DefaultLanguageHighlighterColors.NUMBER) val DOUBLE = TextAttributesKey.createTextAttributesKey("NBTT_DOUBLE", DefaultLanguageHighlighterColors.NUMBER) val MATERIAL = TextAttributesKey.createTextAttributesKey("NBTT_MATERIAL", STRING) val KEYWORD_KEYS = arrayOf(KEYWORD) val STRING_KEYS = arrayOf(STRING) val UNQUOTED_STRING_KEYS = arrayOf(UNQUOTED_STRING) val BYTE_KEYS = arrayOf(BYTE) val SHORT_KEYS = arrayOf(SHORT) val INT_KEYS = arrayOf(INT) val LONG_KEYS = arrayOf(LONG) val FLOAT_KEYS = arrayOf(FLOAT) val DOUBLE_KEYS = arrayOf(DOUBLE) val EMPTY_KEYS = emptyArray<TextAttributesKey>() } }
src/main/kotlin/com/demonwav/mcdev/nbt/lang/colors/NbttSyntaxHighlighter.kt
3205701018
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.impl.ComponentManagerImpl import com.intellij.openapi.components.impl.ServiceManagerImpl import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.module.impl.ModuleManagerImpl import com.intellij.openapi.project.Project import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.util.* import com.intellij.util.containers.forEachGuaranteed import com.intellij.util.io.exists import com.intellij.util.io.outputStream import gnu.trove.THashSet import org.jdom.Element import java.nio.file.FileSystems import java.nio.file.Path internal fun normalizeDefaultProjectElement(defaultProject: Project, element: Element, projectConfigDir: Path) { LOG.runAndLogException { moveComponentConfiguration(defaultProject, element) { projectConfigDir.resolve(it) } } val iterator = element.getChildren("component").iterator() for (component in iterator) { val componentName = component.getAttributeValue("name") fun writeProfileSettings(schemeDir: Path) { component.removeAttribute("name") if (component.isEmpty()) { return } val wrapper = Element("component").setAttribute("name", componentName) component.name = "settings" wrapper.addContent(component) val file = schemeDir.resolve("profiles_settings.xml") if (file.fileSystem == FileSystems.getDefault()) { // VFS must be used to write workspace.xml and misc.xml to ensure that project files will be not reloaded on external file change event writeFile(file, fakeSaveSession, null, createDataWriterForElement(wrapper, "default project"), LineSeparator.LF, prependXmlProlog = false) } else { file.outputStream().use { wrapper.write(it) } } } when (componentName) { "InspectionProjectProfileManager" -> { iterator.remove() val schemeDir = projectConfigDir.resolve("inspectionProfiles") convertProfiles(component.getChildren("profile").iterator(), componentName, schemeDir) component.removeChild("version") writeProfileSettings(schemeDir) } "CopyrightManager" -> { iterator.remove() val schemeDir = projectConfigDir.resolve("copyright") convertProfiles(component.getChildren("copyright").iterator(), componentName, schemeDir) writeProfileSettings(schemeDir) } ModuleManagerImpl.COMPONENT_NAME -> { iterator.remove() } } } } private fun convertProfiles(profileIterator: MutableIterator<Element>, componentName: String, schemeDir: Path) { for (profile in profileIterator) { val schemeName = profile.getChildren("option").find { it.getAttributeValue("name") == "myName" }?.getAttributeValue("value") ?: continue profileIterator.remove() val wrapper = Element("component").setAttribute("name", componentName) wrapper.addContent(profile) val path = schemeDir.resolve("${FileUtil.sanitizeFileName(schemeName, true)}.xml") JDOMUtil.write(wrapper, path.outputStream(), "\n") } } internal fun moveComponentConfiguration(defaultProject: Project, element: Element, fileResolver: (name: String) -> Path) { val componentElements = element.getChildren("component") if (componentElements.isEmpty()) { return } val workspaceComponentNames = THashSet(listOf("GradleLocalSettings")) val compilerComponentNames = THashSet<String>() fun processComponents(aClass: Class<*>) { val stateAnnotation = getStateSpec(aClass) if (stateAnnotation == null || stateAnnotation.name.isEmpty()) { return } val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return when { storage.path == StoragePathMacros.WORKSPACE_FILE -> workspaceComponentNames.add(stateAnnotation.name) storage.path == "compiler.xml" -> compilerComponentNames.add(stateAnnotation.name) } } @Suppress("DEPRECATION") val projectComponents = defaultProject.getComponents(PersistentStateComponent::class.java) projectComponents.forEachGuaranteed { processComponents(it.javaClass) } ServiceManagerImpl.processAllImplementationClasses(defaultProject as ComponentManagerImpl) { aClass, _ -> processComponents(aClass) true } @Suppress("RemoveExplicitTypeArguments") val elements = mapOf(compilerComponentNames to SmartList<Element>(), workspaceComponentNames to SmartList<Element>()) val iterator = componentElements.iterator() for (componentElement in iterator) { val name = componentElement.getAttributeValue("name") ?: continue for ((names, list) in elements) { if (names.contains(name)) { iterator.remove() list.add(componentElement) } } } for ((names, list) in elements) { writeConfigFile(list, fileResolver(if (names === workspaceComponentNames) "workspace.xml" else "compiler.xml")) } } private fun writeConfigFile(elements: List<Element>, file: Path) { if (elements.isEmpty()) { return } var wrapper = Element("project").setAttribute("version", "4") if (file.exists()) { try { wrapper = loadElement(file) } catch (e: Exception) { LOG.warn(e) } } elements.forEach { wrapper.addContent(it) } // .idea component configuration files uses XML prolog due to historical reasons if (file.fileSystem == FileSystems.getDefault()) { // VFS must be used to write workspace.xml and misc.xml to ensure that project files will be not reloaded on external file change event writeFile(file, fakeSaveSession, null, createDataWriterForElement(wrapper, "default project"), LineSeparator.LF, prependXmlProlog = true) } else { file.outputStream().use { it.write(XML_PROLOG) it.write(LineSeparator.LF.separatorBytes) wrapper.write(it) } } } private val fakeSaveSession = object : SaveSession { override fun save() { } }
platform/configuration-store-impl/src/defaultProjectElementNormalizer.kt
1923415349
package boomcity.accessiboard import android.app.AlertDialog import android.content.Context import android.support.design.widget.TabLayout import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import com.github.clans.fab.FloatingActionButton import com.github.clans.fab.FloatingActionMenu import android.content.Intent import android.app.Activity import android.net.Uri import android.speech.tts.TextToSpeech import android.support.v7.widget.RecyclerView import com.google.gson.* import android.support.design.widget.AppBarLayout class MainActivity : AppCompatActivity(), TabLayout.OnTabSelectedListener, TextToSpeech.OnInitListener { private var mSectionsPagerAdapter: SectionsPagerAdapter? = null lateinit var tts: TextToSpeech lateinit var mViewPager: ViewPager lateinit var mToolBar: Toolbar lateinit var tabLayout: TabLayout lateinit var tabFAM: FloatingActionMenu lateinit var renameTabFab: FloatingActionButton lateinit var deleteTabFab: FloatingActionButton companion object { val READ_REQUEST_CODE = 42 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) tts = TextToSpeech(this, this) mToolBar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(mToolBar) getStoredTabData() mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager) mViewPager = findViewById(R.id.container) as ViewPager mViewPager.adapter = mSectionsPagerAdapter mViewPager.setOffscreenPageLimit(10) //10 max tabs DataService.setViewpager(mViewPager) tabLayout = findViewById(R.id.tabs) as TabLayout tabLayout.setupWithViewPager(mViewPager) tabLayout.addOnTabSelectedListener(this) tabFAM = findViewById(R.id.tab_FAM) as FloatingActionMenu renameTabFab = findViewById(R.id.floating_menu_rename) as FloatingActionButton deleteTabFab = findViewById(R.id.floating_menu_delete) as FloatingActionButton tabFAM.visibility = View.INVISIBLE renameTabFab.setOnClickListener({ renameTab() }) deleteTabFab.setOnClickListener({ deleteTab() }) } private fun getStoredTabData() { val sharedPrefs = getPreferences(Context.MODE_PRIVATE) val gson = Gson() val json = sharedPrefs.getString("TabsDataInfo", "") var tabsData = gson.fromJson<TabsData>(json, TabsData::class.java) if (tabsData == null) { //first startup val defaultTabSounds = mutableListOf<TtsObject>(TtsObject("Default TTS Object","Some tts phrase here")) tabsData = TabsData(mutableListOf(TabDataInfo("All",0, defaultTabSounds),TabDataInfo("Favorites", 1, mutableListOf()))) } DataService.init(tabsData,sharedPrefs) } fun addNewTab(tabName: String) { tabLayout.addTab(tabLayout.newTab()) mSectionsPagerAdapter!!.addNewTab(tabName) } fun renameTab() { val newFragment = EditDialogFragment(this) newFragment.show(fragmentManager, tabLayout.selectedTabPosition.toString()) tabFAM.close(true) } fun deleteTab() { val selectedTabIndex = tabLayout.selectedTabPosition if (selectedTabIndex > 1) { mSectionsPagerAdapter!!.removeTab(selectedTabIndex) val tab = tabLayout.getTabAt(selectedTabIndex - 1) tab!!.select() tabFAM.close(true) } } fun newSoundClipName(ttsObjectName: String, audioUri: String) { if (DataService.getTabsData().getTab(0)!!.ttsObjects.any { tts -> tts.Title.toLowerCase() == ttsObjectName.toLowerCase() }) { val errorBuilder = AlertDialog.Builder(this, R.style.DankAlertDialogStyle) errorBuilder.setTitle(R.string.tab_name_in_use) errorBuilder.setNegativeButton(R.string.dialog_aight, { dialog, which -> dialog.dismiss() }) errorBuilder.show() } else { val newTtsObject = TtsObject(ttsObjectName, "Default phrase text" ,System.currentTimeMillis().toInt()) //TODO set the textbox text in here DataService.addTtsObjectToTab(newTtsObject, 0) goToNewlyCreatedTtsObject() } } private fun goToNewlyCreatedTtsObject() { tabLayout.getTabAt(0)!!.select() val recyclerView = mViewPager.getChildAt(0).findViewById(R.id.recycler_view) as RecyclerView val check = recyclerView.adapter.itemCount recyclerView.verticalScrollbarPosition = check recyclerView.smoothScrollToPosition(check - 1) if (mToolBar.getParent() is AppBarLayout) { (mToolBar.getParent() as AppBarLayout).setExpanded(false,true) } } override fun onTabReselected(tab: TabLayout.Tab?) { } override fun onTabUnselected(tab: TabLayout.Tab?) { } override fun onTabSelected(tab: TabLayout.Tab?) { if (tab!!.position != 0){ tabFAM.visibility = View.VISIBLE } else { tabFAM.visibility = View.INVISIBLE } deleteTabFab.isEnabled = tab.position > 1 tabFAM.close(true) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == R.id.action_new_tab) { if (tabLayout.tabCount < 8) { val newFragment = EditDialogFragment(this) newFragment.show(fragmentManager, null) return true } else { val errorBuilder = AlertDialog.Builder(this, R.style.DankAlertDialogStyle) errorBuilder.setTitle("Ya'll got too many tabs dawg.") errorBuilder.setNegativeButton(R.string.dialog_aight, { dialog, which -> dialog.dismiss() }) errorBuilder.show() } } if (id == R.id.action_new_sound) { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.type = "audio/*" startActivityForResult(intent, READ_REQUEST_CODE) } if (id == R.id.action_new_speech_clip) { tts.speak("This is some text yolo", TextToSpeech.QUEUE_FLUSH, null) //TODO this is it here for TTS //dont forget to call shutdown on this...maybe we dont need to do that at all actually since..well its TTS app.. } return super.onOptionsItemSelected(item) } override fun onInit(status: Int) { if (status == TextToSpeech.SUCCESS) { val language = tts.language val result = tts.setLanguage(language) if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { //fuck } } } public override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) { val audioUri: Uri if (resultData != null) { audioUri = resultData.data val newSoundNameFragment = NewSoundClipDialogFragment(this) newSoundNameFragment.show(fragmentManager,audioUri.toString()) } } } inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { private var tabCount: Int = DataService.getTabsData().tabsList!!.size override fun getItem(position: Int): Fragment { return TabFragment.newInstance(position) } override fun getCount(): Int { return tabCount } override fun getPageTitle(position: Int): CharSequence? { when (position) { 0 -> return "All" } return DataService.getTabsData().tabsList!![position].name } fun addNewTab(tabName: String) { DataService.addNewTab(tabName, tabCount) tabCount++ notifyDataSetChanged() } fun removeTab(tabIndex: Int) { DataService.deleteTab(tabIndex) tabCount-- notifyDataSetChanged() } } }
Accessiboard/app/src/main/java/boomcity/accessiboard/MainActivity.kt
128723887
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.codeinsight.actions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase import org.editorconfig.language.messages.EditorConfigBundle import org.jetbrains.annotations.PropertyKey class EditorConfigIntentionTest : LightPlatformCodeInsightFixtureTestCase() { override fun getTestDataPath() = "${PathManagerEx.getCommunityHomePath()}/plugins/editorconfig/testData/org/editorconfig/language/codeinsight/actions/intention/" fun testInvertBooleanValue() = doTest("intention.invert-option-value") fun testInvertSpaceValue() = doTest("intention.invert-option-value") fun testInvertUsualValue() { val testName = getTestName(true) myFixture.configureByFile("$testName/.editorconfig") assertNoIntentions() } private fun doTest(@PropertyKey(resourceBundle = EditorConfigBundle.BUNDLE) intentionKey: String) { val testName = getTestName(true) myFixture.configureByFile("$testName/.editorconfig") val quickFix = findIntention(intentionKey) myFixture.launchAction(quickFix) myFixture.checkResultByFile("$testName/result.txt") } private fun findIntention(@PropertyKey(resourceBundle = EditorConfigBundle.BUNDLE) intentionKey: String): IntentionAction { val availableIntentions = myFixture.availableIntentions val intentionName = EditorConfigBundle[intentionKey] val result = availableIntentions.firstOrNull { it.text == intentionName } return result ?: throw AssertionError("Intention '$intentionName' not found among ${availableIntentions.map(IntentionAction::getText)}") } private fun assertNoIntentions() = assertEquals(0, myFixture.availableIntentions.size) }
plugins/editorconfig/test/org/editorconfig/language/codeinsight/actions/EditorConfigIntentionTest.kt
1584471640
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.configuration import com.intellij.codeInspection.util.IntentionName import com.intellij.execution.ExecutionException import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.ui.IdeBorderFactory import com.intellij.ui.components.JBLabel import com.intellij.util.ui.JBUI import com.jetbrains.python.PyCharmCommunityCustomizationBundle import com.jetbrains.python.sdk.* import com.jetbrains.python.sdk.poetry.* import java.awt.BorderLayout import java.awt.Insets import javax.swing.JComponent import javax.swing.JPanel /** * This source code is created by @koxudaxi Koudai Aono <[email protected]> */ class PyPoetrySdkConfiguration : PyProjectSdkConfigurationExtension { private val LOGGER = Logger.getInstance(PyPoetrySdkConfiguration::class.java) override fun createAndAddSdkForConfigurator(module: Module): Sdk? = createAndAddSDk(module, false) override fun getIntention(module: Module): @IntentionName String? = module.pyProjectToml?.let { PyCharmCommunityCustomizationBundle.message("sdk.create.poetry.environment", it.name) } override fun createAndAddSdkForInspection(module: Module): Sdk? = createAndAddSDk(module, true) private fun createAndAddSDk(module: Module, inspection: Boolean): Sdk? { val poetryEnvExecutable = askForEnvData(module, inspection) ?: return null PropertiesComponent.getInstance().poetryPath = poetryEnvExecutable.poetryPath return createPoetry(module) } private fun askForEnvData(module: Module, inspection: Boolean): PyAddNewPoetryFromFilePanel.Data? { val poetryExecutable = getPoetryExecutable()?.absolutePath if (inspection && validatePoetryExecutable(poetryExecutable) == null) { return PyAddNewPoetryFromFilePanel.Data(poetryExecutable!!) } var permitted = false var envData: PyAddNewPoetryFromFilePanel.Data? = null ApplicationManager.getApplication().invokeAndWait { val dialog = Dialog(module) permitted = dialog.showAndGet() envData = dialog.envData LOGGER.debug("Dialog exit code: ${dialog.exitCode}, $permitted") } return if (permitted) envData else null } private fun createPoetry(module: Module): Sdk? { ProgressManager.progress(PyCharmCommunityCustomizationBundle.message("sdk.progress.text.setting.up.poetry.environment")) LOGGER.debug("Creating poetry environment") val basePath = module.basePath ?: return null val poetry = try { val init = StandardFileSystems.local().findFileByPath(basePath)?.findChild(PY_PROJECT_TOML)?.let { getPyProjectTomlForPoetry(it) } == null setupPoetry(FileUtil.toSystemDependentName(basePath), null, true, init) } catch (e: ExecutionException) { LOGGER.warn("Exception during creating poetry environment", e) showSdkExecutionException(null, e, PyCharmCommunityCustomizationBundle.message("sdk.dialog.title.failed.to.create.poetry.environment")) return null } val path = PythonSdkUtil.getPythonExecutable(poetry).also { if (it == null) { LOGGER.warn("Python executable is not found: $poetry") } } ?: return null val file = LocalFileSystem.getInstance().refreshAndFindFileByPath(path).also { if (it == null) { LOGGER.warn("Python executable file is not found: $path") } } ?: return null LOGGER.debug("Setting up associated poetry environment: $path, $basePath") val sdk = SdkConfigurationUtil.setupSdk( ProjectJdkTable.getInstance().allJdks, file, PythonSdkType.getInstance(), false, null, suggestedSdkName(basePath) ) ?: return null ApplicationManager.getApplication().invokeAndWait { LOGGER.debug("Adding associated poetry environment: $path, $basePath") SdkConfigurationUtil.addSdk(sdk) sdk.isPoetry = true sdk.associateWithModule(module, null) } return sdk } private class Dialog(module: Module) : DialogWrapper(module.project, false, IdeModalityType.PROJECT) { private val panel = PyAddNewPoetryFromFilePanel(module) val envData get() = panel.envData init { title = PyCharmCommunityCustomizationBundle.message("sdk.dialog.title.setting.up.poetry.environment") init() } override fun createCenterPanel(): JComponent { return JPanel(BorderLayout()).apply { val border = IdeBorderFactory.createEmptyBorder(Insets(4, 0, 6, 0)) val message = PyCharmCommunityCustomizationBundle.message("sdk.notification.label.create.poetry.environment.from.pyproject.toml.dependencies") add( JBUI.Panels.simplePanel(JBLabel(message)).withBorder(border), BorderLayout.NORTH ) add(panel, BorderLayout.CENTER) } } override fun postponeValidation(): Boolean = false override fun doValidateAll(): List<ValidationInfo> = panel.validateAll() } }
python/ide/impl/src/com/jetbrains/python/sdk/configuration/PyPoetrySdkConfiguration.kt
1760299052
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package org.jetbrains.intellij.build.devServer import com.intellij.openapi.util.io.NioFiles import com.sun.net.httpserver.HttpContext import com.sun.net.httpserver.HttpExchange import com.sun.net.httpserver.HttpServer import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import java.net.HttpURLConnection import java.net.InetAddress import java.net.InetSocketAddress import java.net.URI import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.Semaphore import kotlin.system.exitProcess private enum class DevIdeaBuildServerStatus { OK, FAILED, IN_PROGRESS, UNDEFINED } object DevIdeaBuildServer { private const val SERVER_PORT = 20854 private val buildQueueLock = Semaphore(1, true) private val doneSignal = CountDownLatch(1) // <product / DevIdeaBuildServerStatus> private var productBuildStatus = HashMap<String, DevIdeaBuildServerStatus>() @JvmStatic fun main(args: Array<String>) { initLog() try { start() } catch (e: ConfigurationException) { e.printStackTrace() exitProcess(1) } } private fun start() { val additionalModules = getAdditionalModules()?.toList() val homePath = getHomePath() val productionClassOutput = (System.getenv("CLASSES_DIR")?.let { Path.of(it).toAbsolutePath().normalize() } ?: homePath.resolve("out/classes/production")) val httpServer = createHttpServer( buildServer = BuildServer( homePath = homePath, productionClassOutput = productionClassOutput ), requestTemplate = BuildRequest( platformPrefix = "", additionalModules = additionalModules ?: emptyList(), homePath = homePath, productionClassOutput = productionClassOutput, ) ) println("Listening on ${httpServer.address.hostString}:${httpServer.address.port}") println( "Custom plugins: ${additionalModules?.joinToString() ?: "not set (use VM property `additional.modules` to specify additional module ids)"}") println( "Run IDE on module intellij.platform.bootstrap with VM properties -Didea.use.dev.build.server=true -Djava.system.class.loader=com.intellij.util.lang.PathClassLoader") httpServer.start() // wait for ctrl-c Runtime.getRuntime().addShutdownHook(Thread { doneSignal.countDown() }) try { doneSignal.await() } catch (ignore: InterruptedException) { } println("Server stopping...") httpServer.stop(10) exitProcess(0) } private fun HttpExchange.getPlatformPrefix() = parseQuery(this.requestURI).get("platformPrefix")?.first() ?: "idea" private fun createBuildEndpoint(httpServer: HttpServer, buildServer: BuildServer, requestTemplate: BuildRequest): HttpContext? { return httpServer.createContext("/build") { exchange -> val platformPrefix = exchange.getPlatformPrefix() var statusMessage: String var statusCode = HttpURLConnection.HTTP_OK productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.UNDEFINED) try { productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.IN_PROGRESS) buildQueueLock.acquire() exchange.responseHeaders.add("Content-Type", "text/plain") runBlocking(Dispatchers.Default) { val ideBuilder = buildServer.checkOrCreateIdeBuilder(requestTemplate.copy(platformPrefix = platformPrefix)) statusMessage = ideBuilder.pluginBuilder.buildChanged() } println(statusMessage) } catch (e: ConfigurationException) { statusCode = HttpURLConnection.HTTP_BAD_REQUEST productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.FAILED) statusMessage = e.message!! } catch (e: Throwable) { productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.FAILED) exchange.sendResponseHeaders(HttpURLConnection.HTTP_UNAVAILABLE, -1) System.err.println("Cannot handle build request: ") e.printStackTrace() return@createContext } finally { buildQueueLock.release() } productBuildStatus.put(platformPrefix, if (statusCode == HttpURLConnection.HTTP_OK) { DevIdeaBuildServerStatus.OK } else { DevIdeaBuildServerStatus.FAILED }) val response = statusMessage.encodeToByteArray() exchange.sendResponseHeaders(statusCode, response.size.toLong()) exchange.responseBody.apply { this.write(response) this.flush() this.close() } } } private fun createStatusEndpoint(httpServer: HttpServer): HttpContext? { return httpServer.createContext("/status") { exchange -> val platformPrefix = exchange.getPlatformPrefix() val buildStatus = productBuildStatus.getOrDefault(platformPrefix, DevIdeaBuildServerStatus.UNDEFINED) exchange.responseHeaders.add("Content-Type", "text/plain") val response = buildStatus.toString().encodeToByteArray() exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size.toLong()) exchange.responseBody.apply { this.write(response) this.flush() this.close() } } } private fun createStopEndpoint(httpServer: HttpServer): HttpContext? { return httpServer.createContext("/stop") { exchange -> exchange.responseHeaders.add("Content-Type", "text/plain") val response = "".encodeToByteArray() exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size.toLong()) exchange.responseBody.apply { this.write(response) this.flush() this.close() } doneSignal.countDown() } } private fun createHttpServer(buildServer: BuildServer, requestTemplate: BuildRequest): HttpServer { val httpServer = HttpServer.create() httpServer.bind(InetSocketAddress(InetAddress.getLoopbackAddress(), SERVER_PORT), 2) createBuildEndpoint(httpServer, buildServer, requestTemplate) createStatusEndpoint(httpServer) createStopEndpoint(httpServer) // Serve requests in parallel. Though, there is no guarantee, that 2 requests will be served for different endpoints httpServer.executor = Executors.newFixedThreadPool(2) return httpServer } } private fun parseQuery(url: URI): Map<String, List<String?>> { val query = url.query ?: return emptyMap() return query.splitToSequence("&") .map { val index = it.indexOf('=') val key = if (index > 0) it.substring(0, index) else it val value = if (index > 0 && it.length > index + 1) it.substring(index + 1) else null java.util.Map.entry(key, value) } .groupBy(keySelector = { it.key }, valueTransform = { it.value }) } internal fun doClearDirContent(child: Path) { Files.newDirectoryStream(child).use { stream -> for (child in stream) { NioFiles.deleteRecursively(child) } } } internal fun clearDirContent(dir: Path): Boolean { if (!Files.isDirectory(dir)) { return false } doClearDirContent(dir) return true }
platform/build-scripts/dev-server/src/DevIdeaBuildServer.kt
131880534
/* * Copyright 2020 Stéphane Baiget * * 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.sbgapps.scoreit.data.repository import android.app.Activity import com.android.billingclient.api.SkuDetails interface BillingRepo { fun getDonationSkus(): List<SkuDetails>? fun startBillingFlow(activity: Activity, skuDetails: SkuDetails, callback: () -> Unit) companion object { const val COFFEE = "com.sbgapps.scoreit.coffee" const val BEER = "com.sbgapps.scoreit.beer" } } fun List<SkuDetails>.getBeerSku(): SkuDetails? = firstOrNull { it.sku == BillingRepo.BEER } fun List<SkuDetails>.getCoffeeSku(): SkuDetails? = firstOrNull { it.sku == BillingRepo.COFFEE }
data/src/main/kotlin/com/sbgapps/scoreit/data/repository/BillingRepo.kt
1428505047
// 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.workspaceModel.ide.impl.legacyBridge.module.roots import com.intellij.openapi.Disposable import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.module.Module import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.ModuleOrderEnumerator import com.intellij.openapi.roots.impl.OrderRootsCache import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import com.intellij.workspaceModel.ide.impl.legacyBridge.RootConfigurationAccessorForWorkspaceModel import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.storage.CachedValue import com.intellij.workspaceModel.storage.WorkspaceEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.impl.DisposableCachedValue import com.intellij.workspaceModel.ide.impl.legacyBridge.module.CompilerModuleExtensionBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerComponentBridge.Companion.findModuleEntity import org.jetbrains.jps.model.module.JpsModuleSourceRoot import org.jetbrains.jps.model.module.JpsModuleSourceRootType class ModuleRootComponentBridge( private val currentModule: Module ) : ModuleRootManagerEx(), Disposable, ModuleRootModelBridge { override val moduleBridge = currentModule as ModuleBridge private val orderRootsCache = OrderRootsCacheBridge(currentModule.project, currentModule) private val modelValue = DisposableCachedValue( { moduleBridge.entityStorage }, CachedValue { storage -> RootModelBridgeImpl( moduleEntity = storage.findModuleEntity(moduleBridge), storage = storage, itemUpdater = null, // TODO rootModel = this, updater = null ) }).also { Disposer.register(this, it) } internal val moduleLibraryTable: ModuleLibraryTableBridgeImpl = ModuleLibraryTableBridgeImpl(moduleBridge) fun getModuleLibraryTable(): ModuleLibraryTableBridge { return moduleLibraryTable } init { MODULE_EXTENSION_NAME.getPoint(moduleBridge).addExtensionPointListener(object : ExtensionPointListener<ModuleExtension?> { override fun extensionAdded(extension: ModuleExtension, pluginDescriptor: PluginDescriptor) { dropRootModelCache() } override fun extensionRemoved(extension: ModuleExtension, pluginDescriptor: PluginDescriptor) { dropRootModelCache() } }, false, null) } private val model: RootModelBridgeImpl get() = modelValue.value override val storage: WorkspaceEntityStorage get() = moduleBridge.entityStorage.current override val accessor: RootConfigurationAccessor get() = RootConfigurationAccessor.DEFAULT_INSTANCE override fun getOrCreateJpsRootProperties(sourceRootUrl: VirtualFileUrl, creator: () -> JpsModuleSourceRoot): JpsModuleSourceRoot { return creator() } override fun removeCachedJpsRootProperties(sourceRootUrl: VirtualFileUrl) { } override fun dispose() = Unit override fun dropCaches() { orderRootsCache.clearCache() dropRootModelCache() } internal fun dropRootModelCache() { modelValue.dropCache() } override fun getModificationCountForTests(): Long = moduleBridge.entityStorage.version override fun getExternalSource(): ProjectModelExternalSource? = ExternalProjectSystemRegistry.getInstance().getExternalSource(module) override fun getFileIndex(): ModuleFileIndex = currentModule.getService(ModuleFileIndex::class.java)!! override fun getModifiableModel(): ModifiableRootModel = getModifiableModel(RootConfigurationAccessor.DEFAULT_INSTANCE) override fun getModifiableModel(accessor: RootConfigurationAccessor): ModifiableRootModel = ModifiableRootModelBridgeImpl( WorkspaceEntityStorageBuilder.from(moduleBridge.entityStorage.current), moduleBridge, moduleBridge.entityStorage.current, accessor) /** * This method is used in Project Structure dialog to ensure that changes made in {@link ModifiableModuleModel} after creation * of this {@link ModifiableRootModel} are available in its storage and references in its {@link OrderEntry} can be resolved properly. */ override fun getModifiableModelForMultiCommit(accessor: RootConfigurationAccessor): ModifiableRootModel = ModifiableRootModelBridgeImpl( (moduleBridge.diff as? WorkspaceEntityStorageBuilder) ?: (accessor as? RootConfigurationAccessorForWorkspaceModel)?.actualDiffBuilder ?: WorkspaceEntityStorageBuilder.from(moduleBridge.entityStorage.current), moduleBridge, moduleBridge.entityStorage.current, accessor) fun getModifiableModel(diff: WorkspaceEntityStorageBuilder, initialStorage: WorkspaceEntityStorage, accessor: RootConfigurationAccessor): ModifiableRootModel = ModifiableRootModelBridgeImpl(diff, moduleBridge, initialStorage, accessor, false) override fun getDependencies(): Array<Module> = moduleDependencies override fun getDependencies(includeTests: Boolean): Array<Module> = getModuleDependencies(includeTests = includeTests) override fun isDependsOn(module: Module): Boolean = orderEntries.any { it is ModuleOrderEntry && it.module == module } override fun getExcludeRoots(): Array<VirtualFile> = model.excludeRoots override fun orderEntries(): OrderEnumerator = ModuleOrderEnumerator(this, orderRootsCache) private val compilerModuleExtension by lazy { CompilerModuleExtensionBridge(moduleBridge, entityStorage = moduleBridge.entityStorage, diff = null) } private val compilerModuleExtensionClass = CompilerModuleExtension::class.java override fun <T : Any?> getModuleExtension(klass: Class<T>): T? { if (compilerModuleExtensionClass.isAssignableFrom(klass)) { @Suppress("UNCHECKED_CAST") return compilerModuleExtension as T } return model.getModuleExtension(klass) } override fun getDependencyModuleNames(): Array<String> = model.dependencyModuleNames override fun getModule(): Module = currentModule override fun isSdkInherited(): Boolean = model.isSdkInherited override fun getOrderEntries(): Array<OrderEntry> = model.orderEntries override fun getSourceRootUrls(): Array<String> = model.sourceRootUrls override fun getSourceRootUrls(includingTests: Boolean): Array<String> = model.getSourceRootUrls(includingTests) override fun getContentEntries(): Array<ContentEntry> = model.contentEntries override fun getExcludeRootUrls(): Array<String> = model.excludeRootUrls override fun <R : Any?> processOrder(policy: RootPolicy<R>, initialValue: R): R = model.processOrder(policy, initialValue) override fun getSdk(): Sdk? = model.sdk override fun getSourceRoots(): Array<VirtualFile> = model.sourceRoots override fun getSourceRoots(includingTests: Boolean): Array<VirtualFile> = model.getSourceRoots(includingTests) override fun getSourceRoots(rootType: JpsModuleSourceRootType<*>): MutableList<VirtualFile> = model.getSourceRoots(rootType) override fun getSourceRoots(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): MutableList<VirtualFile> = model.getSourceRoots( rootTypes) override fun getContentRoots(): Array<VirtualFile> = model.contentRoots override fun getContentRootUrls(): Array<String> = model.contentRootUrls override fun getModuleDependencies(): Array<Module> = model.moduleDependencies override fun getModuleDependencies(includeTests: Boolean): Array<Module> = model.getModuleDependencies(includeTests) companion object { @JvmStatic fun getInstance(module: Module): ModuleRootComponentBridge = ModuleRootManager.getInstance(module) as ModuleRootComponentBridge } }
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModuleRootComponentBridge.kt
3023260258
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.diagnostic.startUpPerformanceReporter import com.fasterxml.jackson.core.JsonGenerator import com.intellij.diagnostic.ActivityImpl import com.intellij.diagnostic.StartUpMeasurer import com.intellij.diagnostic.ThreadNameManager import com.intellij.ide.plugins.IdeaPluginDescriptorImpl import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.diagnostic.Logger import com.intellij.ui.icons.IconLoadMeasurer import com.intellij.util.io.jackson.array import com.intellij.util.io.jackson.obj import com.intellij.util.lang.ClassPath import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap import org.bouncycastle.crypto.generators.Argon2BytesGenerator import org.bouncycastle.crypto.params.Argon2Parameters import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType import java.lang.management.ManagementFactory import java.time.ZoneId import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.util.* import java.util.concurrent.TimeUnit internal class IdeIdeaFormatWriter(activities: Map<String, MutableList<ActivityImpl>>, private val pluginCostMap: MutableMap<String, Object2LongOpenHashMap<String>>, threadNameManager: ThreadNameManager) : IdeaFormatWriter(activities, threadNameManager, StartUpPerformanceReporter.VERSION) { val publicStatMetrics = Object2IntOpenHashMap<String>() init { publicStatMetrics.defaultReturnValue(-1) } fun writeToLog(log: Logger) { stringWriter.write("\n=== Stop: StartUp Measurement ===") log.info(stringWriter.toString()) } override fun writeAppInfo(writer: JsonGenerator) { val appInfo = ApplicationInfo.getInstance() writer.writeStringField("build", appInfo.build.asStringWithoutProductCode()) writer.writeStringField("buildDate", ZonedDateTime.ofInstant(appInfo.buildDate.toInstant(), ZoneId.systemDefault()).format(DateTimeFormatter.RFC_1123_DATE_TIME)) writer.writeStringField("productCode", appInfo.build.productCode) // see CDSManager from platform-impl @Suppress("SpellCheckingInspection") if (ManagementFactory.getRuntimeMXBean().inputArguments.any { it == "-Xshare:auto" || it == "-Xshare:on" }) { writer.writeBooleanField("cds", true) } } override fun writeProjectName(writer: JsonGenerator, projectName: String) { writer.writeStringField("project", System.getProperty("idea.performanceReport.projectName") ?: safeHashValue(projectName)) } override fun writeExtraData(writer: JsonGenerator) { val stats = getClassAndResourceLoadingStats() writer.obj("classLoading") { val time = stats.getValue("classLoadingTime") writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(time)) val defineTime = stats.getValue("classDefineTime") writer.writeNumberField("searchTime", TimeUnit.NANOSECONDS.toMillis(time - defineTime)) writer.writeNumberField("defineTime", TimeUnit.NANOSECONDS.toMillis(defineTime)) writer.writeNumberField("count", stats.getValue("classRequests")) } writer.obj("resourceLoading") { writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stats.getValue("resourceLoadingTime"))) writer.writeNumberField("count", stats.getValue("resourceRequests")) } writeServiceStats(writer) writeIcons(writer) } private fun getClassAndResourceLoadingStats(): Map<String, Long> { // data from bootstrap classloader val classLoader = IdeIdeaFormatWriter::class.java.classLoader @Suppress("UNCHECKED_CAST") val stats = MethodHandles.lookup() .findVirtual(classLoader::class.java, "getLoadingStats", MethodType.methodType(Map::class.java)) .bindTo(classLoader).invokeExact() as MutableMap<String, Long> // data from core classloader val coreStats = ClassPath.getLoadingStats() if (coreStats.get("identity") != stats.get("identity")) { for (entry in coreStats.entries) { val v1 = stats.getValue(entry.key) if (v1 != entry.value) { stats.put(entry.key, v1 + entry.value) } } } return stats } override fun writeItemTimeInfo(item: ActivityImpl, duration: Long, offset: Long, writer: JsonGenerator) { if (item.name == "bootstrap" || item.name == "app initialization") { publicStatMetrics.put(item.name, TimeUnit.NANOSECONDS.toMillis(duration).toInt()) } super.writeItemTimeInfo(item, duration, offset, writer) } override fun writeTotalDuration(writer: JsonGenerator, totalDuration: Long, end: Long, timeOffset: Long): Long { val totalDurationActual = super.writeTotalDuration(writer, totalDuration, end, timeOffset) publicStatMetrics.put("totalDuration", totalDurationActual.toInt()) return totalDurationActual } override fun beforeActivityWrite(item: ActivityImpl, ownOrTotalDuration: Long, fieldName: String) { item.pluginId?.let { StartUpMeasurer.doAddPluginCost(it, item.category?.name ?: "unknown", ownOrTotalDuration, pluginCostMap) } if (fieldName == "prepareAppInitActivities" && item.name == "splash initialization") { publicStatMetrics.put("splash", TimeUnit.NANOSECONDS.toMillis(ownOrTotalDuration).toInt()) } } } private fun writeIcons(writer: JsonGenerator) { writer.array("icons") { for (stat in IconLoadMeasurer.getStats()) { writer.obj { writer.writeStringField("name", stat.name) writer.writeNumberField("count", stat.count) writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stat.totalDuration)) } } } } private fun safeHashValue(value: String): String { val generator = Argon2BytesGenerator() generator.init(Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).build()) // 160 bit is enough for uniqueness val result = ByteArray(20) generator.generateBytes(value.toByteArray(), result, 0, result.size) return Base64.getEncoder().withoutPadding().encodeToString(result) } private fun writeServiceStats(writer: JsonGenerator) { class StatItem(val name: String) { var app = 0 var project = 0 var module = 0 } // components can be inferred from data, but to verify that items reported correctly (and because for items threshold is applied (not all are reported)) val component = StatItem("component") val service = StatItem("service") val plugins = PluginManagerCore.getLoadedPlugins(null).sortedBy { it.pluginId } for (plugin in plugins) { service.app += (plugin as IdeaPluginDescriptorImpl).app.services.size service.project += plugin.project.services.size service.module += plugin.module.services.size component.app += plugin.app.components?.size ?: 0 component.project += plugin.project.components?.size ?: 0 component.module += plugin.module.components?.size ?: 0 } writer.obj("stats") { writer.writeNumberField("plugin", plugins.size) for (statItem in listOf(component, service)) { writer.obj(statItem.name) { writer.writeNumberField("app", statItem.app) writer.writeNumberField("project", statItem.project) writer.writeNumberField("module", statItem.module) } } } writer.array("plugins") { for (plugin in plugins) { val classLoader = plugin.pluginClassLoader as? PluginAwareClassLoader ?: continue writer.obj { writer.writeStringField("id", plugin.pluginId.idString) writer.writeNumberField("classCount", classLoader.loadedClassCount) writer.writeNumberField("classLoadingEdtTime", TimeUnit.NANOSECONDS.toMillis(classLoader.edtTime)) writer.writeNumberField("classLoadingBackgroundTime", TimeUnit.NANOSECONDS.toMillis(classLoader.backgroundTime)) } } } }
platform/diagnostic/src/startUpPerformanceReporter/IdeIdeaFormatWriter.kt
4060351824
package com.farmerbb.taskbar.ui import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProviderInfo import android.content.ComponentName import android.content.Context import android.content.SharedPreferences import android.content.pm.ActivityInfo import android.os.Process import android.view.View import android.widget.LinearLayout import androidx.test.core.app.ApplicationProvider import com.farmerbb.taskbar.Constants.DEFAULT_TEST_CELL_ID import com.farmerbb.taskbar.Constants.TEST_LABEL import com.farmerbb.taskbar.Constants.TEST_NAME import com.farmerbb.taskbar.Constants.TEST_PACKAGE import com.farmerbb.taskbar.Constants.UNSUPPORTED import com.farmerbb.taskbar.R import com.farmerbb.taskbar.helper.LauncherHelper import com.farmerbb.taskbar.mockito.BooleanAnswer import com.farmerbb.taskbar.util.Constants.POSITION_BOTTOM_LEFT import com.farmerbb.taskbar.util.Constants.POSITION_BOTTOM_RIGHT import com.farmerbb.taskbar.util.Constants.POSITION_BOTTOM_VERTICAL_LEFT import com.farmerbb.taskbar.util.Constants.POSITION_BOTTOM_VERTICAL_RIGHT import com.farmerbb.taskbar.util.Constants.POSITION_TOP_LEFT import com.farmerbb.taskbar.util.Constants.POSITION_TOP_RIGHT import com.farmerbb.taskbar.util.Constants.POSITION_TOP_VERTICAL_LEFT import com.farmerbb.taskbar.util.Constants.POSITION_TOP_VERTICAL_RIGHT import com.farmerbb.taskbar.util.Constants.PREF_DASHBOARD_TUTORIAL_SHOWN import com.farmerbb.taskbar.util.Constants.PREF_DASHBOARD_WIDGET_PLACEHOLDER_SUFFIX import com.farmerbb.taskbar.util.Constants.PREF_DASHBOARD_WIDGET_PREFIX import com.farmerbb.taskbar.util.Constants.PREF_DASHBOARD_WIDGET_PROVIDER_SUFFIX import com.farmerbb.taskbar.util.Constants.PREF_DEFAULT_NULL import com.farmerbb.taskbar.util.Constants.PREF_DONT_STOP_DASHBOARD import com.farmerbb.taskbar.util.TaskbarPosition import com.farmerbb.taskbar.util.U import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PowerMockIgnore import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.rule.PowerMockRule import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows import org.robolectric.shadows.AppWidgetProviderInfoBuilder import org.robolectric.shadows.ShadowToast @RunWith(RobolectricTestRunner::class) @PowerMockIgnore("org.mockito.*", "org.robolectric.*", "android.*", "androidx.*", "com.farmerbb.taskbar.shadow.*") @PrepareForTest(value = [U::class, TaskbarPosition::class, DashboardController::class, LauncherHelper::class]) class DashboardControllerTest { @get:Rule val rule = PowerMockRule() private lateinit var uiController: DashboardController private lateinit var context: Context private lateinit var prefs: SharedPreferences private val host: UIHost = MockUIHost() @Before fun setUp() { context = ApplicationProvider.getApplicationContext() uiController = DashboardController(context) prefs = U.getSharedPreferences(context) uiController.onCreateHost(host) } @After fun tearDown() { uiController.onDestroyHost(host) prefs.edit().remove(PREF_DASHBOARD_TUTORIAL_SHOWN).apply() } @Test fun testUpdatePaddingSize() { val paddingDefault = Int.MAX_VALUE val layout = LinearLayout(context) layout.setPadding(paddingDefault, paddingDefault, paddingDefault, paddingDefault) uiController.updatePaddingSize(context, layout, UNSUPPORTED) verifyViewPadding(layout, paddingDefault, paddingDefault, paddingDefault, paddingDefault) val paddingSize = context.resources.getDimensionPixelSize(R.dimen.tb_icon_size) uiController.updatePaddingSize(context, layout, POSITION_TOP_VERTICAL_LEFT) verifyViewPadding(layout, paddingSize, 0, 0, 0) uiController.updatePaddingSize(context, layout, POSITION_BOTTOM_VERTICAL_LEFT) verifyViewPadding(layout, paddingSize, 0, 0, 0) uiController.updatePaddingSize(context, layout, POSITION_TOP_LEFT) verifyViewPadding(layout, 0, paddingSize, 0, 0) uiController.updatePaddingSize(context, layout, POSITION_TOP_RIGHT) verifyViewPadding(layout, 0, paddingSize, 0, 0) uiController.updatePaddingSize(context, layout, POSITION_TOP_VERTICAL_RIGHT) verifyViewPadding(layout, 0, 0, paddingSize, 0) uiController.updatePaddingSize(context, layout, POSITION_BOTTOM_VERTICAL_RIGHT) verifyViewPadding(layout, 0, 0, paddingSize, 0) uiController.updatePaddingSize(context, layout, POSITION_BOTTOM_LEFT) verifyViewPadding(layout, 0, 0, 0, paddingSize) uiController.updatePaddingSize(context, layout, POSITION_BOTTOM_RIGHT) verifyViewPadding(layout, 0, 0, 0, paddingSize) } @Test fun testShouldSendDisappearingBroadcast() { val helper = PowerMockito.mock(LauncherHelper::class.java) val isOnSecondaryHomeScreenAnswer = BooleanAnswer() PowerMockito.`when`(helper.isOnSecondaryHomeScreen(context)) .thenAnswer(isOnSecondaryHomeScreenAnswer) PowerMockito.mockStatic(LauncherHelper::class.java) PowerMockito.`when`(LauncherHelper.getInstance()).thenReturn(helper) isOnSecondaryHomeScreenAnswer.answer = true prefs.edit().putBoolean(PREF_DONT_STOP_DASHBOARD, true).apply() Assert.assertFalse(uiController.shouldSendDisappearingBroadcast(context, prefs)) isOnSecondaryHomeScreenAnswer.answer = true prefs.edit().putBoolean(PREF_DONT_STOP_DASHBOARD, false).apply() Assert.assertTrue(uiController.shouldSendDisappearingBroadcast(context, prefs)) isOnSecondaryHomeScreenAnswer.answer = false prefs.edit().putBoolean(PREF_DONT_STOP_DASHBOARD, true).apply() Assert.assertTrue(uiController.shouldSendDisappearingBroadcast(context, prefs)) isOnSecondaryHomeScreenAnswer.answer = false prefs.edit().putBoolean(PREF_DONT_STOP_DASHBOARD, false).apply() Assert.assertTrue(uiController.shouldSendDisappearingBroadcast(context, prefs)) } @Test fun testSaveWidgetInfo() { val info = AppWidgetProviderInfo() info.provider = ComponentName(TEST_PACKAGE, TEST_NAME) val cellId: Int = DEFAULT_TEST_CELL_ID val appWidgetId = 100 prefs.edit().putString(uiController.generateProviderPlaceholderPrefKey(cellId), "").apply() uiController.saveWidgetInfo(context, info, cellId, appWidgetId) Assert.assertEquals( appWidgetId.toLong(), prefs.getInt(PREF_DASHBOARD_WIDGET_PREFIX + cellId, -1).toLong()) Assert.assertEquals( info.provider.flattenToString(), prefs.getString(uiController.generateProviderPrefKey(cellId), "") ) Assert.assertFalse(prefs.contains(uiController.generateProviderPlaceholderPrefKey(cellId))) } @Test fun testShowDashboardTutorialToast() { prefs.edit().putBoolean(PREF_DASHBOARD_TUTORIAL_SHOWN, true).apply() uiController.showDashboardTutorialToast(context) Assert.assertNull(ShadowToast.getTextOfLatestToast()) prefs.edit().putBoolean(PREF_DASHBOARD_TUTORIAL_SHOWN, false).apply() uiController.showDashboardTutorialToast(context) Assert.assertTrue(prefs.getBoolean(PREF_DASHBOARD_TUTORIAL_SHOWN, false)) val toastText = ShadowToast.getTextOfLatestToast() Assert.assertEquals(context.getString(R.string.tb_dashboard_tutorial, toastText), toastText) } @Test fun testGenerateProviderPrefKey() { Assert.assertEquals( PREF_DASHBOARD_WIDGET_PREFIX + DEFAULT_TEST_CELL_ID + PREF_DASHBOARD_WIDGET_PROVIDER_SUFFIX, uiController.generateProviderPrefKey(DEFAULT_TEST_CELL_ID) ) } @Test fun testGenerateProviderPlaceholderPrefKey() { Assert.assertEquals( PREF_DASHBOARD_WIDGET_PREFIX + DEFAULT_TEST_CELL_ID + PREF_DASHBOARD_WIDGET_PLACEHOLDER_SUFFIX, uiController.generateProviderPlaceholderPrefKey(DEFAULT_TEST_CELL_ID) ) } @Test fun testShowPlaceholderToast() { val appWidgetManager = AppWidgetManager.getInstance(context) val cellId: Int = DEFAULT_TEST_CELL_ID val providerPrefKey = uiController.generateProviderPrefKey(cellId) val shadowAppWidgetManager = Shadows.shadowOf(appWidgetManager) val providerInfo = ActivityInfo() providerInfo.nonLocalizedLabel = TEST_LABEL val info = AppWidgetProviderInfoBuilder.newBuilder().setProviderInfo(providerInfo).build() info.provider = ComponentName(TEST_PACKAGE, TEST_NAME) shadowAppWidgetManager.addInstalledProvidersForProfile(Process.myUserHandle(), info) prefs.edit().putString(providerPrefKey, null).apply() uiController.showPlaceholderToast(context, appWidgetManager, cellId, prefs) Assert.assertNull(ShadowToast.getLatestToast()) prefs.edit().putString(providerPrefKey, PREF_DEFAULT_NULL).apply() uiController.showPlaceholderToast(context, appWidgetManager, cellId, prefs) Assert.assertNull(ShadowToast.getLatestToast()) prefs .edit() .putString(providerPrefKey, info.provider.flattenToString() + UNSUPPORTED) .apply() uiController.showPlaceholderToast(context, appWidgetManager, cellId, prefs) Assert.assertNull(ShadowToast.getLatestToast()) prefs.edit().putString(providerPrefKey, info.provider.flattenToString()).apply() uiController.showPlaceholderToast(context, appWidgetManager, cellId, prefs) val lastToast = ShadowToast.getTextOfLatestToast() Assert.assertNotNull(lastToast) val expectedText = context.getString(R.string.tb_widget_restore_toast, TEST_LABEL) Assert.assertEquals(expectedText, lastToast) } private fun verifyViewPadding(view: View, left: Int, top: Int, right: Int, bottom: Int) { Assert.assertEquals(left.toLong(), view.paddingLeft.toLong()) Assert.assertEquals(top.toLong(), view.paddingTop.toLong()) Assert.assertEquals(right.toLong(), view.paddingRight.toLong()) Assert.assertEquals(bottom.toLong(), view.paddingBottom.toLong()) } }
app/src/test/java/com/farmerbb/taskbar/ui/DashboardControllerTest.kt
607692409
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.wearable.runtimepermissions import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import androidx.activity.result.contract.ActivityResultContract import androidx.appcompat.app.AppCompatActivity import com.example.android.wearable.runtimepermissions.databinding.ActivityRequestPermissionOnPhoneBinding /** * Asks user if they want to open permission screen on their remote device (phone). */ class RequestPermissionOnPhoneActivity : AppCompatActivity() { private lateinit var binding: ActivityRequestPermissionOnPhoneBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRequestPermissionOnPhoneBinding.inflate(layoutInflater) setContentView(binding.root) binding.openOnPhoneContainer.setOnClickListener { setResult(RESULT_OK) finish() } } companion object { /** * An [ActivityResultContract] for checking that the user wants to request permission on * their phone. */ object RequestPermissionOnPhone : ActivityResultContract<Unit, Boolean>() { override fun createIntent(context: Context, input: Unit): Intent = Intent(context, RequestPermissionOnPhoneActivity::class.java) override fun parseResult(resultCode: Int, intent: Intent?): Boolean = resultCode == Activity.RESULT_OK } } }
RuntimePermissionsWear/Wearable/src/main/java/com/example/android/wearable/runtimepermissions/RequestPermissionOnPhoneActivity.kt
1196774632
package json.decoding import codecProvider.CustomCodingContext import io.fluidsonic.json.AbstractJsonCodec import io.fluidsonic.json.JsonCodingType import io.fluidsonic.json.JsonDecoder import io.fluidsonic.json.JsonEncoder import io.fluidsonic.json.missingPropertyError import io.fluidsonic.json.readBooleanOrNull import io.fluidsonic.json.readByteOrNull import io.fluidsonic.json.readCharOrNull import io.fluidsonic.json.readDoubleOrNull import io.fluidsonic.json.readFloatOrNull import io.fluidsonic.json.readFromMapByElementValue import io.fluidsonic.json.readIntOrNull import io.fluidsonic.json.readLongOrNull import io.fluidsonic.json.readShortOrNull import io.fluidsonic.json.readStringOrNull import io.fluidsonic.json.readValueOfType import io.fluidsonic.json.readValueOfTypeOrNull import io.fluidsonic.json.writeBooleanOrNull import io.fluidsonic.json.writeByteOrNull import io.fluidsonic.json.writeCharOrNull import io.fluidsonic.json.writeDoubleOrNull import io.fluidsonic.json.writeFloatOrNull import io.fluidsonic.json.writeIntOrNull import io.fluidsonic.json.writeIntoMap import io.fluidsonic.json.writeLongOrNull import io.fluidsonic.json.writeMapElement import io.fluidsonic.json.writeShortOrNull import io.fluidsonic.json.writeStringOrNull import io.fluidsonic.json.writeValueOrNull import kotlin.Unit internal object AutomaticSecondaryConstructorPrimaryExcludedJsonCodec : AbstractJsonCodec<AutomaticSecondaryConstructorPrimaryExcluded, CustomCodingContext>() { public override fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<AutomaticSecondaryConstructorPrimaryExcluded>): AutomaticSecondaryConstructorPrimaryExcluded { var _value = 0 var value_isPresent = false readFromMapByElementValue { key -> when (key) { "value" -> { _value = readInt() value_isPresent = true } else -> skipValue() } } value_isPresent || missingPropertyError("value") return AutomaticSecondaryConstructorPrimaryExcluded( `value` = _value ) } public override fun JsonEncoder<CustomCodingContext>.encode(`value`: AutomaticSecondaryConstructorPrimaryExcluded): Unit { writeIntoMap { writeMapElement("value", string = value.`value`) } } }
annotation-processor/test-cases/1/output-expected/json/decoding/AutomaticSecondaryConstructorPrimaryExcludedJsonCodec.kt
1803281542
package org.westford.compositor.drm.egl import org.freedesktop.wayland.server.WlBufferResource import org.westford.nativ.libgbm.Libgbm import org.westford.nativ.libgbm.Libgbm.Companion.GBM_BO_IMPORT_WL_BUFFER import org.westford.nativ.libgbm.Libgbm.Companion.GBM_BO_USE_SCANOUT import javax.inject.Inject class GbmBoFactory @Inject internal constructor(private val libgbm: Libgbm, private val privateGbmBoClientFactory: PrivateGbmBoClientFactory, private val privateGbmBoServerFactory: PrivateGbmBoServerFactory) { /** * Create a gbm object from a server side (local) gbm surface. * @param gbmSurface * * * * * @return */ fun create(gbmSurface: Long): GbmBo { val gbmBo = this.libgbm.gbm_surface_lock_front_buffer(gbmSurface) return this.privateGbmBoServerFactory.create(gbmSurface, gbmBo) } /** * Create a gbm object from a client (non local) wayland buffer resource. * @param gbmDevice * * * @param wlBufferResource * * * * * @return */ fun create(gbmDevice: Long, wlBufferResource: WlBufferResource): GbmBo { val gbmBo = this.libgbm.gbm_bo_import(gbmDevice, GBM_BO_IMPORT_WL_BUFFER, wlBufferResource.pointer, GBM_BO_USE_SCANOUT) return this.privateGbmBoClientFactory.create(gbmBo) } }
compositor/src/main/kotlin/org/westford/compositor/drm/egl/GbmBoFactory.kt
3010925246
/* * Copyright (C) 2021 Veli Tasalı * * 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 2 * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.viewmodel.content import org.monora.uprotocol.client.android.model.DateSectionContentModel class DateSectionContentViewModel(dateSectionContentModel: DateSectionContentModel) { val dateText = dateSectionContentModel.dateText }
app/src/main/java/org/monora/uprotocol/client/android/viewmodel/content/DateSectionContentViewModel.kt
2696260328
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.featureStatistics.fusCollectors import org.junit.Test import kotlin.test.assertFalse import kotlin.test.assertTrue class EventsIdentityThrottleTest { private val ONE = -67834 private val TWO = 908542 private val THREE = 12314 private val FOUR = 482309581 @Test fun `test throttling`() { val timer = Timer() val throttle = EventsIdentityThrottle(2, 10) assertTrue(throttle.tryPass(ONE, timer.tick())) assertTrue(throttle.tryPass(TWO, timer.tick())) assert(throttle.size(timer.now()) == 2) assert(throttle.getOldest(timer.now()) == ONE) assertFalse(throttle.tryPass(ONE, timer.tick())) assert(throttle.size(timer.now()) == 2) assert(throttle.getOldest(timer.now()) == ONE) assertFalse(throttle.tryPass(TWO, timer.tick())) assert(throttle.size(timer.now()) == 2) assert(throttle.getOldest(timer.now()) == ONE) } @Test fun `test max size`() { val timer = Timer() val throttle = EventsIdentityThrottle(2, 10) assertTrue(throttle.tryPass(ONE, timer.tick())) assertTrue(throttle.tryPass(TWO, timer.tick())) assertTrue(throttle.tryPass(THREE, timer.tick())) assert(throttle.size(timer.now()) == 2) assert(throttle.getOldest(timer.now()) == TWO) assertTrue(throttle.tryPass(FOUR, timer.tick())) assert(throttle.size(timer.now()) == 2) assert(throttle.getOldest(timer.now()) == THREE) } @Test fun `test timeout`() { val timer = Timer() val throttle = EventsIdentityThrottle(2, 10) assertTrue(throttle.tryPass(ONE, timer.tick())) assertTrue(throttle.tryPass(TWO, timer.tick())) assert(throttle.size(timer.bigTick(9)) == 1) assert(throttle.getOldest(timer.now()) == TWO) assertTrue(throttle.tryPass(ONE, timer.tick())) assert(throttle.size(timer.now()) == 1) assert(throttle.getOldest(timer.now()) == ONE) assertTrue(throttle.tryPass(TWO, timer.tick())) assert(throttle.size(timer.now()) == 2) assert(throttle.getOldest(timer.now()) == ONE) } private class Timer { private var time: Long = -572893L fun now(): Long { return time } fun tick(): Long { time += 1 return time } fun bigTick(value: Long): Long { time += value return time } } }
platform/platform-tests/testSrc/com/intellij/featureStatistics/fusCollectors/EventsIdentityThrottleTest.kt
4189923881
package org.http4k.filter import com.natpryce.hamkrest.and import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.present import com.natpryce.hamkrest.should.shouldMatch import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.Method.PUT import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.Status.Companion.OK import org.http4k.core.Uri import org.http4k.core.then import org.http4k.core.toBody import org.http4k.hamkrest.hasBody import org.http4k.hamkrest.hasHeader import org.junit.Assert.fail import org.junit.Before import org.junit.Test class ClientFiltersTest { val server = { request: Request -> when (request.uri.path) { "/redirect" -> Response(Status.FOUND).header("location", "/ok") "/loop" -> Response(Status.FOUND).header("location", "/loop") "/absolute-target" -> if (request.uri.host == "example.com") Response(Status.OK).body("absolute") else Response(Status.INTERNAL_SERVER_ERROR) "/absolute-redirect" -> Response(Status.MOVED_PERMANENTLY).header("location", "http://example.com/absolute-target") "/redirect-with-charset" -> Response(Status.MOVED_PERMANENTLY).header("location", "/destination; charset=utf8") "/destination" -> Response(OK).body("destination") else -> Response(Status.OK).let { if (request.query("foo") != null) it.body("with query") else it } } } val followRedirects = ClientFilters.FollowRedirects().then(server) @Test fun `does not follow redirect by default`() { val defaultClient = server assertThat(defaultClient(Request(GET, "/redirect")), equalTo(Response(Status.FOUND).header("location", "/ok"))) } @Test fun `follows redirect for temporary redirect response`() { assertThat(followRedirects(Request(GET, "/redirect")), equalTo(Response(Status.OK))) } @Test fun `does not follow redirect for post`() { assertThat(followRedirects(Request(POST, "/redirect")), equalTo(Response(Status.FOUND).header("location", "/ok"))) } @Test fun `does not follow redirect for put`() { assertThat(followRedirects(Request(PUT, "/redirect")), equalTo(Response(Status.FOUND).header("location", "/ok"))) } @Test fun `supports absolute redirects`() { assertThat(followRedirects(Request(GET, "/absolute-redirect")), equalTo(Response(Status.OK).body("absolute"))) } @Test fun `discards query parameters in relative redirects`() { assertThat(followRedirects(Request(GET, "/redirect?foo=bar")), equalTo(Response(Status.OK))) } @Test fun `discards charset from location header`() { assertThat(followRedirects(Request(GET, "/redirect-with-charset")), equalTo(Response(Status.OK).body("destination"))) } @Test fun `prevents redirection loop after 10 redirects`() { try { followRedirects(Request(GET, "/loop")) fail("should have looped") } catch (e: IllegalStateException) { assertThat(e.message, equalTo("Too many redirection")) } } @Before fun before() { ZipkinTraces.THREAD_LOCAL.remove() } @Test fun `adds request tracing to outgoing request when already present`() { val zipkinTraces = ZipkinTraces(TraceId.new(), TraceId.new(), TraceId.new()) ZipkinTraces.THREAD_LOCAL.set(zipkinTraces) var start: Pair<Request, ZipkinTraces>? = null var end: Triple<Request, Response, ZipkinTraces>? = null val svc = ClientFilters.RequestTracing( { req, trace -> start = req to trace }, { req, resp, trace -> end = Triple(req, resp, trace) } ).then { it -> assertThat(ZipkinTraces(it), equalTo(zipkinTraces)) Response(OK) } svc(Request(GET, "")) shouldMatch equalTo(Response(OK)) assertThat(start, equalTo(Request(GET, "") to zipkinTraces)) assertThat(end, equalTo(Triple(Request(GET, ""), Response(OK), zipkinTraces))) } @Test fun `adds new request tracing to outgoing request when not present`() { val svc = ClientFilters.RequestTracing().then { it -> assertThat(ZipkinTraces(it), present()) Response(OK) } svc(Request(GET, "")) shouldMatch equalTo(Response(OK)) } @Test fun `set host on client`() { val handler = ClientFilters.SetHostFrom(Uri.of("http://localhost:8080")).then { Response(OK).header("Host", it.header("Host")).body(it.uri.toString()) } handler(Request(GET, "/loop")) shouldMatch hasBody("http://localhost:8080/loop").and(hasHeader("Host", "localhost")) } @Test fun `gzip request and gunzip response`() { val handler = ClientFilters.GZip().then { it shouldMatch hasHeader("transfer-encoding", "gzip").and(hasBody(equalTo("hello".toBody().gzipped()))) Response(OK).header("transfer-encoding", "gzip").body(it.body) } handler(Request(GET, "/").body("hello")) shouldMatch hasBody("hello") } @Test fun `passes through non-gzipped response`() { val handler = ClientFilters.GZip().then { Response(OK).body("hello") } handler(Request(GET, "/").body("hello")) shouldMatch hasBody("hello") } }
http4k-core/src/test/kotlin/org/http4k/filter/ClientFiltersTest.kt
1315469554
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.common.info /** * Represents credentials for accessing an API. This is useful for representing credentials * for other systems such as AWS keys, Twilio, SendGrid, etc. * @param account : The account for the API * @param key : The key for the API * @param pass : The password for the API ( optional ) * @param env : Optional environment of the API ( e.g. dev, qa ) * @param tag : Optional tag */ data class ApiLogin( @JvmField val account: String = "", @JvmField val key: String = "", @JvmField val pass: String = "", @JvmField val env: String = "", @JvmField val tag: String = "" ) { companion object { @JvmStatic val empty = ApiLogin() } }
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/info/ApiLogin.kt
2557112378
package org.zeroxlab.momodict.model import androidx.room.Entity import androidx.room.PrimaryKey // TODO: null safety @Entity(tableName = "entries") data class Entry( var wordStr: String, var data: String? = null, // Name of the sourceBook of this entry, usually is a dictionary var source: String? = null ) { @PrimaryKey(autoGenerate = true) var entryId: Int = 0 }
app/src/main/java/org/zeroxlab/momodict/model/Entry.kt
2464735104
package com.antyzero.smoksmog.dsl import rx.Observable /** * Rx related */ fun <T> T.observable() = Observable.just(this)
app/src/main/kotlin/com/antyzero/smoksmog/dsl/RxExtension.kt
2836962218
import kotlin.test.* fun <T> compare(expected: T, actual: T, block: CompareContext<T>.() -> Unit) { CompareContext(expected, actual).block() } class CompareContext<out T>(public val expected: T, public val actual: T) { public fun equals(message: String = "") { assertEquals(expected, actual, message) } public fun <P> propertyEquals(message: String = "", getter: T.() -> P) { assertEquals(expected.getter(), actual.getter(), message) } public fun propertyFails(getter: T.() -> Unit) { assertFailEquals({ expected.getter() }, { actual.getter() }) } public fun <P> compareProperty(getter: T.() -> P, block: CompareContext<P>.() -> Unit) { compare(expected.getter(), actual.getter(), block) } private fun assertFailEquals(expected: () -> Unit, actual: () -> Unit) { val expectedFail = assertFails(expected) val actualFail = assertFails(actual) //assertEquals(expectedFail != null, actualFail != null) assertTypeEquals(expectedFail, actualFail) } } fun <T> CompareContext<Iterator<T>>.iteratorBehavior() { propertyEquals { hasNext() } while (expected.hasNext()) { propertyEquals { next() } propertyEquals { hasNext() } } propertyFails { next() } } public fun <N : Any> doTest( sequence: Iterable<N>, expectedFirst: N, expectedLast: N, expectedIncrement: Number, expectedElements: List<N> ) { val first: Any val last: Any val increment: Number when (sequence) { is IntProgression -> { first = sequence.first last = sequence.last increment = sequence.step } is LongProgression -> { first = sequence.first last = sequence.last increment = sequence.step } is CharProgression -> { first = sequence.first last = sequence.last increment = sequence.step } else -> throw IllegalArgumentException("Unsupported sequence type: $sequence") } assertEquals(expectedFirst, first) assertEquals(expectedLast, last) assertEquals(expectedIncrement, increment) if (expectedElements.isEmpty()) assertTrue(sequence.none()) else assertEquals(expectedElements, sequence.toList()) compare(expectedElements.iterator(), sequence.iterator()) { iteratorBehavior() } } fun box() { doTest(5 downTo 5, 5, 5, -1, listOf(5)) doTest(5.toByte() downTo 5.toByte(), 5, 5, -1, listOf(5)) doTest(5.toShort() downTo 5.toShort(), 5, 5, -1, listOf(5)) doTest(5.toLong() downTo 5.toLong(), 5.toLong(), 5.toLong(), -1.toLong(), listOf(5.toLong())) doTest('k' downTo 'k', 'k', 'k', -1, listOf('k')) }
backend.native/tests/external/stdlib/ranges/RangeIterationTest/oneElementDownTo.kt
1896519386
// FILE: 1.kt public inline fun Int.times2(body : () -> Unit) { var count = this; while (count > 0) { body() count-- } } // FILE: 2.kt fun test1(): Int { var s = 0; 2.times2 { s++ } return s; } fun box(): String { if (test1() != 2) return "test1: ${test1()}" return "OK" }
backend.native/tests/external/codegen/boxInline/special/iinc.kt
4094743971
package codegen.inline.inline13 import kotlin.test.* open class A<T1>() class B<T2>() : A<T2>() @Suppress("NOTHING_TO_INLINE") inline fun <reified T: A<*>> foo(f: Any?): Boolean { return f is T? } fun bar(): Boolean { return foo<B<Int>>(B<Int>()) } @Test fun runTest() { println(bar().toString()) }
backend.native/tests/codegen/inline/inline13.kt
1363010587
package com.xenoage.zong.core.music.annotation import com.xenoage.zong.core.music.format.Placement /** * An articulation, like staccato or tenuto. */ class Articulation( /** The type of the articulation, like staccato or tenuto */ val type: ArticulationType ) : Annotation { /** The placement of the articulation: above, below or default (null) */ var placement: Placement? = null } /** * Type of an [Articulation], like staccato or tenuto. */ enum class ArticulationType { Accent, Staccato, Staccatissimo, /** Marcato. In MusicXML called strong accent. */ Marcato, Tenuto }
core/src/com/xenoage/zong/core/music/annotation/Articulation.kt
2209147301
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Handler import android.os.Looper import androidx.test.core.app.ApplicationProvider import androidx.wear.watchface.complications.data.ComplicationType import androidx.wear.watchface.complications.data.ComplicationType.LONG_TEXT import androidx.wear.watchface.complications.data.ComplicationType.MONOCHROMATIC_IMAGE import androidx.wear.watchface.complications.data.ComplicationType.SHORT_TEXT import com.google.common.truth.Truth.assertThat import org.junit.Test import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.verify import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit const val TIME_OUT_MILLIS = 500L public class ComplicationHelperActivityTest { private val mainThreadHandler = Handler(Looper.getMainLooper()) private val scenarios = mapOf( ComplicationHelperActivity.PERMISSION_REQUEST_CODE_PROVIDER_CHOOSER to createIntent(), ComplicationHelperActivity.PERMISSION_REQUEST_CODE_REQUEST_ONLY to createPermissionOnlyIntent() ) @Test public fun createProviderChooserHelperIntent_action() { assertThat(createIntent().action) .isEqualTo(ComplicationHelperActivity.ACTION_START_PROVIDER_CHOOSER) } @Test public fun createProviderChooserHelperIntent_component() { assertThat(createIntent().component) .isEqualTo(ComponentName(context, ComplicationHelperActivity::class.java)) } @Test public fun createProviderChooserHelperIntent_watchFaceComponentName() { ComponentName("package-name", "watch-face-service-name").let { assertThat(createIntent(watchFaceComponentName = it).watchFaceComponentName) .isEqualTo(it) } ComponentName(context, "service-name").let { assertThat(createIntent(watchFaceComponentName = it).watchFaceComponentName) .isEqualTo(it) } } @Test public fun createProviderChooserHelperIntent_complicationSlotId() { assertThat(createIntent(complicationSlotId = -1).complicationSlotId).isEqualTo(-1) assertThat(createIntent(complicationSlotId = 1234).complicationSlotId).isEqualTo(1234) assertThat(createIntent(complicationSlotId = 30000).complicationSlotId).isEqualTo(30000) } @Test public fun createProviderChooserHelperIntent_supportedTypes() { arrayOf<ComplicationType>().let { assertThat(createIntent(supportedTypes = it).supportedTypes).isEqualTo(it) } arrayOf(LONG_TEXT).let { assertThat(createIntent(supportedTypes = it).supportedTypes).isEqualTo(it) } arrayOf(SHORT_TEXT, LONG_TEXT, MONOCHROMATIC_IMAGE).let { assertThat(createIntent(supportedTypes = it).supportedTypes).isEqualTo(it) } } @Test public fun instanceId() { assertThat( createIntent(instanceId = "ID-1") .getStringExtra(ComplicationDataSourceChooserIntent.EXTRA_WATCHFACE_INSTANCE_ID) ).isEqualTo("ID-1") } fun runOnMainThread(task: () -> Unit) { val latch = CountDownLatch(1) mainThreadHandler.post { task() latch.countDown() } latch.await(TIME_OUT_MILLIS, TimeUnit.MILLISECONDS) } @Test public fun complicationRationaleDialogFragment_shown_if_needed() { runOnMainThread { scenarios.forEach { (_, intent) -> val helper = ComplicationHelperActivity() helper.intent = intent helper.mDelegate = mock() { on { shouldShowRequestPermissionRationale() } doReturn true } helper.start(true) verify(helper.mDelegate).launchComplicationRationaleActivity() } } } @Test public fun complicationRationaleDialogFragment_not_shown_if_not_needed() { runOnMainThread { scenarios.forEach { (_, intent) -> val helper = ComplicationHelperActivity() helper.intent = intent helper.mDelegate = mock() { on { shouldShowRequestPermissionRationale() } doReturn false } helper.start(true) verify(helper.mDelegate, never()).launchComplicationRationaleActivity() } } } @Test public fun complicationRationaleDialogFragment_not_shown_if_not_requested() { runOnMainThread { scenarios.forEach { (_, intent) -> val helper = ComplicationHelperActivity() helper.intent = intent helper.mDelegate = mock() { on { shouldShowRequestPermissionRationale() } doReturn true } helper.start(false) verify(helper.mDelegate, never()).launchComplicationRationaleActivity() } } } @Test public fun permissions_requested_if_needed() { runOnMainThread { scenarios.forEach { (requestId, intent) -> val helper = ComplicationHelperActivity() helper.intent = intent helper.mDelegate = mock() { on { shouldShowRequestPermissionRationale() } doReturn false on { checkPermission() } doReturn false } helper.start(true) verify(helper.mDelegate).requestPermissions(requestId) } } } @Test public fun permissions_not_requested_if_not_needed() { runOnMainThread { scenarios.forEach { (requestId, intent) -> val helper = ComplicationHelperActivity() helper.intent = intent helper.mDelegate = mock() { on { shouldShowRequestPermissionRationale() } doReturn false on { checkPermission() } doReturn true } helper.start(true) verify(helper.mDelegate, never()).requestPermissions(requestId) } } } @Test public fun onRequestPermissionsResult_permission_granted() { runOnMainThread { val helper = ComplicationHelperActivity() helper.intent = createIntent() helper.mDelegate = mock() helper.onRequestPermissionsResult( ComplicationHelperActivity.PERMISSION_REQUEST_CODE_PROVIDER_CHOOSER, emptyArray(), intArrayOf(PackageManager.PERMISSION_GRANTED) ) verify(helper.mDelegate).startComplicationDataSourceChooser() verify(helper.mDelegate).requestUpdateAll() } } @Test public fun onRequestPermissionsResult_permission_only_permission_granted() { runOnMainThread { val helper = ComplicationHelperActivity() helper.intent = createIntent() helper.mDelegate = mock() helper.onRequestPermissionsResult( ComplicationHelperActivity.PERMISSION_REQUEST_CODE_REQUEST_ONLY, emptyArray(), intArrayOf(PackageManager.PERMISSION_GRANTED) ) verify(helper.mDelegate, never()).startComplicationDataSourceChooser() verify(helper.mDelegate).requestUpdateAll() } } @Test public fun complicationDeniedActivity_launched_if_permission_denied() { runOnMainThread { scenarios.forEach { (requestId, intent) -> val helper = ComplicationHelperActivity() helper.intent = intent helper.mDelegate = mock() helper.onRequestPermissionsResult( requestId, emptyArray(), intArrayOf(PackageManager.PERMISSION_DENIED) ) verify(helper.mDelegate).launchComplicationDeniedActivity() } } } @Test public fun complicationDeniedActivity_not_launched_if_permission_denied_with_dont_show() { val deniedScenarios = mapOf( ComplicationHelperActivity.PERMISSION_REQUEST_CODE_PROVIDER_CHOOSER_NO_DENIED_INTENT to createIntent(), ComplicationHelperActivity.PERMISSION_REQUEST_CODE_REQUEST_ONLY_NO_DENIED_INTENT to createPermissionOnlyIntent() ) runOnMainThread { deniedScenarios.forEach { (requestId, intent) -> val helper = ComplicationHelperActivity() helper.intent = intent helper.mDelegate = mock() helper.onRequestPermissionsResult( requestId, emptyArray(), intArrayOf(PackageManager.PERMISSION_DENIED) ) verify(helper.mDelegate, never()).launchComplicationDeniedActivity() } } } /** Creates an intent with default xml for unspecified parameters. */ private fun createIntent( watchFaceComponentName: ComponentName = defaultWatchFaceComponentName, complicationSlotId: Int = defaultComplicationSlotId, instanceId: String? = null, vararg supportedTypes: ComplicationType = defaultSupportedTypes, complicationDeniedIntent: Intent? = Intent(), complicationRationalIntent: Intent? = Intent() ) = ComplicationHelperActivity.createComplicationDataSourceChooserHelperIntent( context, watchFaceComponentName, complicationSlotId, supportedTypes.asList(), instanceId, complicationDeniedIntent, complicationRationalIntent ) private fun createPermissionOnlyIntent( watchFaceComponentName: ComponentName = defaultWatchFaceComponentName, complicationDeniedIntent: Intent? = Intent(), complicationRationalIntent: Intent? = Intent() ) = ComplicationHelperActivity.createPermissionRequestHelperIntent( context, watchFaceComponentName, complicationDeniedIntent, complicationRationalIntent ) private companion object { /** The context to be used in the various tests. */ private val context = ApplicationProvider.getApplicationContext<Context>() /** The default watch face component name used in the test. */ private val defaultWatchFaceComponentName = ComponentName("test.package", "test.class") /** The default complication slot ID used in the test. */ private const val defaultComplicationSlotId = 1234 /** The default supported types used in the test. */ private val defaultSupportedTypes = arrayOf(SHORT_TEXT, LONG_TEXT) } } /** The watch face component name encoded in the intent. */ @Suppress("DEPRECATION") private val Intent.watchFaceComponentName get() = getParcelableExtra<ComponentName>( ComplicationDataSourceChooserIntent.EXTRA_WATCH_FACE_COMPONENT_NAME ) /** The complication ID encoded in the intent. */ private val Intent.complicationSlotId get() = getIntExtra(ComplicationDataSourceChooserIntent.EXTRA_COMPLICATION_ID, -1) /** The support types encoded in the intent. */ private val Intent.supportedTypes get() = ComplicationType.fromWireTypes( getIntArrayExtra(ComplicationDataSourceChooserIntent.EXTRA_SUPPORTED_TYPES)!! )
wear/watchface/watchface/src/androidTest/java/androidx/wear/watchface/ComplicationHelperActivityTest.kt
2897879042
package abi43_0_0.host.exp.exponent.modules.universal.notifications import android.content.Context import abi43_0_0.expo.modules.core.Promise import abi43_0_0.expo.modules.notifications.serverregistration.ServerRegistrationModule import host.exp.exponent.di.NativeModuleDepsProvider import host.exp.exponent.storage.ExponentSharedPreferences import javax.inject.Inject class ScopedServerRegistrationModule(context: Context) : ServerRegistrationModule(context) { @Inject lateinit var exponentSharedPreferences: ExponentSharedPreferences override fun getInstallationIdAsync(promise: Promise) { // If there is an existing installation ID, so if: // - we're in Expo Go and running an experience // which has previously been run on an older SDK // (where it persisted an installation ID in // the legacy storage) or // - we're in a standalone app after update // from SDK where installation ID has been // persisted in legacy storage // we let the migration do its job of moving // expo-notifications-specific installation ID // from scoped SharedPreferences to scoped noBackupDir // and use it from now on. val legacyUuid = mInstallationId.uuid if (legacyUuid != null) { promise.resolve(legacyUuid) } else { // Otherwise we can use the "common" installation ID // that has the benefit of being used if the project // is ejected to bare. promise.resolve(exponentSharedPreferences.getOrCreateUUID()) } } init { NativeModuleDepsProvider.instance.inject(ScopedServerRegistrationModule::class.java, this) } }
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/universal/notifications/ScopedServerRegistrationModule.kt
138294651
class A { fun foo() { bar() } } class B { fun bar() { foo() } } <caret> // EXIST: abstract // EXIST: class // EXIST: class AfterClasses_LangLevel11 // EXIST: enum class // EXIST: enum class AfterClasses_LangLevel11 // EXIST: final // EXIST: fun // EXIST: internal // EXIST: object // EXIST: object AfterClasses_LangLevel11 // EXIST: open // EXIST: private // EXIST: public // EXIST: interface // EXIST: interface AfterClasses_LangLevel11 // EXIST: val // EXIST: var // EXIST: operator // EXIST: infix // EXIST: sealed class // EXIST: sealed class AfterClasses_LangLevel11 // EXIST: data class // EXIST: { "lookupString":"data class", "itemText":"data class", "tailText":" AfterClasses_LangLevel11(...)", "attributes":"bold" } // EXIST: inline // EXIST: value // EXIST: tailrec // EXIST: external // EXIST: annotation class // EXIST: annotation class AfterClasses_LangLevel11 // EXIST: const val // EXIST: suspend fun // EXIST: typealias // NOTHING_ELSE
plugins/kotlin/completion/tests/testData/keywords/AfterClasses_LangLevel11.kt
2193168537
// IS_APPLICABLE: false import kotlin.reflect.KProperty class C { <caret>var foo by Delegate } object Delegate { operator fun getValue(instance: Any?, property: KProperty<*>): String = "" operator fun setValue(instance: Any?, property: KProperty<*>, value: String) {} }
plugins/kotlin/idea/tests/testData/intentions/convertNullablePropertyToLateinit/delegate.kt
2022004627
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector class <warning descr="Statistics collector is not registered in plugin.xml">U<caret>nregisteredStatisticsCounterCollector</warning> : CounterUsagesCollector()
plugins/devkit/devkit-kotlin-tests/testData/inspections/statisticsCollectorNotRegistered/UnregisteredCounterCollector.kt
650831636
val x = foo .bar() .baz() .quux() val x2 = foo() .bar() .baz() .quux() val x3 = ((foo().bar())) .baz() .quux() val x4 = (foo() .bar() .baz()).quux() val x5 = (foo()) .bar() .baz() .quux() val x6 = foo!! .bar() .baz()!! .quux()!! val x7 = foo!! .bar() .baz()!! .quux()!! val x8 = foo!!!!!!!! .bar() .baz()!! .quux()!! val x9 = ((b!!)!!!!)!!.f val x10 = a()!!.a() val x11 = a()!!!!.a() val x12 = a()!! .a()!! .a() val x13 = a()!!!! .a() .a() val x14 = a().a() val x15 = (a()).a() val x16 = (a()) .a() .a() val x17 = (a().a()).a() val x18 = (a().a()) .a() .a() val x18 = (a() .a() .a()) .a() .a() val x19 = (a() .a() .a()).a() val x20 = foo!!.foo .baz()!! .quux()!!.foo.foo.foo.baz().foo .baz() .baz() val y = xyzzy(foo .bar() .baz() .quux()) fun foo() { foo .bar() .baz() .quux() z = foo .bar() .baz() .quux() z += foo .bar() .baz() .quux() return foo .bar() .baz() .quux() } fun top() = "" .plus("") .plus("") class C { fun member() = "" .plus("") .plus("") } fun foo() { fun local() = "" .plus("") .plus("") val anonymous = fun() = "" .plus("") .plus("") } // SET_INT: METHOD_CALL_CHAIN_WRAP = 2 // SET_FALSE: WRAP_FIRST_METHOD_IN_CALL_CHAIN // SET_TRUE: ALLOW_TRAILING_COMMA
plugins/kotlin/idea/tests/testData/formatter/callChain/CallChainWrapping.after.inv.kt
537201643
//ALLOW_AST_ACCESS package test internal val x = { 0 }() internal fun f() = { 0 }()
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/visibility/InternalTopLevelMembers.kt
1492130939
fun Int.<caret>foo(a: Int): Int { return this + a }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/RenameExtensionParameterBefore.kt
3889679701
// EXTRACTION_TARGET: property with initializer val a = 1 fun foo(): Int { return <selection>1++</selection> }
plugins/kotlin/idea/tests/testData/refactoring/introduceConstant/binaryExpression/integerInc.kt
1109954361
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtTypeParameter // OPTIONS: usages fun <<caret>T> T.foo(t: T, list: List<T>): T { return t }
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findTypeParameterUsages/kotlinFunctionTypeParameterUsages.0.kt
1077009297
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.handler import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import org.apache.causeway.client.kroviz.to.* import org.apache.causeway.client.kroviz.to.mb.Menubars /** * File to group all handlers that only have a parse() function */ class DomainTypeHandler : BaseHandler() { override fun parse(response: String): TransferObject { return Json.decodeFromString<DomainType>(response) } } class MemberHandler : BaseHandler() { override fun parse(response: String): TransferObject { return Json.decodeFromString<Member>(response) } } class MenuBarsHandler : BaseHandler() { override fun parse(response: String): TransferObject { return Json.decodeFromString<Menubars>(response) } } class PropertyHandler : BaseHandler() { override fun parse(response: String): TransferObject { return Json.decodeFromString<Property>(response) } } class ServiceHandler : BaseHandler() { override fun parse(response: String): TransferObject { return Json.decodeFromString<Service>(response) } } class UserHandler : BaseHandler() { override fun parse(response: String): TransferObject { return Json.decodeFromString<User>(response) } } class VersionHandler : BaseHandler() { override fun parse(response: String): TransferObject { return Json.decodeFromString<Version>(response) } }
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/handler/PlainHandlers.kt
3890397903
package com.werb.library.link import androidx.recyclerview.widget.DiffUtil /** * Created by wanbo on 2017/12/19. */ abstract class XDiffCallback(val oldItem: List<Any>, val newItem: List<Any>) : DiffUtil.Callback()
library/src/main/kotlin/com/werb/library/link/XDiffCallback.kt
436463672
package com.cout970.modeler.gui.leguicomp import com.cout970.modeler.gui.GuiResources /** * Created by cout970 on 2017/09/15. */ interface IResourceReloadable { fun loadResources(resources: GuiResources) }
src/main/kotlin/com/cout970/modeler/gui/leguicomp/IResourceReloadable.kt
226909619
package com.mypurecloud.sdk.v2.extensions.notifications import com.fasterxml.jackson.databind.ObjectMapper import com.mypurecloud.sdk.v2.ApiClient import com.mypurecloud.sdk.v2.ApiException import com.mypurecloud.sdk.v2.Configuration.defaultApiClient import com.mypurecloud.sdk.v2.api.NotificationsApi import com.mypurecloud.sdk.v2.api.request.PostNotificationsChannelsRequest import com.mypurecloud.sdk.v2.model.Channel import com.mypurecloud.sdk.v2.model.ChannelTopic import com.mypurecloud.sdk.v2.model.SystemMessageSystemMessage import com.neovisionaries.ws.client.* import org.slf4j.LoggerFactory import java.io.IOException import java.util.* class NotificationHandler private constructor(builder: Builder) : Any() { private var notificationsApi: NotificationsApi? = NotificationsApi() private var webSocket: WebSocket? var channel: Channel? = null private val typeMap: MutableMap<String?, NotificationListener<*>> = mutableMapOf() private var webSocketListener: WebSocketListener? = null private var objectMapper: ObjectMapper? = null constructor() : this(Builder.standard()) {} class Builder { var notificationListeners: MutableList<NotificationListener<*>>? = null var webSocketListener: WebSocketListener? = null var channel: Channel? = null var connectAsync: Boolean? = null var apiClient: ApiClient? = null var notificationsApi: NotificationsApi? = null var objectMapper: ObjectMapper? = null var proxyHost: String? = null fun withNotificationListener(notificationListener: NotificationListener<*>): Builder { notificationListeners!!.add(notificationListener) return this } fun withNotificationListeners(notificationListeners: List<NotificationListener<*>>): Builder { this.notificationListeners!!.addAll(notificationListeners) return this } fun withWebSocketListener(webSocketListener: WebSocketListener?): Builder { this.webSocketListener = webSocketListener return this } fun withChannel(channel: Channel?): Builder { this.channel = channel return this } fun withAutoConnect(connectAsync: Boolean?): Builder { this.connectAsync = connectAsync return this } fun withApiClient(apiClient: ApiClient?): Builder { this.apiClient = apiClient return this } fun withNotificationsApi(notificationsApi: NotificationsApi?): Builder { this.notificationsApi = notificationsApi return this } fun withObjectMapper(objectMapper: ObjectMapper?): Builder { this.objectMapper = objectMapper return this } fun withProxyHost(proxyHost: String?): Builder { this.proxyHost = proxyHost return this } @Throws(IOException::class, ApiException::class, WebSocketException::class) fun build(): NotificationHandler { return NotificationHandler(this) } companion object { fun standard(): Builder { val builder = Builder() builder.notificationListeners = mutableListOf() builder.webSocketListener = null builder.channel = null builder.connectAsync = null builder.apiClient = null builder.notificationsApi = null builder.objectMapper = null builder.proxyHost = null return builder } } } fun sendPing() { webSocket!!.sendText("{\"message\":\"ping\"}") } fun setWebSocketListener(webSocketListener: WebSocketListener?) { this.webSocketListener = webSocketListener } @Throws(IOException::class, ApiException::class) fun <T> addSubscription(listener: NotificationListener<T>) { addSubscriptions(listOf<NotificationListener<*>>(listener)) } @Throws(IOException::class, ApiException::class) fun addSubscriptions(listeners: List<NotificationListener<*>>?) { val topics: MutableList<ChannelTopic> = LinkedList() for (listener in listeners!!) { typeMap[listener.getTopic()] = listener if ("channel.metadata" != listener.getTopic() && !listener.getTopic()?.startsWith("v2.system")!!) { val channelTopic = ChannelTopic() channelTopic.id = listener.getTopic() topics.add(channelTopic) } } notificationsApi!!.postNotificationsChannelSubscriptions(channel!!.id!!, topics) } fun <T> addHandlerNoSubscribe(listener: NotificationListener<T>) { addHandlersNoSubscribe(listOf<NotificationListener<*>>(listener)) } fun addHandlersNoSubscribe(listeners: List<NotificationListener<*>>?) { for (listener in listeners!!) { typeMap[listener.getTopic()] = listener } } @Throws(IOException::class, ApiException::class) fun RemoveSubscription(topic: String?) { val channels = notificationsApi!!.getNotificationsChannelSubscriptions(channel!!.id!!) var match: ChannelTopic? = null for (channelTopic in channels!!.entities!!) { if (channelTopic.id.equals(topic, ignoreCase = true)) { match = channelTopic break } } if (match == null) return channels.entities!!.remove(match) notificationsApi!!.putNotificationsChannelSubscriptions(channel!!.id!!, channels.entities!!) typeMap.remove(topic) } @Throws(IOException::class, ApiException::class) fun RemoveAllSubscriptions() { notificationsApi!!.deleteNotificationsChannelSubscriptions(channel!!.id!!) typeMap.clear() } @Throws(WebSocketException::class) fun connect(async: Boolean) { if (async) webSocket!!.connectAsynchronously() else webSocket!!.connect() } fun disconnect() { if (webSocket != null && webSocket?.isOpen!!) webSocket?.disconnect() } @Throws(Throwable::class) protected fun finalize() { try { // Ensure socket is closed on GC disconnect() } catch (ex: Exception) { LOGGER.error(ex.message, ex) } } companion object { private val LOGGER = LoggerFactory.getLogger(NotificationHandler::class.java) } init { // Construct notifications API notificationsApi = when { builder.notificationsApi != null -> { builder.notificationsApi } builder.apiClient != null -> { NotificationsApi(builder.apiClient) } else -> { NotificationsApi() } } // Set object mapper objectMapper = when { builder.objectMapper != null -> { builder.objectMapper } builder.apiClient != null -> { builder.apiClient!!.objectMapper } else -> { defaultApiClient!!.objectMapper } } // Set channel channel = when (builder.channel) { null -> { notificationsApi!!.postNotificationsChannels(PostNotificationsChannelsRequest.builder().build()) } else -> { builder.channel } } // Set notification listeners addSubscriptions(builder.notificationListeners) // Add handler for socket closing event addHandlerNoSubscribe(SocketClosingHandler()) // Set web socket listener setWebSocketListener(builder.webSocketListener) // Initialize web socket val factory = WebSocketFactory() if (builder.proxyHost != null) factory.proxySettings.setServer(builder.proxyHost) webSocket = factory .createSocket(channel!!.connectUri) .addListener(object : WebSocketAdapter() { @Throws(Exception::class) override fun onStateChanged(websocket: WebSocket, newState: WebSocketState) { if (webSocketListener != null) webSocketListener!!.onStateChanged(newState) } @Throws(Exception::class) override fun onConnected(websocket: WebSocket, headers: Map<String, List<String>>) { if (webSocketListener != null) webSocketListener!!.onConnected() } @Throws(Exception::class) override fun onConnectError(websocket: WebSocket, exception: WebSocketException) { if (webSocketListener != null) webSocketListener!!.onConnectError(exception) } @Throws(Exception::class) override fun onDisconnected(websocket: WebSocket, serverCloseFrame: WebSocketFrame, clientCloseFrame: WebSocketFrame, closedByServer: Boolean) { if (webSocketListener != null) webSocketListener!!.onDisconnected(closedByServer) } override fun onTextMessage(websocket: WebSocket, message: String) { try { if (LOGGER.isDebugEnabled) { LOGGER.debug("---WEBSOCKET MESSAGE---\n$message") } // Deserialize without knowing body type to figure out topic name val genericEventType = objectMapper!!.typeFactory.constructParametricType(NotificationEvent::class.java, Any::class.java) val genericEventData = objectMapper!!.readValue<NotificationEvent<Any>>(message, genericEventType) // Look up Listener based on topic name val specificType = typeMap[genericEventData.getTopicName()] if (specificType != null) { // Deserialize to specific type provided by listener val specificEventType = objectMapper!!.typeFactory.constructParametricType(NotificationEvent::class.java, specificType.getEventBodyClass()) val notificationEvent = objectMapper!!.readValue<Any>(message, specificEventType) as NotificationEvent<*> // Set raw body notificationEvent.setEventBodyRaw(message) // Raise event specificType.onEvent(notificationEvent) } else { // Unhandled topic if (webSocketListener != null) webSocketListener!!.onUnhandledEvent(message) } } catch (ex: Exception) { LOGGER.error(ex.message, ex) } } @Throws(Exception::class) override fun onError(websocket: WebSocket, cause: WebSocketException) { if (webSocketListener != null) webSocketListener!!.onError(cause) } @Throws(Exception::class) override fun handleCallbackError(websocket: WebSocket, cause: Throwable) { if (webSocketListener != null) webSocketListener!!.onCallbackError(cause) } }) if (builder.connectAsync != null) connect(builder.connectAsync!!) } inner class SocketClosingHandler : NotificationListener<SystemMessageSystemMessage?> { private val topic: String = "v2.system.socket_closing" override fun getTopic(): String? { return topic } override fun getEventBodyClass(): Class<SystemMessageSystemMessage>? { return SystemMessageSystemMessage::class.java } override fun onEvent(event: NotificationEvent<*>?) { try { webSocket = webSocket!!.recreate() } catch (ex: Exception) { LOGGER.error(ex.message, ex) } } } }
resources/sdk/purecloudkotlin/extensions/extensions/notifications/NotificationHandler.kt
3720421249
/* * Copyright (c) 2016. See AUTHORS file. * * 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.mbrlabs.mundus.editor.ui.modules.inspector.components.terrain import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.ui.Table import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.badlogic.gdx.utils.Align import com.kotcrab.vis.ui.util.dialog.Dialogs import com.kotcrab.vis.ui.widget.VisLabel import com.kotcrab.vis.ui.widget.VisTable import com.kotcrab.vis.ui.widget.VisTextButton import com.kotcrab.vis.ui.widget.tabbedpane.Tab import com.mbrlabs.mundus.editor.Mundus import com.mbrlabs.mundus.editor.core.project.ProjectManager import com.mbrlabs.mundus.editor.history.CommandHistory import com.mbrlabs.mundus.editor.history.commands.TerrainHeightCommand import com.mbrlabs.mundus.editor.terrain.Terraformer import com.mbrlabs.mundus.editor.ui.UI import com.mbrlabs.mundus.editor.ui.widgets.FileChooserField import com.mbrlabs.mundus.editor.ui.widgets.FloatFieldWithLabel import com.mbrlabs.mundus.editor.ui.widgets.IntegerFieldWithLabel import com.mbrlabs.mundus.editor.utils.isImage /** * @author Marcus Brummer * @version 04-03-2016 */ class TerrainGenTab(private val parent: TerrainComponentWidget) : Tab(false, false) { private val root = VisTable() private val hmInput = FileChooserField() private val loadHeightMapBtn = VisTextButton("Load heightmap") private val perlinNoiseBtn = VisTextButton("Generate Perlin noise") private val perlinNoiseSeed = IntegerFieldWithLabel("Seed", -1, false) private val perlinNoiseMinHeight = FloatFieldWithLabel("Min height", -1, true) private val perlinNoiseMaxHeight = FloatFieldWithLabel("Max height", -1, true) private val history: CommandHistory = Mundus.inject() private val projectManager: ProjectManager = Mundus.inject() init { root.align(Align.left) root.add(VisLabel("Load Heightmap")).pad(5f).left().row() root.add(hmInput).left().expandX().fillX().row() root.add(loadHeightMapBtn).padLeft(5f).left().row() root.add(VisLabel("Perlin Noise")).pad(5f).padTop(10f).left().row() root.add(perlinNoiseSeed).pad(5f).left().fillX().expandX().row() root.add(perlinNoiseMinHeight).pad(5f).left().fillX().expandX().row() root.add(perlinNoiseMaxHeight).pad(5f).left().fillX().expandX().row() root.add(perlinNoiseBtn).pad(5f).left().row() setupListeners() } private fun setupListeners() { loadHeightMapBtn.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { val hm = hmInput.file if (hm != null && hm.exists() && isImage(hm)) { loadHeightMap(hm) projectManager.current().assetManager.addDirtyAsset(parent.component.terrain) } else { Dialogs.showErrorDialog(UI, "Please select a heightmap image") } } }) perlinNoiseBtn.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { val seed = perlinNoiseSeed.int val min = perlinNoiseMinHeight.float val max = perlinNoiseMaxHeight.float generatePerlinNoise(seed, min, max) projectManager.current().assetManager.addDirtyAsset(parent.component.terrain) } }) } private fun loadHeightMap(heightMap: FileHandle) { val terrain = parent.component.terrain.terrain val command = TerrainHeightCommand(terrain) command.setHeightDataBefore(terrain.heightData) val originalMap = Pixmap(heightMap) // scale pixmap if it doesn't fit the terrainAsset if (originalMap.width != terrain.vertexResolution || originalMap.height != terrain.vertexResolution) { val scaledPixmap = Pixmap(terrain.vertexResolution, terrain.vertexResolution, originalMap.format) scaledPixmap.drawPixmap(originalMap, 0, 0, originalMap.width, originalMap.height, 0, 0, scaledPixmap.width, scaledPixmap.height) originalMap.dispose() Terraformer.heightMap(terrain).maxHeight(terrain.terrainWidth * 0.17f).map(scaledPixmap).terraform() scaledPixmap.dispose() } else { Terraformer.heightMap(terrain).maxHeight(terrain.terrainWidth * 0.17f).map(originalMap).terraform() originalMap.dispose() } command.setHeightDataAfter(terrain.heightData) history.add(command) } private fun generatePerlinNoise(seed: Int, min: Float, max: Float) { val terrain = parent.component.terrain.terrain val command = TerrainHeightCommand(terrain) command.setHeightDataBefore(terrain.heightData) Terraformer.perlin(terrain).minHeight(min).maxHeight(max).seed(seed.toLong()).terraform() command.setHeightDataAfter(terrain.heightData) history.add(command) } override fun getTabTitle(): String { return "Gen" } override fun getContentTable(): Table { return root } }
editor/src/main/com/mbrlabs/mundus/editor/ui/modules/inspector/components/terrain/TerrainGenTab.kt
2849539313
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages import com.intellij.openapi.util.SystemInfo import com.intellij.ui.HyperlinkLabel import com.intellij.ui.RelativeFont import com.intellij.util.ui.AsyncProcessIcon import com.intellij.util.ui.components.BorderLayoutPanel import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledEmptyBorder import com.jetbrains.packagesearch.intellij.plugin.ui.util.scrollbarWidth import java.awt.BorderLayout import java.awt.FlowLayout import javax.swing.JLabel @Suppress("MagicNumber") // Thanks Swing internal class HeaderPanel( onUpdateAllLinkClicked: (List<PackageSearchOperation<*>>) -> Unit ) : BorderLayoutPanel() { private val titleLabel = JLabel().apply { border = scaledEmptyBorder(right = 20) font = RelativeFont.BOLD.derive(font) } private val countLabel = JLabel().apply { foreground = PackageSearchUI.GRAY_COLOR border = scaledEmptyBorder(right = 8) } private val progressAnimation = AsyncProcessIcon("pkgs-header-progress").apply { isVisible = false suspend() } private val updateAllLink = HyperlinkLabel( PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.upgradeAll.text") ).apply { isVisible = false border = scaledEmptyBorder(top = 4) insets.top = 3.scaled() } private var updateAllOperations: List<PackageSearchOperation<*>> = emptyList() init { PackageSearchUI.setHeight(this, PackageSearchUI.SmallHeaderHeight) border = emptyBorder(top = 5.scaled(), left = 5.scaled(), right = 1.scaled() + scrollbarWidth()) background = PackageSearchUI.SectionHeaderBackgroundColor add( PackageSearchUI.flowPanel(PackageSearchUI.SectionHeaderBackgroundColor) { layout = FlowLayout(FlowLayout.LEFT, 6.scaled(), 0) add(titleLabel) add(countLabel) add(progressAnimation) }, BorderLayout.WEST ) add( PackageSearchUI.flowPanel(PackageSearchUI.SectionHeaderBackgroundColor) { layout = FlowLayout(FlowLayout.RIGHT, 6.scaled(), 0) add(updateAllLink) }, BorderLayout.EAST ) updateAllLink.addHyperlinkListener { onUpdateAllLinkClicked(updateAllOperations) } } fun showBusyIndicator(showIndicator: Boolean) { if (showIndicator) { progressAnimation.isVisible = true progressAnimation.resume() } else { progressAnimation.isVisible = false progressAnimation.suspend() } } fun display(title: String, rowsCount: Int?, availableUpdatesCount: Int, updateOperations: List<PackageSearchOperation<*>>) { titleLabel.text = title if (rowsCount != null) { countLabel.isVisible = true countLabel.text = rowsCount.toString() } else { countLabel.isVisible = false } updateAllOperations = updateOperations if (availableUpdatesCount > 0) { updateAllLink.setHyperlinkText( PackageSearchBundle.message( "packagesearch.ui.toolwindow.actions.upgradeAll.text.withCount", availableUpdatesCount ) ) updateAllLink.isVisible = true } else { updateAllLink.isVisible = false } } fun adjustForScrollbar(scrollbarVisible: Boolean, scrollbarOpaque: Boolean) { // Non-opaque scrollbars for JTable are supported on Mac only (as of IJ 2020.3): // See JBScrollPane.Layout#isAlwaysOpaque val isAlwaysOpaque = !SystemInfo.isMac /* && ScrollSettings.isNotSupportedYet(view), == true for JTable */ val includeScrollbar = scrollbarVisible && (isAlwaysOpaque || scrollbarOpaque) @ScaledPixels val rightBorder = if (includeScrollbar) scrollbarWidth() else 1.scaled() border = emptyBorder(top = 5.scaled(), left = 5.scaled(), right = rightBorder) updateAndRepaint() } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/HeaderPanel.kt
2824457877
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui import com.intellij.ui.scale.ScaleContext import com.intellij.ui.scale.ScaleType import com.intellij.util.IconUtil import com.intellij.util.ui.ImageUtil import java.awt.Component import java.awt.Graphics import java.awt.Image import javax.swing.Icon class ScalingDeferredSquareImageIcon<K : Any>(size: Int, defaultIcon: Icon, private val key: K, imageLoader: (K) -> Image?) : Icon { private val baseIcon = IconUtil.resizeSquared(defaultIcon, size) private val scaledIconCache = ScaleContext.Cache { scaleCtx -> IconDeferrer.getInstance().defer(baseIcon, key) { try { val image = imageLoader(it) val hidpiImage = ImageUtil.ensureHiDPI(image, scaleCtx) val scaledSize = scaleCtx.apply(size.toDouble(), ScaleType.USR_SCALE).toInt() val scaledImage = ImageUtil.scaleImage(hidpiImage, scaledSize, scaledSize) IconUtil.createImageIcon(scaledImage) } catch (e: Exception) { baseIcon } } } override fun getIconHeight() = baseIcon.iconHeight override fun getIconWidth() = baseIcon.iconWidth override fun paintIcon(c: Component, g: Graphics, x: Int, y: Int) { scaledIconCache.getOrProvide(ScaleContext.create(c))?.paintIcon(c, g, x, y) } }
platform/core-ui/src/ui/ScalingDeferredSquareImageIcon.kt
2290826814
package io.github.feelfreelinux.wykopmobilny.ui.modules.profile.links.comments import android.os.Bundle import io.github.feelfreelinux.wykopmobilny.base.BaseLinkCommentFragment import io.github.feelfreelinux.wykopmobilny.ui.modules.profile.ProfileActivity import javax.inject.Inject class ProfileLinkCommentsFragment : BaseLinkCommentFragment(), ProfileLinkCommentsView { @Inject lateinit var presenter: ProfileLinksFragmentPresenter override var loadDataListener: (Boolean) -> Unit = { presenter.loadData(it) } private val username by lazy { (activity as ProfileActivity).username } companion object { fun newInstance() = ProfileLinkCommentsFragment() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) presenter.subscribe(this) presenter.username = username linkCommentsAdapter.linkCommentActionListener = presenter linkCommentsAdapter.loadNewDataListener = { loadDataListener(false) } presenter.loadData(true) } override fun onDestroy() { presenter.unsubscribe() super.onDestroy() } }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/profile/links/comments/ProfileLinkCommentsFragment.kt
627026483
// PROBLEM: none // WITH_RUNTIME fun test(): String { <caret>with("") { return this@with } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantWith/notApplicable_labeledReturn2.kt
330425923
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails import com.jetbrains.packagesearch.api.v2.ApiStandardPackage import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.fus.FUSGroupIds import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint import com.jetbrains.packagesearch.intellij.plugin.ui.util.Displayable import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder import com.jetbrains.packagesearch.intellij.plugin.ui.util.noInsets import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledAsString import com.jetbrains.packagesearch.intellij.plugin.ui.util.skipInvisibleComponents import com.jetbrains.packagesearch.intellij.plugin.ui.util.withHtmlStyling import com.jetbrains.packagesearch.intellij.plugin.util.AppUI import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import net.miginfocom.layout.AC import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.apache.commons.lang3.StringUtils import java.awt.Component import java.awt.Dimension import javax.swing.JComponent import javax.swing.JPanel @Suppress("MagicNumber") // Swing dimension constants internal class PackageDetailsInfoPanel : JPanel(), Displayable<PackageDetailsInfoPanel.ViewModel> { @ScaledPixels private val maxRowHeight = 180.scaled() private val noDataLabel = PackageSearchUI.createLabel { foreground = PackageSearchUI.GRAY_COLOR text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.noData") .withHtmlStyling(wordWrap = true) }.withMaxHeight(maxRowHeight) private val descriptionLabel = PackageSearchUI.createLabel() private val repositoriesLabel = PackageSearchUI.createLabel() .withMaxHeight(maxRowHeight) private val gitHubPanel = GitHubInfoPanel() .withMaxHeight(maxRowHeight) private val licensesLinkLabel = PackageSearchUI.createLabelWithLink() .withMaxHeight(maxRowHeight) private val projectWebsiteLinkLabel = PackageSearchUI.createLabelWithLink() private val documentationLinkLabel = PackageSearchUI.createLabelWithLink() private val readmeLinkLabel = PackageSearchUI.createLabelWithLink() private val kotlinPlatformsPanel = PackageKotlinPlatformsPanel() private val usagesPanel = PackageUsagesPanel() private val authorsLabel = PackageSearchUI.createLabel() init { layout = MigLayout( LC().fillX() .noInsets() .skipInvisibleComponents() .gridGap("0", 8.scaledAsString()), AC().grow(), // One column only AC().fill().gap() // All rows are filling all available width .fill().gap() .fill().gap() .fill().gap() .fill().gap() .fill().gap() .fill().gap() .fill().gap() ) background = PackageSearchUI.UsualBackgroundColor alignmentX = Component.LEFT_ALIGNMENT @ScaledPixels val horizontalBorder = 12.scaled() border = emptyBorder(left = horizontalBorder, bottom = 20.scaled(), right = horizontalBorder) fun CC.compensateForHighlightableComponentMarginLeft() = pad(0, (-2).scaled(), 0, 0) add(noDataLabel, CC().wrap()) add(repositoriesLabel, CC().wrap()) add(descriptionLabel, CC().wrap()) add(gitHubPanel, CC().wrap()) add(licensesLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap()) add(projectWebsiteLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap()) add(documentationLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap()) add(readmeLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap()) add(kotlinPlatformsPanel, CC().wrap()) add(usagesPanel, CC().wrap()) add(authorsLabel, CC().wrap()) } internal data class ViewModel( val packageModel: PackageModel, val selectedVersion: PackageVersion, val allKnownRepositories: KnownRepositories.All ) override suspend fun display(viewModel: ViewModel) = withContext(Dispatchers.AppUI) { clearPanelContents() if (viewModel.packageModel.remoteInfo == null) { return@withContext } noDataLabel.isVisible = false displayDescriptionIfAny(viewModel.packageModel.remoteInfo) val selectedVersionInfo = viewModel.packageModel.remoteInfo .versions.find { it.version == viewModel.selectedVersion.versionName } displayRepositoriesIfAny(selectedVersionInfo, viewModel.allKnownRepositories) displayAuthorsIfAny(viewModel.packageModel.remoteInfo.authors) val linkExtractor = LinkExtractor(viewModel.packageModel.remoteInfo) displayGitHubInfoIfAny(linkExtractor.scm()) displayLicensesIfAny(linkExtractor.licenses()) displayProjectWebsiteIfAny(linkExtractor.projectWebsite()) displayDocumentationIfAny(linkExtractor.documentation()) displayReadmeIfAny(linkExtractor.readme()) displayKotlinPlatformsIfAny(viewModel.packageModel.remoteInfo) displayUsagesIfAny(viewModel.packageModel) updateAndRepaint() (parent as JComponent).updateAndRepaint() } private fun clearPanelContents() { noDataLabel.isVisible = true descriptionLabel.isVisible = false repositoriesLabel.isVisible = false authorsLabel.isVisible = false gitHubPanel.isVisible = false licensesLinkLabel.isVisible = false projectWebsiteLinkLabel.isVisible = false documentationLinkLabel.isVisible = false readmeLinkLabel.isVisible = false kotlinPlatformsPanel.isVisible = false usagesPanel.isVisible = false kotlinPlatformsPanel.clear() usagesPanel.clear() updateAndRepaint() } private fun displayDescriptionIfAny(remoteInfo: ApiStandardPackage) { @Suppress("HardCodedStringLiteral") // Comes from the API, it's @NlsSafe val description = remoteInfo.description if (description.isNullOrBlank() || description == remoteInfo.name) { descriptionLabel.isVisible = false return } descriptionLabel.isVisible = true descriptionLabel.text = description.withHtmlStyling(wordWrap = true) } private fun displayRepositoriesIfAny( selectedVersionInfo: ApiStandardPackage.ApiStandardVersion?, allKnownRepositories: KnownRepositories.All ) { if (selectedVersionInfo == null) { repositoriesLabel.isVisible = false return } val repositoryNames = selectedVersionInfo.repositoryIds .mapNotNull { repoId -> allKnownRepositories.findById(repoId)?.displayName } .filterNot { it.isBlank() } val repositoryNamesToDisplay = repositoryNames.joinToString() repositoriesLabel.text = if (repositoryNames.size == 1) { PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.repository", repositoryNamesToDisplay) } else { PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.repositories", repositoryNamesToDisplay) }.withHtmlStyling(wordWrap = true) repositoriesLabel.isVisible = true } private fun displayAuthorsIfAny(authors: List<ApiStandardPackage.ApiAuthor>?) { if (authors.isNullOrEmpty()) { authorsLabel.isVisible = false return } val authorNames = authors.filterNot { it.name.isNullOrBlank() } .map { StringUtils.normalizeSpace(it.name) } val authorsString = if (authorNames.size == 1) { PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.author", authorNames.joinToString()) } else { PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.authors", authorNames.joinToString()) } authorsLabel.text = authorsString.withHtmlStyling(wordWrap = true) authorsLabel.isVisible = true } private fun displayGitHubInfoIfAny(scmInfoLink: InfoLink.ScmRepository?) { if (scmInfoLink !is InfoLink.ScmRepository.GitHub || !scmInfoLink.hasBrowsableUrl()) { gitHubPanel.isVisible = false return } gitHubPanel.isVisible = true gitHubPanel.text = scmInfoLink.displayNameCapitalized gitHubPanel.url = scmInfoLink.url gitHubPanel.stars = scmInfoLink.stars } private fun displayLicensesIfAny(licenseInfoLink: List<InfoLink.License>) { // TODO move this to a separate component, handle multiple licenses val mainLicense = licenseInfoLink.firstOrNull() if (mainLicense == null || !mainLicense.hasBrowsableUrl()) { licensesLinkLabel.isVisible = false return } licensesLinkLabel.isVisible = true licensesLinkLabel.url = mainLicense.url licensesLinkLabel.setDisplayText( if (mainLicense.licenseName != null) { PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.license", mainLicense.licenseName) } else { mainLicense.displayNameCapitalized } ) licensesLinkLabel.urlClickedListener = { PackageSearchEventsLogger.logDetailsLinkClick(FUSGroupIds.DetailsLinkTypes.License, mainLicense.url) } } private fun displayProjectWebsiteIfAny(projectWebsiteLink: InfoLink.ProjectWebsite?) { if (projectWebsiteLink == null || !projectWebsiteLink.hasBrowsableUrl()) { projectWebsiteLinkLabel.isVisible = false return } projectWebsiteLinkLabel.isVisible = true projectWebsiteLinkLabel.url = projectWebsiteLink.url projectWebsiteLinkLabel.setDisplayText(projectWebsiteLink.displayNameCapitalized) projectWebsiteLinkLabel.urlClickedListener = { PackageSearchEventsLogger.logDetailsLinkClick(FUSGroupIds.DetailsLinkTypes.ProjectWebsite, projectWebsiteLink.url) } } private fun displayDocumentationIfAny(documentationLink: InfoLink.Documentation?) { if (documentationLink == null || !documentationLink.hasBrowsableUrl()) { documentationLinkLabel.isVisible = false return } documentationLinkLabel.isVisible = true documentationLinkLabel.url = documentationLink.url documentationLinkLabel.setDisplayText(documentationLink.displayNameCapitalized) documentationLinkLabel.urlClickedListener = { PackageSearchEventsLogger.logDetailsLinkClick(FUSGroupIds.DetailsLinkTypes.Documentation, documentationLink.url) } } private fun displayReadmeIfAny(readmeLink: InfoLink.Readme?) { if (readmeLink == null || !readmeLink.hasBrowsableUrl()) { readmeLinkLabel.isVisible = false return } readmeLinkLabel.isVisible = true readmeLinkLabel.url = readmeLink.url readmeLinkLabel.setDisplayText(readmeLink.displayNameCapitalized) readmeLinkLabel.urlClickedListener = { PackageSearchEventsLogger.logDetailsLinkClick(FUSGroupIds.DetailsLinkTypes.Readme, readmeLink.url) } } private fun displayKotlinPlatformsIfAny(packageDetails: ApiStandardPackage?) { val isKotlinMultiplatform = packageDetails?.mpp != null if (isKotlinMultiplatform && packageDetails?.platforms?.isNotEmpty() == true) { kotlinPlatformsPanel.display(packageDetails.platforms ?: emptyList()) kotlinPlatformsPanel.isVisible = true } else { kotlinPlatformsPanel.clear() kotlinPlatformsPanel.isVisible = false } } private fun displayUsagesIfAny(packageModel: PackageModel) { if (packageModel is PackageModel.Installed) { usagesPanel.display(packageModel) usagesPanel.isVisible = true } else { usagesPanel.clear() usagesPanel.isVisible = false } } private fun <T : JComponent> T.withMaxHeight(@ScaledPixels maxHeight: Int): T { maximumSize = Dimension(Int.MAX_VALUE, maxHeight) return this } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packagedetails/PackageDetailsInfoPanel.kt
1034577080
// 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.configuration import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.DummyLibraryProperties import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryType import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.framework.JSLibraryKind import org.jetbrains.kotlin.idea.framework.JSLibraryStdDescription import org.jetbrains.kotlin.idea.framework.JSLibraryType import org.jetbrains.kotlin.idea.framework.JsLibraryStdDetectionUtil import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.versions.LibraryJarDescriptor import org.jetbrains.kotlin.js.JavaScript import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.js.JsPlatforms open class KotlinJsModuleConfigurator : KotlinWithLibraryConfigurator() { override val name: String get() = NAME override val targetPlatform: TargetPlatform get() = JsPlatforms.defaultJsPlatform @Suppress("DEPRECATION_ERROR") override fun getTargetPlatform() = JsPlatforms.CompatJsPlatform override val presentableText: String get() = KotlinJvmBundle.message("language.name.javascript") override fun isConfigured(module: Module) = hasKotlinJsRuntimeInScope(module) override val libraryName: String get() = JSLibraryStdDescription.LIBRARY_NAME override val dialogTitle: String get() = JSLibraryStdDescription.DIALOG_TITLE override val libraryCaption: String get() = JSLibraryStdDescription.LIBRARY_CAPTION override val messageForOverrideDialog: String get() = JSLibraryStdDescription.JAVA_SCRIPT_LIBRARY_CREATION override fun getLibraryJarDescriptors(sdk: Sdk?): List<LibraryJarDescriptor> = listOf( LibraryJarDescriptor.JS_STDLIB_JAR, LibraryJarDescriptor.JS_STDLIB_SRC_JAR ) override val libraryMatcher: (Library, Project) -> Boolean = { library, project -> JsLibraryStdDetectionUtil.hasJsStdlibJar(library, project) } override val libraryType: LibraryType<DummyLibraryProperties>? get() = JSLibraryType.getInstance() companion object { const val NAME = JavaScript.LOWER_NAME } /** * Migrate pre-1.1.3 projects which didn't have explicitly specified kind for JS libraries. */ override fun findAndFixBrokenKotlinLibrary(module: Module, collector: NotificationMessageCollector): Library? { val allLibraries = mutableListOf<LibraryEx>() var brokenStdlib: Library? = null for (orderEntry in ModuleRootManager.getInstance(module).orderEntries) { val library = (orderEntry as? LibraryOrderEntry)?.library as? LibraryEx ?: continue allLibraries.add(library) if (JsLibraryStdDetectionUtil.hasJsStdlibJar(library, module.project, ignoreKind = true) && library.kind == null) { brokenStdlib = library } } if (brokenStdlib != null) { runWriteAction { for (library in allLibraries.filter { it.kind == null }) { library.modifiableModel.apply { kind = JSLibraryKind commit() } } } collector.addMessage(KotlinJvmBundle.message("updated.javascript.libraries.in.module.0", module.name)) } return brokenStdlib } }
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinJsModuleConfigurator.kt
4210611524
// PROBLEM: none // WITH_RUNTIME fun test() { listOf(listOf(1)).flatMap<caret> { it + 1 } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCall/notOnlyReference.kt
3710128438
// 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.workspaceModel.storage import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageBuilderImpl import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageImpl fun WorkspaceEntityStorage.checkConsistency() { if (this is WorkspaceEntityStorageImpl) { this.assertConsistency() return } if (this is WorkspaceEntityStorageBuilderImpl) { this.assertConsistency() return } } internal fun createEmptyBuilder(): WorkspaceEntityStorageBuilderImpl { return WorkspaceEntityStorageBuilderImpl.create() } internal fun createBuilderFrom(storage: WorkspaceEntityStorage): WorkspaceEntityStorageBuilderImpl { return WorkspaceEntityStorageBuilderImpl.from(storage) } internal inline fun makeBuilder(from: WorkspaceEntityStorage? = null, action: WorkspaceEntityStorageBuilder.() -> Unit): WorkspaceEntityStorageBuilderImpl { val builder = if (from == null) { createEmptyBuilder() } else { createBuilderFrom(from) } builder.action() return builder }
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/storageTestUtils.kt
323979981
// IS_APPLICABLE: false // WITH_RUNTIME val x = listOf(java.lang.String("")).map { <caret>it.bytes }
plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/syntheticProperty.kt
255252859
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * econsim-tr01 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.ch0202 /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ data class Sim1ScenarioDescriptor( val initialNetworkSize:Int, val averageNetworkActivity:Double, var averageSuggestibilityOfStrangers:Double )
src/test/java/cc/altruix/econsimtr01/ch0202/Sim1ScenarioDescriptor.kt
3576880139
// PROBLEM: none // WITH_RUNTIME fun test() { listOf("A").forEach { setOf(1).map { <caret>_ -> it.length } } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantLambdaArrow/nestedLambda.kt
3162545438
// WITH_RUNTIME fun test(list: List<Int>) { val firstOrNull: Int? = list.<caret>filter { it > 1 }.firstOrNull() }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/firstOrNull.kt
1387475006
package test class A { fun argumentAdded() {} fun argumentRemoved(x: Int = 2) {} fun valueAdded(x: Int) {} fun valueRemoved(x: Int = 4) {} fun valueChanged(x: Int = 5) {} } class ConstructorValueAdded(x: Int) class ConstructorValueRemoved(x: Int = 8) class ConstructorValueChanged(x: Int = 19) class ConstructorArgumentAdded() class ConstructorArgumentRemoved(x: Int = 10)
plugins/kotlin/jps/jps-plugin/tests/testData/comparison/classMembersOnlyChanged/defaultValues/old.kt
3446945423
package com.maly.domain.room import com.maly.domain.event.Event import com.maly.domain.order.Ticket import org.springframework.data.jpa.domain.Specification /** * @author Aleksander Brzozowski */ class SeatSpecification private constructor(){ companion object { fun forFree(eventId: Long): Specification<Seat> { return Specification { root, query, cb -> val seatId = root.get<Long>("id") val sq = query.subquery(Long::class.java) val ticket = sq.from(Ticket::class.java) val seat = ticket.get<Seat>("seat") val seatPredicate = cb.equal(seat.get<Long>("id"), seatId) val event = ticket.get<Event>("event") val eventPredicate = cb.equal(event.get<Long>("id"), eventId) sq.where(cb.and(eventPredicate, seatPredicate)) cb.equal(sq.select(cb.count(ticket)), 0) } } fun forRoom(roomId: Long): Specification<Seat> { return Specification { root, _, cb -> val room = root.get<Room>("room") cb.equal(room.get<Long>("id"), roomId) } } } }
src/main/kotlin/com/maly/domain/room/SeatSpecification.kt
4270524929
// 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.ide.bookmark.actions import com.intellij.ide.bookmark.Bookmark import com.intellij.ide.bookmark.BookmarkBundle import com.intellij.ide.bookmark.BookmarkType import com.intellij.ide.bookmark.BookmarksManager import com.intellij.ide.bookmark.ui.tree.BookmarkNode import com.intellij.ide.projectView.PresentationData import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.ide.util.treeView.AbstractTreeNodeCache import com.intellij.ide.util.treeView.AbstractTreeStructure import com.intellij.ide.util.treeView.NodeDescriptor import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys.NAVIGATABLE import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.Disposer import com.intellij.ui.components.JBScrollPane import com.intellij.ui.popup.PopupState import com.intellij.ui.tree.AsyncTreeModel import com.intellij.ui.tree.StructureTreeModel import com.intellij.ui.treeStructure.Tree import com.intellij.util.EditSourceOnDoubleClickHandler import com.intellij.util.containers.toArray import com.intellij.util.ui.JBUI import com.intellij.util.ui.tree.TreeUtil import java.awt.Dimension import javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION internal class ShowTypeBookmarksAction : DumbAwareAction(BookmarkBundle.messagePointer("show.type.bookmarks.action.text")) { private val popupState = PopupState.forPopup() private val BookmarksManager.typeBookmarks get() = BookmarkType.values().mapNotNull { getBookmark(it)?.run { it to this } }.ifEmpty { null } override fun update(event: AnActionEvent) { event.presentation.isEnabled = event.bookmarksManager?.assignedTypes?.isNotEmpty() ?: false } override fun actionPerformed(event: AnActionEvent) { if (popupState.isRecentlyHidden) return if (popupState.isShowing) return popupState.hidePopup() val bookmarks = event.bookmarksManager?.typeBookmarks ?: return val root = MyRoot(bookmarks.map { it.second }) val tree = Tree(AsyncTreeModel(StructureTreeModel(MyStructure(root), root), root)).apply { isRootVisible = false showsRootHandles = false visibleRowCount = bookmarks.size selectionModel.selectionMode = SINGLE_TREE_SELECTION } bookmarks.forEach { tree.registerBookmarkTypeAction(root, it.first) } tree.registerEditSourceAction(root) tree.registerNavigateOnEnterAction() EditSourceOnDoubleClickHandler.install(tree) TreeUtil.promiseSelectFirstLeaf(tree).onSuccess { // show popup when tree is loaded val popup = JBPopupFactory.getInstance() .createComponentPopupBuilder(MyScrollPane(tree), tree) .setTitle(BookmarkBundle.message("popup.title.type.bookmarks")) .setFocusable(true) .setRequestFocus(true) .setCancelOnOtherWindowOpen(true) .createPopup() Disposer.register(popup, root) popupState.prepareToShow(popup) popup.showCenteredInCurrentWindow(event.project!!) } } private class MyScrollPane(val tree: Tree) : DataProvider, JBScrollPane(tree) { init { border = JBUI.Borders.empty() viewportBorder = JBUI.Borders.empty() horizontalScrollBarPolicy = HORIZONTAL_SCROLLBAR_NEVER } override fun getPreferredSize(): Dimension? = super.getPreferredSize()?.also { if (!isPreferredSizeSet) it.width = it.width.coerceAtMost(JBUI.scale(640)) } override fun getData(dataId: String): Any? = when { NAVIGATABLE.`is`(dataId) -> TreeUtil.getAbstractTreeNode(tree.selectionPath) else -> null } } private class MyRoot(bookmarks: List<Bookmark>) : Disposable, AbstractTreeNode<List<Bookmark>>(null, bookmarks) { private val cache = AbstractTreeNodeCache<Bookmark, AbstractTreeNode<*>>(this) { it.createNode() } override fun isAlwaysShowPlus() = true override fun getChildren() = cache.getNodes(value).onEach { if (it is BookmarkNode) it.bookmarkGroup = it.value.firstGroupWithDescription } override fun shouldUpdateData() = false override fun update(presentation: PresentationData) = Unit override fun dispose() = Unit } private class MyStructure(val root: MyRoot) : AbstractTreeStructure() { override fun commit() = Unit override fun hasSomethingToCommit() = false override fun createDescriptor(element: Any, parent: NodeDescriptor<*>?) = element as NodeDescriptor<*> override fun getRootElement() = root override fun getParentElement(element: Any): Any? = (element as? AbstractTreeNode<*>)?.parent override fun getChildElements(element: Any) = when (element) { root -> root.children.toArray(arrayOf()) else -> emptyArray() } } }
platform/lang-impl/src/com/intellij/ide/bookmark/actions/ShowTypeBookmarksAction.kt
2549492318
package de.stefanmedack.ccctv.ui.main import android.os.Bundle import android.view.KeyEvent import de.stefanmedack.ccctv.R import de.stefanmedack.ccctv.ui.base.BaseInjectableActivity import de.stefanmedack.ccctv.util.replaceFragmentInTransaction class MainActivity : BaseInjectableActivity() { private val MAIN_TAG = "MAIN_TAG" var fragment: MainFragment? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.fragment_activity) fragment = supportFragmentManager.findFragmentByTag(MAIN_TAG) as? MainFragment ?: MainFragment() fragment?.let { frag -> replaceFragmentInTransaction(frag, R.id.fragment, MAIN_TAG) } } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { return (fragment?.onKeyDown(keyCode) == true) || super.onKeyDown(keyCode, event) } }
app/src/main/java/de/stefanmedack/ccctv/ui/main/MainActivity.kt
2289849532
package com.maubis.scarlet.base.support import android.app.PendingIntent import android.content.Context import android.content.pm.ShortcutInfo import android.content.pm.ShortcutManager import com.maubis.scarlet.base.support.utils.OsVersionUtils fun addShortcut(context: Context, shortcut: ShortcutInfo) { if (!OsVersionUtils.canAddLauncherShortcuts()) { return } val shortcutManager = context.getSystemService(ShortcutManager::class.java) if (shortcutManager === null) { return } shortcutManager.dynamicShortcuts = listOf(shortcut) if (shortcutManager.isRequestPinShortcutSupported) { val pinShortcutInfo = ShortcutInfo.Builder(context, shortcut.id).build() val pinnedShortcutCallbackIntent = shortcutManager.createShortcutResultIntent(pinShortcutInfo) val successCallback = PendingIntent.getBroadcast( context, 0, pinnedShortcutCallbackIntent, 0) shortcutManager.requestPinShortcut(pinShortcutInfo, successCallback.intentSender) } }
base/src/main/java/com/maubis/scarlet/base/support/ShortcutUtils.kt
3910883542
package me.bemind.glitchappcore.history import android.content.Context import android.content.SharedPreferences import android.graphics.Bitmap import com.google.gson.Gson import com.google.gson.reflect.TypeToken import me.bemind.glitch.Effect import me.bemind.glitchappcore.ImageDescriptor import me.bemind.glitchappcore.ImageStorage import java.util.* /** * Created by angelomoroni on 14/04/17. */ interface IHistoryLogic { fun getStack(): ArrayList<ImageDescriptor> fun setStack(list: List<ImageDescriptor>?) fun back() : Bitmap? fun canBack() : Boolean fun addBitmap(bitmap: Bitmap, newImage:Boolean = false) fun clearHistory() var lastBitmap : Bitmap? var firstBitmap : Bitmap? var sizeHistory : Int var hasHistory : Boolean } class HistoryLogic(val context:Context) : IHistoryLogic { private val PREFERENCES_NAME = "history_preferences" private val STACK_K: String? = "stack_k" private val imageStorage = ImageStorage private val historyPref : SharedPreferences by lazy { context.getSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE) } init { imageStorage.context = context } override var lastBitmap: Bitmap? get() = imageStorage.getLastBitmap() set(value) {/*nothing*/ } override var firstBitmap: Bitmap? get() = imageStorage.firstBitmap() set(value) {/*nothing*/} override var sizeHistory: Int get() = imageStorage.size() set(value) {/*nothing*/} override var hasHistory: Boolean get() = sizeHistory>0 set(value) {/*nothing*/} override fun addBitmap(bitmap: Bitmap,newImage: Boolean) { if(newImage) clearHistory() imageStorage.addBitmap(bitmap,Effect.BASE,newImage) } override fun clearHistory() { imageStorage.clear() historyPref.edit().putString(STACK_K,"").apply() } override fun setStack(list: List<ImageDescriptor>?) { imageStorage.stack.clear() if(list !=null) { imageStorage.stack.addAll(list ) }else{ imageStorage.stack.addAll(getListFromStorage()) } } override fun back(): Bitmap? = imageStorage.back() override fun getStack(): ArrayList<ImageDescriptor> { val l = imageStorage.stack.getAllAsList() historyPref.edit().putString(STACK_K,Gson().toJson(l)).apply() return l } override fun canBack(): Boolean = imageStorage.canBack() private fun getListFromStorage(): Collection<ImageDescriptor> { val list = historyPref.getString(STACK_K,"") if (list.isEmpty()){ return LinkedList() }else{ val listType = object : TypeToken<LinkedList<ImageDescriptor>>() {}.type return Gson().fromJson(list,listType) } } }
glitchappcore/src/main/java/me/bemind/glitchappcore/history/HistoryLogic.kt
1998100504
val example = "STRING_${extracted<caret>()}_BIG" private fun extracted() = "SAMPLE"
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/inplace/StringTemplate.after.kt
3330530983
// 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.testFramework import com.intellij.openapi.util.ThrowableComputable import com.intellij.util.ThrowableRunnable import org.jetbrains.annotations.TestOnly /** * Consider using Kotlin coroutines and [Dispatchers.EDT][com.intellij.openapi.application.EDT]. * @see com.intellij.openapi.application.AppUIExecutor.onUiThread */ @TestOnly inline fun <V> runInEdtAndGet(crossinline compute: () -> V): V { @Suppress("DEPRECATION", "RemoveExplicitTypeArguments") return EdtTestUtil.runInEdtAndGet(ThrowableComputable<V, Throwable> { compute() }) } /** * Consider using Kotlin coroutines and [Dispatchers.EDT][com.intellij.openapi.application.EDT]. * @see com.intellij.openapi.application.AppUIExecutor.onUiThread */ @TestOnly inline fun runInEdtAndWait(crossinline runnable: () -> Unit) { @Suppress("DEPRECATION", "RemoveExplicitTypeArguments") EdtTestUtil.runInEdtAndWait(ThrowableRunnable<Throwable> { runnable() }) }
platform/testFramework/src/com/intellij/testFramework/EdtTestUtil.kt
3882511045
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy /** * Contains useful information about an individual item in lazy lists like [LazyColumn] * or [LazyRow]. * * @see LazyListLayoutInfo */ interface LazyListItemInfo { /** * The index of the item in the list. */ val index: Int /** * The key of the item which was passed to the item() or items() function. */ val key: Any /** * The main axis offset of the item in pixels. It is relative to the start of the lazy list container. */ val offset: Int /** * The main axis size of the item in pixels. Note that if you emit multiple layouts in the composable * slot for the item then this size will be calculated as the sum of their sizes. */ val size: Int }
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListItemInfo.kt
2704062803
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.requiredSize import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.hasAnyDescendant import androidx.compose.ui.test.hasTestTag import androidx.compose.ui.test.isPopup import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performClick import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalTestApi::class) class MenuTest { @get:Rule val rule = createComposeRule() @Test fun menu_canBeTriggered() { var expanded by mutableStateOf(false) rule.setContent { Box(Modifier.requiredSize(20.dp).background(color = Color.Blue)) { DropdownMenu( expanded = expanded, onDismissRequest = {} ) { DropdownMenuItem(modifier = Modifier.testTag("MenuContent"), onClick = {}) { Text("Option 1") } } } } rule.onNodeWithTag("MenuContent").assertDoesNotExist() rule.mainClock.autoAdvance = false rule.runOnUiThread { expanded = true } rule.mainClock.advanceTimeByFrame() // Trigger the popup rule.waitForIdle() rule.mainClock.advanceTimeByFrame() // Kick off the animation rule.mainClock.advanceTimeBy(InTransitionDuration.toLong()) rule.onNodeWithTag("MenuContent").assertExists() rule.runOnUiThread { expanded = false } rule.mainClock.advanceTimeByFrame() // Trigger the popup rule.mainClock.advanceTimeByFrame() // Kick off the animation rule.mainClock.advanceTimeBy(OutTransitionDuration.toLong()) rule.mainClock.advanceTimeByFrame() rule.onNodeWithTag("MenuContent").assertDoesNotExist() rule.runOnUiThread { expanded = true } rule.mainClock.advanceTimeByFrame() // Trigger the popup rule.waitForIdle() rule.mainClock.advanceTimeByFrame() // Kick off the animation rule.mainClock.advanceTimeBy(InTransitionDuration.toLong()) rule.onNodeWithTag("MenuContent").assertExists() } @Test fun menu_hasExpectedSize() { rule.setContent { with(LocalDensity.current) { Box(Modifier.requiredSize(20.toDp()).background(color = Color.Blue)) { DropdownMenu( expanded = true, onDismissRequest = {} ) { Box(Modifier.testTag("MenuContent1").size(70.toDp())) Box(Modifier.testTag("MenuContent2").size(130.toDp())) } } } } rule.onNodeWithTag("MenuContent1").assertExists() rule.onNodeWithTag("MenuContent2").assertExists() val node = rule.onNode( isPopup() and hasAnyDescendant(hasTestTag("MenuContent1")) and hasAnyDescendant(hasTestTag("MenuContent2")) ).assertExists().fetchSemanticsNode() with(rule.density) { assertThat(node.size.width).isEqualTo(130) assertThat(node.size.height) .isEqualTo(DropdownMenuVerticalPadding.roundToPx() * 2 + 200) } } @Test fun menu_positioning_bottomEnd() { val screenWidth = 500 val screenHeight = 1000 val density = Density(1f) val windowSize = IntSize(screenWidth, screenHeight) val anchorPosition = IntOffset(100, 200) val anchorSize = IntSize(10, 20) val offsetX = 20 val offsetY = 40 val popupSize = IntSize(50, 80) val ltrPosition = DropdownMenuPositionProvider( DpOffset(offsetX.dp, offsetY.dp), density ).calculatePosition( IntRect(anchorPosition, anchorSize), windowSize, LayoutDirection.Ltr, popupSize ) assertThat(ltrPosition.x).isEqualTo( anchorPosition.x + offsetX ) assertThat(ltrPosition.y).isEqualTo( anchorPosition.y + anchorSize.height + offsetY ) val rtlPosition = DropdownMenuPositionProvider( DpOffset(offsetX.dp, offsetY.dp), density ).calculatePosition( IntRect(anchorPosition, anchorSize), windowSize, LayoutDirection.Rtl, popupSize ) assertThat(rtlPosition.x).isEqualTo( anchorPosition.x + anchorSize.width - offsetX - popupSize.width ) assertThat(rtlPosition.y).isEqualTo( anchorPosition.y + anchorSize.height + offsetY ) } @Test fun menu_positioning_topStart() { val screenWidth = 500 val screenHeight = 1000 val density = Density(1f) val windowSize = IntSize(screenWidth, screenHeight) val anchorPosition = IntOffset(450, 950) val anchorPositionRtl = IntOffset(50, 950) val anchorSize = IntSize(10, 20) val offsetX = 20 val offsetY = 40 val popupSize = IntSize(150, 80) val ltrPosition = DropdownMenuPositionProvider( DpOffset(offsetX.dp, offsetY.dp), density ).calculatePosition( IntRect(anchorPosition, anchorSize), windowSize, LayoutDirection.Ltr, popupSize ) assertThat(ltrPosition.x).isEqualTo( anchorPosition.x + anchorSize.width - offsetX - popupSize.width ) assertThat(ltrPosition.y).isEqualTo( anchorPosition.y - popupSize.height - offsetY ) val rtlPosition = DropdownMenuPositionProvider( DpOffset(offsetX.dp, offsetY.dp), density ).calculatePosition( IntRect(anchorPositionRtl, anchorSize), windowSize, LayoutDirection.Rtl, popupSize ) assertThat(rtlPosition.x).isEqualTo( anchorPositionRtl.x + offsetX ) assertThat(rtlPosition.y).isEqualTo( anchorPositionRtl.y - popupSize.height - offsetY ) } @Test fun menu_positioning_top() { val screenWidth = 500 val screenHeight = 1000 val density = Density(1f) val windowSize = IntSize(screenWidth, screenHeight) val anchorPosition = IntOffset(0, 0) val anchorSize = IntSize(50, 20) val popupSize = IntSize(150, 500) // The min margin above and below the menu, relative to the screen. val MenuVerticalMargin = 48.dp val verticalMargin = with(density) { MenuVerticalMargin.roundToPx() } val position = DropdownMenuPositionProvider( DpOffset(0.dp, 0.dp), density ).calculatePosition( IntRect(anchorPosition, anchorSize), windowSize, LayoutDirection.Ltr, popupSize ) assertThat(position.y).isEqualTo( verticalMargin ) } @Test fun menu_positioning_anchorPartiallyVisible() { val screenWidth = 500 val screenHeight = 1000 val density = Density(1f) val windowSize = IntSize(screenWidth, screenHeight) val anchorPosition = IntOffset(-25, -10) val anchorPositionRtl = IntOffset(525, -10) val anchorSize = IntSize(50, 20) val popupSize = IntSize(150, 500) // The min margin above and below the menu, relative to the screen. val MenuVerticalMargin = 48.dp val verticalMargin = with(density) { MenuVerticalMargin.roundToPx() } val position = DropdownMenuPositionProvider( DpOffset(0.dp, 0.dp), density ).calculatePosition( IntRect(anchorPosition, anchorSize), windowSize, LayoutDirection.Ltr, popupSize ) assertThat(position.x).isEqualTo( 0 ) assertThat(position.y).isEqualTo( verticalMargin ) val rtlPosition = DropdownMenuPositionProvider( DpOffset(0.dp, 0.dp), density ).calculatePosition( IntRect(anchorPositionRtl, anchorSize), windowSize, LayoutDirection.Rtl, popupSize ) assertThat(rtlPosition.x).isEqualTo( screenWidth - popupSize.width ) assertThat(rtlPosition.y).isEqualTo( verticalMargin ) } @Test fun menu_positioning_callback() { val screenWidth = 500 val screenHeight = 1000 val density = Density(1f) val windowSize = IntSize(screenWidth, screenHeight) val anchorPosition = IntOffset(100, 200) val anchorSize = IntSize(10, 20) val offsetX = 20 val offsetY = 40 val popupSize = IntSize(50, 80) var obtainedParentBounds = IntRect(0, 0, 0, 0) var obtainedMenuBounds = IntRect(0, 0, 0, 0) DropdownMenuPositionProvider( DpOffset(offsetX.dp, offsetY.dp), density ) { parentBounds, menuBounds -> obtainedParentBounds = parentBounds obtainedMenuBounds = menuBounds }.calculatePosition( IntRect(anchorPosition, anchorSize), windowSize, LayoutDirection.Ltr, popupSize ) assertThat(obtainedParentBounds).isEqualTo(IntRect(anchorPosition, anchorSize)) assertThat(obtainedMenuBounds).isEqualTo( IntRect( anchorPosition.x + offsetX, anchorPosition.y + anchorSize.height + offsetY, anchorPosition.x + offsetX + popupSize.width, anchorPosition.y + anchorSize.height + offsetY + popupSize.height ) ) } @Test fun dropdownMenuItem_emphasis() { var onSurface = Color.Unspecified var enabledContentColor = Color.Unspecified var disabledContentColor = Color.Unspecified var enabledContentAlpha = 1f var disabledContentAlpha = 1f rule.setContent { onSurface = MaterialTheme.colors.onSurface enabledContentAlpha = ContentAlpha.high disabledContentAlpha = ContentAlpha.disabled Box(Modifier.requiredSize(20.dp)) { DropdownMenu( onDismissRequest = {}, expanded = true ) { DropdownMenuItem(onClick = {}) { enabledContentColor = LocalContentColor.current .copy(alpha = LocalContentAlpha.current) } DropdownMenuItem(enabled = false, onClick = {}) { disabledContentColor = LocalContentColor.current .copy(alpha = LocalContentAlpha.current) } } } } assertThat(enabledContentColor).isEqualTo(onSurface.copy(alpha = enabledContentAlpha)) assertThat(disabledContentColor).isEqualTo(onSurface.copy(alpha = disabledContentAlpha)) } @Test fun dropdownMenuItem_onClick() { var clicked = false val onClick: () -> Unit = { clicked = true } rule.setContent { DropdownMenuItem( onClick, modifier = Modifier.testTag("MenuItem").clickable(onClick = onClick) ) { Box(Modifier.requiredSize(40.dp)) } } rule.onNodeWithTag("MenuItem").performClick() rule.runOnIdle { assertThat(clicked).isTrue() } } }
compose/material/material/src/androidAndroidTest/kotlin/androidx/compose/material/MenuTest.kt
2577293698
/* * 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.health.services.client.data import androidx.health.services.client.data.ExerciseTrackedStatus.Companion.toProto import androidx.health.services.client.proto.DataProto /** High-level info about the exercise. */ @Suppress("ParcelCreator") public class ExerciseInfo( /** Returns the [ExerciseTrackedStatus]. */ @ExerciseTrackedStatus public val exerciseTrackedStatus: Int, /** * Returns the [ExerciseType] of the active exercise, or [ExerciseType.UNKNOWN] if there is no * active exercise. */ public val exerciseType: ExerciseType, ) { internal constructor( proto: DataProto.ExerciseInfo ) : this( ExerciseTrackedStatus.fromProto(proto.exerciseTrackedStatus), ExerciseType.fromProto(proto.exerciseType) ) internal val proto: DataProto.ExerciseInfo = DataProto.ExerciseInfo.newBuilder() .setExerciseTrackedStatus(exerciseTrackedStatus.toProto()) .setExerciseType(exerciseType.toProto()) .build() }
health/health-services-client/src/main/java/androidx/health/services/client/data/ExerciseInfo.kt
4221546057
import org.junit.Test class IncorrectKeyCipherTest { @Test(expected = IllegalArgumentException::class) fun cipherThrowsWithAllCapsKey() { Cipher("ABCDEF") } @Test(expected = IllegalArgumentException::class) fun cipherThrowsWithAnyCapsKey() { Cipher("abcdEFg") } @Test(expected = IllegalArgumentException::class) fun cipherThrowsWithNumericKey() { Cipher("12345") } @Test(expected = IllegalArgumentException::class) fun cipherThrowsWithAnyNumericKey() { Cipher("abcd345ef") } @Test(expected = IllegalArgumentException::class) fun cipherThrowsWithEmptyKey() { Cipher("") } }
kotlin/simple-cipher/src/test/kotlin/IncorrectKeyCipherTest.kt
4016291107
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.samples import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.viewbinding.samples.R import androidx.compose.ui.viewbinding.samples.databinding.TestFragmentLayoutBinding import androidx.compose.ui.viewinterop.AndroidViewBinding import androidx.fragment.app.FragmentActivity import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.google.common.truth.Truth.assertWithMessage import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class FragmentRemoveTest { @get:Rule val rule = createAndroidComposeRule<EmptyFragmentActivity>() @Test fun testRemoval() { var show by mutableStateOf(true) rule.setContent { if (show) { AndroidViewBinding(TestFragmentLayoutBinding::inflate) } } var fragment = rule.activity.supportFragmentManager .findFragmentById(R.id.fragment_container) assertWithMessage("Fragment should be present when AndroidViewBinding is in the hierarchy") .that(fragment) .isNotNull() show = false rule.waitForIdle() fragment = rule.activity.supportFragmentManager .findFragmentById(R.id.fragment_container) assertWithMessage("Fragment should be removed when the AndroidViewBinding is removed") .that(fragment) .isNull() } } class EmptyFragmentActivity : FragmentActivity()
compose/ui/ui-viewbinding/samples/src/androidTest/java/androidx/compose/ui/samples/FragmentRemoveTest.kt
1573957279
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build import java.util.Locale import org.gradle.api.Project /** * A comma separated list of KMP target platforms you wish to enable / disable. * e.g. '-jvm,+mac,+linux,+js' */ const val ENABLED_KMP_TARGET_PLATFORMS = "androidx.enabled.kmp.target.platforms" enum class KmpPlatform { JVM, // Do _not_ enable unless you have read and understand this: // https://blog.jetbrains.com/kotlin/2021/10/important-ua-parser-js-exploit-and-kotlin-js/ JS, MAC, LINUX; companion object { val native = listOf(MAC, LINUX) val enabledByDefault = listOf(JVM) private const val JVM_PLATFORM = "jvm" private const val JS_PLATFORM = "js" private const val MAC_ARM_64 = "macosarm64" private const val MAC_OSX_64 = "macosx64" private const val LINUX_64 = "linuxx64" private const val IOS_SIMULATOR_ARM_64 = "iossimulatorarm64" private const val IOS_X_64 = "iosx64" private const val IOS_ARM_64 = "iosarm64" val macPlatforms = listOf(MAC_ARM_64, MAC_OSX_64) val linuxPlatforms = listOf(LINUX_64) val iosPlatforms = listOf(IOS_SIMULATOR_ARM_64, IOS_ARM_64, IOS_X_64) val nativePlatforms = macPlatforms + linuxPlatforms + iosPlatforms } } object KmpFlagParser { fun parse(flag: String?): Set<KmpPlatform> { if (flag.isNullOrBlank()) { return KmpPlatform.enabledByDefault.toSortedSet() } val enabled = KmpPlatform.enabledByDefault.toMutableList() flag.split(",").forEach { val directive = it.firstOrNull() ?: "" val platform = it.drop(1) when (directive) { '+' -> enabled.addAll(matchingPlatforms(platform)) '-' -> enabled.removeAll(matchingPlatforms(platform)) else -> { throw RuntimeException("Invalid value $flag for $ENABLED_KMP_TARGET_PLATFORMS") } } } return enabled.toSortedSet() } private fun matchingPlatforms(flag: String) = if (flag == "native") { KmpPlatform.native } else { listOf(KmpPlatform.valueOf(flag.uppercase(Locale.getDefault()))) } } fun Project.enabledKmpPlatforms(): Set<KmpPlatform> { val enabledPlatformsFlag = project.findProperty(ENABLED_KMP_TARGET_PLATFORMS) as? String return KmpFlagParser.parse(enabledPlatformsFlag) } fun Project.enableJs(): Boolean = enabledKmpPlatforms().contains(KmpPlatform.JS) fun Project.enableMac(): Boolean = enabledKmpPlatforms().contains(KmpPlatform.MAC) || Multiplatform.isKotlinNativeEnabled(this) fun Project.enableLinux(): Boolean = enabledKmpPlatforms().contains(KmpPlatform.LINUX) || Multiplatform.isKotlinNativeEnabled(this) fun Project.enableJvm(): Boolean = enabledKmpPlatforms().contains(KmpPlatform.JVM) fun Project.enableNative(): Boolean = enableMac() && enableLinux()
buildSrc/public/src/main/kotlin/androidx/build/KmpPlatforms.kt
3201752566
package domain.versioncheck import io.reactivex.Single interface VersionCheck { fun versionCheck(): Single<DomainVersionCheckResponse> }
domain/src/main/kotlin/domain/versioncheck/VersionCheck.kt
1577247693
internal class C( @Deprecated("") private val p1: Int, @Deprecated("") private val myP2: Int, @Deprecated("") var p3: Int )
plugins/kotlin/j2k/old/tests/testData/fileOrElement/constructors/fieldsInitializedFromParamsAnnotations.kt
892427844
// 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.webSymbols import com.intellij.webSymbols.impl.WebSymbolOriginImpl import javax.swing.Icon /* * INAPPLICABLE_JVM_NAME -> https://youtrack.jetbrains.com/issue/KT-31420 * DEPRECATION -> @JvmDefault **/ interface WebSymbolOrigin { val framework: FrameworkId? get() = null val library: String? get() = null val version: String? get() = null val defaultIcon: Icon? get() = null val typeSupport: WebSymbolTypeSupport? get() = null companion object { @JvmStatic fun create(framework: FrameworkId? = null, library: String? = null, version: String? = null, defaultIcon: Icon? = null, typeSupport: WebSymbolTypeSupport? = null): WebSymbolOrigin = WebSymbolOriginImpl(framework, library, version, defaultIcon, typeSupport) @JvmStatic fun empty(): WebSymbolOrigin = WebSymbolOriginImpl.empty } }
platform/webSymbols/src/com/intellij/webSymbols/WebSymbolOrigin.kt
334468827
internal class F { //c3 //c4 fun f2() {} fun f3() {} fun f4() {} companion object { //c1 /*c2*/ fun f1() {} var i: Int? = 0 //c5 fun f5() {} } //c6 }
plugins/kotlin/j2k/old/tests/testData/fileOrElement/formatting/staticAndNonStaticMembersWithComments.kt
655071338
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.application import com.intellij.configurationStore.saveSettings import com.intellij.ide.CliResult import com.intellij.ide.IdeBundle import com.intellij.openapi.fileEditor.FileDocumentManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext internal class SaveStarter private constructor() : ApplicationStarterBase(0) { override val commandName: String get() = "save" override val usageMessage: String get() = IdeBundle.message("wrong.number.of.arguments.usage.ide.executable.save") override suspend fun executeCommand(args: List<String>, currentDirectory: String?): CliResult { withContext(Dispatchers.EDT) { FileDocumentManager.getInstance().saveAllDocuments() } saveSettings(ApplicationManager.getApplication()) return CliResult.OK } }
platform/platform-impl/src/com/intellij/openapi/application/SaveStarter.kt
278341313
// 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.idea.maven.externalSystemIntegration.output.quickfixes import com.intellij.build.events.MessageEvent import com.intellij.build.issue.BuildIssue import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.compiler.progress.BuildIssueContributor import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ui.configuration.ClasspathEditor import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.openapi.vfs.VirtualFile import com.intellij.pom.Navigatable import com.intellij.pom.java.LanguageLevel import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.project.MavenProjectBundle.message import org.jetbrains.idea.maven.project.MavenProjectsManager import java.util.concurrent.CompletableFuture class JpsLanguageLevelQuickFix : BuildIssueContributor { private val matchersList = listOf( listOf("source release", "requires target release"), listOf("release version", "not supported"), listOf("invalid source release:"), listOf("invalid target release") ) override fun createBuildIssue(project: Project, moduleNames: Collection<String>, title: String, message: String, kind: MessageEvent.Kind, virtualFile: VirtualFile?, navigatable: Navigatable?): BuildIssue? { if (project.isDisposed) return null val mavenManager = MavenProjectsManager.getInstance(project) if (!mavenManager.isMavenizedProject) return null if (moduleNames.size != 1) { return null } val moduleName = moduleNames.first() val module = ModuleManager.getInstance(project).findModuleByName(moduleName) ?: return null val mavenProject = mavenManager.findProject(module) ?: return null val moduleRootManager = ModuleRootManager.getInstance(module) ?: return null val moduleJdk = moduleRootManager.sdk val moduleProjectLanguageLevel = moduleJdk?.let { LanguageLevel.parse(it.versionString) } ?: return null val sourceLanguageLevel = getLanguageLevelFromError(message) ?: return null if (sourceLanguageLevel.isLessThan(moduleProjectLanguageLevel)) { return getBuildIssueSourceVersionLess(sourceLanguageLevel, moduleProjectLanguageLevel, message, mavenProject, moduleRootManager) } else { return getBuildIssueSourceVersionGreat(sourceLanguageLevel, moduleProjectLanguageLevel, message, moduleRootManager) } } fun getLanguageLevelFromError(message: String): LanguageLevel? { val targetMessage = matchersList .filter { it.all { message.contains(it) } } .map { message.substring(message.indexOf(it.first())) } .firstOrNull() ?: return null return targetMessage.replace("[^.0123456789]".toRegex(), " ") .trim().split(" ") .firstOrNull()?.let { LanguageLevel.parse(it) } } private fun getBuildIssueSourceVersionGreat(sourceLanguageLevel: LanguageLevel, moduleProjectLanguageLevel: LanguageLevel, errorMessage: String, moduleRootManager: ModuleRootManager): BuildIssue { val moduleName = moduleRootManager.module.name val setupModuleSdkQuickFix = SetupModuleSdkQuickFix(moduleName, moduleRootManager.isSdkInherited) val quickFixes = listOf(setupModuleSdkQuickFix) val issueDescription = StringBuilder(errorMessage) issueDescription.append("\n\n") issueDescription.append(message("maven.quickfix.source.version.great", moduleName, moduleProjectLanguageLevel.toJavaVersion(), sourceLanguageLevel.toJavaVersion(), setupModuleSdkQuickFix.id)) return object : BuildIssue { override val title: String = errorMessage override val description: String = issueDescription.toString() override val quickFixes = quickFixes override fun getNavigatable(project: Project): Navigatable? = null } } private fun getBuildIssueSourceVersionLess(sourceLanguageLevel: LanguageLevel, moduleProjectLanguageLevel: LanguageLevel, errorMessage: String, mavenProject: MavenProject, moduleRootManager: ModuleRootManager): BuildIssue { val moduleName = moduleRootManager.module.name val quickFixes = mutableListOf<BuildIssueQuickFix>() val issueDescription = StringBuilder(errorMessage) issueDescription.append("\n\n") issueDescription.append(message("maven.quickfix.source.version.less.header", moduleName, moduleProjectLanguageLevel.toJavaVersion(), sourceLanguageLevel.toJavaVersion())) val setupModuleSdkQuickFix = SetupModuleSdkQuickFix(moduleName, moduleRootManager.isSdkInherited) quickFixes.add(setupModuleSdkQuickFix) issueDescription.append("\n") issueDescription.append(message("maven.quickfix.source.version.less.part1", sourceLanguageLevel.toJavaVersion(), setupModuleSdkQuickFix.id)) val updateSourceLevelQuickFix = UpdateSourceLevelQuickFix(mavenProject) quickFixes.add(updateSourceLevelQuickFix) issueDescription.append("\n") issueDescription.append(message("maven.quickfix.source.version.less.part2", moduleProjectLanguageLevel.toJavaVersion(), updateSourceLevelQuickFix.id)) return object : BuildIssue { override val title: String = errorMessage override val description: String = issueDescription.toString() override val quickFixes = quickFixes override fun getNavigatable(project: Project): Navigatable? = null } } } class SetupModuleSdkQuickFix(val moduleName: String, private val isSdkInherited: Boolean) : BuildIssueQuickFix { override val id: String = "setup_module_sdk_quick_fix" override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { if (isSdkInherited) { ProjectSettingsService.getInstance(project).openProjectSettings() } else { ProjectSettingsService.getInstance(project).showModuleConfigurationDialog(moduleName, ClasspathEditor.getName()) } return CompletableFuture.completedFuture<Any>(null) } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/externalSystemIntegration/output/quickfixes/JpsLanguageLevelQuickFix.kt
179319860
import org.pythonbyte.krux.properties.PropertyReader class KBirdConfiguration { var baseEBirdUrl = "" var jsoupForHotspotDetailsSpeciesCount = "" companion object { const val PROPERTIES_FILE = "/k-bird.properties" fun loadConfiguration(): KBirdConfiguration { val propertyReader = PropertyReader(PROPERTIES_FILE) val configuration = KBirdConfiguration() configuration.baseEBirdUrl = propertyReader.get("kbird.baseEBirdUrl") return configuration } } }
src/main/kotlin/KBirdConfiguration.kt
1454411298
package io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty @JsonIgnoreProperties(ignoreUnknown = true) class RelatedResponse( @JsonProperty("id") val id: Int, @JsonProperty("url") val url: String, @JsonProperty("vote_count") val voteCount: Int, @JsonProperty("author") val author: AuthorResponse?, @JsonProperty("title") val title: String, @JsonProperty("user_vote") val userVote: Int? )
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/pojo/apiv2/models/RelatedResponse.kt
1452371755
// WITH_RUNTIME // PROBLEM: none // ERROR: Type mismatch: inferred type is Int? but Int was expected fun foo() { val a: Int? = 5 val t: String = Integer.<caret>toString(a, 5) }
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/toString/nullableIntToString2.kt
1943334944
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.ethereum.longrun import org.ethereum.config.CommonConfig import org.ethereum.core.AccountState import org.ethereum.core.BlockchainImpl import org.ethereum.core.BlockchainImpl.calcReceiptsTrie import org.ethereum.core.Bloom import org.ethereum.crypto.HashUtil import org.ethereum.datasource.Source import org.ethereum.facade.Ethereum import org.ethereum.trie.SecureTrie import org.ethereum.trie.TrieImpl import org.ethereum.util.FastByteComparisons import org.junit.Assert import org.slf4j.LoggerFactory import java.util.concurrent.atomic.AtomicInteger /** * Validation for all kind of blockchain data */ internal object BlockchainValidation { private val testLogger = LoggerFactory.getLogger("TestLogger") private fun getReferencedTrieNodes(stateDS: Source<ByteArray, ByteArray>, includeAccounts: Boolean, vararg roots: ByteArray): Int { val ret = AtomicInteger(0) roots .map { SecureTrie(stateDS, it) } .forEach { it.scanTree(object : TrieImpl.ScanAction { override fun doOnNode(hash: ByteArray, node: TrieImpl.Node) { ret.incrementAndGet() } override fun doOnValue(nodeHash: ByteArray, node: TrieImpl.Node, key: ByteArray, value: ByteArray) { if (includeAccounts) { val accountState = AccountState(value) if (!FastByteComparisons.equal(accountState.codeHash, HashUtil.EMPTY_DATA_HASH)) { ret.incrementAndGet() } if (!FastByteComparisons.equal(accountState.stateRoot, HashUtil.EMPTY_TRIE_HASH)) { ret.addAndGet(getReferencedTrieNodes(stateDS, false, accountState.stateRoot)) } } } }) } return ret.get() } fun checkNodes(ethereum: Ethereum, commonConfig: CommonConfig, fatalErrors: AtomicInteger) { try { val stateDS = commonConfig.stateSource() val stateRoot = ethereum.blockchain.bestBlock.header.stateRoot val rootsSize = getReferencedTrieNodes(stateDS, true, stateRoot) testLogger.info("Node validation successful") testLogger.info("Non-unique node size: {}", rootsSize) } catch (ex: Exception) { testLogger.error("Node validation error", ex) fatalErrors.incrementAndGet() } catch (ex: AssertionError) { testLogger.error("Node validation error", ex) fatalErrors.incrementAndGet() } } private fun checkHeaders(ethereum: Ethereum, fatalErrors: AtomicInteger) { var blockNumber = ethereum.blockchain.bestBlock.header.number.toInt() var lastParentHash: ByteArray? = null testLogger.info("Checking headers from best block: {}", blockNumber) try { while (blockNumber >= 0) { val currentBlock = ethereum.blockchain.getBlockByNumber(blockNumber.toLong()) if (lastParentHash != null) { assert(FastByteComparisons.equal(currentBlock.hash, lastParentHash)) } lastParentHash = currentBlock.header.parentHash assert(lastParentHash != null) blockNumber-- } testLogger.info("Checking headers successful, ended on block: {}", blockNumber + 1) } catch (ex: Exception) { testLogger.error(String.format("Block header validation error on block #%s", blockNumber), ex) fatalErrors.incrementAndGet() } catch (ex: AssertionError) { testLogger.error(String.format("Block header validation error on block #%s", blockNumber), ex) fatalErrors.incrementAndGet() } } fun checkFastHeaders(ethereum: Ethereum, commonConfig: CommonConfig, fatalErrors: AtomicInteger) { val headerStore = commonConfig.headerSource() var blockNumber = headerStore.size - 1 var lastParentHash: ByteArray? = null try { testLogger.info("Checking fast headers from best block: {}", blockNumber) while (blockNumber > 0) { val header = headerStore[blockNumber] if (lastParentHash != null) { assert(FastByteComparisons.equal(header.hash, lastParentHash)) } lastParentHash = header.parentHash assert(lastParentHash != null) blockNumber-- } val genesis = ethereum.blockchain.getBlockByNumber(0) assert(FastByteComparisons.equal(genesis.hash, lastParentHash)) testLogger.info("Checking fast headers successful, ended on block: {}", blockNumber + 1) } catch (ex: Exception) { testLogger.error(String.format("Fast header validation error on block #%s", blockNumber), ex) fatalErrors.incrementAndGet() } catch (ex: AssertionError) { testLogger.error(String.format("Fast header validation error on block #%s", blockNumber), ex) fatalErrors.incrementAndGet() } } private fun checkBlocks(ethereum: Ethereum, fatalErrors: AtomicInteger) { var currentBlock = ethereum.blockchain.bestBlock var blockNumber = currentBlock.header.number.toInt() try { val blockStore = ethereum.blockchain.blockStore testLogger.info("Checking blocks from best block: {}", blockNumber) var curTotalDiff = blockStore.getTotalDifficultyForHash(currentBlock.hash) while (blockNumber > 0) { currentBlock = ethereum.blockchain.getBlockByNumber(blockNumber.toLong()) // Validate uncles assert((ethereum.blockchain as BlockchainImpl).validateUncles(currentBlock)) // Validate total difficulty Assert.assertTrue(String.format("Total difficulty, count %s == %s blockStore", curTotalDiff, blockStore.getTotalDifficultyForHash(currentBlock.hash)), curTotalDiff.compareTo(blockStore.getTotalDifficultyForHash(currentBlock.hash)) == 0) curTotalDiff = curTotalDiff.subtract(currentBlock.difficultyBI) blockNumber-- } // Checking total difficulty for genesis currentBlock = ethereum.blockchain.getBlockByNumber(0) Assert.assertTrue(String.format("Total difficulty for genesis, count %s == %s blockStore", curTotalDiff, blockStore.getTotalDifficultyForHash(currentBlock.hash)), curTotalDiff.compareTo(blockStore.getTotalDifficultyForHash(currentBlock.hash)) == 0) Assert.assertTrue(String.format("Total difficulty, count %s == %s genesis", curTotalDiff, currentBlock.difficultyBI), curTotalDiff.compareTo(currentBlock.difficultyBI) == 0) testLogger.info("Checking blocks successful, ended on block: {}", blockNumber + 1) } catch (ex: Exception) { testLogger.error(String.format("Block validation error on block #%s", blockNumber), ex) fatalErrors.incrementAndGet() } catch (ex: AssertionError) { testLogger.error(String.format("Block validation error on block #%s", blockNumber), ex) fatalErrors.incrementAndGet() } } private fun checkTransactions(ethereum: Ethereum, fatalErrors: AtomicInteger) { var blockNumber = ethereum.blockchain.bestBlock.header.number.toInt() testLogger.info("Checking block transactions from best block: {}", blockNumber) try { while (blockNumber > 0) { val currentBlock = ethereum.blockchain.getBlockByNumber(blockNumber.toLong()) val receipts = currentBlock.transactionsList .map { (ethereum.blockchain as BlockchainImpl).getTransactionInfo(it.hash)!! } .map { it.receipt } val logBloom = Bloom() for (receipt in receipts) { logBloom.or(receipt.bloomFilter) } assert(FastByteComparisons.equal(currentBlock.logBloom, logBloom.data)) assert(FastByteComparisons.equal(currentBlock.receiptsRoot, calcReceiptsTrie(receipts))) blockNumber-- } testLogger.info("Checking block transactions successful, ended on block: {}", blockNumber + 1) } catch (ex: Exception) { testLogger.error(String.format("Transaction validation error on block #%s", blockNumber), ex) fatalErrors.incrementAndGet() } catch (ex: AssertionError) { testLogger.error(String.format("Transaction validation error on block #%s", blockNumber), ex) fatalErrors.incrementAndGet() } } fun fullCheck(ethereum: Ethereum, commonConfig: CommonConfig, fatalErrors: AtomicInteger) { // nodes testLogger.info("Validating nodes: Start") BlockchainValidation.checkNodes(ethereum, commonConfig, fatalErrors) testLogger.info("Validating nodes: End") // headers testLogger.info("Validating block headers: Start") BlockchainValidation.checkHeaders(ethereum, fatalErrors) testLogger.info("Validating block headers: End") // blocks testLogger.info("Validating blocks: Start") BlockchainValidation.checkBlocks(ethereum, fatalErrors) testLogger.info("Validating blocks: End") // receipts testLogger.info("Validating transaction receipts: Start") BlockchainValidation.checkTransactions(ethereum, fatalErrors) testLogger.info("Validating transaction receipts: End") } }
free-ethereum-core/src/test/java/org/ethereum/longrun/BlockchainValidation.kt
992982941
/* * Copyright 2010-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. */ fun main(args: Array<String>) { print(readLine()!!) }
backend.native/tests/runtime/basic/readline1.kt
3488805426
fun neq(a: Boolean, b: Boolean) { if (a <caret>and b) {} }
plugins/kotlin/idea/tests/testData/intentions/swapBinaryExpression/conjunctionLiteral.kt
909301354
package io.fotoapparat.view import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.GestureDetector import android.view.MotionEvent import android.widget.FrameLayout import io.fotoapparat.hardware.metering.FocalRequest import io.fotoapparat.hardware.metering.PointF import io.fotoapparat.parameter.Resolution /** * A view which is metering the focus & exposure of the camera to specific areas, if possible. * * If the camera doesn't support focus metering on specific area this will only display a visual feedback. */ class FocusView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr), FocalPointSelector { private val visualFeedbackCircle = FeedbackCircleView(context, attrs, defStyleAttr) private var focusMeteringListener: ((FocalRequest) -> Unit)? = null init { clipToPadding = false clipChildren = false addView(visualFeedbackCircle) } override fun setFocalPointListener(listener: (FocalRequest) -> Unit) { focusMeteringListener = listener } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { tapDetector.onTouchEvent(event) return true } private val gestureDetectorListener = object : GestureDetector.SimpleOnGestureListener() { override fun onSingleTapUp(e: MotionEvent): Boolean { return focusMeteringListener ?.let { it(FocalRequest( point = PointF( x = e.x, y = e.y), previewResolution = Resolution( width = width, height = height))) visualFeedbackCircle.showAt( x = e.x - visualFeedbackCircle.width / 2, y = e.y - visualFeedbackCircle.height / 2) performClick() true } ?: super.onSingleTapUp(e) } } private val tapDetector = GestureDetector(context, gestureDetectorListener) }
fotoapparat/src/main/java/io/fotoapparat/view/FocusView.kt
1987635820
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.service.project import com.intellij.ide.plugins.DependencyCollector import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.project.Project import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginAdvertiserService import org.jetbrains.plugins.gradle.util.GradleConstants class GradleDependencyCollector : DependencyCollector { override fun collectDependencies(project: Project): List<String> { val projectInfoList = ProjectDataManager.getInstance().getExternalProjectsData(project, GradleConstants.SYSTEM_ID) val result = mutableListOf<String>() for (externalProjectInfo in projectInfoList) { val projectStructure = externalProjectInfo.externalProjectStructure ?: continue val libraries = ExternalSystemApiUtil.findAll(projectStructure, ProjectKeys.LIBRARY) for (libraryNode in libraries) { val groupId = libraryNode.data.groupId val artifactId = libraryNode.data.artifactId if (groupId != null && artifactId != null) { result.add("$groupId:$artifactId") } } } return result } } class GradleDependencyUpdater : ExternalSystemTaskNotificationListenerAdapter() { override fun onEnd(id: ExternalSystemTaskId) { if (id.projectSystemId == GradleConstants.SYSTEM_ID && id.type == ExternalSystemTaskType.RESOLVE_PROJECT) { id.findProject()?.let { ApplicationManager.getApplication().executeOnPooledThread { PluginAdvertiserService.getInstance().rescanDependencies(it) } } } } }
plugins/gradle/java/src/service/project/GradleDependencyCollector.kt
1330684037
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.diagnostic.PluginException import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.StateStorage import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.JDOMUtil import com.intellij.util.isEmpty import org.jdom.Element import org.jetbrains.annotations.ApiStatus abstract class StorageBaseEx<T : Any> : StateStorageBase<T>() { internal fun <S : Any> createGetSession(component: PersistentStateComponent<S>, componentName: String, stateClass: Class<S>, reload: Boolean = false): StateGetter<S> { return StateGetterImpl(component, componentName, getStorageData(reload), stateClass, this) } /** * serializedState is null if state equals to default (see XmlSerializer.serializeIfNotDefault) */ abstract fun archiveState(storageData: T, componentName: String, serializedState: Element?) } internal fun <S : Any> createStateGetter(isUseLoadedStateAsExisting: Boolean, storage: StateStorage, component: PersistentStateComponent<S>, componentName: String, stateClass: Class<S>, reloadData: Boolean): StateGetter<S> { if (isUseLoadedStateAsExisting && storage is StorageBaseEx<*>) { return storage.createGetSession(component, componentName, stateClass, reloadData) } return object : StateGetter<S> { override fun getState(mergeInto: S?): S? { return storage.getState(component, componentName, stateClass, mergeInto, reloadData) } override fun archiveState(): S? = null } } @ApiStatus.Internal interface StateGetter<S : Any> { fun getState(mergeInto: S? = null): S? fun archiveState(): S? } private class StateGetterImpl<S : Any, T : Any>(private val component: PersistentStateComponent<S>, private val componentName: String, private val storageData: T, private val stateClass: Class<S>, private val storage: StorageBaseEx<T>) : StateGetter<S> { private var serializedState: Element? = null override fun getState(mergeInto: S?): S? { LOG.assertTrue(serializedState == null) serializedState = storage.getSerializedState(storageData, component, componentName, archive = false) return storage.deserializeState(serializedState, stateClass, mergeInto) } override fun archiveState() : S? { if (serializedState == null) { return null } val stateAfterLoad = try { component.state } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { PluginException.logPluginError(LOG, "Cannot get state after load", e, component.javaClass) null } val serializedStateAfterLoad = if (stateAfterLoad == null) { serializedState } else { serializeState(stateAfterLoad)?.normalizeRootName().let { if (it.isEmpty()) null else it } } if (ApplicationManager.getApplication().isUnitTestMode && serializedState != serializedStateAfterLoad && (serializedStateAfterLoad == null || !JDOMUtil.areElementsEqual(serializedState, serializedStateAfterLoad))) { LOG.debug("$componentName (from ${component.javaClass.name}) state changed after load. \nOld: ${JDOMUtil.writeElement(serializedState!!)}\n\nNew: ${serializedStateAfterLoad?.let { JDOMUtil.writeElement(it) } ?: "null"}\n") } storage.archiveState(storageData, componentName, serializedStateAfterLoad) return stateAfterLoad } }
platform/configuration-store-impl/src/StorageBaseEx.kt
189783634
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable import com.intellij.codeInsight.template.TemplateBuilderImpl import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Pair import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiReference import com.intellij.ui.NonFocusableCheckBox import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractKotlinInplaceIntroducer import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.isIdentifier import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.types.KotlinType import javax.swing.JCheckBox class KotlinVariableInplaceIntroducer( addedVariable: KtProperty, originalExpression: KtExpression?, occurrencesToReplace: Array<KtExpression>, suggestedNames: Collection<String>, val isVar: Boolean, val doNotChangeVar: Boolean, val expressionType: KotlinType?, val noTypeInference: Boolean, project: Project, editor: Editor, private val postProcess: (KtDeclaration) -> Unit ) : AbstractKotlinInplaceIntroducer<KtProperty>( localVariable = addedVariable.takeIf { it.isLocal }, expression = originalExpression, occurrences = occurrencesToReplace, title = KotlinIntroduceVariableHandler.INTRODUCE_VARIABLE, project = project, editor = editor, ) { private val suggestedNames = suggestedNames.toTypedArray() private var expressionTypeCheckBox: JCheckBox? = null private val addedVariablePointer = addedVariable.createSmartPointer() private val addedVariable get() = addedVariablePointer.element init { initFormComponents { if (!doNotChangeVar) { val varCheckBox = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.declare.with.var")) varCheckBox.isSelected = isVar varCheckBox.addActionListener { myProject.executeWriteCommand(commandName, commandName) { PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.document) val psiFactory = KtPsiFactory(myProject) val keyword = if (varCheckBox.isSelected) psiFactory.createVarKeyword() else psiFactory.createValKeyword() addedVariable.valOrVarKeyword.replace(keyword) } } addComponent(varCheckBox) } if (expressionType != null && !noTypeInference) { val renderedType = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(expressionType) expressionTypeCheckBox = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.specify.type.explicitly")).apply { isSelected = false addActionListener { runWriteCommandAndRestart { updateVariableName() if (isSelected) { addedVariable.typeReference = KtPsiFactory(myProject).createType(renderedType) } else { addedVariable.typeReference = null } } } addComponent(this) } } } } override fun getVariable() = addedVariable override fun suggestNames(replaceAll: Boolean, variable: KtProperty?) = suggestedNames override fun createFieldToStartTemplateOn(replaceAll: Boolean, names: Array<out String>) = addedVariable override fun addAdditionalVariables(builder: TemplateBuilderImpl) { val variable = addedVariable ?: return variable.typeReference?.let { val expression = SpecifyTypeExplicitlyIntention.createTypeExpressionForTemplate(expressionType!!, variable) ?: return@let builder.replaceElement(it, "TypeReferenceVariable", expression, false) } } override fun buildTemplateAndStart( refs: Collection<PsiReference>, stringUsages: Collection<Pair<PsiElement, TextRange>>, scope: PsiElement, containingFile: PsiFile ): Boolean { myNameSuggestions = myNameSuggestions.mapTo(LinkedHashSet(), String::quoteIfNeeded) myEditor.caretModel.moveToOffset(nameIdentifier!!.startOffset) val result = super.buildTemplateAndStart(refs, stringUsages, scope, containingFile) val templateState = TemplateManagerImpl .getTemplateState(com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil.getTopLevelEditor(myEditor)) val variable = addedVariable if (templateState != null && variable?.typeReference != null) { templateState.addTemplateStateListener(SpecifyTypeExplicitlyIntention.createTypeReferencePostprocessor(variable)) } return result } override fun getInitialName() = super.getInitialName().quoteIfNeeded() override fun updateTitle(variable: KtProperty?, value: String?) { expressionTypeCheckBox?.isEnabled = value == null || value.isIdentifier() // No preview to update } override fun deleteTemplateField(psiField: KtProperty?) { // Do not delete introduced variable as it was created outside of in-place refactoring } override fun isReplaceAllOccurrences() = true override fun setReplaceAllOccurrences(allOccurrences: Boolean) { } override fun getComponent() = myWholePanel override fun performIntroduce() { val newName = inputName ?: return val replacement = KtPsiFactory(myProject).createExpression(newName) runWriteAction { addedVariable?.setName(newName) occurrences.forEach { if (it.isValid) { it.replace(replacement) } } } } override fun moveOffsetAfter(success: Boolean) { super.moveOffsetAfter(success) if (success) { addedVariable?.let { postProcess(it) } } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinVariableInplaceIntroducer.kt
1939447980
package org.ccci.gto.android.common.util.view import android.graphics.Rect import android.view.View import android.view.ViewGroup import androidx.annotation.IdRes fun ViewGroup.calculateTopOffsetOrNull(@IdRes descendant: Int) = findViewById<View>(descendant)?.let { calculateTopOffset(it) } fun ViewGroup.calculateTopOffset(descendant: View) = with(Rect()) { descendant.getDrawingRect(this) offsetDescendantRectToMyCoords(descendant, this) top }
gto-support-util/src/main/kotlin/org/ccci/gto/android/common/util/view/ViewGroup.kt
1033792440
/* * Copyright 2019-2020 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.views.dsl.material.styles import android.content.Context import android.view.View import androidx.annotation.IdRes import androidx.annotation.StyleRes import com.google.android.material.textfield.TextInputLayout import splitties.views.dsl.core.NO_THEME import splitties.views.dsl.core.styles.styledView import splitties.views.dsl.material.R import kotlin.contracts.InvocationKind import kotlin.contracts.contract @JvmInline value class TextInputLayoutStyles @PublishedApi internal constructor( @PublishedApi internal val ctx: Context ) { inline fun filledBox( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: TextInputLayout.() -> Unit = {} ): TextInputLayout { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.styledView( newViewRef = ::TextInputLayout, styleAttr = R.attr.Widget_MaterialComponents_TextInputLayout_FilledBox, id = id, theme = theme, initView = initView ) } inline fun filledBoxDense( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: TextInputLayout.() -> Unit = {} ): TextInputLayout { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.styledView( newViewRef = ::TextInputLayout, styleAttr = R.attr.Widget_MaterialComponents_TextInputLayout_FilledBox_Dense, id = id, theme = theme, initView = initView ) } inline fun outlinedBox( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: TextInputLayout.() -> Unit = {} ): TextInputLayout { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.styledView( newViewRef = ::TextInputLayout, styleAttr = R.attr.Widget_MaterialComponents_TextInputLayout_OutlinedBox, id = id, theme = theme, initView = initView ) } inline fun outlinedBoxDense( @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: TextInputLayout.() -> Unit = {} ): TextInputLayout { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return ctx.styledView( newViewRef = ::TextInputLayout, styleAttr = R.attr.Widget_MaterialComponents_TextInputLayout_OutlinedBox_Dense, id = id, theme = theme, initView = initView ) } }
modules/views-dsl-material/src/androidMain/kotlin/splitties/views/dsl/material/styles/TextInputLayoutStyles.kt
2940648697
open class A interface I class B : A(), I { fun foo() { super<<caret>> } } // EXIST: A // EXIST: I // NOTHING_ELSE
plugins/kotlin/completion/tests/testData/basic/common/super/QualifierType2.kt
3945825257
@file:Suppress("unused") import platform.posix.fopen object NativeMain { val fromPosix = fopen("my_file", "r") }
plugins/kotlin/idea/tests/testData/gradle/commonizerImportAndCheckHighlighting/singleNativeTarget/p1/src/nativeMain/kotlin/NativeMain.kt
824442161
try { } catch (e: Exception) { println(1) } catch (e: IOException) { println(0) } finally { }
plugins/kotlin/j2k/old/tests/testData/fileOrElement/tryStatement/emptyTryWithTwoCatchesWithEmptyFinally.kt
616548370
val x get() = 1
plugins/kotlin/maven/tests/testData/languageFeature/updateLanguageVersionProperty/src.kt
644145718
package test.hello import org.w3c.dom.* import org.w3c.dom.events.* import kotlin.browser.* import kotlin.dom.* class WebLinesView(val linesHolder: Element, formRoot: Element) : LinesView { lateinit override var presenter: LinesPresenter @Suppress("UNCHECKED_CAST_TO_NATIVE_INTERFACE") private val input = formRoot.querySelector("input") as HTMLInputElement @Suppress("UNCHECKED_CAST_TO_NATIVE_INTERFACE") private val addButton = formRoot.querySelector("button") as HTMLButtonElement private val buttonHandler: (Event) -> Unit = { presenter.addButtonClicked() } private val inputHandler: (Event) -> Unit = { e -> if (e is KeyboardEvent && e.keyCode == 13) { presenter.inputEnterPressed() } } init { register() } override var inputText: String get() = input.value set(newValue) { input.value = newValue } override fun focusInput() { input.focus() } override fun addLine(lineText: String) { document.createElement("p").apply { textContent = " + " + lineText linesHolder.appendChild(this) } } override fun clearLines() { linesHolder.clear() } override fun dispose() { unregister() } private fun register() { addButton.addEventListener("click", buttonHandler) input.addEventListener("keypress", inputHandler) } private fun unregister() { addButton.removeEventListener("click", buttonHandler) input.removeEventListener("keypress", inputHandler) } }
examples/frontend-only/src/main/kotlin/test/hello/WebLinesView.kt
555064868
@file:Suppress("ConstantConditionIf") package com.agog.mathdisplay.render import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.os.Build import com.agog.mathdisplay.parse.NSNotFound import com.agog.mathdisplay.parse.NSRange import com.agog.mathdisplay.parse.* import com.agog.mathdisplay.render.MTLinePosition.* const val DEBUG = false data class CGPoint(var x: Float = 0.0f, var y: Float = 0.0f) data class CGRect(var x: Float = 0.0f, var y: Float = 0.0f, var width: Float = 0.0f, var height: Float = 0.0f) open class MTDisplay(open var ascent: Float = 0.0f, open var descent: Float = 0.0f, open var width: Float = 0.0f, var range: NSRange = NSRange(), var hasScript: Boolean = false) { var shiftDown: Float = 0.0f /// The distance from the axis to the top of the display /// The distance from the axis to the bottom of the display /// The width of the display /// position: Position of the display with respect to the parent view or display. // range: The range of characters supported by this item /// Whether the display has a subscript/superscript following it. /// The text color for this display // The local color, if the color was mutated local with the color // command var position: CGPoint = CGPoint() set(value) { field = value.copy() positionChanged() } var textColor: Int = Color.BLACK set(value) { field = value colorChanged() } var localTextColor: Int = Color.TRANSPARENT set(value) { field = value colorChanged() } init { this.range = range.copy() } open fun positionChanged() { } open fun colorChanged() { } open fun draw(canvas: Canvas) { if (DEBUG) { val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG) strokePaint.setColor(Color.RED) canvas.drawLine(0.0f, -descent, width, ascent, strokePaint) strokePaint.setColor(Color.GREEN) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { canvas.drawArc(position.x - 2, position.y - 2, position.x + 2, position.y + 2, 0f, 360f, false, strokePaint) } } } fun displayBounds(): CGRect { return CGRect(position.x, position.y - descent, width, ascent + descent) } } // List of normal atoms to display that would be an attributed string on iOS // Since we do not allow kerning attribute changes this is a string displayed using the advances for the font // Normally this is a single character. In some cases the string will be fused atoms class MTCTLineDisplay(val str: String, range: NSRange, val font: MTFont, val atoms: List<MTMathAtom>) : MTDisplay(range = range) { init { computeDimensions() } // Our own implementation of the ios6 function to get glyph path bounds. fun computeDimensions() { val glyphs = font.getGidListForString(str) val num = glyphs.count() val bboxes: Array<BoundingBox?> = arrayOfNulls(num) val advances: Array<Float> = Array(num, { 0.0f }) // Get the bounds for these glyphs font.mathTable.getBoundingRectsForGlyphs(glyphs.toList(), bboxes, num) font.mathTable.getAdvancesForGlyphs(glyphs.toList(), advances, num) this.width = 0.0f for (i in 0 until num) { val b = bboxes[i] if (b != null) { val ascent = maxOf(0.0f, b.upperRightY - 0) // Descent is how much the line goes below the origin. However if the line is all above the origin, then descent can't be negative. val descent = maxOf(0.0f, 0.0f - b.lowerLeftY) if (ascent > this.ascent) { this.ascent = ascent } if (descent > this.descent) { this.descent = descent } this.width += advances[i] } } } override fun draw(canvas: Canvas) { super.draw(canvas) val textPaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG) textPaint.setColor(textColor) val drawer = MTDrawFreeType(font.mathTable) val glyphs = font.getGidListForString(str) val num = glyphs.count() val advances: Array<Float> = Array(num, { 0.0f }) font.mathTable.getAdvancesForGlyphs(glyphs, advances, num) canvas.save() canvas.translate(position.x, position.y) canvas.scale(1.0f, -1.0f) var x = 0.0f for (i in 0 until num) { drawer.drawGlyph(canvas, textPaint, glyphs[i], x, 0.0f) x += advances[i] } textPaint.setColor(Color.RED) canvas.restore() } } /** @typedef MTLinePosition @brief The type of position for a line, i.e. subscript/superscript or regular. */ enum class MTLinePosition { /// Regular KMTLinePositionRegular, /// Positioned at a subscript KMTLinePositionSubscript, /// Positioned at a superscript KMTLinePositionSuperscript } class MTMathListDisplay(displays: List<MTDisplay>, range: NSRange) : MTDisplay(range = range) { /// Where the line is positioned var type: MTLinePosition = KMTLinePositionRegular /// An array of MTDisplays which are positioned relative to the position of the /// the current display. var subDisplays: List<MTDisplay>? = null /// If a subscript or superscript this denotes the location in the parent MTList. For a /// regular list this is NSNotFound var index = NSNotFound init { this.subDisplays = displays this.recomputeDimensions() } override fun colorChanged() { val sd = this.subDisplays if (sd != null) { for (displayAtom in sd.toList()) { // set the global color, if there is no local color if (displayAtom.localTextColor == Color.TRANSPARENT) { displayAtom.textColor = this.textColor } else { displayAtom.textColor = displayAtom.localTextColor } } } } override fun draw(canvas: Canvas) { canvas.save() if (DEBUG) { val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG) strokePaint.setColor(Color.BLACK) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { canvas.drawArc(-4f, -4f, 4f, 4f, 4f, 180f, false, strokePaint) } } canvas.translate(position.x, position.y) if (DEBUG) { val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG) strokePaint.setColor(Color.BLUE) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { canvas.drawArc(-3f, -3f, 3f, 3f, 0f, 360f, false, strokePaint) } } // draw each atom separately val sd = this.subDisplays if (sd != null) { for (displayAtom in sd.toList()) { displayAtom.draw(canvas) } } canvas.restore() } fun recomputeDimensions() { var max_ascent = 0.0f var max_descent = 0.0f var max_width = 0.0f val sd = this.subDisplays if (sd != null) { for (atom in sd.toList()) { val ascent = maxOf(0.0f, atom.position.y + atom.ascent) if (ascent > max_ascent) { max_ascent = ascent } val descent = maxOf(0.0f, 0 - (atom.position.y - atom.descent)) if (descent > max_descent) { max_descent = descent } val width = atom.width + atom.position.x if (width > max_width) { max_width = width } } } this.ascent = max_ascent this.descent = max_descent this.width = max_width } } // MTFractionDisplay class MTFractionDisplay(var numerator: MTMathListDisplay, var denominator: MTMathListDisplay, range: NSRange) : MTDisplay(range = range) { var linePosition = 0.0f var lineThickness = 0.0f // NSAssert(self.range.length == 1, @"Fraction range length not 1 - range (%lu, %lu)", (unsigned long)range.location, (unsigned long)range.length) var numeratorUp: Float = 0.0f set(value) { field = value this.updateNumeratorPosition() } var denominatorDown: Float = 0.0f set(value) { field = value this.updateDenominatorPosition() } override var ascent: Float get() = this.numerator.ascent + this.numeratorUp set(value) { } override var descent: Float get() = this.denominator.descent + this.denominatorDown set(value) { } override var width: Float get() = maxOf(this.numerator.width, this.denominator.width) set(value) { } fun updateDenominatorPosition() { this.denominator.position = CGPoint(this.position.x + (this.width - this.denominator.width) / 2, this.position.y - this.denominatorDown) } fun updateNumeratorPosition() { this.numerator.position = CGPoint(this.position.x + (this.width - this.numerator.width) / 2, this.position.y + this.numeratorUp) } override fun positionChanged() { this.updateDenominatorPosition() this.updateNumeratorPosition() } override fun colorChanged() { this.numerator.textColor = this.textColor this.denominator.textColor = this.textColor } override fun draw(canvas: Canvas) { this.numerator.draw(canvas) this.denominator.draw(canvas) if (lineThickness != 0f) { val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG) strokePaint.setColor(textColor) strokePaint.strokeWidth = lineThickness canvas.drawLine(position.x, position.y + linePosition, position.x + width, position.y + linePosition, strokePaint) } } } // MTRadicalDisplay class MTRadicalDisplay(val radicand: MTMathListDisplay, val radicalGlyph: MTDisplay, range: NSRange) : MTDisplay(range = range) { init { updateRadicandPosition() } var radicalShift: Float = 0.0f var degree: MTMathListDisplay? = null var topKern: Float = 0.0f var lineThickness: Float = 0.0f fun setDegree(degree: MTMathListDisplay, fontMetrics: MTFontMathTable) { // sets up the degree of the radical var kernBefore = fontMetrics.radicalKernBeforeDegree val kernAfter = fontMetrics.radicalKernAfterDegree val raise = fontMetrics.radicalDegreeBottomRaisePercent * (this.ascent - this.descent) // The layout is: // kernBefore, raise, degree, kernAfter, radical this.degree = degree // the radical is now shifted by kernBefore + degree.width + kernAfter this.radicalShift = kernBefore + degree.width + kernAfter if (radicalShift < 0) { // we can't have the radical shift backwards, so instead we increase the kernBefore such // that _radicalShift will be 0. kernBefore -= radicalShift radicalShift = 0.0f } // Note: position of degree is relative to parent. val deg = this.degree if (deg != null) { deg.position = CGPoint(this.position.x + kernBefore, this.position.y + raise) // Update the width by the _radicalShift this.width = radicalShift + radicalGlyph.width + this.radicand.width } // update the position of the radicand this.updateRadicandPosition() } override fun positionChanged() { updateRadicandPosition() } fun updateRadicandPosition() { // The position of the radicand includes the position of the MTRadicalDisplay // This is to make the positioning of the radical consistent with fractions and // have the cursor position finding algorithm work correctly. // move the radicand by the width of the radical sign this.radicand.position = CGPoint(this.position.x + radicalShift + radicalGlyph.width, this.position.y) } override fun colorChanged() { this.radicand.textColor = this.textColor this.radicalGlyph.textColor = this.textColor val deg = this.degree if (deg != null) { deg.textColor = this.textColor } } override fun draw(canvas: Canvas) { this.radicand.draw(canvas) degree?.draw(canvas) canvas.save() // Make the current position the origin as all the positions of the sub atoms are relative to the origin. canvas.translate(position.x + radicalShift, position.y) // Draw the glyph. radicalGlyph.draw(canvas) // Draw the VBOX // for the kern of, we don't need to draw anything. val heightFromTop = topKern // draw the horizontal line with the given thickness val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG) strokePaint.setColor(textColor) strokePaint.strokeWidth = lineThickness strokePaint.strokeCap = Paint.Cap.ROUND val x = radicalGlyph.width val y = ascent - heightFromTop - lineThickness / 2 canvas.drawLine(x, y, x + radicand.width, y, strokePaint) canvas.restore() } } // MTGlyphDisplay class MTGlyphDisplay(val glyph: CGGlyph, range: NSRange, val myfont: MTFont) : MTDisplay(range = range) { override fun draw(canvas: Canvas) { super.draw(canvas) val textPaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG) textPaint.setColor(textColor) val drawer = MTDrawFreeType(myfont.mathTable) canvas.save() canvas.translate(position.x, position.y - this.shiftDown) canvas.scale(1.0f, -1.0f) drawer.drawGlyph(canvas, textPaint, glyph.gid, 0.0f, 0.0f) canvas.restore() } override var ascent: Float get() = super.ascent - this.shiftDown set(value) { super.ascent = value } override var descent: Float get() = super.descent + this.shiftDown set(value) { super.descent = value } } // MTGlyphConstructionDisplay class MTGlyphConstructionDisplay(val glyphs: MutableList<Int>, val offsets: MutableList<Float>, val myfont: MTFont) : MTDisplay() { init { assert(glyphs.size == offsets.size) } override fun draw(canvas: Canvas) { val drawer = MTDrawFreeType(myfont.mathTable) canvas.save() // Make the current position the origin as all the positions of the sub atoms are relative to the origin. canvas.translate(position.x, position.y - shiftDown) // Draw the glyphs. // positions these are x&y (0,offsets[i]) val textPaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG) textPaint.setColor(textColor) //textPaint.setTextSize(myfont.fontSize) //textPaint.setTypeface(myfont.typeface) for (i in 0 until glyphs.count()) { //val textstr = myfont.getGlyphString(glyphs[i]) canvas.save() canvas.translate(0f, offsets[i]) canvas.scale(1.0f, -1.0f) drawer.drawGlyph(canvas, textPaint, glyphs[i], 0.0f, 0.0f) //canvas.drawText(textstr, 0.0f, 0.0f, textPaint) canvas.restore() } canvas.restore() } override var ascent: Float get() = super.ascent - this.shiftDown set(value) { super.ascent = value } override var descent: Float get() = super.descent + this.shiftDown set(value) { super.descent = value } } // MTLargeOpLimitsDisplay class MTLargeOpLimitsDisplay(val nucleus: MTDisplay, var upperLimit: MTMathListDisplay?, var lowerLimit: MTMathListDisplay?, var limitShift: Float, var extraPadding: Float) : MTDisplay() { init { var maxWidth: Float = nucleus.width if (upperLimit != null) { maxWidth = maxOf(maxWidth, upperLimit!!.width) } if (lowerLimit != null) { maxWidth = maxOf(maxWidth, lowerLimit!!.width) } this.width = maxWidth } override var ascent get() = if (this.upperLimit != null) { nucleus.ascent + extraPadding + upperLimit!!.ascent + upperLimitGap + upperLimit!!.descent } else { nucleus.ascent } set(value) { } override var descent: Float get() = if (this.lowerLimit != null) { nucleus.descent + extraPadding + lowerLimitGap + lowerLimit!!.descent + lowerLimit!!.ascent } else { nucleus.descent } set(value) { } var lowerLimitGap: Float = 0.0f set(value) { field = value this.updateLowerLimitPosition() } var upperLimitGap: Float = 0.0f set(value) { field = value this.updateUpperLimitPosition() } override fun positionChanged() { this.updateLowerLimitPosition() this.updateUpperLimitPosition() this.updateNucleusPosition() } fun updateLowerLimitPosition() { val ll = this.lowerLimit if (ll != null) { // The position of the lower limit includes the position of the MTLargeOpLimitsDisplay // This is to make the positioning of the radical consistent with fractions and radicals // Move the starting point to below the nucleus leaving a gap of _lowerLimitGap and subtract // the ascent to to get the baseline. Also center and shift it to the left by _limitShift. ll.position = CGPoint(position.x - limitShift + (this.width - ll.width) / 2, position.y - nucleus.descent - lowerLimitGap - ll.ascent) } } fun updateUpperLimitPosition() { val ul = this.upperLimit if (ul != null) { // The position of the upper limit includes the position of the MTLargeOpLimitsDisplay // This is to make the positioning of the radical consistent with fractions and radicals // Move the starting point to above the nucleus leaving a gap of _upperLimitGap and add // the descent to to get the baseline. Also center and shift it to the right by _limitShift. ul.position = CGPoint(position.x + limitShift + (this.width - ul.width) / 2, position.y + nucleus.ascent + upperLimitGap + ul.descent) } } fun updateNucleusPosition() { // Center the nucleus nucleus.position = CGPoint(position.x + (this.width - nucleus.width) / 2, position.y) } override fun colorChanged() { this.nucleus.textColor = this.textColor val ul = this.upperLimit if (ul != null) { ul.textColor = this.textColor } val ll = this.lowerLimit if (ll != null) { ll.textColor = this.textColor } } override fun draw(canvas: Canvas) { // Draw the elements. upperLimit?.draw(canvas) lowerLimit?.draw(canvas) nucleus.draw(canvas) } } // MTLineDisplay overline or underline class MTLineDisplay(val inner: MTMathListDisplay, range: NSRange) : MTDisplay(range = range) { // How much the line should be moved up. var lineShiftUp: Float = 0.0f var lineThickness: Float = 0.0f override fun colorChanged() { this.inner.textColor = this.textColor } override fun draw(canvas: Canvas) { this.inner.draw(canvas) if (lineThickness != 0f) { val strokePaint = Paint(Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG) strokePaint.setColor(textColor) strokePaint.strokeWidth = lineThickness canvas.drawLine(position.x, position.y + lineShiftUp, position.x + width, position.y + lineShiftUp, strokePaint) } } override fun positionChanged() { this.updateInnerPosition() } fun updateInnerPosition() { this.inner.position = CGPoint(this.position.x, this.position.y) } } // MTAccentDisplay class MTAccentDisplay(val accent: MTGlyphDisplay, val accentee: MTMathListDisplay, range: NSRange) : MTDisplay(range = range) { init { accentee.position = CGPoint() super.range = range.copy() } override fun colorChanged() { this.accentee.textColor = this.textColor this.accent.textColor = this.textColor } override fun positionChanged() { this.updateAccenteePosition() } fun updateAccenteePosition() { this.accentee.position = CGPoint(this.position.x, this.position.y) } override fun draw(canvas: Canvas) { this.accentee.draw(canvas) canvas.save() canvas.translate(position.x, position.y) this.accent.draw(canvas) canvas.restore() } }
mathdisplaylib/src/main/java/com/agog/mathdisplay/render/MTMathListDisplay.kt
2566926256
package org.maxur.mserv.frame.kotlin import org.maxur.mserv.frame.LocatorImpl import javax.inject.Inject import kotlin.reflect.KClass import kotlin.reflect.KParameter /** * @author Maxim Yunusov * @version 1.0 * @since <pre>26.08.2017</pre> */ class Locator @Inject constructor(val impl: LocatorImpl) : LocatorImpl by impl { companion object { /** * Current Locator's property. */ val current get() = Locator(LocatorImpl.holder.get()) /** * Gets the best service from this locator that implements * this contract or has this implementation and has the given name (Kotlin edition). * <p> * @param contractOrImpl May not be null, and is the contract * or concrete implementation to get the best instance of * @param name Is the name of the implementation to be returned * @return An instance of the contract or impl. May return * null if there is no provider that provides the given * implementation or contract */ fun <T : Any> bean(contractOrImpl: KClass<T>, name: String? = null): T? = current.service(contractOrImpl, name) @Suppress("UNCHECKED_CAST") /** * Gets the best service from this locator that satisfied to function's parameter. * <p> * @param parameter The function's parameter * @return An instance of the contract or impl. May return * null if there is no provider that provides the given * implementation or contract */ fun <T : Any> bean(parameter: KParameter): T? = current.service(parameter.type.classifier as KClass<T>) /** * Gets all services from this locator that implement this contract or have this * implementation (Kotlin edition). * <p> * @param contractOrImpl May not be null, and is the contract * or concrete implementation to get the best instance of * @return A list of services implementing this contract * or concrete implementation. May return an empty list */ fun <T : Any> beans(contractOrImpl: KClass<T>): List<T> = current.services(contractOrImpl) /** * This method will shutdown every service associated with this Locator. * Those services that have a preDestroy shall have their preDestroy called */ fun stop() = current.shutdown() } /** * Gets the best service from this locator that implements * this contract or has this implementation and has the given name (Kotlin edition). * <p> * @param contractOrImpl May not be null, and is the contract * or concrete implementation to get the best instance of * @param name Is the name of the implementation to be returned * @return An instance of the contract or impl. * @throw IllegalStateException if there is no provider that * provides the given implementation or contract */ fun <T : Any> locate(contractOrImpl: KClass<T>, name: String?): T = locate(contractOrImpl.java, name) /** * Gets the best service from this locator that satisfied to function's parameter. * <p> * @param parameter The function's parameter * @return An instance of the contract or impl. May return * null if there is no provider that provides the given * implementation or contract */ @Suppress("UNCHECKED_CAST") fun <T : Any> service(parameter: KParameter): T? = service(parameter.type.classifier as KClass<T>) /** * Gets the best service from this locator that implements * this contract or has this implementation and has the given name (Java edition). * <p> * @param contractOrImpl May not be null, and is the contract * or concrete implementation to get the best instance of * @param name Is the name of the implementation to be returned * @return An instance of the contract or impl. May return * null if there is no provider that provides the given * implementation or contract */ fun <T : Any> service(contractOrImpl: KClass<T>, name: String? = null): T? = service(contractOrImpl.java, name) /** * Gets all services from this locator that implement this contract or have this * implementation (Java edition). * <p> * @param contractOrImpl May not be null, and is the contract * or concrete implementation to get the best instance of * @return A list of services implementing this contract * or concrete implementation. May return an empty list */ fun <T : Any> services(contractOrImpl: KClass<T>): List<T> = services(contractOrImpl.java) /** * Gets all services names from this locator that implement this contract or have this * implementation (Kotlin edition). * <p> * @param contractOrImpl May not be null, and is the contract * or concrete implementation to get the best instance of * @return A list of services names implementing this contract * or concrete implementation. May return an empty list */ fun <T : Any> names(contractOrImpl: KClass<T>): List<String> = names(contractOrImpl.java) /** * Gets property value by key name. * <p> * @param key The key name * @return The property value as String or nul */ fun property(key: String): String? = property(key, String::class) /** * Gets property value by key name (Kotlin edition). * <p> * @param key The key name * @param clazz The required type. * @return The property value of required type or nul */ fun <T : Any> property(key: String, clazz: KClass<T>): T? = property(key, clazz.java) /** {@inheritDoc} */ override fun toString(): String = name /** {@inheritDoc} */ override fun equals(other: Any?): Boolean = other is Locator && other.name.equals(name) /** {@inheritDoc} */ override fun hashCode(): Int { return name.hashCode() } inline fun <reified R : Any> service(name: String? = null): R? { return service(R::class, name) as R } }
maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/kotlin/Locator.kt
3790333845
// GENERATED package com.fkorotkov.kubernetes.policy.v1beta1 import io.fabric8.kubernetes.api.model.IntOrString as model_IntOrString import io.fabric8.kubernetes.api.model.policy.v1beta1.PodDisruptionBudgetSpec as v1beta1_PodDisruptionBudgetSpec fun v1beta1_PodDisruptionBudgetSpec.`maxUnavailable`(block: model_IntOrString.() -> Unit = {}) { if(this.`maxUnavailable` == null) { this.`maxUnavailable` = model_IntOrString() } this.`maxUnavailable`.block() }
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/policy/v1beta1/maxUnavailable.kt
677929593
package permissions.dispatcher.test import android.Manifest import android.support.v7.app.AppCompatActivity import permissions.dispatcher.NeedsPermission import permissions.dispatcher.OnNeverAskAgain import permissions.dispatcher.OnPermissionDenied import permissions.dispatcher.OnShowRationale import permissions.dispatcher.PermissionRequest import permissions.dispatcher.RuntimePermissions @RuntimePermissions open class ActivityWithAllAnnotationsKt : AppCompatActivity() { @NeedsPermission(Manifest.permission.CAMERA) fun showCamera() { } /** * PermissionRequest is nullable for testing, but it shouldn't */ @OnShowRationale(Manifest.permission.CAMERA) fun showRationaleForCamera(request: PermissionRequest?) { } @OnPermissionDenied(Manifest.permission.CAMERA) fun showDeniedForCamera() { } @OnNeverAskAgain(Manifest.permission.CAMERA) fun showNeverAskForCamera() { } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) onRequestPermissionsResult(requestCode, grantResults) } }
test/src/main/java/permissions/dispatcher/test/ActivityWithAllAnnotationsKt.kt
2920568287
/* * Copyright 2016 lizhaotailang * * 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.marktony.zhihudaily.data.source.remote import android.support.annotation.VisibleForTesting import com.marktony.zhihudaily.BuildConfig import com.marktony.zhihudaily.data.ZhihuDailyContent import com.marktony.zhihudaily.data.source.RemoteDataNotFoundException import com.marktony.zhihudaily.data.source.Result import com.marktony.zhihudaily.data.source.datasource.ZhihuDailyContentDataSource import com.marktony.zhihudaily.retrofit.RetrofitService import com.marktony.zhihudaily.util.AppExecutors import kotlinx.coroutines.experimental.withContext import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** * Created by lizhaotailang on 2017/5/26. * * Implementation of the [ZhihuDailyContent] data source that accesses network. */ class ZhihuDailyContentRemoteDataSource private constructor( private val mAppExecutors: AppExecutors ) : ZhihuDailyContentDataSource { private val mZhihuDailyService: RetrofitService.ZhihuDailyService by lazy { val httpClientBuilder = OkHttpClient.Builder() if (BuildConfig.DEBUG) { httpClientBuilder.addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) } httpClientBuilder.retryOnConnectionFailure(true) val retrofit = Retrofit.Builder() .baseUrl(RetrofitService.ZHIHU_DAILY_BASE) .addConverterFactory(GsonConverterFactory.create()) .client(httpClientBuilder.build()) .build() retrofit.create(RetrofitService.ZhihuDailyService::class.java) } companion object { private var INSTANCE: ZhihuDailyContentRemoteDataSource? = null @JvmStatic fun getInstance(appExecutors: AppExecutors): ZhihuDailyContentRemoteDataSource { if (INSTANCE == null) { synchronized(ZhihuDailyContentRemoteDataSource::javaClass) { INSTANCE = ZhihuDailyContentRemoteDataSource(appExecutors) } } return INSTANCE!! } @VisibleForTesting fun clearInstance() { INSTANCE = null } } override suspend fun getZhihuDailyContent(id: Int): Result<ZhihuDailyContent> = withContext(mAppExecutors.ioContext) { try { val response = mZhihuDailyService.getZhihuContent(id).execute() if (response.isSuccessful) { response.body()?.let { Result.Success(it) } ?: run { Result.Error(RemoteDataNotFoundException()) } } else { Result.Error(RemoteDataNotFoundException()) } } catch (e: Exception) { Result.Error(RemoteDataNotFoundException()) } } override suspend fun saveContent(content: ZhihuDailyContent) { // Not required because the [com.marktony.zhihudaily.data.source.repository.ZhihuDailyNewsRepository] handles the logic of refreshing the // news from all the available data sources. } }
app/src/main/java/com/marktony/zhihudaily/data/source/remote/ZhihuDailyContentRemoteDataSource.kt
803017197
/* * Copyright (C) 2013-2021 Dario Scoppelletti, <http://www.scoppelletti.it/>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("JoinDeclarationAndAssignment", "RedundantVisibilityModifier", "unused") package it.scoppelletti.spaceship.app import android.app.Activity import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager import androidx.annotation.UiThread import it.scoppelletti.spaceship.inject.AppComponent import it.scoppelletti.spaceship.inject.AppComponentProvider import it.scoppelletti.spaceship.inject.StdlibComponent import it.scoppelletti.spaceship.inject.StdlibComponentProvider /** * Application model extensions. * * @since 1.0.0 */ public object AppExt { /** * Tag of `AlertDialogFragment` fragment. * * @see it.scoppelletti.spaceship.app.AlertDialogFragment */ public const val TAG_ALERTDIALOG = "it.scoppelletti.spaceship.1" /** * Tag of `ExceptionDialogFragment` fragment. * * @see it.scoppelletti.spaceship.app.ExceptionDialogFragment */ public const val TAG_EXCEPTIONDIALOG = "it.scoppelletti.spaceship.2" /** * Tag of `BottomSheetDialogFragmentEx` fragment. * * @see it.scoppelletti.spaceship.app.BottomSheetDialogFragmentEx */ public const val TAG_BOTTOMSHEETDIALOG = "it.scoppelletti.spaceship.3" /** * Property containing an item. */ public const val PROP_ITEM = "it.scoppelletti.spaceship.1" /** * Property containing a message. */ public const val PROP_MESSAGE = "it.scoppelletti.spaceship.2" /** * Property containing a result. */ public const val PROP_RESULT = "it.scoppelletti.spaceship.3" } /** * Returns the `UIComponent` component. * * @receiver Activity. * @return The object. * @since 1.0.0 */ public fun Activity.appComponent(): AppComponent = (this.application as AppComponentProvider).appComponent() /** * Returns the `StdlibComponent` component. * * @receiver Activity. * @return The object. * @since 1.0.0 */ public fun Activity.stdlibComponent(): StdlibComponent = (this.application as StdlibComponentProvider).stdlibComponent() /** * Tries to finish an activity. * * @receiver Activity. * @return Returns `true` if the finish process has been started, `false` if * this activity was already finishing. * @since 1.0.0 */ @UiThread public fun Activity.tryFinish(): Boolean { if (this.isFinishing) { return false } this.finish() return true } /** * Hides the soft keyboard. * * @receiver Activity. * @since 1.0.0 */ @UiThread public fun Activity.hideSoftKeyboard() { val view: View? val inputMgr: InputMethodManager view = this.currentFocus if (view != null) { inputMgr = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMgr.hideSoftInputFromWindow(view.windowToken, 0) } }
lib/src/main/kotlin/it/scoppelletti/spaceship/app/AppExt.kt
229380205
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.action.item import assertk.assertThat import assertk.assertions.isEqualTo import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import okio.buffer import okio.sink import okio.source import org.junit.Test import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream class VibrationSingleActionTest { @Test fun testDecodeEncode() { val json = """{"0":500}""" val reader = JsonReader.of(ByteArrayInputStream(json.toByteArray()).source().buffer()) val action = VibrationSingleAction(0, reader) assertThat(action.time).isEqualTo(500) assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT) val os = ByteArrayOutputStream() val writer = JsonWriter.of(os.sink().buffer()) writer.beginArray() action.writeIdAndData(writer) writer.endArray() writer.flush() assertThat(os.toString()).isEqualTo("""[0,{"0":500}]""") } }
legacy/src/test/java/jp/hazuki/yuzubrowser/legacy/action/item/VibrationSingleActionTest.kt
916054554
/* * Copyright (C) 2016/2022 Litote * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.litote.kmongo.issues import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.Serializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import org.bson.BsonReader import org.bson.BsonWriter import org.bson.codecs.Codec import org.bson.codecs.DecoderContext import org.bson.codecs.EncoderContext import org.bson.codecs.configuration.CodecRegistries import org.junit.Test import org.litote.kmongo.AllCategoriesKMongoBaseTest import org.litote.kmongo.eq import org.litote.kmongo.findOne import org.litote.kmongo.serialization.registerSerializer import java.util.UUID import kotlin.test.assertNotNull /** * */ @ExperimentalSerializationApi @Serializer(forClass = UUID::class) object EntitySerializer : KSerializer<UUID> { override val descriptor: SerialDescriptor get() = PrimitiveSerialDescriptor( serialName = "com.malachid.poc.Entity", kind = PrimitiveKind.STRING ) override fun deserialize(decoder: Decoder): UUID = UUID.fromString(decoder.decodeString()) override fun serialize(encoder: Encoder, value: UUID) { encoder.encodeString(value.toString()) } } @ExperimentalSerializationApi @Serializable data class ClassUUID(val _id: @Serializable(with = EntitySerializer::class) UUID) /** * */ @ExperimentalSerializationApi class Issue287UUID : AllCategoriesKMongoBaseTest<ClassUUID>() { @Test fun canFindOne() { val c = col.withCodecRegistry( CodecRegistries.fromRegistries( CodecRegistries.fromCodecs( object : Codec<UUID> { override fun encode(writer: BsonWriter, value: UUID, encoderContext: EncoderContext) { writer.writeString(value.toString()) } override fun getEncoderClass(): Class<UUID> = UUID::class.java override fun decode(reader: BsonReader, decoderContext: DecoderContext): UUID { return UUID.fromString(reader.readString()) } } ), col.codecRegistry )) registerSerializer(EntitySerializer) val uuid = UUID.randomUUID() c.insertOne(ClassUUID(uuid)) assertNotNull(c.findOne(ClassUUID::_id eq uuid)) } }
kmongo-serialization/src/test/kotlin/Issue287UUID.kt
4153436190
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.text.format.DateUtils import android.util.Log import androidx.core.content.ContextCompat import dagger.hilt.android.AndroidEntryPoint import net.jami.services.PreferencesService import javax.inject.Inject @AndroidEntryPoint class BootReceiver : BroadcastReceiver() { @Inject lateinit var mPreferencesService: PreferencesService override fun onReceive(context: Context, intent: Intent) { val action = intent.action ?: return if (Intent.ACTION_BOOT_COMPLETED == action || Intent.ACTION_REBOOT == action || Intent.ACTION_MY_PACKAGE_REPLACED == action) { try { if (mPreferencesService.settings.runOnStartup) { try { ContextCompat.startForegroundService(context, Intent(SyncService.ACTION_START) .setClass(context, SyncService::class.java) .putExtra(SyncService.EXTRA_TIMEOUT, 5 * DateUtils.SECOND_IN_MILLIS)) } catch (e: IllegalStateException) { Log.e(TAG, "Error starting service", e) } } } catch (e: Exception) { Log.e(TAG, "Can't start on boot", e) } } } companion object { private val TAG = BootReceiver::class.simpleName!! } }
ring-android/app/src/main/java/cx/ring/service/BootReceiver.kt
2994287288