content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package pl.expensive.transaction.details import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import pl.expensive.Injector import pl.expensive.R import pl.expensive.storage.TransactionDbo class TransactionDetailsActivity : AppCompatActivity(), NewTransactionFragment.NewTransactionCallbacks { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_transaction_details) Injector.app().inject(this) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .add(R.id.vNewTransactionContainer, createNewTransactionFragment(intent.extras), "new_transaction_fragment") .commit() } else { supportFragmentManager.beginTransaction() .replace(R.id.vNewTransactionContainer, createNewTransactionFragment(intent.extras), "new_transaction_fragment") .commit() } } override fun onNewTransaction(transaction: TransactionDbo) { finishWithResult(getString(R.string.new_withdrawal_success_message, transaction.amount.abs())) } override fun onTransactionEdited(transaction: TransactionDbo) { finishWithResult(getString(R.string.withdrawal_edited_success_message, transaction.amount.abs())) } override fun onCanceled() { setResult(Activity.RESULT_CANCELED) finish() } private fun finishWithResult(msg: String) { val extras = Bundle() extras.putString("message", msg) setResult(Activity.RESULT_OK, Intent().putExtras(extras)) finish() } }
app/src/main/java/pl/expensive/transaction/details/TransactionDetailsActivity.kt
3114513157
package com.stripe.android.ui.core.elements.autocomplete.model import android.text.SpannableString import androidx.annotation.RestrictTo import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class FindAutocompletePredictionsResponse( val autocompletePredictions: List<AutocompletePrediction> ) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class AutocompletePrediction( val primaryText: SpannableString, val secondaryText: SpannableString, val placeId: String ) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class FetchPlaceResponse( val place: Place ) @Serializable @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class Place( @SerialName("address_components") val addressComponents: List<AddressComponent>? ) { enum class Type(val value: String) { ADMINISTRATIVE_AREA_LEVEL_1("administrative_area_level_1"), ADMINISTRATIVE_AREA_LEVEL_2("administrative_area_level_2"), ADMINISTRATIVE_AREA_LEVEL_3("administrative_area_level_3"), ADMINISTRATIVE_AREA_LEVEL_4("administrative_area_level_4"), COUNTRY("country"), LOCALITY("locality"), NEIGHBORHOOD("neighborhood"), POSTAL_TOWN("postal_town"), POSTAL_CODE("postal_code"), PREMISE("premise"), ROUTE("route"), STREET_NUMBER("street_number"), SUBLOCALITY("sublocality"), SUBLOCALITY_LEVEL_1("sublocality_level_1"), SUBLOCALITY_LEVEL_2("sublocality_level_2"), SUBLOCALITY_LEVEL_3("sublocality_level_3"), SUBLOCALITY_LEVEL_4("sublocality_level_4") } } @Serializable @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class AddressComponent( @SerialName("short_name") val shortName: String?, @SerialName("long_name") val longName: String, @SerialName("types") val types: List<String> ) { fun contains(type: Place.Type): Boolean { return types.contains(type.value) } }
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/autocomplete/model/Place.kt
2808114425
package tech.salroid.filmy.ui.activities import androidx.appcompat.app.AppCompatActivity import tech.salroid.filmy.R import android.os.Bundle import androidx.core.content.res.ResourcesCompat import androidx.preference.Preference.OnPreferenceChangeListener import androidx.preference.Preference.OnPreferenceClickListener import android.content.Intent import android.graphics.Color import android.view.MenuItem import androidx.preference.* import tech.salroid.filmy.databinding.ActivitySettingsBinding class SettingsActivity : AppCompatActivity() { private var nightMode = false private lateinit var binding: ActivitySettingsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val sp = PreferenceManager.getDefaultSharedPreferences(this) nightMode = sp.getBoolean("dark", false) if (nightMode) setTheme(R.style.AppTheme_Base_Dark) else setTheme(R.style.AppTheme_Base) binding = ActivitySettingsBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = "" binding.logo.typeface = ResourcesCompat.getFont(this, R.font.rubik) if (nightMode) allThemeLogic() supportFragmentManager.beginTransaction().replace(R.id.container, FilmyPreferenceFragment()).commit() } private fun allThemeLogic() { binding.logo.setTextColor(Color.parseColor("#bdbdbd")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() } return super.onOptionsItemSelected(item) } class FilmyPreferenceFragment : PreferenceFragmentCompat() { private var imagePref: SwitchPreferenceCompat? = null private var darkPref: SwitchPreferenceCompat? = null override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preference, rootKey) val myPreference = PreferenceManager.getDefaultSharedPreferences(requireContext()).edit() imagePref = findPreference("imagequality") as? SwitchPreferenceCompat imagePref?.onPreferenceChangeListener = OnPreferenceChangeListener { preference, o -> val quality: String val switchPreference = preference as SwitchPreferenceCompat quality = if (!switchPreference.isChecked) { "original" } else { "w1280" } myPreference.putString("image_quality", quality) myPreference.apply() true } darkPref = findPreference("dark") as? SwitchPreferenceCompat darkPref?.onPreferenceChangeListener = OnPreferenceChangeListener { _, _ -> recreateActivity() true } val license = findPreference("license") as? Preference license?.onPreferenceClickListener = OnPreferenceClickListener { startActivity(Intent(activity, License::class.java)) true } val share = findPreference("Share") as? Preference share?.onPreferenceClickListener = OnPreferenceClickListener { val appShareDetails = resources.getString(R.string.app_share_link) val myIntent = Intent(Intent.ACTION_SEND) myIntent.type = "text/plain" myIntent.putExtra( Intent.EXTRA_TEXT, "Check out this awesome movie app.\n*filmy*\n$appShareDetails" ) startActivity(Intent.createChooser(myIntent, "Share with")) true } val about = findPreference("About") as? Preference about?.onPreferenceClickListener = OnPreferenceClickListener { startActivity(Intent(activity, AboutActivity::class.java)) true } } private fun recreateActivity() { activity?.recreate() } } }
app/src/main/java/tech/salroid/filmy/ui/activities/SettingsActivity.kt
3775067982
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3 import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.systemBars import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.unit.LayoutDirection import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import java.util.concurrent.TimeUnit import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalMaterial3Api::class) @MediumTest @RunWith(AndroidJUnit4::class) class MaterialComponentsInsetSupportTest { @get:Rule val rule = createAndroidComposeRule<MaterialWindowInsetsActivity>() @Before fun setup() { rule.activity.createdLatch.await(1, TimeUnit.SECONDS) } @Test fun topAppBar_respectsInsetsDefault() { var contentPadding: WindowInsets? = null var expected: WindowInsets? = null rule.setContent { expected = WindowInsets.systemBars .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top) contentPadding = TopAppBarDefaults.windowInsets } rule.runOnIdle { assertThat(contentPadding).isEqualTo(expected) } } @Test fun bottomAppBar_respectsInsetsDefault() { var contentPadding: WindowInsets? = null var expected: WindowInsets? = null rule.setContent { expected = WindowInsets.systemBars .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom) contentPadding = BottomAppBarDefaults.windowInsets } rule.runOnIdle { // only checking bottom as bottom app bar has special optional padding on the sides assertThat(contentPadding).isEqualTo(expected) } } @Test fun drawerSheets_respectsInsetsDefault() { var contentPadding: WindowInsets? = null var expected: WindowInsets? = null rule.setContent { expected = WindowInsets.systemBars .only(WindowInsetsSides.Start + WindowInsetsSides.Vertical) contentPadding = DrawerDefaults.windowInsets } rule.runOnIdle { assertThat(contentPadding).isEqualTo(expected) } } @Test fun navigationBar_respectsInsetsDefault() { var contentPadding: WindowInsets? = null var expected: WindowInsets? = null rule.setContent { expected = WindowInsets.systemBars .only(WindowInsetsSides.Bottom + WindowInsetsSides.Horizontal) contentPadding = NavigationBarDefaults.windowInsets } rule.runOnIdle { assertThat(contentPadding).isEqualTo(expected) } } @Test fun NavRail_respectsInsetsDefault() { var contentPadding: WindowInsets? = null var expected: WindowInsets? = null rule.setContent { expected = WindowInsets.systemBars .only(WindowInsetsSides.Start + WindowInsetsSides.Vertical) contentPadding = NavigationRailDefaults.windowInsets } rule.runOnIdle { assertThat(contentPadding).isEqualTo(expected) } } @Test fun scaffold_providesInsets() { var contentPadding: PaddingValues? = null var expected: PaddingValues? = null var layoutDirection: LayoutDirection? = null rule.setContent { layoutDirection = LocalLayoutDirection.current expected = WindowInsets.systemBars .asPaddingValues(LocalDensity.current) Scaffold { paddingValues -> contentPadding = paddingValues } } rule.runOnIdle { assertThat(contentPadding?.calculateBottomPadding()) .isEqualTo(expected?.calculateBottomPadding()) assertThat(contentPadding?.calculateTopPadding()) .isEqualTo(expected?.calculateTopPadding()) assertThat(contentPadding?.calculateLeftPadding(layoutDirection!!)) .isEqualTo(expected?.calculateLeftPadding(layoutDirection!!)) assertThat(contentPadding?.calculateRightPadding(layoutDirection!!)) .isEqualTo(expected?.calculateRightPadding(layoutDirection!!)) } } }
compose/material3/material3/src/androidAndroidTest/kotlin/androidx/compose/material3/MaterialComponentsInsetSupportTest.kt
3430396809
package abi43_0_0.host.exp.exponent.modules.api.components.pagerview import android.view.View import android.view.ViewGroup import androidx.viewpager2.widget.ViewPager2 import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback import com.facebook.infer.annotation.Assertions import abi43_0_0.com.facebook.react.bridge.ReadableArray import abi43_0_0.com.facebook.react.common.MapBuilder import abi43_0_0.com.facebook.react.uimanager.PixelUtil import abi43_0_0.com.facebook.react.uimanager.ThemedReactContext import abi43_0_0.com.facebook.react.uimanager.UIManagerModule import abi43_0_0.com.facebook.react.uimanager.ViewGroupManager import abi43_0_0.com.facebook.react.uimanager.annotations.ReactProp import abi43_0_0.com.facebook.react.uimanager.events.EventDispatcher import abi43_0_0.host.exp.exponent.modules.api.components.pagerview.event.PageScrollEvent import abi43_0_0.host.exp.exponent.modules.api.components.pagerview.event.PageScrollStateChangedEvent import abi43_0_0.host.exp.exponent.modules.api.components.pagerview.event.PageSelectedEvent class PagerViewViewManager : ViewGroupManager<NestedScrollableHost>() { private lateinit var eventDispatcher: EventDispatcher override fun getName(): String { return REACT_CLASS } override fun createViewInstance(reactContext: ThemedReactContext): NestedScrollableHost { val host = NestedScrollableHost(reactContext) host.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) host.isSaveEnabled = false val vp = ViewPager2(reactContext) vp.adapter = ViewPagerAdapter() // https://github.com/callstack/react-native-viewpager/issues/183 vp.isSaveEnabled = false eventDispatcher = reactContext.getNativeModule(UIManagerModule::class.java)!!.eventDispatcher vp.post { vp.registerOnPageChangeCallback(object : OnPageChangeCallback() { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { super.onPageScrolled(position, positionOffset, positionOffsetPixels) eventDispatcher.dispatchEvent( PageScrollEvent(host.id, position, positionOffset) ) } override fun onPageSelected(position: Int) { super.onPageSelected(position) eventDispatcher.dispatchEvent( PageSelectedEvent(host.id, position) ) } override fun onPageScrollStateChanged(state: Int) { super.onPageScrollStateChanged(state) val pageScrollState: String = when (state) { ViewPager2.SCROLL_STATE_IDLE -> "idle" ViewPager2.SCROLL_STATE_DRAGGING -> "dragging" ViewPager2.SCROLL_STATE_SETTLING -> "settling" else -> throw IllegalStateException("Unsupported pageScrollState") } eventDispatcher.dispatchEvent( PageScrollStateChangedEvent(host.id, pageScrollState) ) } }) eventDispatcher.dispatchEvent(PageSelectedEvent(host.id, vp.currentItem)) } host.addView(vp) return host } private fun getViewPager(view: NestedScrollableHost): ViewPager2 { if (view.getChildAt(0) is ViewPager2) { return view.getChildAt(0) as ViewPager2 } else { throw ClassNotFoundException("Could not retrieve ViewPager2 instance") } } private fun setCurrentItem(view: ViewPager2, selectedTab: Int, scrollSmooth: Boolean) { refreshViewChildrenLayout(view) view.setCurrentItem(selectedTab, scrollSmooth) } override fun addView(host: NestedScrollableHost, child: View?, index: Int) { if (child == null) { return } val parent = getViewPager(host) (parent.adapter as ViewPagerAdapter?)?.addChild(child, index) if (parent.currentItem == index) { // Solves https://github.com/callstack/react-native-pager-view/issues/219 // Required so ViewPager actually displays first dynamically added child // (otherwise a white screen is shown until the next user interaction). // https://github.com/facebook/react-native/issues/17968#issuecomment-697136929 refreshViewChildrenLayout(parent) } } override fun getChildCount(parent: NestedScrollableHost) = getViewPager(parent).adapter?.itemCount ?: 0 override fun getChildAt(parent: NestedScrollableHost, index: Int): View { val view = getViewPager(parent) return (view.adapter as ViewPagerAdapter?)!!.getChildAt(index) } override fun removeView(parent: NestedScrollableHost, view: View) { val pager = getViewPager(parent) (pager.adapter as ViewPagerAdapter?)?.removeChild(view) // Required so ViewPager actually animates the removed view right away (otherwise // a white screen is shown until the next user interaction). // https://github.com/facebook/react-native/issues/17968#issuecomment-697136929 refreshViewChildrenLayout(pager) } override fun removeAllViews(parent: NestedScrollableHost) { val pager = getViewPager(parent) pager.isUserInputEnabled = false val adapter = pager.adapter as ViewPagerAdapter? adapter?.removeAll() } override fun removeViewAt(parent: NestedScrollableHost, index: Int) { val pager = getViewPager(parent) val adapter = pager.adapter as ViewPagerAdapter? adapter?.removeChildAt(index) // Required so ViewPager actually animates the removed view right away (otherwise // a white screen is shown until the next user interaction). // https://github.com/facebook/react-native/issues/17968#issuecomment-697136929 refreshViewChildrenLayout(pager) } override fun needsCustomLayoutForChildren(): Boolean { return true } @ReactProp(name = "scrollEnabled", defaultBoolean = true) fun setScrollEnabled(host: NestedScrollableHost, value: Boolean) { getViewPager(host).isUserInputEnabled = value } @ReactProp(name = "initialPage", defaultInt = 0) fun setInitialPage(host: NestedScrollableHost, value: Int) { val view = getViewPager(host) // https://github.com/callstack/react-native-pager-view/issues/456 // Initial index should be set only once. if (host.initialIndex === null) { view.post { setCurrentItem(view, value, false) host.initialIndex = value } } } @ReactProp(name = "orientation") fun setOrientation(host: NestedScrollableHost, value: String) { getViewPager(host).orientation = if (value == "vertical") ViewPager2.ORIENTATION_VERTICAL else ViewPager2.ORIENTATION_HORIZONTAL } @ReactProp(name = "offscreenPageLimit", defaultInt = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT) operator fun set(host: NestedScrollableHost, value: Int) { getViewPager(host).offscreenPageLimit = value } @ReactProp(name = "overScrollMode") fun setOverScrollMode(host: NestedScrollableHost, value: String) { val child = getViewPager(host).getChildAt(0) when (value) { "never" -> { child.overScrollMode = ViewPager2.OVER_SCROLL_NEVER } "always" -> { child.overScrollMode = ViewPager2.OVER_SCROLL_ALWAYS } else -> { child.overScrollMode = ViewPager2.OVER_SCROLL_IF_CONTENT_SCROLLS } } } @ReactProp(name = "layoutDirection") fun setLayoutDirection(host: NestedScrollableHost, value: String) { val view = getViewPager(host) when (value) { "rtl" -> { view.layoutDirection = View.LAYOUT_DIRECTION_RTL } else -> { view.layoutDirection = View.LAYOUT_DIRECTION_LTR } } } override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Map<String, String>> { return MapBuilder.of( PageScrollEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageScroll"), PageScrollStateChangedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageScrollStateChanged"), PageSelectedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageSelected") ) } override fun getCommandsMap(): Map<String, Int>? { return MapBuilder.of( "setPage", COMMAND_SET_PAGE, "setPageWithoutAnimation", COMMAND_SET_PAGE_WITHOUT_ANIMATION, "setScrollEnabled", COMMAND_SET_SCROLL_ENABLED ) } override fun receiveCommand(root: NestedScrollableHost, commandId: Int, args: ReadableArray?) { super.receiveCommand(root, commandId, args) val view = getViewPager(root) Assertions.assertNotNull(view) Assertions.assertNotNull(args) val childCount = view.adapter?.itemCount when (commandId) { COMMAND_SET_PAGE, COMMAND_SET_PAGE_WITHOUT_ANIMATION -> { val pageIndex = args!!.getInt(0) val canScroll = childCount != null && childCount > 0 && pageIndex >= 0 && pageIndex < childCount if (canScroll) { val scrollWithAnimation = commandId == COMMAND_SET_PAGE setCurrentItem(view, pageIndex, scrollWithAnimation) eventDispatcher.dispatchEvent(PageSelectedEvent(root.id, pageIndex)) } } COMMAND_SET_SCROLL_ENABLED -> { view.isUserInputEnabled = args!!.getBoolean(0) } else -> throw IllegalArgumentException( String.format( "Unsupported command %d received by %s.", commandId, javaClass.simpleName ) ) } } @ReactProp(name = "pageMargin", defaultFloat = 0F) fun setPageMargin(host: NestedScrollableHost, margin: Float) { val pager = getViewPager(host) val pageMargin = PixelUtil.toPixelFromDIP(margin).toInt() /** * Don't use MarginPageTransformer to be able to support negative margins */ pager.setPageTransformer { page, position -> val offset = pageMargin * position if (pager.orientation == ViewPager2.ORIENTATION_HORIZONTAL) { val isRTL = pager.layoutDirection == View.LAYOUT_DIRECTION_RTL page.translationX = if (isRTL) -offset else offset } else { page.translationY = offset } } } private fun refreshViewChildrenLayout(view: View) { view.post { view.measure( View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(view.height, View.MeasureSpec.EXACTLY) ) view.layout(view.left, view.top, view.right, view.bottom) } } companion object { private const val REACT_CLASS = "RNCViewPager" private const val COMMAND_SET_PAGE = 1 private const val COMMAND_SET_PAGE_WITHOUT_ANIMATION = 2 private const val COMMAND_SET_SCROLL_ENABLED = 3 } }
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/components/pagerview/PagerViewViewManager.kt
1209250340
package com.mvcoding.expensius.data import com.mvcoding.expensius.model.AppUser import com.mvcoding.expensius.model.NullModels.noAppUser import com.mvcoding.expensius.model.NullModels.noSettings import com.mvcoding.expensius.model.defaultCurrency import com.mvcoding.expensius.model.extensions.anAppUser import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.junit.Test import rx.Observable import rx.observers.TestSubscriber class AppUserSourceTest { @Test fun `behaves like memory cache`() { testMemoryCache(anAppUser(), anAppUser()) { AppUserSource({ it.data() }, mock()) } } @Test fun `updates app user when it changes`() { val updateAppUser = mock<(AppUser) -> Unit>() val appUserSource = AppUserSource(mock(), updateAppUser) val appUser = anAppUser() appUserSource.write(appUser) verify(updateAppUser).invoke(appUser) } @Test fun `puts default values for app user before writing`() { val updateAppUser = mock<(AppUser) -> Unit>() val getAppUser = mock<() -> Observable<AppUser>>() whenever(getAppUser()).thenReturn(Observable.never()) val appUserSource = AppUserSource(getAppUser, updateAppUser) val appUser = noAppUser val subscriber = TestSubscriber<AppUser>() appUserSource.data().subscribe(subscriber) appUserSource.write(appUser) val appUserWithDefaultValues = noAppUser.copy(settings = noSettings.copy(mainCurrency = defaultCurrency())) subscriber.assertValue(appUserWithDefaultValues) verify(updateAppUser).invoke(appUserWithDefaultValues) } }
app-core/src/test/kotlin/com/mvcoding/expensius/data/AppUserSourceTest.kt
2832062942
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi import org.intellij.lang.annotations.Language import org.rust.MockAdditionalCfgOptions import org.rust.RsTestBase import org.rust.fileTreeFromText import org.rust.lang.core.psi.ext.RsElement import org.rust.lang.core.psi.ext.isUnderCfgTest class RsIsUnderCfgTestTest : RsTestBase() { fun `test cfg test mod`() = doTest(""" #[cfg(test)] mod tests { fn foo() {} //^ true } """) fun `test cfg not test mod`() = doTest(""" #[cfg(not(test))] mod tests { fn foo() {} //^ false } """) fun `test test fn`() = doTest(""" #[test] fn foo() { foo; } //^ true """) @MockAdditionalCfgOptions("intellij_rust") fun `test cfg or option test mod`() = doTest(""" #[cfg(any(test, intellij_rust))] mod tests { fn foo() {} //^ false } """) @MockAdditionalCfgOptions("intellij_rust") fun `test cfg and option test mod`() = doTest(""" #[cfg(all(test, intellij_rust))] mod tests { fn foo() {} //^ true } """) fun `test cfg test out-of-line mod 1`() = doTestByTree(""" //- main.rs #[cfg(test)] mod tests; //- tests.rs fn foo() {} //^ true """) fun `test cfg test out-of-line mod 2`() = doTestByTree(""" //- main.rs mod tests; //- tests.rs #![cfg(test)] fn foo() {} //^ true """) private fun doTest(@Language("Rust") code: String) { InlineFile(code) doTest() } private fun doTestByTree(@Language("Rust") code: String) { fileTreeFromText(code).createAndOpenFileWithCaretMarker() doTest() } private fun doTest() { val (element, data) = findElementAndDataInEditor<RsElement>() val expected = when (data) { "true" -> true "false" -> false else -> error("Unknown value `$data`") } val actual = element.isUnderCfgTest assertEquals(expected, actual) } }
src/test/kotlin/org/rust/lang/core/psi/RsIsUnderCfgTestTest.kt
1038678356
@file:JvmName("Sdk21LayoutsKt") package org.jetbrains.anko import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import android.widget.FrameLayout import android.appwidget.AppWidgetHostView import android.view.View import android.webkit.WebView import android.widget.AbsoluteLayout import android.widget.ActionMenuView import android.widget.Gallery import android.widget.GridLayout import android.widget.GridView import android.widget.AbsListView import android.widget.HorizontalScrollView import android.widget.ImageSwitcher import android.widget.LinearLayout import android.widget.RadioGroup import android.widget.RelativeLayout import android.widget.ScrollView import android.widget.TableLayout import android.widget.TableRow import android.widget.TextSwitcher import android.widget.Toolbar import android.app.ActionBar import android.widget.ViewAnimator import android.widget.ViewSwitcher open class _AppWidgetHostView(ctx: Context): AppWidgetHostView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _WebView(ctx: Context): WebView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: ViewGroup.LayoutParams.() -> Unit ): T { val layoutParams = ViewGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = ViewGroup.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: ViewGroup.LayoutParams.() -> Unit ): T { val layoutParams = ViewGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = ViewGroup.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: ViewGroup.LayoutParams.() -> Unit ): T { val layoutParams = ViewGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = ViewGroup.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _AbsoluteLayout(ctx: Context): AbsoluteLayout(ctx) { inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ActionMenuView(ctx: Context): ActionMenuView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ViewGroup.LayoutParams?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ViewGroup.LayoutParams? ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ActionMenuView.LayoutParams?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ActionMenuView.LayoutParams? ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = ActionMenuView.LayoutParams(width, height) [email protected] = layoutParams return this } } open class _FrameLayout(ctx: Context): FrameLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Gallery(ctx: Context): Gallery(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Gallery.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Gallery.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _GridLayout(ctx: Context): GridLayout(ctx) { inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec? ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = GridLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet? ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) [email protected] = layoutParams return this } } open class _GridView(ctx: Context): GridView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = AbsListView.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsListView.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _HorizontalScrollView(ctx: Context): HorizontalScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ImageSwitcher(ctx: Context): ImageSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _LinearLayout(ctx: Context): LinearLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = LinearLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RadioGroup(ctx: Context): RadioGroup(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RadioGroup.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RelativeLayout(ctx: Context): RelativeLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ScrollView(ctx: Context): ScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableLayout(ctx: Context): TableLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableRow(ctx: Context): TableRow(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableRow.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableRow.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(column) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int ): T { val layoutParams = TableRow.LayoutParams(column) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableRow.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableRow.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TextSwitcher(ctx: Context): TextSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Toolbar(ctx: Context): Toolbar(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Toolbar.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Toolbar.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = Toolbar.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( gravity: Int, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( gravity: Int ): T { val layoutParams = Toolbar.LayoutParams(gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: Toolbar.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: Toolbar.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ActionBar.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ActionBar.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewAnimator(ctx: Context): ViewAnimator(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewSwitcher(ctx: Context): ViewSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } }
anko/library/generated/sdk21/src/Layouts.kt
819978345
package org.jetbrains.dokka.gradle import groovy.lang.Closure import org.gradle.api.DefaultTask import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.file.FileCollection import org.gradle.api.plugins.JavaBasePlugin import org.gradle.api.plugins.JavaPluginConvention import org.gradle.api.tasks.* import org.gradle.api.tasks.Optional import org.gradle.api.tasks.compile.AbstractCompile import org.jetbrains.dokka.* import org.jetbrains.dokka.ReflectDsl.isNotInstance import org.jetbrains.dokka.gradle.ClassloaderContainer.fatJarClassLoader import org.jetbrains.dokka.gradle.DokkaVersion.version import ru.yole.jkid.JsonExclude import ru.yole.jkid.serialization.serialize import java.io.File import java.io.InputStream import java.io.Serializable import java.net.URLClassLoader import java.util.* import java.util.concurrent.Callable import java.util.function.BiConsumer open class DokkaPlugin : Plugin<Project> { override fun apply(project: Project) { DokkaVersion.loadFrom(javaClass.getResourceAsStream("/META-INF/gradle-plugins/org.jetbrains.dokka.properties")) project.tasks.create("dokka", DokkaTask::class.java).apply { moduleName = project.name outputDirectory = File(project.buildDir, "dokka").absolutePath } } } object DokkaVersion { var version: String? = null fun loadFrom(stream: InputStream) { version = Properties().apply { load(stream) }.getProperty("dokka-version") } } object ClassloaderContainer { @JvmField var fatJarClassLoader: ClassLoader? = null } const val `deprecationMessage reportNotDocumented` = "Will be removed in 0.9.17, see dokka#243" open class DokkaTask : DefaultTask() { fun defaultKotlinTasks() = with(ReflectDsl) { val abstractKotlinCompileClz = try { project.buildscript.classLoader.loadClass(ABSTRACT_KOTLIN_COMPILE) } catch (cnfe: ClassNotFoundException) { logger.warn("$ABSTRACT_KOTLIN_COMPILE class not found, default kotlin tasks ignored") return@with emptyList<Task>() } return@with project.tasks.filter { it isInstance abstractKotlinCompileClz }.filter { "Test" !in it.name } } init { group = JavaBasePlugin.DOCUMENTATION_GROUP description = "Generates dokka documentation for Kotlin" @Suppress("LeakingThis") dependsOn(Callable { kotlinTasks.map { it.taskDependencies } }) } @Input var moduleName: String = "" @Input var outputFormat: String = "html" var outputDirectory: String = "" @Deprecated("Going to be removed in 0.9.16, use classpath + sourceDirs instead if kotlinTasks is not suitable for you") @Input var processConfigurations: List<Any?> = emptyList() @InputFiles var classpath: Iterable<File> = arrayListOf() @Input var includes: List<Any?> = arrayListOf() @Input var linkMappings: ArrayList<LinkMapping> = arrayListOf() @Input var samples: List<Any?> = arrayListOf() @Input var jdkVersion: Int = 6 @Input var generateClassIndexPage = true @Input var generatePackageIndexPage = true @Input var sourceDirs: Iterable<File> = emptyList() @Input var sourceRoots: MutableList<SourceRoot> = arrayListOf() @Input var dokkaFatJar: Any = "org.jetbrains.dokka:dokka-fatjar:$version" @Input var includeNonPublic = false @Input var skipDeprecated = false @Input var skipEmptyPackages = true @Input var outlineRoot: String = "" @Input var dacRoot: String = "" @Deprecated(`deprecationMessage reportNotDocumented`, replaceWith = ReplaceWith("reportUndocumented")) var reportNotDocumented get() = reportUndocumented set(value) { logger.warn("Dokka: reportNotDocumented is deprecated and " + `deprecationMessage reportNotDocumented`.decapitalize()) reportUndocumented = value } @Input var reportUndocumented = true @Input var perPackageOptions: MutableList<PackageOptions> = arrayListOf() @Input var impliedPlatforms: MutableList<String> = arrayListOf() @Input var externalDocumentationLinks = mutableListOf<DokkaConfiguration.ExternalDocumentationLink>() @Input var noStdlibLink: Boolean = false @Input var noJdkLink: Boolean = false @Optional @Input var cacheRoot: String? = null @Optional @Input var languageVersion: String? = null @Optional @Input var apiVersion: String? = null @Input var collectInheritedExtensionsFromLibraries: Boolean = false @get:Internal internal val kotlinCompileBasedClasspathAndSourceRoots: ClasspathAndSourceRoots by lazy { extractClasspathAndSourceRootsFromKotlinTasks() } private var kotlinTasksConfigurator: () -> List<Any?>? = { defaultKotlinTasks() } private val kotlinTasks: List<Task> by lazy { extractKotlinCompileTasks() } fun kotlinTasks(closure: Closure<Any?>) { kotlinTasksConfigurator = { closure.call() as? List<Any?> } } fun linkMapping(closure: Closure<Unit>) { val mapping = LinkMapping() closure.delegate = mapping closure.call() if (mapping.path.isEmpty()) { throw IllegalArgumentException("Link mapping should have dir") } if (mapping.url.isEmpty()) { throw IllegalArgumentException("Link mapping should have url") } linkMappings.add(mapping) } fun sourceRoot(closure: Closure<Unit>) { val sourceRoot = SourceRoot() closure.delegate = sourceRoot closure.call() sourceRoots.add(sourceRoot) } fun packageOptions(closure: Closure<Unit>) { val packageOptions = PackageOptions() closure.delegate = packageOptions closure.call() perPackageOptions.add(packageOptions) } fun externalDocumentationLink(closure: Closure<Unit>) { val builder = DokkaConfiguration.ExternalDocumentationLink.Builder() closure.delegate = builder closure.call() externalDocumentationLinks.add(builder.build()) } fun tryResolveFatJar(project: Project): File { return try { val dependency = project.buildscript.dependencies.create(dokkaFatJar) val configuration = project.buildscript.configurations.detachedConfiguration(dependency) configuration.description = "Dokka main jar" configuration.resolve().first() } catch (e: Exception) { project.parent?.let { tryResolveFatJar(it) } ?: throw e } } fun loadFatJar() { if (fatJarClassLoader == null) { val fatjar = if (dokkaFatJar is File) dokkaFatJar as File else tryResolveFatJar(project) fatJarClassLoader = URLClassLoader(arrayOf(fatjar.toURI().toURL()), ClassLoader.getSystemClassLoader().parent) } } internal data class ClasspathAndSourceRoots(val classpathFileCollection: FileCollection, val sourceRoots: List<File>) : Serializable private fun extractKotlinCompileTasks(): List<Task> { val inputList = (kotlinTasksConfigurator.invoke() ?: emptyList()).filterNotNull() val (paths, other) = inputList.partition { it is String } val taskContainer = project.tasks val tasksByPath = paths.map { taskContainer.findByPath(it as String) ?: throw IllegalArgumentException("Task with path '$it' not found") } other .filter { it !is Task || it isNotInstance getAbstractKotlinCompileFor(it) } .forEach { throw IllegalArgumentException("Illegal entry in kotlinTasks, must be subtype of $ABSTRACT_KOTLIN_COMPILE or String, but was $it") } tasksByPath .filter { it == null || it isNotInstance getAbstractKotlinCompileFor(it) } .forEach { throw IllegalArgumentException("Illegal task path in kotlinTasks, must be subtype of $ABSTRACT_KOTLIN_COMPILE, but was $it") } return (tasksByPath + other) as List<Task> } private fun extractClasspathAndSourceRootsFromKotlinTasks(): ClasspathAndSourceRoots { val allTasks = kotlinTasks val allClasspath = mutableSetOf<File>() var allClasspathFileCollection: FileCollection = project.files() val allSourceRoots = mutableSetOf<File>() allTasks.forEach { logger.debug("Dokka found AbstractKotlinCompile task: $it") with(ReflectDsl) { val taskSourceRoots: List<File> = it["sourceRootsContainer"]["sourceRoots"].v() val abstractKotlinCompileClz = getAbstractKotlinCompileFor(it)!! val taskClasspath: Iterable<File> = (it["getClasspath", AbstractCompile::class].takeIfIsFunc()?.invoke() ?: it["compileClasspath", abstractKotlinCompileClz].takeIfIsProp()?.v() ?: it["getClasspath", abstractKotlinCompileClz]()) if (taskClasspath is FileCollection) { allClasspathFileCollection += taskClasspath } else { allClasspath += taskClasspath } allSourceRoots += taskSourceRoots.filter { it.exists() } } } return ClasspathAndSourceRoots(allClasspathFileCollection + project.files(allClasspath), allSourceRoots.toList()) } private fun Iterable<File>.toSourceRoots(): List<SourceRoot> = this.filter { it.exists() }.map { SourceRoot().apply { path = it.path } } protected open fun collectSuppressedFiles(sourceRoots: List<SourceRoot>): List<String> = emptyList() @TaskAction fun generate() { val kotlinColorsEnabledBefore = System.getProperty(COLORS_ENABLED_PROPERTY) ?: "false" System.setProperty(COLORS_ENABLED_PROPERTY, "false") try { loadFatJar() val (tasksClasspath, tasksSourceRoots) = kotlinCompileBasedClasspathAndSourceRoots val project = project val sourceRoots = collectSourceRoots() + tasksSourceRoots.toSourceRoots() if (sourceRoots.isEmpty()) { logger.warn("No source directories found: skipping dokka generation") return } val fullClasspath = collectClasspathFromOldSources() + tasksClasspath + classpath val bootstrapClass = fatJarClassLoader!!.loadClass("org.jetbrains.dokka.DokkaBootstrapImpl") val bootstrapInstance = bootstrapClass.constructors.first().newInstance() val bootstrapProxy: DokkaBootstrap = automagicTypedProxy(javaClass.classLoader, bootstrapInstance) val configuration = SerializeOnlyDokkaConfiguration( moduleName, fullClasspath.map { it.absolutePath }, sourceRoots, samples.filterNotNull().map { project.file(it).absolutePath }, includes.filterNotNull().map { project.file(it).absolutePath }, outputDirectory, outputFormat, includeNonPublic, false, reportUndocumented, skipEmptyPackages, skipDeprecated, jdkVersion, generateClassIndexPage, generatePackageIndexPage, linkMappings, impliedPlatforms, perPackageOptions, externalDocumentationLinks, noStdlibLink, noJdkLink, cacheRoot, collectSuppressedFiles(sourceRoots), languageVersion, apiVersion, collectInheritedExtensionsFromLibraries, outlineRoot, dacRoot) bootstrapProxy.configure( BiConsumer { level, message -> when (level) { "info" -> logger.info(message) "warn" -> logger.warn(message) "error" -> logger.error(message) } }, serialize(configuration) ) bootstrapProxy.generate() } finally { System.setProperty(COLORS_ENABLED_PROPERTY, kotlinColorsEnabledBefore) } } private fun collectClasspathFromOldSources(): List<File> { val allConfigurations = project.configurations val fromConfigurations = processConfigurations.flatMap { allConfigurations.getByName(it.toString()) } return fromConfigurations } private fun collectSourceRoots(): List<SourceRoot> { val sourceDirs = if (sourceDirs.any()) { logger.info("Dokka: Taking source directories provided by the user") sourceDirs.toSet() } else if (kotlinTasks.isEmpty()) { project.convention.findPlugin(JavaPluginConvention::class.java)?.let { javaPluginConvention -> logger.info("Dokka: Taking source directories from default java plugin") val sourceSets = javaPluginConvention.sourceSets.findByName(SourceSet.MAIN_SOURCE_SET_NAME) sourceSets?.allSource?.srcDirs } } else { emptySet() } return sourceRoots + (sourceDirs?.toSourceRoots() ?: emptyList()) } @Classpath fun getInputClasspath(): FileCollection { val (classpathFileCollection) = extractClasspathAndSourceRootsFromKotlinTasks() return project.files(collectClasspathFromOldSources() + classpath) + classpathFileCollection } @InputFiles fun getInputFiles(): FileCollection { val (_, tasksSourceRoots) = extractClasspathAndSourceRootsFromKotlinTasks() return project.files(tasksSourceRoots.map { project.fileTree(it) }) + project.files(collectSourceRoots().map { project.fileTree(File(it.path)) }) + project.files(includes) + project.files(samples.filterNotNull().map { project.fileTree(it) }) } @OutputDirectory fun getOutputDirectoryAsFile(): File = project.file(outputDirectory) companion object { const val COLORS_ENABLED_PROPERTY = "kotlin.colors.enabled" const val ABSTRACT_KOTLIN_COMPILE = "org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile" private fun getAbstractKotlinCompileFor(task: Task) = try { task.project.buildscript.classLoader.loadClass(ABSTRACT_KOTLIN_COMPILE) } catch (e: ClassNotFoundException) { null } } } class SourceRoot : DokkaConfiguration.SourceRoot, Serializable { override var path: String = "" set(value) { field = File(value).absolutePath } override var platforms: List<String> = arrayListOf() override fun toString(): String { return "${platforms.joinToString()}::$path" } } open class LinkMapping : Serializable, DokkaConfiguration.SourceLinkDefinition { @JsonExclude var dir: String get() = path set(value) { path = value } override var path: String = "" override var url: String = "" @JsonExclude var suffix: String? get() = lineSuffix set(value) { lineSuffix = value } override var lineSuffix: String? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as LinkMapping if (path != other.path) return false if (url != other.url) return false if (lineSuffix != other.lineSuffix) return false return true } override fun hashCode(): Int { var result = path.hashCode() result = 31 * result + url.hashCode() result = 31 * result + (lineSuffix?.hashCode() ?: 0) return result } companion object { const val serialVersionUID: Long = -8133501684312445981L } } class PackageOptions : Serializable, DokkaConfiguration.PackageOptions { override var prefix: String = "" override var includeNonPublic: Boolean = false override var reportUndocumented: Boolean = true override var skipDeprecated: Boolean = false override var suppress: Boolean = false }
runners/gradle-plugin/src/main/kotlin/main.kt
1432331512
package org.jetbrains.dokka.gradle import org.junit.Test // TODO: add tests back class JavadocRSuppressionTest : AbstractAndroidAppTest("androidAppJavadoc") { // @Test // fun `test kotlin 1_1_2-5 and gradle 4_0 and abt 3_0_0-alpha3`() { // doTest("4.0", "1.1.2-5", AndroidPluginParams("3.0.0-alpha3", "25.0.2", 25)) // } // // @Test // fun `test kotlin 1_1_2 and gradle 3_5 and abt 2_3_0`() { // doTest("3.5", "1.1.2", AndroidPluginParams("2.3.0", "25.0.0", 24)) // } // // @Test // fun `test kotlin 1_0_7 and gradle 2_14_1 and abt 2_2_3`() { // doTest("2.14.1", "1.0.7", AndroidPluginParams("2.2.3", "25.0.0", 24)) // } // // @Test fun `test kotlin 1_2_20 and gradle 4_5 and abt 3_0_1`() { // doTest("4.5", "1.2.20", AndroidPluginParams("3.0.1", "27.0.0", 27)) // } }
runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/JavadocRSuppressionTest.kt
179091401
package com.ddu.icore.common.ext import android.app.Activity import android.app.Service import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Bundle import android.os.Parcelable import java.io.Serializable object ICoreInternals { @JvmStatic fun <T> createIntent(ctx: Context, clazz: Class<out T>, vararg args: Pair<String, Any?>): Intent { val intent = Intent(ctx, clazz) if (args.isNotEmpty()) { fillIntentArguments(intent, *args) } return intent } @JvmStatic fun internalStartActivity( ctx: Context, activity: Class<out Activity>, vararg args: Pair<String, Any?> ) { ctx.startActivity(createIntent(ctx, activity, *args)) } @JvmStatic fun internalStartActivityForResult( act: Activity, activity: Class<out Activity>, requestCode: Int, vararg args: Pair<String, Any?> ) { act.startActivityForResult(createIntent(act, activity, *args), requestCode) } @JvmStatic fun internalStartService( ctx: Context, service: Class<out Service>, vararg args: Pair<String, Any?> ): ComponentName? = ctx.startService(createIntent(ctx, service, *args)) @JvmStatic fun internalStopService( ctx: Context, service: Class<out Service>, vararg args: Pair<String, Any?> ): Boolean = ctx.stopService(createIntent(ctx, service, *args)) @JvmStatic fun fillIntentArguments(intent: Intent, vararg pairs: Pair<String, Any?>) { intent.apply { for ((key, value) in pairs) { when (value) { null -> putExtra(key, null as Serializable?) // Any nullable type will suffice. // Scalars is Boolean -> putExtra(key, value) is Byte -> putExtra(key, value) is Char -> putExtra(key, value) is Double -> putExtra(key, value) is Float -> putExtra(key, value) is Int -> putExtra(key, value) is Long -> putExtra(key, value) is Short -> putExtra(key, value) // References is String -> putExtra(key, value) is Bundle -> putExtra(key, value) is CharSequence -> putExtra(key, value) is Parcelable -> putExtra(key, value) // Last resort. Also we must check this after Array<*> as all arrays are serializable. is Serializable -> putExtra(key, value) // Scalar arrays is BooleanArray -> putExtra(key, value) is ByteArray -> putExtra(key, value) is CharArray -> putExtra(key, value) is DoubleArray -> putExtra(key, value) is FloatArray -> putExtra(key, value) is IntArray -> putExtra(key, value) is LongArray -> putExtra(key, value) is ShortArray -> putExtra(key, value) // Reference arrays is Array<*> -> { val componentType = value::class.java.componentType!! @Suppress("UNCHECKED_CAST") // Checked by reflection. when { Parcelable::class.java.isAssignableFrom(componentType) -> { putExtra(key, value as Array<Parcelable>) } String::class.java.isAssignableFrom(componentType) -> { putExtra(key, value as Array<String>) } CharSequence::class.java.isAssignableFrom(componentType) -> { putExtra(key, value as Array<CharSequence>) } Int::class.java.isAssignableFrom(componentType) -> { putExtra(key, value as Array<Int>) } else -> { val valueType = componentType.canonicalName throw IllegalArgumentException( "Illegal value array type $valueType for key \"$key\"") } } } } } } } }
icore/src/main/java/com/ddu/icore/common/ext/ICoreInternals.kt
3212497876
package com.habitrpg.android.habitica.ui.fragments.inventory.items import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.data.SocialRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.databinding.FragmentItemsBinding import com.habitrpg.android.habitica.extensions.addCloseButton import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.interactors.FeedPetUseCase import com.habitrpg.android.habitica.interactors.HatchPetUseCase import com.habitrpg.android.habitica.models.inventory.Egg import com.habitrpg.android.habitica.models.inventory.Food import com.habitrpg.android.habitica.models.inventory.HatchingPotion import com.habitrpg.android.habitica.models.inventory.Item import com.habitrpg.android.habitica.models.inventory.Pet import com.habitrpg.android.habitica.models.inventory.QuestContent import com.habitrpg.android.habitica.models.inventory.SpecialItem import com.habitrpg.android.habitica.models.user.OwnedPet import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.BaseActivity import com.habitrpg.android.habitica.ui.activities.MainActivity import com.habitrpg.android.habitica.ui.adapter.inventory.ItemRecyclerAdapter import com.habitrpg.android.habitica.ui.fragments.BaseDialogFragment import com.habitrpg.android.habitica.ui.helpers.EmptyItem import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator import com.habitrpg.android.habitica.ui.helpers.loadImage import com.habitrpg.android.habitica.ui.views.dialogs.OpenedMysteryitemDialog import javax.inject.Inject class ItemDialogFragment : BaseDialogFragment<FragmentItemsBinding>(), SwipeRefreshLayout.OnRefreshListener { @Inject lateinit var inventoryRepository: InventoryRepository @Inject lateinit var socialRepository: SocialRepository @Inject lateinit var userRepository: UserRepository @Inject lateinit var hatchPetUseCase: HatchPetUseCase @Inject lateinit var feedPetUseCase: FeedPetUseCase var adapter: ItemRecyclerAdapter? = null var itemType: String? = null var itemTypeText: String? = null var isHatching: Boolean = false var isFeeding: Boolean = false internal var hatchingItem: Item? = null var feedingPet: Pet? = null var user: User? = null internal var layoutManager: androidx.recyclerview.widget.LinearLayoutManager? = null override var binding: FragmentItemsBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentItemsBinding { return FragmentItemsBinding.inflate(inflater, container, false) } override fun onDestroy() { inventoryRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { when { this.isHatching -> { dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE) } this.isFeeding -> { dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE) } else -> { } } return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.refreshLayout?.setOnRefreshListener(this) binding?.recyclerView?.emptyItem = EmptyItem( getString(R.string.empty_items, itemTypeText ?: itemType), getString(R.string.open_market) ) { openMarket() } val context = activity layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) binding?.recyclerView?.layoutManager = layoutManager adapter = binding?.recyclerView?.adapter as? ItemRecyclerAdapter if (adapter == null) { context?.let { adapter = ItemRecyclerAdapter(context) adapter?.isHatching = this.isHatching adapter?.isFeeding = this.isFeeding adapter?.fragment = this } if (this.hatchingItem != null) { adapter?.hatchingItem = this.hatchingItem } if (this.feedingPet != null) { adapter?.feedingPet = this.feedingPet } binding?.recyclerView?.adapter = adapter adapter?.let { adapter -> compositeSubscription.add( adapter.getSellItemFlowable() .flatMap { item -> inventoryRepository.sellItem(item) } .subscribe({ }, RxErrorHandler.handleEmptyError()) ) compositeSubscription.add( adapter.getQuestInvitationFlowable() .flatMap { quest -> inventoryRepository.inviteToQuest(quest) } .flatMap { socialRepository.retrieveGroup("party") } .subscribe( { if (isModal) { dismiss() } else { MainNavigationController.navigate(R.id.partyFragment) } }, RxErrorHandler.handleEmptyError() ) ) compositeSubscription.add( adapter.getOpenMysteryItemFlowable() .flatMap { inventoryRepository.openMysteryItem(user) } .doOnNext { val activity = activity as? MainActivity if (activity != null) { val dialog = OpenedMysteryitemDialog(activity) dialog.isCelebratory = true dialog.setTitle(R.string.mystery_item_title) dialog.binding.iconView.loadImage("shop_${it.key}") dialog.binding.titleView.text = it.text dialog.binding.descriptionView.text = it.notes dialog.addButton(R.string.equip, true) { _, _ -> inventoryRepository.equip("equipped", it.key ?: "").subscribe({}, RxErrorHandler.handleEmptyError()) } dialog.addCloseButton() dialog.enqueue() } } .subscribe({ }, RxErrorHandler.handleEmptyError()) ) compositeSubscription.add(adapter.hatchPetEvents.subscribeWithErrorHandler { hatchPet(it.first, it.second) }) compositeSubscription.add(adapter.feedPetEvents.subscribeWithErrorHandler { feedPet(it) }) } } activity?.let { binding?.recyclerView?.addItemDecoration(androidx.recyclerview.widget.DividerItemDecoration(it, androidx.recyclerview.widget.DividerItemDecoration.VERTICAL)) } binding?.recyclerView?.itemAnimator = SafeDefaultItemAnimator() if (savedInstanceState != null) { this.itemType = savedInstanceState.getString(ITEM_TYPE_KEY, "") } when { this.isHatching -> { binding?.titleTextView?.text = getString(R.string.hatch_with, this.hatchingItem?.text) binding?.titleTextView?.visibility = View.VISIBLE binding?.footerTextView?.text = getString(R.string.hatching_market_info) binding?.footerTextView?.visibility = View.VISIBLE binding?.openMarketButton?.visibility = View.VISIBLE } this.isFeeding -> { binding?.titleTextView?.text = getString(R.string.dialog_feeding, this.feedingPet?.text) binding?.titleTextView?.visibility = View.VISIBLE binding?.footerTextView?.text = getString(R.string.feeding_market_info) binding?.footerTextView?.visibility = View.VISIBLE binding?.openMarketButton?.visibility = View.VISIBLE } else -> { binding?.titleTextView?.visibility = View.GONE binding?.footerTextView?.visibility = View.GONE binding?.openMarketButton?.visibility = View.GONE } } binding?.openMarketButton?.setOnClickListener { dismiss() openMarket() } this.loadItems() } private fun feedPet(food: Food) { val pet = feedingPet ?: return (activity as? BaseActivity)?.let { it.compositeSubscription.add( feedPetUseCase.observable( FeedPetUseCase.RequestValues( pet, food, it ) ).subscribeWithErrorHandler {} ) } } override fun onResume() { if ((this.isHatching || this.isFeeding) && dialog?.window != null) { val params = dialog?.window?.attributes params?.width = ViewGroup.LayoutParams.MATCH_PARENT params?.verticalMargin = 60f dialog?.window?.attributes = params } super.onResume() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(ITEM_TYPE_KEY, this.itemType) } override fun onRefresh() { binding?.refreshLayout?.isRefreshing = true compositeSubscription.add( userRepository.retrieveUser(true, true) .doOnTerminate { binding?.refreshLayout?.isRefreshing = false }.subscribe({ }, RxErrorHandler.handleEmptyError()) ) } private fun hatchPet(potion: HatchingPotion, egg: Egg) { dismiss() (activity as? BaseActivity)?.let { it.compositeSubscription.add( hatchPetUseCase.observable( HatchPetUseCase.RequestValues( potion, egg, it ) ).subscribeWithErrorHandler {} ) } } private fun loadItems() { val itemClass: Class<out Item> = when (itemType) { "eggs" -> Egg::class.java "hatchingPotions" -> HatchingPotion::class.java "food" -> Food::class.java "quests" -> QuestContent::class.java "special" -> SpecialItem::class.java else -> Egg::class.java } itemType?.let { type -> compositeSubscription.add( inventoryRepository.getOwnedItems(type) .doOnNext { items -> val filteredItems = if (isFeeding) { items.filter { it.key != "Saddle" } } else { items } adapter?.data = filteredItems } .map { items -> items.mapNotNull { it.key } } .flatMap { inventoryRepository.getItems(itemClass, it.toTypedArray()) } .map { val itemMap = mutableMapOf<String, Item>() for (item in it) { itemMap[item.key] = item } itemMap } .subscribe( { items -> adapter?.items = items }, RxErrorHandler.handleEmptyError() ) ) } compositeSubscription.add(inventoryRepository.getPets().subscribe({ adapter?.setExistingPets(it) }, RxErrorHandler.handleEmptyError())) compositeSubscription.add( inventoryRepository.getOwnedPets() .map { ownedMounts -> val mountMap = mutableMapOf<String, OwnedPet>() ownedMounts.forEach { mountMap[it.key ?: ""] = it } return@map mountMap } .subscribe({ adapter?.setOwnedPets(it) }, RxErrorHandler.handleEmptyError()) ) } private fun openMarket() { MainNavigationController.navigate(R.id.marketFragment) } companion object { private const val ITEM_TYPE_KEY = "CLASS_TYPE_KEY" } }
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/items/ItemDialogFragment.kt
1161643906
/* * 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.lifecycle import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.launch /** * Flow operator that emits values from `this` upstream Flow when the [lifecycle] is * at least at [minActiveState] state. The emissions will be stopped when the lifecycle state * falls below [minActiveState] state. * * The flow will automatically start and cancel collecting from `this` upstream flow as the * [lifecycle] moves in and out of the target state. * * If [this] upstream Flow completes emitting items, `flowWithLifecycle` will trigger the flow * collection again when the [minActiveState] state is reached. * * This is NOT a terminal operator. This operator is usually followed by [collect], or * [onEach] and [launchIn] to process the emitted values. * * Note: this operator creates a hot flow that only closes when the [lifecycle] is destroyed or * the coroutine that collects from the flow is cancelled. * * ``` * class MyActivity : AppCompatActivity() { * override fun onCreate(savedInstanceState: Bundle?) { * /* ... */ * // Launches a coroutine that collects items from a flow when the Activity * // is at least started. It will automatically cancel when the activity is stopped and * // start collecting again whenever it's started again. * lifecycleScope.launch { * flow * .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED) * .collect { * // Consume flow emissions * } * } * } * } * ``` * * `flowWithLifecycle` cancels the upstream Flow when [lifecycle] falls below * [minActiveState] state. However, the downstream Flow will be active without receiving any * emissions as long as the scope used to collect the Flow is active. As such, please take care * when using this function in an operator chain, as the order of the operators matters. For * example, `flow1.flowWithLifecycle(lifecycle).combine(flow2)` behaves differently than * `flow1.combine(flow2).flowWithLifecycle(lifecycle)`. The former continues to combine both * flows even when [lifecycle] falls below [minActiveState] state whereas the combination is * cancelled in the latter case. * * Warning: [Lifecycle.State.INITIALIZED] is not allowed in this API. Passing it as a * parameter will throw an [IllegalArgumentException]. * * Tip: If multiple flows need to be collected using `flowWithLifecycle`, consider using * the [Lifecycle.repeatOnLifecycle] API to collect from all of them using a different * [launch] per flow instead. That's more efficient and consumes less resources as no hot flows * are created. * * @param lifecycle The [Lifecycle] where the restarting collecting from `this` flow work will be * kept alive. * @param minActiveState [Lifecycle.State] in which the upstream flow gets collected. The * collection will stop if the lifecycle falls below that state, and will restart if it's in that * state again. * @return [Flow] that only emits items from `this` upstream flow when the [lifecycle] is at * least in the [minActiveState]. */ @OptIn(ExperimentalCoroutinesApi::class) public fun <T> Flow<T>.flowWithLifecycle( lifecycle: Lifecycle, minActiveState: Lifecycle.State = Lifecycle.State.STARTED ): Flow<T> = callbackFlow { lifecycle.repeatOnLifecycle(minActiveState) { [email protected] { send(it) } } close() }
lifecycle/lifecycle-runtime-ktx/src/main/java/androidx/lifecycle/FlowExt.kt
1410125910
/* * 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. */ @file:Suppress("unused", "UnstableApiUsage") package androidx.paging.samples import androidx.annotation.Sampled import androidx.paging.ListenableFuturePagingSource import androidx.paging.PagingState import com.google.common.util.concurrent.FluentFuture import com.google.common.util.concurrent.ListenableFuture import retrofit2.HttpException import java.io.IOException import java.util.concurrent.Executor data class RemoteResult( val items: List<Item>, val prev: String, val next: String ) private class GuavaBackendService { @Suppress("UNUSED_PARAMETER") fun searchUsers(searchTerm: String, pageKey: String?): FluentFuture<RemoteResult> { throw NotImplementedError() } } lateinit var networkExecutor: Executor @Sampled fun listenableFuturePagingSourceSample() { class MyListenableFuturePagingSource( val myBackend: GuavaBackendService, val searchTerm: String ) : ListenableFuturePagingSource<String, Item>() { override fun loadFuture( params: LoadParams<String> ): ListenableFuture<LoadResult<String, Item>> { return myBackend .searchUsers( searchTerm = searchTerm, pageKey = params.key ) .transform<LoadResult<String, Item>>( { response -> LoadResult.Page( data = response!!.items, prevKey = response.prev, nextKey = response.next ) }, networkExecutor ) // Retrofit calls that return the body type throw either IOException for // network failures, or HttpException for any non-2xx HTTP status codes. // This code reports all errors to the UI, but you can inspect/wrap the // exceptions to provide more context. .catching( IOException::class.java, { t: IOException? -> LoadResult.Error(t!!) }, networkExecutor ) .catching( HttpException::class.java, { t: HttpException? -> LoadResult.Error(t!!) }, networkExecutor ) } override fun getRefreshKey(state: PagingState<String, Item>): String? { return state.anchorPosition?.let { state.closestItemToPosition(it)?.id } } } }
paging/samples/src/main/java/androidx/paging/samples/ListenableFuturePagingSourceSample.kt
1105801272
package com.simplemobiletools.commons.dialogs import android.view.animation.AnimationUtils import com.simplemobiletools.commons.R import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.extensions.applyColorFilter import com.simplemobiletools.commons.extensions.getAlertDialogBuilder import com.simplemobiletools.commons.extensions.getProperTextColor import com.simplemobiletools.commons.extensions.setupDialogStuff import kotlinx.android.synthetic.main.dialog_call_confirmation.view.* class CallConfirmationDialog(val activity: BaseSimpleActivity, val callee: String, private val callback: () -> Unit) { private var view = activity.layoutInflater.inflate(R.layout.dialog_call_confirmation, null) init { view.call_confirm_phone.applyColorFilter(activity.getProperTextColor()) activity.getAlertDialogBuilder() .setNegativeButton(R.string.cancel, null) .apply { val title = String.format(activity.getString(R.string.call_person), callee) activity.setupDialogStuff(view, this, titleText = title) { alertDialog -> view.call_confirm_phone.apply { startAnimation(AnimationUtils.loadAnimation(activity, R.anim.pulsing_animation)) setOnClickListener { callback.invoke() alertDialog.dismiss() } } } } } }
commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/CallConfirmationDialog.kt
1016979750
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.framework import com.intellij.codeInspection.LocalInspectionTool import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture import com.intellij.testFramework.fixtures.JavaTestFixtureFactory import com.intellij.testFramework.fixtures.TempDirTestFixture import com.intellij.testFramework.fixtures.impl.LightTempDirTestFixtureImpl import kotlin.reflect.KClass import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach abstract class ProjectBuilderTest(descriptor: LightProjectDescriptor? = null) { protected val fixture: JavaCodeInsightTestFixture protected val project: Project get() = fixture.project protected val module: Module get() = fixture.module private val tempDirFixture: TempDirTestFixture init { val lightFixture = IdeaTestFixtureFactory.getFixtureFactory() .createLightFixtureBuilder(descriptor) .fixture // This is a poorly named class - it actually means create a temp dir test fixture _in-memory_ tempDirFixture = LightTempDirTestFixtureImpl(true) fixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(lightFixture, tempDirFixture) } fun buildProject(builder: ProjectBuilder.() -> Unit) = ProjectBuilder(fixture, tempDirFixture).build(builder) fun JavaCodeInsightTestFixture.enableInspections(vararg classes: KClass<out LocalInspectionTool>) { this.enableInspections(classes.map { it.java }) } @NoEdt @BeforeEach fun setup() { fixture.setUp() } @AfterEach fun tearDown() { fixture.tearDown() } }
src/test/kotlin/framework/ProjectBuilderTest.kt
718892287
/* * Copyright (C) 2015 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.data import android.provider.BaseColumns import org.andstatus.app.database.table.ActivityTable import org.andstatus.app.database.table.ActorTable import org.andstatus.app.database.table.DownloadTable import org.andstatus.app.database.table.NoteTable import java.util.* object ProjectionMap { val ACTIVITY_TABLE_ALIAS: String = "act1" val NOTE_TABLE_ALIAS: String = "msg1" val ATTACHMENT_IMAGE_TABLE_ALIAS: String = "img" /** * Projection map used by SQLiteQueryBuilder * Projection map for a Timeline * @see android.database.sqlite.SQLiteQueryBuilder.setProjectionMap */ val TIMELINE: MutableMap<String, String> = HashMap() init { TIMELINE[ActivityTable.ACTIVITY_ID] = (ACTIVITY_TABLE_ALIAS + "." + BaseColumns._ID + " AS " + ActivityTable.ACTIVITY_ID) TIMELINE[ActivityTable.ORIGIN_ID] = ActivityTable.ORIGIN_ID TIMELINE[ActivityTable.ACCOUNT_ID] = ActivityTable.ACCOUNT_ID TIMELINE[ActivityTable.ACTIVITY_TYPE] = ActivityTable.ACTIVITY_TYPE TIMELINE[ActivityTable.ACTOR_ID] = ActivityTable.ACTOR_ID TIMELINE[ActivityTable.AUTHOR_ID] = ActivityTable.AUTHOR_ID TIMELINE[ActivityTable.NOTE_ID] = ActivityTable.NOTE_ID TIMELINE[ActivityTable.OBJ_ACTOR_ID] = ActivityTable.OBJ_ACTOR_ID TIMELINE[ActivityTable.SUBSCRIBED] = ActivityTable.SUBSCRIBED TIMELINE[ActivityTable.NOTIFIED] = ActivityTable.NOTIFIED TIMELINE[ActivityTable.INS_DATE] = ActivityTable.INS_DATE TIMELINE[ActivityTable.UPDATED_DATE] = ActivityTable.UPDATED_DATE TIMELINE[BaseColumns._ID] = NOTE_TABLE_ALIAS + "." + BaseColumns._ID + " AS " + BaseColumns._ID TIMELINE[NoteTable.NOTE_ID] = NOTE_TABLE_ALIAS + "." + BaseColumns._ID + " AS " + NoteTable.NOTE_ID TIMELINE[NoteTable.ORIGIN_ID] = NoteTable.ORIGIN_ID TIMELINE[NoteTable.NOTE_OID] = NoteTable.NOTE_OID TIMELINE[NoteTable.CONVERSATION_ID] = NoteTable.CONVERSATION_ID TIMELINE[NoteTable.AUTHOR_ID] = NoteTable.AUTHOR_ID TIMELINE[ActorTable.AUTHOR_NAME] = ActorTable.AUTHOR_NAME TIMELINE[DownloadTable.DOWNLOAD_STATUS] = DownloadTable.DOWNLOAD_STATUS TIMELINE[DownloadTable.FILE_NAME] = DownloadTable.FILE_NAME TIMELINE[DownloadTable.IMAGE_FILE_NAME] = (ATTACHMENT_IMAGE_TABLE_ALIAS + "." + DownloadTable.FILE_NAME + " AS " + DownloadTable.IMAGE_FILE_NAME) TIMELINE[DownloadTable.IMAGE_ID] = (ATTACHMENT_IMAGE_TABLE_ALIAS + "." + BaseColumns._ID + " AS " + DownloadTable.IMAGE_ID) TIMELINE[DownloadTable.IMAGE_URI] = (ATTACHMENT_IMAGE_TABLE_ALIAS + "." + DownloadTable.URL + " AS " + DownloadTable.IMAGE_URI) TIMELINE[DownloadTable.PREVIEW_OF_DOWNLOAD_ID] = DownloadTable.PREVIEW_OF_DOWNLOAD_ID TIMELINE[DownloadTable.WIDTH] = DownloadTable.WIDTH TIMELINE[DownloadTable.HEIGHT] = DownloadTable.HEIGHT TIMELINE[DownloadTable.DURATION] = DownloadTable.DURATION TIMELINE[NoteTable.NAME] = NoteTable.NAME TIMELINE[NoteTable.SUMMARY] = NoteTable.SUMMARY TIMELINE[NoteTable.SENSITIVE] = NoteTable.SENSITIVE TIMELINE[NoteTable.CONTENT] = NoteTable.CONTENT TIMELINE[NoteTable.CONTENT_TO_SEARCH] = NoteTable.CONTENT_TO_SEARCH TIMELINE[NoteTable.VIA] = NoteTable.VIA TIMELINE[NoteTable.URL] = NoteTable.URL TIMELINE[NoteTable.IN_REPLY_TO_NOTE_ID] = NoteTable.IN_REPLY_TO_NOTE_ID TIMELINE[NoteTable.IN_REPLY_TO_ACTOR_ID] = NoteTable.IN_REPLY_TO_ACTOR_ID TIMELINE[NoteTable.VISIBILITY] = NoteTable.VISIBILITY TIMELINE[NoteTable.FAVORITED] = NoteTable.FAVORITED TIMELINE[NoteTable.REBLOGGED] = NoteTable.REBLOGGED TIMELINE[NoteTable.LIKES_COUNT] = NoteTable.LIKES_COUNT TIMELINE[NoteTable.REBLOGS_COUNT] = NoteTable.REBLOGS_COUNT TIMELINE[NoteTable.REPLIES_COUNT] = NoteTable.REPLIES_COUNT TIMELINE[NoteTable.UPDATED_DATE] = NoteTable.UPDATED_DATE TIMELINE[NoteTable.NOTE_STATUS] = NoteTable.NOTE_STATUS TIMELINE[NoteTable.INS_DATE] = NoteTable.INS_DATE TIMELINE[NoteTable.ATTACHMENTS_COUNT] = NoteTable.ATTACHMENTS_COUNT } }
app/src/main/kotlin/org/andstatus/app/data/ProjectionMap.kt
1968681648
/* * Copyright 2017 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.powermanager.model import android.support.annotation.CheckResult interface PermissionObserver { @CheckResult fun hasPermission(): Boolean }
powermanager-model/src/main/java/com/pyamsoft/powermanager/model/PermissionObserver.kt
1667486415
package info.metadude.android.eventfahrplan.commons.temporal import org.threeten.bp.Instant import org.threeten.bp.OffsetDateTime import org.threeten.bp.ZoneId import org.threeten.bp.ZoneOffset import org.threeten.bp.ZonedDateTime import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.format.FormatStyle /** * Format timestamps according to system locale and system time zone. */ class DateFormatter private constructor( val useDeviceTimeZone: Boolean ) { private val timeShortNumberOnlyFormatter = DateTimeFormatter.ofPattern("HH:mm") private val timeShortFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT) private val dateShortFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT) private val dateShortTimeShortFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT) private val dateLongTimeShortFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT) private val dateFullTimeShortFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.SHORT) private val timeZoneOffsetFormatter = DateTimeFormatter.ofPattern("z") /** * Returns a formatted `hours:minutes` string. Formatting happens by taking the [original time * zone of the associated session][sessionZoneOffset] into account. If [sessionZoneOffset] is * missing then formatting falls back to using the current time zone offset of the device. * * The returned text is formatted equally for all locales, e.g. 01:00, 14:00 etc. - always * without AM or PM postfix - in 24 hours format. */ fun getFormattedTime24Hour(moment: Moment, sessionZoneOffset: ZoneOffset?): String { val zoneOffset = getAvailableZoneOffset(sessionZoneOffset) return timeShortNumberOnlyFormatter.format(moment.toZonedDateTime(zoneOffset)) } /** * Returns 01:00 AM, 02:00 PM, 14:00 etc, depending on current system locale either * in 24 or 12 hour format. The latter featuring AM or PM postfixes. * * Formatting happens by taking the [original time zone of the associated session][sessionZoneOffset] * into account. If [sessionZoneOffset] is missing then formatting falls back to using the * current time zone offset of the device. */ fun getFormattedTime(time: Long, sessionZoneOffset: ZoneOffset?): String { val zoneOffset = getAvailableZoneOffset(sessionZoneOffset) return timeShortFormatter.withZone(zoneOffset).format(Instant.ofEpochMilli(time)) } /** * Returns day, month and year in current system locale. * E.g. 1/22/19 or 22.01.19 * * Formatting happens by taking the [original time zone of the associated session][sessionZoneOffset] * into account. If [sessionZoneOffset] is missing then formatting falls back to using the * current time zone offset of the device. */ fun getFormattedDate(time: Long, sessionZoneOffset: ZoneOffset?): String { val zoneOffset = getAvailableZoneOffset(sessionZoneOffset) return dateShortFormatter.withZone(zoneOffset).format(Instant.ofEpochMilli(time)) } /** * Returns a formatted string suitable for sharing it with people worldwide. * It consists of day, month, year, time, time zone offset in the time zone of the event or * in current system time zone if the former is not provided. * * The human readable name '{area}/{city}' of the time zone ID is appended if available. * * Formatting example: * Tuesday, January 22, 2019, 1:00 AM GMT+01:00 (Europe/Berlin) */ fun getFormattedShareable(time: Long, timeZoneId: ZoneId?): String { val displayTimeZone = timeZoneId ?: ZoneId.systemDefault() val sessionStartTime = Instant.ofEpochMilli(time) val timeZoneOffset = timeZoneOffsetFormatter.withZone(displayTimeZone).format(sessionStartTime) val sessionDateTime = dateFullTimeShortFormatter.withZone(displayTimeZone).format(sessionStartTime) var shareableText = "$sessionDateTime $timeZoneOffset" if (timeZoneId != null) { shareableText += " (${displayTimeZone.id})" } return shareableText } /** * Returns day, month, year and time in short format. Formatting happens by taking the [original * time zone of the associated session][sessionZoneOffset] into account. If [sessionZoneOffset] * is missing then formatting falls back to using the current time zone offset of the device. * * E.g. 1/22/19, 1:00 AM */ fun getFormattedDateTimeShort(time: Long, sessionZoneOffset: ZoneOffset?): String { val zoneOffset = getAvailableZoneOffset(sessionZoneOffset) val toZonedDateTime: ZonedDateTime = Moment.ofEpochMilli(time).toZonedDateTime(zoneOffset) return dateShortTimeShortFormatter.format(toZonedDateTime) } /** * Returns day, month, year and time in long format. Formatting happens by taking the [original * time zone of the associated session][sessionZoneOffset] into account. If [sessionZoneOffset] * is missing then formatting falls back to using the current time zone offset of the device. * * E.g. January 22, 2019, 1:00 AM */ fun getFormattedDateTimeLong(time: Long, sessionZoneOffset: ZoneOffset?): String { val zoneOffset = getAvailableZoneOffset(sessionZoneOffset) val toZonedDateTime = Moment.ofEpochMilli(time).toZonedDateTime(zoneOffset) return dateLongTimeShortFormatter.format(toZonedDateTime) } /** * Returns the available zone offset - either the given [sessionZoneOffset] or the zone offset * of the device. The user can overrule the logic by setting [useDeviceTimeZone]. */ private fun getAvailableZoneOffset(sessionZoneOffset: ZoneOffset?): ZoneOffset { val deviceZoneOffset = OffsetDateTime.now().offset val useDeviceZoneOffset = sessionZoneOffset == null || sessionZoneOffset == deviceZoneOffset return if (useDeviceTimeZone || useDeviceZoneOffset) deviceZoneOffset else sessionZoneOffset!! } companion object { @JvmStatic fun newInstance(useDeviceTimeZone: Boolean): DateFormatter { return DateFormatter(useDeviceTimeZone) } } }
commons/src/main/java/info/metadude/android/eventfahrplan/commons/temporal/DateFormatter.kt
2160111817
package com.veyndan.paper.reddit import com.veyndan.paper.reddit.api.reddit.Reddit interface Filter { fun requestFilter(): Reddit.Filter }
app/src/main/java/com/veyndan/paper/reddit/Filter.kt
731865478
package me.proxer.app.anime.resolver import android.net.Uri import io.reactivex.Single import me.proxer.app.MainApplication.Companion.USER_AGENT import me.proxer.app.exception.StreamResolutionException import me.proxer.app.util.extension.buildSingle import me.proxer.app.util.extension.toBodySingle import me.proxer.app.util.extension.toPrefixedUrlOrNull import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Request /** * @author Ruben Gees */ object ProxerStreamResolver : StreamResolver() { private val regex = Regex("<source type=\"(.*?)\" src=\"(.*?)\">") override val name = "Proxer-Stream" override fun resolve(id: String): Single<StreamResolutionResult> { return api.anime.vastLink(id) .buildSingle() .flatMap { (link, adTag) -> client .newCall( Request.Builder() .get() .url(link.toPrefixedUrlOrNull() ?: throw StreamResolutionException()) .header("User-Agent", USER_AGENT) .header("Connection", "close") .build() ) .toBodySingle() .map { val regexResult = regex.find(it) ?: throw StreamResolutionException() val url = regexResult.groupValues[2].toHttpUrlOrNull() ?: throw StreamResolutionException() val type = regexResult.groupValues[1] val adTagUri = if (adTag.isNotBlank()) Uri.parse(adTag) else null StreamResolutionResult.Video(url, type, adTag = adTagUri) } } } }
src/main/kotlin/me/proxer/app/anime/resolver/ProxerStreamResolver.kt
2748867551
package at.ac.tuwien.caa.docscan.db.model.state /** * The locked state describes restricted writing/editing access to [Document]s and [Page]s. * * E.g. if an upload or export is performed, the file states should be preserved, otherwise * it could easily happen, that while a large document upload is ongoing, someone meanwhile * deletes/modifies or adds a new page. */ enum class LockState(val id: String) { /** * Neither a document, nor any of the pages are locked. They can be modified. */ NONE("NONE"), /** * Some of the document pages are locked, but not the entire document itself, i.e. a page * could be added to the document, while another page is being processed. */ PARTIAL_LOCK("PARTIAL_LOCK"), /** * The entire document, with all of if its pages is locked, it cannot be modified, neither * any of its data. */ FULL_LOCK("FULL_LOCK"); fun isLocked(): Boolean { return when (this) { NONE -> false PARTIAL_LOCK, FULL_LOCK -> true } } companion object { fun getLockStateById(id: String?): LockState { id ?: return NONE values().forEach { value -> if (value.id == id) { return value } } return NONE } } }
app/src/main/java/at/ac/tuwien/caa/docscan/db/model/state/LockState.kt
2353295990
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.ads.dto import com.google.gson.annotations.SerializedName import kotlin.String enum class AdsGetStatisticsIdsType( val value: String ) { @SerializedName("ad") AD("ad"), @SerializedName("campaign") CAMPAIGN("campaign"), @SerializedName("client") CLIENT("client"), @SerializedName("office") OFFICE("office"); }
api/src/main/java/com/vk/sdk/api/ads/dto/AdsGetStatisticsIdsType.kt
3681051008
package eu.kanade.tachiyomi.extension.en.readgoblinslayermangaonline import eu.kanade.tachiyomi.multisrc.mangacatalog.MangaCatalog import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.util.asJsoup import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.Request import rx.Observable import org.jsoup.nodes.Document import org.jsoup.nodes.Element class ReadGoblinSlayerMangaOnline : MangaCatalog("Read Goblin Slayer Manga Online", "https://manga.watchgoblinslayer.com", "en") { override val sourceList = listOf( Pair("Goblin Slayer", "$baseUrl/manga/goblin-slayer/"), Pair("Side Story: Brand New Day", "$baseUrl/manga/goblin-slayer-side-story-brand-new-day/"), Pair("Side Story: Year One", "$baseUrl/manga/goblin-slayer-side-story-year-one/"), Pair("Side Story: Gaiden 2", "$baseUrl/manga/goblin-slayer-gaiden-2-tsubanari-no-daikatana/"), ).sortedBy { it.first }.distinctBy { it.second } override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply { description = document.select("div.card-body > p").text() title = document.select("h2 > span").text() thumbnail_url = document.select(".card-img-right").attr("src") } override fun chapterListSelector(): String = "tbody > tr" override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply { name = element.select("td:first-child").text() url = element.select("a.btn-primary").attr("abs:href") date_upload = System.currentTimeMillis() //I have no idear how to parse Date stuff } }
multisrc/overrides/mangacatalog/readgoblinslayermangaonline/src/ReadGoblinSlayerMangaOnline.kt
2959910612
package reagent.operator import reagent.runTest import reagent.source.emptyObservable import reagent.source.observableOf import reagent.tester.testObservable import kotlin.test.Test class ObservableIgnoreElementsTest { @Test fun empty() = runTest { emptyObservable() .ignoreElements() .testObservable { complete() } } @Test fun items() = runTest { observableOf(1, 2, 3) .ignoreElements() .testObservable { complete() } } }
reagent/common/src/test/kotlin/reagent/operator/ObservableIgnoreElementsTest.kt
1636036848
package eu.kanade.tachiyomi.extension.pt.neoxxxscans import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.multisrc.madara.Madara import okhttp3.OkHttpClient import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit @Nsfw class NeoXXXScans : Madara( "NeoXXX Scans", "https://xxx.neoxscans.net", "pt-BR", SimpleDateFormat("dd/MM/yyyy", Locale("pt", "BR")) ) { override val client: OkHttpClient = super.client.newBuilder() .addInterceptor(RateLimitInterceptor(1, 2, TimeUnit.SECONDS)) .build() }
multisrc/overrides/madara/neoxxxscans/src/NeoXXXScans.kt
23750574
package com.eden.orchid.mock import java.util.Collections.emptyList /** * This class _freaking awesome_ class links to [KotlinInterface], **yo**! */ class KotlinClassGenerics<T : Any> /** * This class _freaking awesome_ constructor links to [KotlinInterface], **yo**! * * @param s1 This class _freaking awesome_ param links to [KotlinInterface], **yo**! */ constructor(s1: T?) { constructor(s2: String) : this(null) /** * This class _freaking awesome_ field links to [KotlinInterface], **yo**! */ var someData = "" /** * This class _freaking awesome_ field links to [KotlinInterface], **yo**! */ lateinit var someData2: String /** * This class _freaking awesome_ field links to [KotlinInterface], **yo**! */ lateinit var someData3: T /** * This class _freaking awesome_ field links to [KotlinInterface], **yo**! */ lateinit var someData4: List<String> /** * This class _freaking awesome_ field links to [KotlinInterface], **yo**! */ lateinit var someData5: List<T> /** * This class _freaking awesome_ field links to [KotlinInterface], **yo**! */ lateinit var someData5: List<KotlinClassGenerics<String>> /** * This class _freaking awesome_ method links to [KotlinInterface], **yo**! * * @param s1 This class _freaking awesome_ param links to [KotlinInterface], **yo**! * @return This class _freaking awesome_ return value links to [KotlinInterface], **yo**! */ fun doThing(s1: String): String { return "" } /** * This class _freaking awesome_ method links to [KotlinInterface], **yo**! * * @param s1 This class _freaking awesome_ param links to [KotlinInterface], **yo**! * @return This class _freaking awesome_ return value links to [KotlinInterface], **yo**! */ fun doThing2(s1: T): T? { return null } /** * This class _freaking awesome_ method links to [KotlinInterface], **yo**! * * @param s1 This class _freaking awesome_ param links to [KotlinInterface], **yo**! * @return This class _freaking awesome_ return value links to [KotlinInterface], **yo**! */ fun doThing3(s1: List<String>): List<String> { return emptyList() } /** * This class _freaking awesome_ method links to [KotlinInterface], **yo**! * * @param s1 This class _freaking awesome_ param links to [KotlinInterface], **yo**! * @return This class _freaking awesome_ return value links to [KotlinInterface], **yo**! */ fun doThing4(s1: List<T>): List<T> { return emptyList() } }
plugins/OrchidKotlindoc/src/mockKotlin/com/eden/orchid/mock/KotlinClassGenerics.kt
2289411704
package org.xdty.callerinfo.contract import android.content.Context import org.xdty.callerinfo.model.db.Caller import org.xdty.callerinfo.model.db.InCall import org.xdty.phone.number.model.INumber import org.xdty.phone.number.model.caller.Status interface MainContract { interface View : BaseView<Presenter> { fun showNoCallLog(show: Boolean) fun showLoading(active: Boolean) fun showCallLogs(inCalls: List<InCall>) fun showEula() fun showSearchResult(number: INumber) fun showSearching() fun showSearchFailed(isOnline: Boolean) fun attachCallerMap(callerMap: Map<String, Caller>) val context: Context fun notifyUpdateData(status: Status) fun showUpdateData(status: Status) fun updateDataFinished(result: Boolean) fun showBottomSheet(inCall: InCall) } interface Presenter : BasePresenter { fun result(requestCode: Int, resultCode: Int) fun loadInCallList() fun loadCallerMap() fun removeInCallFromList(inCall: InCall) fun removeInCall(inCall: InCall) fun clearAll() fun search(number: String) fun checkEula() fun setEula() fun canDrawOverlays(): Boolean fun checkPermission(permission: String): Int fun clearSearch() fun dispatchUpdate(status: Status) fun getCaller(number: String): Caller fun clearCache() fun itemOnLongClicked(inCall: InCall) fun invalidateDataUpdate(isInvalidate: Boolean) } }
app/src/main/java/org/xdty/callerinfo/contract/MainContract.kt
2646422485
package com.sebastiansokolowski.auctionhunter.allegro_api.response enum class SellingModeFormat { BUY_NOW, AUCTION, ADVERTISEMENT }
server/src/main/kotlin/com/sebastiansokolowski/auctionhunter/allegro_api/response/SellingModeFormat.kt
3745371177
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.checks import com.felipebz.flr.api.AstNode import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.annotations.* import org.sonar.plugins.plsqlopen.api.symbols.Scope import org.sonar.plugins.plsqlopen.api.symbols.Symbol @Rule(priority = Priority.MAJOR, tags = [Tags.UNUSED]) @ConstantRemediation("2min") @RuleInfo(scope = RuleInfo.Scope.ALL) @ActivatedByDefault class UnusedVariableCheck : AbstractBaseCheck() { override fun leaveFile(node: AstNode) { val scopes = context.symbolTable.scopes for (scope in scopes) { if (scope.tree().isNot(PlSqlGrammar.CREATE_PACKAGE, PlSqlGrammar.FOR_STATEMENT)) { checkScope(scope) } } } private fun checkScope(scope: Scope) { val symbols = scope.getSymbols(Symbol.Kind.VARIABLE) for (symbol in symbols) { if (symbol.usages().isEmpty()) { addIssue(symbol.declaration(), getLocalizedMessage(), symbol.declaration().tokenOriginalValue) } } } }
zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/UnusedVariableCheck.kt
1981815997
/* * Copyright (C) 2016, 2020-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.xpath.psi.blockOpen import uk.co.reecedunn.intellij.plugin.xpath.psi.isEmptyEnclosedExpr import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryUnorderedExpr class XQueryUnorderedExprPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQueryUnorderedExpr, XpmSyntaxValidationElement { // region XpmExpression override val expressionElement: PsiElement? = null // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() { val blockOpen = blockOpen return when (blockOpen?.isEmptyEnclosedExpr) { true -> blockOpen else -> firstChild } } // endregion }
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryUnorderedExprPsiImpl.kt
487632774
/* * Copyright (C) 2016-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xdm.types.XdmSequenceType import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathEQName import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryCaseClause class XQueryCaseClausePsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQueryCaseClause { // region PsiElement override fun getUseScope(): SearchScope = LocalSearchScope(this) // endregion // region XpmVariableBinding override val variableName: XsQNameValue? get() = children().filterIsInstance<XPathEQName>().firstOrNull() // endregion // region XpmAssignableVariable override val variableType: XdmSequenceType? get() = children().filterIsInstance<XdmSequenceType>().firstOrNull() override val variableExpression: XpmExpression? get() = parent.children().filterIsInstance<XpmExpression>().firstOrNull() // endregion }
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryCaseClausePsiImpl.kt
639339058
// Copyright (C) 2016, 2018, 2022 Reece H. Dunn. SPDX-License-Identifier: Apache-2.0 package xqt.platform.intellij.lexer.token import com.intellij.lang.Language import com.intellij.psi.tree.IElementType import org.jetbrains.annotations.NonNls import xqt.platform.xml.lexer.tokens.NCNameTokenType /** * An NCName token in an IntelliJ implementation of an XQT language. * * This can also be a keyword as keywords are valid NCNames. */ open class INCNameTokenType(@NonNls debugName: String, language: Language) : IElementType(debugName, language), NCNameTokenType { override val symbol: String = "NCName" }
src/xqt-platform-intellij/main/xqt/platform/intellij/lexer/token/INCNameTokenType.kt
699798658
package com.netflix.spinnaker.orca.pipeline.model import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty data class SourceControl @JsonCreator constructor( @param:JsonProperty("name") val name: String, @param:JsonProperty("branch") val branch: String, @param:JsonProperty("sha1") val sha1: String )
orca-core/src/main/java/com/netflix/spinnaker/orca/pipeline/model/SourceControl.kt
1231965172
package app.errors import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes import org.springframework.boot.autoconfigure.web.ErrorAttributes import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.web.context.request.RequestAttributes @Configuration class ErrorConfig { /** * This is required because not all errors are caught by ControllerAdvice. * It overrides default Spring Boot behaviour. */ @Bean fun errorAttributes(): ErrorAttributes { return object : DefaultErrorAttributes() { override fun getErrorAttributes(requestAttributes: RequestAttributes, includeStackTrace: Boolean): Map<String, Any?> { val message = super.getErrorAttributes(requestAttributes, includeStackTrace)["message"] if (message is String) { return ErrorResponse("UNKNOWN_ERROR", message).asMap() } else { return ErrorResponse("UNKNOWN_ERROR", null).asMap() } } } } }
backend/src/main/kotlin/app/errors/ErrorConfig.kt
1980739769
package org.stepic.droid.analytic enum class LoginInteractionType { ime, button; }
app/src/main/java/org/stepic/droid/analytic/LoginInteractionType.kt
2151681685
package org.stepik.android.domain.video_player.analytic import org.stepik.android.domain.base.analytic.AnalyticEvent class VideoPlayerControlClickedEvent( action: String ) : AnalyticEvent { companion object { private const val PARAM_ACTION = "action" const val ACTION_PREVIOS = "previos" const val ACTION_REWIND = "rewind" const val ACTION_FORWARD = "forward" const val ACTION_NEXT = "next" const val ACTION_SEEK_BACK = "seek_back" const val ACTION_SEEK_FORWARD = "seek_forward" const val ACTION_DOUBLE_CLICK_LEFT = "double_click_left" const val ACTION_DOUBLE_CLICK_RIGHT = "double_click_right" const val ACTION_PLAY = "play" const val ACTION_PAUSE = "pause" } override val name: String = "Video player control clicked" override val params: Map<String, Any> = mapOf(PARAM_ACTION to action) }
app/src/main/java/org/stepik/android/domain/video_player/analytic/VideoPlayerControlClickedEvent.kt
3742669509
//package org.koin.core // //import kotlin.test.Test //import kotlin.test.assertEquals //import kotlin.test.assertTrue // //class AttributesTest { // // @Test // fun `can store & get an attribute value`() { // val attr = Properties() // // attr.set("myKey", "myString") // // val string = attr.get<String>("myKey") // assertEquals("myString", string) // } // // @Test // fun `attribute empty - no value`() { // val attr = Properties() // // assertTrue(attr.getOrNull<String>("myKey") == null) // } // // @Test // fun `attribute value overwrite`() { // val attr = Properties() // // attr.set("myKey", "myString") // attr.set("myKey", "myString2") // // val string = attr.get<String>("myKey") // assertEquals("myString2", string) // } //}
core/koin-core/src/commonTest/kotlin/org/koin/core/AttributesTest.kt
2574437390
package exh.search import exh.plusAssign import exh.search.SearchEngine.Companion.escapeLike class Text: QueryComponent() { val components = mutableListOf<TextComponent>() private var query: String? = null private var lenientTitleQuery: String? = null private var lenientTagQueries: List<String>? = null private var rawText: String? = null fun asQuery(): String { if(query == null) { query = rBaseBuilder().toString() } return query!! } fun asLenientTitleQuery(): String { if(lenientTitleQuery == null) { lenientTitleQuery = StringBuilder("%").append(rBaseBuilder()).append("%").toString() } return lenientTitleQuery!! } fun asLenientTagQueries(): List<String> { if(lenientTagQueries == null) { lenientTagQueries = listOf( //Match beginning of tag rBaseBuilder().append("%").toString(), //Tag word matcher (that matches multiple words) //Can't make it match a single word in Realm :( StringBuilder(" ").append(rBaseBuilder()).append(" ").toString(), StringBuilder(" ").append(rBaseBuilder()).toString(), rBaseBuilder().append(" ").toString() ) } return lenientTagQueries!! } fun rBaseBuilder(): StringBuilder { val builder = StringBuilder() for(component in components) { when(component) { is StringTextComponent -> builder += escapeLike(component.value) is SingleWildcard -> builder += "_" is MultiWildcard -> builder += "%" } } return builder } fun rawTextOnly() = if(rawText != null) rawText!! else { rawText = components .joinToString(separator = "", transform = { it.rawText }) rawText!! } fun rawTextEscapedForLike() = escapeLike(rawTextOnly()) }
app/src/main/java/exh/search/Text.kt
1345596095
/* * Copyright (c) 2017 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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.deltadna.android.sdk.notifications import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat /** * Factory class responsible for filling details from a push message and * creating a notification to be posted on the UI. * * * The default implementation uses the 'title' and 'alert' fields from the push * message as the title and message respectively for the notification. If the * title has not been defined in the message then the application's name will * be used instead. Upon selection the notification will open the launch * `Intent` of your application. * * * The default behaviour can be customised by extending the class and overriding * [.configure]. The * [NotificationListenerService] will then need to be extended in order * to define the new factory to be used for creating notifications. */ open class NotificationFactory(protected val context: Context) { companion object { /** * Identifier for the default [NotificationChannel] used for * notifications. */ const val DEFAULT_CHANNEL = "com.deltadna.default" } /** * Fills a [androidx.core.app.NotificationCompat.Builder] * with details from a [PushMessage]. * * @param context the context for the notification * @param message the push message * * @return configured notification builder */ open fun configure(context: Context?, message: PushMessage): NotificationCompat.Builder? { var builder: NotificationCompat.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationCompat.Builder(context!!, getChannel().id) } else { NotificationCompat.Builder(context) } builder = builder .setSmallIcon(message.icon) .setContentTitle(message.title) .setContentText(message.message) .setAutoCancel(true) if (message.imageUrl != null) { builder.setLargeIcon(message.imageUrl) .setStyle( NotificationCompat.BigPictureStyle() .bigPicture(message.imageUrl).bigLargeIcon(null) ) } return builder } /** * Creates a [Notification] from a previously configured * [NotificationCompat.Builder] and a [NotificationInfo] * instance. * * Implementations which call * [NotificationCompat.Builder.setContentIntent] * or * [NotificationCompat.Builder.setDeleteIntent] * on the [NotificationCompat.Builder] and thus override the default * behaviour should notify the SDK that the push notification has been * opened or dismissed respectively. * * @param builder the configured notification builder * @param info the notification info * * @return notification to post on the UI, or `null` if a * notification shouldn't be posted * * @see EventReceiver */ fun create(builder: NotificationCompat.Builder, info: NotificationInfo): Notification? { val intentFlags: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT } else { PendingIntent.FLAG_UPDATE_CURRENT } builder.setContentIntent(createContentIntent(info, intentFlags)) builder.setDeleteIntent(createDeleteIntent(info, intentFlags)) return builder.build() } /** * Gets the [NotificationChannel] to be used for configuring the * push notification. * * The [.DEFAULT_CHANNEL] is used as the default identifier. * * @return notification channel to be used */ @RequiresApi(Build.VERSION_CODES.O) protected fun getChannel(): NotificationChannel { val channel = NotificationChannel( DEFAULT_CHANNEL, context.getString(R.string.ddna_notification_channel_name), NotificationManager.IMPORTANCE_DEFAULT ) (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) .createNotificationChannel(channel) return channel } /** * Creates the intent which is used when a user opens the host app from a notification. In most * cases, this will be a set of two activities - our DeltaDNA tracking activity that records the * opened notification, and the host app's launch intent. Once the deltaDNA Intent completes, the * launch intent will be shown as part of Android's normal behaviour, and won't be blocked by the * trampolining prevention that blocks launching intents from Broadcast Receivers. */ private fun createContentIntent(info: NotificationInfo, intentFlags: Int): PendingIntent { val notificationOpenedHandlerClass = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { NotificationOpenedHandlerAndroid23AndHigher::class.java } else { NotificationOpenedHandlerPreAndroid23::class.java } val notificationOpenedHandlerIntent = Intent(context, notificationOpenedHandlerClass) .setPackage(context.packageName) .setAction(Actions.NOTIFICATION_OPENED_INTERNAL) .putExtra(Actions.NOTIFICATION_INFO, info) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) // Only ever have one notification opened tracking activity val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName) if (launchIntent == null) { // If the app hasn't specified a launch intent, we just use our notification handler activity, to still enable notificationOpened tracking. return PendingIntent.getActivity(context, info.id, notificationOpenedHandlerIntent, intentFlags) } else { // If the app specifies a launch intent, we add it to the activity stack, so that once we've finished capturing the notificationOpened behaviour // the app will open as normal, without the need for a BroadcastReceiver trampoline which is no longer allowed in Android 12. launchIntent.setPackage(null) // This makes the app start as if it was launched externally, preventing duplicate activities from being created launchIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED val intents: Array<Intent> = arrayOf(launchIntent, notificationOpenedHandlerIntent) return PendingIntent.getActivities(context, info.id, intents, intentFlags) } } /** * Creates the intent which is used when a user dismisses our push notification without opening it. Now * that we've moved to using a custom activity to track notification opens, and we previously had no custom * behaviour on notification dismissed, we can instead directly signal our notifications receiver that the notification * was dismissed, instead of relaying via an intermediate broadcast receiver. */ private fun createDeleteIntent(info: NotificationInfo, intentFlags: Int): PendingIntent { val intent = Intent(Actions.NOTIFICATION_DISMISSED) synchronized(DDNANotifications::class.java) { if (DDNANotifications.receiver != null) { intent.setClass(context, DDNANotifications.receiver!!) } } return PendingIntent.getBroadcast( context, info.id, intent, intentFlags ) } }
library-notifications/src/main/java/com/deltadna/android/sdk/notifications/NotificationFactory.kt
721656059
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2021 Asqatasun.org * * This file is part of Asqatasun. * * Asqatasun is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.crawler import org.asqatasun.entity.audit.AuditImpl import org.asqatasun.entity.parameterization.Parameter import org.asqatasun.entity.parameterization.ParameterElementImpl import org.asqatasun.entity.parameterization.ParameterImpl import org.asqatasun.entity.service.subject.WebResourceDataService import org.asqatasun.entity.subject.PageImpl import org.asqatasun.entity.subject.SiteImpl import org.junit.jupiter.api.Test import org.mockito.Matchers.anyString import org.mockito.Mockito import org.mockito.Mockito.never import org.mockito.Mockito.times class CrawlerImplTest { private val webResourceDataService: WebResourceDataService = Mockito.mock(WebResourceDataService::class.java) companion object { private const val URL = "https://site-robot.asqatasun.ovh/" private const val rootPageUrl = URL private const val depthOnePageUrl = URL + "page-1.html" private const val depthTwoPageUrl = URL + "page-2.html" private const val robotsAccessForbiddenPageUrl = URL + "page-access-forbidden-for-robots.html" private const val politenessDelay = 100 } @Test fun crawlSiteDepth0() { crawlSite(0, listOf(rootPageUrl), listOf(depthOnePageUrl, depthTwoPageUrl, robotsAccessForbiddenPageUrl)) } @Test fun crawlSiteDepth1() { crawlSite(1, listOf(rootPageUrl, depthOnePageUrl), listOf(depthTwoPageUrl, robotsAccessForbiddenPageUrl)) } @Test fun crawlSiteDepth2() { crawlSite(2, listOf(rootPageUrl, depthOnePageUrl, depthTwoPageUrl), listOf(robotsAccessForbiddenPageUrl)) } @Test fun crawlSiteDepth2AndNotRespectRobotsTxtDirectives() { crawlSite(2, listOf(rootPageUrl, depthOnePageUrl, depthTwoPageUrl, robotsAccessForbiddenPageUrl), listOf(), false) } private fun crawlSite(depth: Int, calledUrlList: List<String>, neverCalledUrlList: List<String>, respectRobotsTxt: Boolean = true) { val site = SiteImpl() Mockito.`when`(webResourceDataService.createSite(URL)).thenReturn(site) Mockito.`when`(webResourceDataService.createPage(anyString())).thenReturn(PageImpl()) Mockito.`when`(webResourceDataService.saveOrUpdate(site)).thenReturn(site) val audit = AuditImpl() audit.parameterSet = setParameters(depth, respectRobotsTxt) val crawler = CrawlerImpl(audit, URL, webResourceDataService, "", "", "", "", emptyList(), politenessDelay) crawler.run() calledUrlList.forEach { Mockito.verify(webResourceDataService, times(1)).createPage(it) } neverCalledUrlList.forEach { Mockito.verify(webResourceDataService, never()).createPage(it) } } private fun setParameters(depth: Int, respectRobotsTxt: Boolean): Set<Parameter> { val param1 = ParameterImpl() param1.value = "10" val paramElem1 = ParameterElementImpl() paramElem1.parameterElementCode = "MAX_DOCUMENTS" param1.parameterElement = paramElem1 val param2 = ParameterImpl() param2.value = depth.toString() val paramElem2 = ParameterElementImpl() paramElem2.parameterElementCode = "DEPTH" param2.parameterElement = paramElem2 val param3 = ParameterImpl() param3.value = "" val paramElem3 = ParameterElementImpl() paramElem3.parameterElementCode = "INCLUSION_REGEXP" param3.parameterElement = paramElem3 val param4 = ParameterImpl() param4.value = "" val paramElem4 = ParameterElementImpl() paramElem4.parameterElementCode = "EXCLUSION_REGEXP" param4.parameterElement = paramElem4 val param5 = ParameterImpl() param5.value = "600" val paramElem5 = ParameterElementImpl() paramElem5.parameterElementCode = "MAX_DURATION" param5.parameterElement = paramElem5 val param6 = ParameterImpl() param6.value = respectRobotsTxt.toString() val paramElem6 = ParameterElementImpl() paramElem6.parameterElementCode = "ROBOTS_TXT_ACTIVATION" param6.parameterElement = paramElem6 return setOf(param1, param2, param3, param4, param5, param6) } }
engine/crawler/src/test/kotlin/org/asqatasun/crawler/CrawlerImplTest.kt
3158006872
package com.apollographql.apollo3.fetcher import com.apollographql.apollo3.api.Optional import com.apollographql.apollo3.exception.ApolloException import com.apollographql.apollo3.integration.normalizer.EpisodeHeroNameQuery import com.apollographql.apollo3.integration.normalizer.type.Episode import com.apollographql.apollo3.isFromCache import com.google.common.truth.Truth import com.google.common.truth.Truth.assertThat import okhttp3.mockwebserver.MockResponse import org.junit.Test import java.io.IOException import java.net.HttpURLConnection class CacheAndNetworkFetcherTest : BaseFetcherTest() { @Test @Throws(IOException::class, ApolloException::class) fun enqueue() { val query = EpisodeHeroNameQuery(episode = Episode.EMPIRE) var trackingCallback: TrackingCallback // Has error when cache empty, and network error server.enqueue(MockResponse().setResponseCode(HttpURLConnection.HTTP_INTERNAL_ERROR).setBody("Server Error")) trackingCallback = TrackingCallback() apolloClient.query(query).responseFetcher(ApolloResponseFetchers.CACHE_AND_NETWORK).enqueue(trackingCallback) Truth.assertThat(trackingCallback.exceptions.size).isEqualTo(1) // Goes to network when cache empty, one response server.enqueue(mockResponse("HeroNameResponse.json")) trackingCallback = TrackingCallback() apolloClient.query(query).responseFetcher(ApolloResponseFetchers.CACHE_AND_NETWORK).enqueue(trackingCallback) Truth.assertThat(trackingCallback.exceptions).isEmpty() Truth.assertThat(trackingCallback.responseList.size).isEqualTo(1) Truth.assertThat(trackingCallback.responseList[0].isFromCache).isFalse() assertThat(trackingCallback.responseList[0].data!!.hero?.name).isEqualTo("R2-D2") // Goes to network and cache after cache populated server.enqueue(mockResponse("HeroNameResponse.json")) trackingCallback = TrackingCallback() apolloClient.query(query).responseFetcher(ApolloResponseFetchers.CACHE_AND_NETWORK).enqueue(trackingCallback) Truth.assertThat(trackingCallback.exceptions).isEmpty() Truth.assertThat(trackingCallback.responseList.size).isEqualTo(2) // Cache is always first Truth.assertThat(trackingCallback.responseList[0].isFromCache).isTrue() assertThat(trackingCallback.responseList[0].data!!.hero?.name).isEqualTo("R2-D2") Truth.assertThat(trackingCallback.responseList[1].isFromCache).isFalse() assertThat(trackingCallback.responseList[1].data!!.hero?.name).isEqualTo("R2-D2") // Falls back to cache if network error server.enqueue(MockResponse().setResponseCode(HttpURLConnection.HTTP_INTERNAL_ERROR).setBody("Server Error")) trackingCallback = TrackingCallback() apolloClient.query(query).responseFetcher(ApolloResponseFetchers.CACHE_AND_NETWORK).enqueue(trackingCallback) Truth.assertThat(trackingCallback.exceptions).hasSize(1) Truth.assertThat(trackingCallback.responseList.size).isEqualTo(1) Truth.assertThat(trackingCallback.responseList[0].isFromCache).isTrue() assertThat(trackingCallback.responseList[0].data!!.hero?.name).isEqualTo("R2-D2") } }
composite/integration-tests/src/testShared/kotlin/com/apollographql/apollo3/fetcher/CacheAndNetworkFetcherTest.kt
2219962009
package info.nightscout.androidaps.plugins.pump.medtronic.events import info.nightscout.androidaps.events.Event class EventMedtronicPumpValuesChanged : Event()
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/events/EventMedtronicPumpValuesChanged.kt
2055352801
package me.toptas.rssreader.mock import me.toptas.rssreader.features.main.MainRepository import me.toptas.rssreader.model.Feed class MockMainRepository : MainRepository { override fun parseFeeds(): List<Feed> { return MockData.FEEDS } }
app/src/test/java/me/toptas/rssreader/mock/MockMainRepository.kt
4119832236
package abi44_0_0.expo.modules.facedetector import android.os.Bundle import com.google.android.gms.vision.face.Landmark import com.google.firebase.ml.vision.face.FirebaseVisionFace import com.google.firebase.ml.vision.common.FirebaseVisionPoint object FaceDetectorUtils { @JvmStatic @JvmOverloads fun serializeFace(face: FirebaseVisionFace, scaleX: Double = 1.0, scaleY: Double = 1.0): Bundle { val encodedFace = Bundle().apply { putInt("faceID", face.trackingId) putDouble("rollAngle", face.headEulerAngleZ.toDouble()) putDouble("yawAngle", face.headEulerAngleY.toDouble()) if (face.smilingProbability >= 0) { putDouble("smilingProbability", face.smilingProbability.toDouble()) } if (face.leftEyeOpenProbability >= 0) { putDouble("leftEyeOpenProbability", face.leftEyeOpenProbability.toDouble()) } if (face.rightEyeOpenProbability >= 0) { putDouble("rightEyeOpenProbability", face.rightEyeOpenProbability.toDouble()) } LandmarkId.values() .forEach { id -> face.getLandmark(id.id)?.let { faceLandmark -> putBundle(id.name, mapFromPoint(faceLandmark.position, scaleX, scaleY)) } } val box = face.boundingBox val origin = Bundle(2).apply { putDouble("x", box.left * scaleX) putDouble("y", box.top * scaleY) } val size = Bundle(2).apply { putDouble("width", (box.right - box.left) * scaleX) putDouble("height", (box.bottom - box.top) * scaleY) } val bounds = Bundle(2).apply { putBundle("origin", origin) putBundle("size", size) } putBundle("bounds", bounds) } return mirrorRollAngle(encodedFace) } @JvmStatic fun rotateFaceX(face: Bundle, sourceWidth: Int, scaleX: Double): Bundle { val faceBounds = face.getBundle("bounds") as Bundle val oldOrigin = faceBounds.getBundle("origin") val mirroredOrigin = positionMirroredHorizontally(oldOrigin, sourceWidth, scaleX) val translateX = - (faceBounds.getBundle("size") as Bundle).getDouble("width") val translatedMirroredOrigin = positionTranslatedHorizontally(mirroredOrigin, translateX) val newBounds = Bundle(faceBounds).apply { putBundle("origin", translatedMirroredOrigin) } face.apply { LandmarkId.values().forEach { id -> face.getBundle(id.name)?.let { landmark -> val mirroredPosition = positionMirroredHorizontally(landmark, sourceWidth, scaleX) putBundle(id.name, mirroredPosition) } } putBundle("bounds", newBounds) } return mirrorYawAngle(mirrorRollAngle(face)) } private fun mirrorRollAngle(face: Bundle) = face.apply { putDouble("rollAngle", (-face.getDouble("rollAngle") + 360) % 360) } private fun mirrorYawAngle(face: Bundle) = face.apply { putDouble("yawAngle", (-face.getDouble("yawAngle") + 360) % 360) } private fun mapFromPoint(point: FirebaseVisionPoint, scaleX: Double, scaleY: Double) = Bundle().apply { putDouble("x", point.x * scaleX) putDouble("y", point.y * scaleY) } private fun positionTranslatedHorizontally(position: Bundle, translateX: Double) = Bundle(position).apply { putDouble("x", position.getDouble("x") + translateX) } private fun positionMirroredHorizontally(position: Bundle?, containerWidth: Int, scaleX: Double) = Bundle(position).apply { putDouble("x", valueMirroredHorizontally(position!!.getDouble("x"), containerWidth, scaleX)) } private fun valueMirroredHorizontally(elementX: Double, containerWidth: Int, scaleX: Double) = -elementX + containerWidth * scaleX // All the landmarks reported by Google Mobile Vision in constants' order. // https://developers.google.com/android/reference/com/google/android/gms/vision/face/Landmark private enum class LandmarkId(val id: Int, val landmarkName: String) { BOTTOM_MOUTH(Landmark.BOTTOM_MOUTH, "bottomMouthPosition"), LEFT_CHEEK(Landmark.LEFT_CHEEK, "leftCheekPosition"), LEFT_EAR(Landmark.LEFT_EAR, "leftEarPosition"), LEFT_EAR_TIP(Landmark.LEFT_EAR_TIP, "leftEarTipPosition"), LEFT_EYE(Landmark.LEFT_EYE, "leftEyePosition"), LEFT_MOUTH(Landmark.LEFT_MOUTH, "leftMouthPosition"), NOSE_BASE(Landmark.NOSE_BASE, "noseBasePosition"), RIGHT_CHEEK(Landmark.RIGHT_CHEEK, "rightCheekPosition"), RIGHT_EAR(Landmark.RIGHT_EAR, "rightEarPosition"), RIGHT_EAR_TIP(Landmark.RIGHT_EAR_TIP, "rightEarTipPosition"), RIGHT_EYE(Landmark.RIGHT_EYE, "rightEyePosition"), RIGHT_MOUTH(Landmark.RIGHT_MOUTH, "rightMouthPosition"); } }
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/facedetector/FaceDetectorUtils.kt
2836562104
package io.boxtape.core.configuration import io.boxtape.withPlaceholdersReplaced import org.apache.commons.lang3.text.StrSubstitutor /** * Project configuration -- allows components * to register properties that will be ultimately written out * and configure the running application * * Not the same as BoxtapeSettings -- which focusses on Boxtape itself */ class Configuration { private val properties: MutableMap<String, String> = hashMapOf() val vagrantSettings = VagrantSettings() fun registerPropertyWithDefault(propertyName: String, defaultValue: String) { properties.put(propertyName, defaultValue) } fun registerPropertyWithoutValue(propertyName:String) { if (!properties.containsKey(propertyName)) { properties.put(propertyName,"") } } fun registerProperty(property: String) { // remove ${ and } at either end val strippedProperty = if (property.startsWith("\${") && property.endsWith("}")) { property.substring(2, property.length() - 1) } else { property } if (strippedProperty.contains(":")) { val keyValue = strippedProperty.splitBy(":") registerPropertyWithDefault(keyValue.get(0), keyValue.get(1)) } else { registerPropertyWithoutValue(strippedProperty) } } fun getValue(property: String): String? { return properties.get(property).withPlaceholdersReplaced(properties) } fun hasProperty(property: String): Boolean { return properties.contains(property) } fun asStrings(): List<String> { return properties.map { "${it.key}=${it.value.withPlaceholdersReplaced(properties)}" } } fun addForwardedPort(hostPort: String, guestPort: String) { vagrantSettings.addForwardedPort(hostPort, guestPort) } fun resolveProperties(source: Map<String, Any>): Map<String,Any> { fun internalResolveProperties(value:Any):Any { return when (value) { is String -> value.withPlaceholdersReplaced(properties) is List<*> -> value.map { internalResolveProperties(it as Any) } is Map<*,*> -> resolveProperties(value as Map<String, Any>) else -> value } } val result:MutableMap<String,Any> = hashMapOf() val updated = source.map { entry -> val resolved = internalResolveProperties(entry.value) Pair(entry.key,resolved) } result.plusAssign(updated) return result } }
src/main/java/io/boxtape/core/configuration/Configuration.kt
2385629396
package io.github.notsyncing.lightfur.entity.read import io.github.notsyncing.lightfur.DataSession import io.github.notsyncing.lightfur.entity.EntityModel import java.util.concurrent.CompletableFuture interface EntityModelListReader<T: EntityModel> : EntityModelReader<T> { fun getList(db: DataSession<*, *, *>): CompletableFuture<List<T>> { return query().execute(db) .thenApply { (l, _) -> l } } }
lightfur-entity/src/main/kotlin/io/github/notsyncing/lightfur/entity/read/EntityModelListReader.kt
2570703205
/* * Copyright 2013 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire import okio.ByteString.Companion.decodeHex object TestAllTypesData { const val expectedToString = ( "" + "AllTypes{opt_int32=111, opt_uint32=112, opt_sint32=113, opt_fixed32=114, opt_sfixed32=115," + " opt_int64=116, opt_uint64=117, opt_sint64=118, opt_fixed64=119, opt_sfixed64=120, opt_boo" + "l=true, opt_float=122.0, opt_double=123.0, opt_string=124, opt_bytes=[hex=7de1], opt_neste" + "d_enum=A, opt_nested_message=NestedMessage{a=999}, req_int32=111, req_uint32=112, req_sint" + "32=113, req_fixed32=114, req_sfixed32=115, req_int64=116, req_uint64=117, req_sint64=118, " + "req_fixed64=119, req_sfixed64=120, req_bool=true, req_float=122.0, req_double=123.0, req_s" + "tring=124, req_bytes=[hex=7de1], req_nested_enum=A, req_nested_message=NestedMessage{a=999" + "}, rep_int32=[111, 111], rep_uint32=[112, 112], rep_sint32=[113, 113], rep_fixed32=[114, 1" + "14], rep_sfixed32=[115, 115], rep_int64=[116, 116], rep_uint64=[117, 117], rep_sint64=[118" + ", 118], rep_fixed64=[119, 119], rep_sfixed64=[120, 120], rep_bool=[true, true], rep_float=" + "[122.0, 122.0], rep_double=[123.0, 123.0], rep_string=[124, 124], rep_bytes=[[hex=7de1], [" + "hex=7de1]], rep_nested_enum=[A, A], rep_nested_message=[NestedMessage{a=999}, NestedMessag" + "e{a=999}], pack_int32=[111, 111], pack_uint32=[112, 112], pack_sint32=[113, 113], pack_fix" + "ed32=[114, 114], pack_sfixed32=[115, 115], pack_int64=[116, 116], pack_uint64=[117, 117], " + "pack_sint64=[118, 118], pack_fixed64=[119, 119], pack_sfixed64=[120, 120], pack_bool=[true" + ", true], pack_float=[122.0, 122.0], pack_double=[123.0, 123.0], pack_nested_enum=[A, A], e" + "xt_opt_bool=true, ext_rep_bool=[true, true], ext_pack_bool=[true, true]}" ) val expectedOutput = ( "" + // optional "08" + // tag = 1, type = 0 "6f" + // value = 111 "10" + // tag = 2, type = 0 "70" + // value = 112 "18" + // tag = 3, type = 0 "e201" + // value = 226 (=113 zig-zag) "25" + // tag = 4, type = 5 "72000000" + // value = 114 (fixed32) "2d" + // tag = 5, type = 5 "73000000" + // value = 115 (sfixed32) "30" + // tag = 6, type = 0 "74" + // value = 116 "38" + // tag = 7, type = 0 "75" + // value = 117 "40" + // tag = 8, type = 0 "ec01" + // value = 236 (=118 zigzag) "49" + // tag = 9, type = 1 "7700000000000000" + // value = 119 "51" + // tag = 10, type = 1 "7800000000000000" + // value = 120 "58" + // tag = 11, type = 0 "01" + // value = 1 (true) "65" + // tag = 12, type = 5 "0000f442" + // value = 122.0F "69" + // tag = 13, type = 1 "0000000000c05e40" + // value = 123.0 "72" + // tag = 14, type = 2 "03" + // length = 3 "313234" + "7a" + // tag = 15, type = 2 "02" + // length = 2 "7de1" + // value = { 125, 225 } "8001" + // tag = 16, type = 0 "01" + // value = 1 "8a01" + // tag = 17, type = 2 "03" + // length = 3 "08" + // nested tag = 1, type = 0 "e707" + // value = 999 // required "a806" + // tag = 101, type = 0 "6f" + // value = 111 "b006" + // tag = 102, type = 0 "70" + // value = 112 "b806" + // tag = 103, type = 0 "e201" + // value = 226 (=113 zig-zag) "c506" + // tag = 104, type = 5 "72000000" + // value = 114 (fixed32) "cd06" + // tag = 105, type = 5 "73000000" + // value = 115 (sfixed32) "d006" + // tag = 106, type = 0 "74" + // value = 116 "d806" + // tag = 107, type = 0 "75" + // value = 117 "e006" + // tag = 108, type = 0 "ec01" + // value = 236 (=118 zigzag) "e906" + // tag = 109, type = 1 "7700000000000000" + // value = 119 "f106" + // tag = 110, type = 1 "7800000000000000" + // value = 120 "f806" + // tag = 111, type = 0 "01" + // value = 1 (true) "8507" + // tag = 112, type = 5 "0000f442" + // value = 122.0F "8907" + // tag = 113, type = 1 "0000000000c05e40" + // value = 123.0 "9207" + // tag = 114, type = 2 "03" + // length = 3 "313234" + // value = "124" "9a07" + // tag = 115, type = 2 "02" + // length = 2 "7de1" + // value = { 125, 225 } "a007" + // tag = 116, type = 0 "01" + // value = 1 "aa07" + // tag = 117, type = 2 "03" + // length = 3 "08" + // nested tag = 1, type = 0 "e707" + // value = 999 // repeated "c80c" + // tag = 201, type = 0 "6f" + // value = 111 "c80c" + // tag = 201, type = 0 "6f" + // value = 111 "d00c" + // tag = 202, type = 0 "70" + // value = 112 "d00c" + // tag = 202, type = 0 "70" + // value = 112 "d80c" + // tag = 203, type = 0 "e201" + // value = 226 (=113 zig-zag) "d80c" + // tag = 203, type = 0 "e201" + // value = 226 (=113 zig-zag) "e50c" + // tag = 204, type = 5 "72000000" + // value = 114 (fixed32) "e50c" + // tag = 204, type = 5 "72000000" + // value = 114 (fixed32) "ed0c" + // tag = 205, type = 5 "73000000" + // value = 115 (sfixed32) "ed0c" + // tag = 205, type = 5 "73000000" + // value = 115 (sfixed32) "f00c" + // tag = 206, type = 0 "74" + // value = 116 "f00c" + // tag = 206, type = 0 "74" + // value = 116 "f80c" + // tag = 207, type = 0 "75" + // value = 117 "f80c" + // tag = 207, type = 0 "75" + // value = 117 "800d" + // tag = 208, type = 0 "ec01" + // value = 236 (=118 zigzag) "800d" + // tag = 208, type = 0 "ec01" + // value = 236 (=118 zigzag) "890d" + // tag = 209, type = 1 "7700000000000000" + // value = 119 "890d" + // tag = 209, type = 1 "7700000000000000" + // value = 119 "910d" + // tag = 210, type = 1 "7800000000000000" + // value = 120 "910d" + // tag = 210, type = 1 "7800000000000000" + // value = 120 "980d" + // tag = 211, type = 0 "01" + // value = 1 (true) "980d" + // tag = 211, type = 0 "01" + // value = 1 (true) "a50d" + // tag = 212, type = 5 "0000f442" + // value = 122.0F "a50d" + // tag = 212, type = 5 "0000f442" + // value = 122.0F "a90d" + // tag = 213, type = 1 "0000000000c05e40" + // value = 123.0 "a90d" + // tag = 213, type = 1 "0000000000c05e40" + // value = 123.0 "b20d" + // tag = 214, type = 2 "03" + // length = 3 "313234" + // value = "124" "b20d" + // tag = 214, type = 2 "03" + // length = 3 "313234" + // value = "124" "ba0d" + // tag = 215, type = 2 "02" + // length = 2 "7de1" + // value = { 125, 225 } "ba0d" + // tag = 215, type = 2 "02" + // length = 2 "7de1" + // value = { 125, 225 } "c00d" + // tag = 216, type = 0 "01" + // value = 1 "c00d" + // tag = 216, type = 0 "01" + // value = 1 "ca0d" + // tag = 217, type = 2 "03" + // length = 3 "08" + // nested tag = 1, type = 0 "e707" + // value = 999 "ca0d" + // tag = 217, type = 2 "03" + // length = 3 "08" + // nested tag = 1, type = 0 "e707" + // value = 999 // packed "ea12" + // tag = 301, type = 2 "02" + // length = 2 "6f" + // value = 111 "6f" + // value = 111 "f212" + // tag = 302, type = 2 "02" + // length = 2 "70" + // value = 112 "70" + // value = 112 "fa12" + // tag = 303, type = 2 "04" + // length = 4 "e201" + // value = 226 (=113 zig-zag) "e201" + // value = 226 (=113 zig-zag) "8213" + // tag = 304, type = 2 "08" + // length = 8 "72000000" + // value = 114 (fixed32) "72000000" + // value = 114 (fixed32) "8a13" + // tag = 305, type = 2 "08" + // length = 8 "73000000" + // value = 115 (sfixed32) "73000000" + // value = 115 (sfixed32) "9213" + // tag = 306, type = 2 "02" + // length = 2 "74" + // value = 116 "74" + // value = 116 "9a13" + // tag = 307, type = 2 "02" + // length = 2 "75" + // value = 117 "75" + // value = 117 "a213" + // tag = 308, type = 2 "04" + // length = 4 "ec01" + // value = 236 (=118 zigzag) "ec01" + // value = 236 (=118 zigzag) "aa13" + // tag = 309, type = 2 "10" + // length = 16 "7700000000000000" + // value = 119 "7700000000000000" + // value = 119 "b213" + // tag = 310, type = 2 "10" + // length = 16 "7800000000000000" + // value = 120 "7800000000000000" + // value = 120 "ba13" + // tag = 311, type = 2 "02" + // length = 2 "01" + // value = 1 (true) "01" + // value = 1 (true) "c213" + // tag = 312, type = 2 "08" + // length = 8 "0000f442" + // value = 122.0F "0000f442" + // value = 122.0F "ca13" + // tag = 313, type = 2 "10" + // length = 16 "0000000000c05e40" + // value = 123.0 "0000000000c05e40" + // value = 123.0 "e213" + // tag = 316, type = 2 "02" + // length = 2 "01" + // value = 1 "01" + // value = 1 // extensions "983f" + // tag = 1011, type = 0 "01" + // value = 1 (true) "b845" + // tag = 1111, type = 0 "01" + // value = 1 (true) "b845" + // tag = 1111, type = 0 "01" + // value = 1 (true) "da4b" + // tag = 1211, type = 2 "02" + // length = 2 "01" + // value = 1 (true) "01" // value = 1 (true) ).decodeHex() // message with 'packed' fields stored non-packed, must still be readable val nonPacked = ( "" + // optional "08" + // tag = 1, type = 0 "6f" + // value = 111 "10" + // tag = 2, type = 0 "70" + // value = 112 "18" + // tag = 3, type = 0 "e201" + // value = 226 (=113 zig-zag) "25" + // tag = 4, type = 5 "72000000" + // value = 114 (fixed32) "2d" + // tag = 5, type = 5 "73000000" + // value = 115 (sfixed32) "30" + // tag = 6, type = 0 "74" + // value = 116 "38" + // tag = 7, type = 0 "75" + // value = 117 "40" + // tag = 8, type = 0 "ec01" + // value = 236 (=118 zigzag) "49" + // tag = 9, type = 1 "7700000000000000" + // value = 119 "51" + // tag = 10, type = 1 "7800000000000000" + // value = 120 "58" + // tag = 11, type = 0 "01" + // value = 1 (true) "65" + // tag = 12, type = 5 "0000f442" + // value = 122.0F "69" + // tag = 13, type = 1 "0000000000c05e40" + // value = 123.0 "72" + // tag = 14, type = 2 "03" + // length = 3 "313234" + "7a" + // tag = 15, type = 2 "02" + // length = 2 "7de1" + // value = { 125, 225 } "8001" + // tag = 16, type = 0 "01" + // value = 1 "8a01" + // tag = 17, type = 2 "03" + // length = 3 "08" + // nested tag = 1, type = 0 "e707" + // value = 999 // required "a806" + // tag = 101, type = 0 "6f" + // value = 111 "b006" + // tag = 102, type = 0 "70" + // value = 112 "b806" + // tag = 103, type = 0 "e201" + // value = 226 (=113 zig-zag) "c506" + // tag = 104, type = 5 "72000000" + // value = 114 (fixed32) "cd06" + // tag = 105, type = 5 "73000000" + // value = 115 (sfixed32) "d006" + // tag = 106, type = 0 "74" + // value = 116 "d806" + // tag = 107, type = 0 "75" + // value = 117 "e006" + // tag = 108, type = 0 "ec01" + // value = 236 (=118 zigzag) "e906" + // tag = 109, type = 1 "7700000000000000" + // value = 119 "f106" + // tag = 110, type = 1 "7800000000000000" + // value = 120 "f806" + // tag = 111, type = 0 "01" + // value = 1 (true) "8507" + // tag = 112, type = 5 "0000f442" + // value = 122.0F "8907" + // tag = 113, type = 1 "0000000000c05e40" + // value = 123.0 "9207" + // tag = 114, type = 2 "03" + // length = 3 "313234" + // value = "124" "9a07" + // tag = 115, type = 2 "02" + // length = 2 "7de1" + // value = { 125, 225 } "a007" + // tag = 116, type = 0 "01" + // value = 1 "aa07" + // tag = 117, type = 2 "03" + // length = 3 "08" + // nested tag = 1, type = 0 "e707" + // value = 999 // repeated "c80c" + // tag = 201, type = 0 "6f" + // value = 111 "c80c" + // tag = 201, type = 0 "6f" + // value = 111 "d00c" + // tag = 202, type = 0 "70" + // value = 112 "d00c" + // tag = 202, type = 0 "70" + // value = 112 "d80c" + // tag = 203, type = 0 "e201" + // value = 226 (=113 zig-zag) "d80c" + // tag = 203, type = 0 "e201" + // value = 226 (=113 zig-zag) "e50c" + // tag = 204, type = 5 "72000000" + // value = 114 (fixed32) "e50c" + // tag = 204, type = 5 "72000000" + // value = 114 (fixed32) "ed0c" + // tag = 205, type = 5 "73000000" + // value = 115 (sfixed32) "ed0c" + // tag = 205, type = 5 "73000000" + // value = 115 (sfixed32) "f00c" + // tag = 206, type = 0 "74" + // value = 116 "f00c" + // tag = 206, type = 0 "74" + // value = 116 "f80c" + // tag = 207, type = 0 "75" + // value = 117 "f80c" + // tag = 207, type = 0 "75" + // value = 117 "800d" + // tag = 208, type = 0 "ec01" + // value = 236 (=118 zigzag) "800d" + // tag = 208, type = 0 "ec01" + // value = 236 (=118 zigzag) "890d" + // tag = 209, type = 1 "7700000000000000" + // value = 119 "890d" + // tag = 209, type = 1 "7700000000000000" + // value = 119 "910d" + // tag = 210, type = 1 "7800000000000000" + // value = 120 "910d" + // tag = 210, type = 1 "7800000000000000" + // value = 120 "980d" + // tag = 211, type = 0 "01" + // value = 1 (true) "980d" + // tag = 211, type = 0 "01" + // value = 1 (true) "a50d" + // tag = 212, type = 5 "0000f442" + // value = 122.0F "a50d" + // tag = 212, type = 5 "0000f442" + // value = 122.0F "a90d" + // tag = 213, type = 1 "0000000000c05e40" + // value = 123.0 "a90d" + // tag = 213, type = 1 "0000000000c05e40" + // value = 123.0 "b20d" + // tag = 214, type = 2 "03" + // length = 3 "313234" + // value = "124" "b20d" + // tag = 214, type = 2 "03" + // length = 3 "313234" + // value = "124" "ba0d" + // tag = 215, type = 2 "02" + // length = 2 "7de1" + // value = { 125, 225 } "ba0d" + // tag = 215, type = 2 "02" + // length = 2 "7de1" + // value = { 125, 225 } "c00d" + // tag = 216, type = 0 "01" + // value = 1 "c00d" + // tag = 216, type = 0 "01" + // value = 1 "ca0d" + // tag = 217, type = 2 "03" + // length = 3 "08" + // nested tag = 1, type = 0 "e707" + // value = 999 "ca0d" + // tag = 217, type = 2 "03" + // length = 3 "08" + // nested tag = 1, type = 0 "e707" + // value = 999 // packed "e812" + // tag = 301, type = 0 "6f" + // value = 111 "e812" + // tag = 301, type = 0 "6f" + // value = 111 "f012" + // tag = 302, type = 0 "70" + // value = 112 "f012" + // tag = 302, type = 0 "70" + // value = 112 "f812" + // tag = 303, type = 0 "e201" + // value = 226 (=113 zig-zag) "f812" + // tag = 303, type = - "e201" + // value = 226 (=113 zig-zag) "8513" + // tag = 304, type = 5 "72000000" + // value = 114 (fixed32) "8513" + // tag = 304, type = 5 "72000000" + // value = 114 (fixed32) "8d13" + // tag = 305, type = 5 "73000000" + // value = 115 (sfixed32) "8d13" + // tag = 305, type = 5 "73000000" + // value = 115 (sfixed32) "9013" + // tag = 306, type = 0 "74" + // value = 116 "9013" + // tag = 306, type = 0 "74" + // value = 116 "9813" + // tag = 307, type = 0 "75" + // value = 117 "9813" + // tag = 307, type = 0 "75" + // value = 117 "a013" + // tag = 308, type = 0 "ec01" + // value = 236 (=118 zigzag) "a013" + // tag = 308, type = 0 "ec01" + // value = 236 (=118 zigzag) "a913" + // tag = 309, type = 0 "7700000000000000" + // value = 119 "a913" + // tag = 309, type = 0 "7700000000000000" + // value = 119 "b113" + // tag = 310, type = 0 "7800000000000000" + // value = 120 "b113" + // tag = 310, type = 0 "7800000000000000" + // value = 120 "b813" + // tag = 311, type = 0 "01" + // value = 1 (true) "b813" + // tag = 311, type = 0 "01" + // value = 1 (true) "c513" + // tag = 312, type = 0 "0000f442" + // value = 122.0F "c513" + // tag = 312, type = 0 "0000f442" + // value = 122.0F "c913" + // tag = 313, type = 0 "0000000000c05e40" + // value = 123.0 "c913" + // tag = 313, type = 0 "0000000000c05e40" + // value = 123.0 "e013" + // tag = 316, type = 0 "01" + // value = 1 "e013" + // tag = 316, type = 0 "01" + // value = 1 // extension "983f" + // tag = 1011, type = 0 "01" + // value = 1 (true) "b845" + // tag = 1111, type = 0 "01" + // value = 1 (true) "b845" + // tag = 1111, type = 0 "01" + // value = 1 (true) "d84b" + // tag = 1211, type = 0 "01" + // value = 1 (true) "d84b" + // tag = 1211, type = 0 "01" // value = 1 (true) ).decodeHex() }
wire-library/wire-tests/src/commonTest/kotlin/com/squareup/wire/TestAllTypesData.kt
603240575
package com.auth0.android.request import java.io.IOException import java.io.Reader /** * Adapter that converts from different sources into the <T> class that represents an error. */ public interface ErrorAdapter<T> { /** * Converts the JSON input given in the Reader to the <T> instance. * @param statusCode the response HTTP status code. * @param reader the reader that contains the JSON encoded string. * @throws IOException could be thrown to signal that the input was invalid. */ @Throws(IOException::class) public fun fromJsonResponse(statusCode: Int, reader: Reader): T /** * Converts the raw input to a <T> instance. * @param statusCode the response HTTP status code. * @param bodyText the plain text received in the response body. * @param headers the response headers received. */ public fun fromRawResponse( statusCode: Int, bodyText: String, headers: Map<String, List<String>> ): T /** * Constructs a <T> instance from the given stack trace. * @param cause the cause of this error. */ public fun fromException(cause: Throwable): T }
auth0/src/main/java/com/auth0/android/request/ErrorAdapter.kt
135961739
package com.bajdcc.LALR1.grammar.tree /** * 【语义分析】基本语句接口 * * @author bajdcc */ interface IStmt : ICommon
src/main/kotlin/com/bajdcc/LALR1/grammar/tree/IStmt.kt
3712333789
// 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.rename import com.intellij.openapi.editor.Editor import com.intellij.psi.* import com.intellij.refactoring.RefactoringActionHandler import com.intellij.refactoring.rename.inplace.VariableInplaceRenameHandler import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer import org.jetbrains.kotlin.idea.base.psi.unquoteKotlinIdentifier import org.jetbrains.kotlin.psi.* open class KotlinVariableInplaceRenameHandler : VariableInplaceRenameHandler() { companion object { fun isInplaceRenameAvailable(element: PsiElement): Boolean { when (element) { is KtTypeParameter -> return true is KtDestructuringDeclarationEntry -> return true is KtParameter -> { val parent = element.parent if (parent is KtForExpression) { return true } if (parent is KtParameterList) { val grandparent = parent.parent return grandparent is KtCatchClause || grandparent is KtFunctionLiteral } } is KtLabeledExpression, is KtImportAlias -> return true } return false } } protected open class RenamerImpl : VariableInplaceRenamer { constructor(elementToRename: PsiNamedElement, editor: Editor) : super(elementToRename, editor) constructor( elementToRename: PsiNamedElement, editor: Editor, currentName: String, oldName: String ) : super(elementToRename, editor, editor.project!!, currentName, oldName) override fun acceptReference(reference: PsiReference): Boolean { val refElement = reference.element val textRange = reference.rangeInElement val referenceText = refElement.text.substring(textRange.startOffset, textRange.endOffset).unquoteKotlinIdentifier() return referenceText == myElementToRename.name } override fun startsOnTheSameElement(handler: RefactoringActionHandler?, element: PsiElement?): Boolean { return variable == element && (handler is VariableInplaceRenameHandler || handler is KotlinRenameDispatcherHandler) } override fun createInplaceRenamerToRestart(variable: PsiNamedElement, editor: Editor, initialName: String): VariableInplaceRenamer { return RenamerImpl(variable, editor, initialName, myOldName) } } override fun createRenamer(elementToRename: PsiElement, editor: Editor): VariableInplaceRenamer? { val currentElementToRename = elementToRename as PsiNameIdentifierOwner val currentName = currentElementToRename.nameIdentifier?.text ?: "" return RenamerImpl(currentElementToRename, editor, currentName, currentName) } public override fun isAvailable(element: PsiElement?, editor: Editor, file: PsiFile) = editor.settings.isVariableInplaceRenameEnabled && element != null && isInplaceRenameAvailable(element) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinVariableInplaceRenameHandler.kt
3092366113
package com.fsck.k9.ui.settings import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import com.fsck.k9.Account import com.fsck.k9.preferences.AccountManager import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch internal class SettingsViewModel( private val accountManager: AccountManager, private val coroutineScope: CoroutineScope = GlobalScope, private val coroutineDispatcher: CoroutineDispatcher = Dispatchers.IO, ) : ViewModel() { val accounts = accountManager.getAccountsFlow().asLiveData() fun moveAccount(account: Account, newPosition: Int) { coroutineScope.launch(coroutineDispatcher) { // Delay saving the account so the animation is not disturbed delay(500) accountManager.moveAccount(account, newPosition) } } }
app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/SettingsViewModel.kt
1923917743
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.referrersx import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class MainEntityImpl: MainEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _x: String? = null override val x: String get() = _x!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: MainEntityData?): ModifiableWorkspaceEntityBase<MainEntity>(), MainEntity.Builder { constructor(): this(MainEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity MainEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isXInitialized()) { error("Field MainEntity#x should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field MainEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var x: String get() = getEntityData().x set(value) { checkModificationAllowed() getEntityData().x = value changedProperty.add("x") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): MainEntityData = result ?: super.getEntityData() as MainEntityData override fun getEntityClass(): Class<MainEntity> = MainEntity::class.java } } class MainEntityData : WorkspaceEntityData<MainEntity>() { lateinit var x: String fun isXInitialized(): Boolean = ::x.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<MainEntity> { val modifiable = MainEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): MainEntity { val entity = MainEntityImpl() entity._x = x entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return MainEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as MainEntityData if (this.x != other.x) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as MainEntityData if (this.x != other.x) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + x.hashCode() return result } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/MainEntityImpl.kt
130585790
package nl.jstege.adventofcode.aoc2016.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.Direction import nl.jstege.adventofcode.aoccommon.utils.Point import nl.jstege.adventofcode.aoccommon.utils.extensions.scan import kotlin.reflect.KProperty1 /** * * @author Jelle Stege */ class Day01 : Day(title = "No Time for a Taxicab") { override fun first(input: Sequence<String>): Any { var dir = Direction.NORTH return input .first() .parse() .fold(Point.ZERO_ZERO) { p, (turn, steps) -> dir = dir.let(turn.directionMod) p.moveDirection(dir, steps) } .manhattan(Point.ZERO_ZERO) } override fun second(input: Sequence<String>): Any { var dir = Direction.NORTH var coordinate = Point.ZERO_ZERO val visited = mutableSetOf(coordinate) input.first().parse().forEach { (turn, steps) -> dir = dir.let(turn.directionMod) val first = coordinate.moveDirection(dir) val last = coordinate.moveDirection(dir, steps) val xs = if (last.x < first.x) first.x downTo last.x else first.x..last.x val ys = if (last.y < first.y) first.y downTo last.y else first.y..last.y Point.of(xs, ys).forEach { coordinate = it if (coordinate in visited) return coordinate.manhattan(Point.ZERO_ZERO) visited += coordinate } } throw IllegalStateException("No answer found.") } private fun String.parse(): List<Instruction> = this.split(", ").map { Instruction(Turn.parse(it.substring(0, 1)), it.substring(1).toInt()) } private data class Instruction(val turn: Turn, val steps: Int) private enum class Turn(val directionMod: KProperty1<Direction, Direction>) { LEFT(Direction::left), RIGHT(Direction::right); companion object { fun parse(v: String) = when (v) { "L" -> LEFT else -> RIGHT } } } }
aoc-2016/src/main/kotlin/nl/jstege/adventofcode/aoc2016/days/Day01.kt
3192272549
package com.github.felipehjcosta.marvelapp.cache.data import androidx.room.Embedded import androidx.room.Relation data class StoryListRelations( @Embedded var storyListEntity: StoryListEntity = StoryListEntity(), @Relation( parentColumn = "story_list_id", entityColumn = "summary_story_list_id", entity = SummaryEntity::class ) var storyListSummary: List<SummaryEntity> = mutableListOf() )
library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/StoryListRelations.kt
1998841740
package org.ligi.passandroid.ui.quirk_fix import android.content.Intent import android.os.Bundle import androidx.core.net.toUri import androidx.fragment.app.commit import org.ligi.passandroid.ui.AlertFragment import org.ligi.passandroid.ui.PassAndroidActivity import org.ligi.passandroid.ui.PassImportActivity class USAirwaysLoadActivity : PassAndroidActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val data = intent.data if (data == null || "$data".indexOf("/") == -1){ val alert = AlertFragment() supportFragmentManager.commit { add(alert,"AlertFrag") } return } val url = "$data".removeSuffix("/") ?: "" val split = url.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val passId = split[split.size - 2] + "/" + split[split.size - 1] val redirectUrl = "http://prod.wap.ncrwebhost.mobi/mobiqa/wap/$passId/passbook" tracker.trackEvent("quirk_fix", "redirect", "usairways", null) val intent = Intent(this, PassImportActivity::class.java) intent.data = redirectUrl.toUri() startActivity(intent) finish() } }
android/src/main/java/org/ligi/passandroid/ui/quirk_fix/USAirwaysLoadActivity.kt
3256049519
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package promotion import common.VersionedSettingsBranch import configurations.branchFilter import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.schedule import vcsroots.gradlePromotionBranches class PublishNightlySnapshot(branch: VersionedSettingsBranch) : PublishGradleDistributionBothSteps( promotedBranch = branch.branchName, prepTask = branch.prepNightlyTaskName(), step2TargetTask = branch.promoteNightlyTaskName(), triggerName = "ReadyforNightly", vcsRootId = gradlePromotionBranches ) { init { id("Promotion_Nightly") name = "Nightly Snapshot" description = "Promotes the latest successful changes on '${branch.branchName}' from Ready for Nightly as a new nightly snapshot" triggers { branch.triggeredHour()?.apply { schedule { schedulingPolicy = daily { this.hour = this@apply } triggerBuild = always() withPendingChangesOnly = true enabled = branch.enableTriggers branchFilter = branch.branchFilter() } } } } } // Avoid two jobs running at the same time and causing troubles private fun VersionedSettingsBranch.triggeredHour() = when { isMaster -> 0 isRelease -> 1 else -> null }
.teamcity/src/main/kotlin/promotion/PublishNightlySnapshot.kt
966457920
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.extensions import net.dv8tion.jda.api.utils.concurrent.Task import java.util.concurrent.CompletableFuture import java.util.concurrent.ExecutionException @Throws(InterruptedException::class, ExecutionException::class) fun <T> Task<T>.sync(): T { val retrieveFuture = CompletableFuture<T>() this.onSuccess { retrieveFuture.complete(it) } this.onError { retrieveFuture.completeExceptionally(it) } return retrieveFuture.get() }
src/main/kotlin/ml/duncte123/skybot/extensions/Task.kt
3028794862
package org.wordpress.android.ui.stats.refresh.lists.sections.viewholders import android.content.Context import android.graphics.Typeface import android.text.Spannable import android.text.SpannableString import android.text.TextPaint import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.text.style.StyleSpan import android.view.View import android.view.ViewGroup import org.wordpress.android.R import org.wordpress.android.databinding.StatsBlockListGuideCardBinding import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ListItemGuideCard import org.wordpress.android.util.extensions.getColorFromAttribute import org.wordpress.android.util.extensions.viewBinding class GuideCardViewHolder( val parent: ViewGroup, val binding: StatsBlockListGuideCardBinding = parent.viewBinding(StatsBlockListGuideCardBinding::inflate) ) : BlockListItemViewHolder(binding.root) { fun bind( item: ListItemGuideCard ) = with(binding) { val spannableString = SpannableString(item.text) item.links?.forEach { link -> link.link?.let { spannableString.withClickableSpan(root.context, it) { link.navigationAction.click() } } } item.bolds?.forEach { bold -> spannableString.withBoldSpan(bold) } guideMessage.movementMethod = LinkMovementMethod.getInstance() guideMessage.text = spannableString } } private fun SpannableString.withClickableSpan( context: Context, clickablePart: String, onClickListener: (Context) -> Unit ): SpannableString { val clickableSpan = object : ClickableSpan() { override fun onClick(widget: View) { widget.context?.let { onClickListener.invoke(it) } } override fun updateDrawState(ds: TextPaint) { ds.color = context.getColorFromAttribute(R.attr.colorPrimary) ds.typeface = Typeface.create( Typeface.DEFAULT_BOLD, Typeface.NORMAL ) ds.isUnderlineText = false } } val clickablePartStart = indexOf(clickablePart) setSpan( clickableSpan, clickablePartStart, clickablePartStart + clickablePart.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) return this } private fun SpannableString.withBoldSpan(boldPart: String): SpannableString { val boldPartIndex = indexOf(boldPart) setSpan( StyleSpan(Typeface.BOLD), boldPartIndex, boldPartIndex + boldPart.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) return this }
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/viewholders/GuideCardViewHolder.kt
545453388
package xyz.koleno.sunwidget.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.widget.RemoteViews import androidx.preference.PreferenceManager import xyz.koleno.sunwidget.PrefHelper import xyz.koleno.sunwidget.R /** * Broadcast receiver that controls the widgets * @author Dusan Koleno */ class SunWidgetProvider : AppWidgetProvider() { companion object { const val ACTION_NO_CONNECTION = "actionNoConnection" // no internet connection notification const val ACTION_UPDATE_WIDGETS = "actionUpdateViews" // sent by update service to update views with new data const val ACTION_RUN_UPDATE = "actionRunUpdate" // generated after refresh button click to start update service } /** * Called by the system when widgets need to be updated */ override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { val prefs = PrefHelper(PreferenceManager.getDefaultSharedPreferences(context)) // start service if user's location is set if (prefs.hasLocation()) { updateWidgetsFromSaved(context, appWidgetIds) // first get saved data UpdateService.enqueueWork(context, appWidgetIds) } else { // notify user about missing location updateWidgets(context, appWidgetIds, context.resources.getString(R.string.no_location), context.resources.getString(R.string.no_location)) } } /** * Custom actions used to handle various widget updates */ override fun onReceive(context: Context, intent: Intent) { val prefs = PrefHelper(PreferenceManager.getDefaultSharedPreferences(context)) val widgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS) ?: return // stop if no widget ids when (intent.action) { ACTION_NO_CONNECTION -> { updateWidgets(context, widgetIds, context.getString(R.string.no_internet), context.getString(R.string.no_internet_try)) } ACTION_UPDATE_WIDGETS -> { updateWidgetsFromSaved(context, widgetIds) } ACTION_RUN_UPDATE -> { if (!prefs.hasTimes()) { // no previous times saved, show loading updateWidgets(context, widgetIds, context.getString(R.string.loading), context.getString(R.string.loading)) } // start the update service UpdateService.enqueueWork(context, widgetIds) } } super.onReceive(context, intent) } /** * Generates widget update intent for the refresh button click */ private fun generateUpdateIntent(context: Context, appWidgetIds: IntArray): PendingIntent { val intent = Intent(context, javaClass) intent.action = ACTION_RUN_UPDATE intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds) return PendingIntent.getBroadcast(context, 0, intent, 0) } /** * Updates widgets with given data */ private fun updateWidgets(context: Context, appWidgetIds: IntArray, sunriseText: String, sunsetText: String) { val manager = AppWidgetManager.getInstance(context.applicationContext) val remoteViews = RemoteViews(context.applicationContext.packageName, R.layout.sunwidget) remoteViews.setOnClickPendingIntent(R.id.button_refresh, generateUpdateIntent(context, appWidgetIds)) for (widgetId in appWidgetIds) { remoteViews.setTextViewText(R.id.text_sunrise_value, sunriseText) remoteViews.setTextViewText(R.id.text_sunset_value, sunsetText) manager.updateAppWidget(widgetId, remoteViews) } } /** * Updates widgets from saved data */ private fun updateWidgetsFromSaved(context: Context, appWidgetIds: IntArray) { val prefs = PrefHelper(PreferenceManager.getDefaultSharedPreferences(context)) if (prefs.hasTimes()) { val data = prefs.loadTimes() updateWidgets(context, appWidgetIds, data.sunrise, data.sunset) } } }
app/src/main/kotlin/xyz/koleno/sunwidget/widget/SunWidgetProvider.kt
699027746
/* * Copyright (c) 2016 by David Hardy. Licensed under the Apache License, Version 2.0. */ package nl.endran.productbrowser.fragments import nl.endran.productbrowser.interactors.Catalog import nl.endran.productbrowser.interactors.CatalogRetriever import nl.endran.productbrowser.interactors.Product import nl.endran.productbrowser.interactors.ScreenFlowController import nl.endran.productbrowser.mvp.BaseFragmentPresenter import rx.Subscription import javax.inject.Inject class OverviewFragmentPresenter @Inject constructor( val screenFlowController: ScreenFlowController, val catalogRetriever: CatalogRetriever) : BaseFragmentPresenter<OverviewFragmentPresenter.ViewModel>() { interface ViewModel { fun showProducts(catalog: Catalog) } var subscription: Subscription? = null override fun onStart() { catalogRetriever.start() subscription = catalogRetriever.observable.subscribe() { viewModel?.showProducts(it) } } override fun onStop() { subscription?.unsubscribe() subscription = null catalogRetriever.stop() } fun productSelected(product: Product) { screenFlowController.showProductDetail(product) } fun refresh() { catalogRetriever.refresh() } }
Mobile/app/src/main/java/nl/endran/productbrowser/fragments/OverviewFragmentPresenter.kt
2192663968
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.committed import com.intellij.icons.AllIcons import com.intellij.ide.actions.EditSourceAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys.PROJECT import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsDataKeys.SELECTED_CHANGES import com.intellij.openapi.vcs.changes.ChangesUtil.getNavigatableArray import com.intellij.openapi.vcs.changes.ChangesUtil.iterateFiles import com.intellij.openapi.vcs.changes.committed.CommittedChangesBrowserUseCase.IN_AIR import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.pom.Navigatable internal class EditSourceFromChangesBrowserAction : EditSourceAction() { override fun update(e: AnActionEvent) { super.update(e) e.presentation.apply { icon = AllIcons.Actions.EditSource text = VcsBundle.message("edit.source.action.text") val isModalContext = e.getData(PlatformCoreDataKeys.IS_MODAL_CONTEXT) == true val changesBrowser = e.getData(ChangesBrowserBase.DATA_KEY) isVisible = isVisible && changesBrowser != null isEnabled = isEnabled && changesBrowser != null && !isModalContext && e.getData(CommittedChangesBrowserUseCase.DATA_KEY) != IN_AIR } } override fun getNavigatables(dataContext: DataContext): Array<Navigatable>? { val project = PROJECT.getData(dataContext) ?: return null val changes = SELECTED_CHANGES.getData(dataContext) ?: return null return getNavigatableArray(project, iterateFiles(changes.asList())) } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/EditSourceFromChangesBrowserAction.kt
2979796699
// INTENTION_TEXT: Remove 'private' modifier class Test { var foo: String = "" <caret>private set }
plugins/kotlin/idea/tests/testData/intentions/changeVisibility/public/propertyPrivateSetter.kt
1299147515
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.dfa import com.intellij.codeInspection.dataFlow.jvm.descriptors.JvmVariableDescriptor import com.intellij.codeInspection.dataFlow.types.DfType import com.intellij.codeInspection.dataFlow.value.DfaValueFactory import com.intellij.codeInspection.dataFlow.value.DfaVariableValue import com.intellij.psi.PsiElement import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.builtins.getValueParameterTypesFromFunctionType import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.resolveType import org.jetbrains.kotlin.idea.refactoring.move.moveMethod.type import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.util.findAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration import org.jetbrains.kotlin.resolve.jvm.annotations.VOLATILE_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.source.KotlinSourceElement import org.jetbrains.kotlin.types.KotlinType class KtVariableDescriptor(val variable: KtCallableDeclaration) : JvmVariableDescriptor() { val stable: Boolean = calculateStable() private fun calculateStable(): Boolean { if (variable is KtParameter && variable.isMutable) return false if (variable !is KtProperty || !variable.isVar) return true if (!variable.isLocal) return false return !getVariablesChangedInNestedFunctions(variable.parent).contains(variable) } private fun getVariablesChangedInNestedFunctions(parent: PsiElement): Set<KtProperty> = CachedValuesManager.getProjectPsiDependentCache(parent) { scope -> val result = hashSetOf<KtProperty>() PsiTreeUtil.processElements(scope) { e -> if (e is KtSimpleNameExpression && e.readWriteAccess(false).isWrite) { val target = e.mainReference.resolve() if (target is KtProperty && target.isLocal && PsiTreeUtil.isAncestor(parent, target, true)) { var parentScope : KtFunction? var context = e while(true) { parentScope = PsiTreeUtil.getParentOfType(context, KtFunction::class.java) val maybeLambda = parentScope?.parent as? KtLambdaExpression val maybeCall = (maybeLambda?.parent as? KtLambdaArgument)?.parent as? KtCallExpression if (maybeCall != null && getInlineableLambda(maybeCall)?.lambda == maybeLambda) { context = maybeCall continue } break } if (parentScope != null && PsiTreeUtil.isAncestor(parent, parentScope, true)) { result.add(target) } } } return@processElements true } return@getProjectPsiDependentCache result } override fun isStable(): Boolean = stable override fun canBeCapturedInClosure(): Boolean { if (variable is KtParameter && variable.isMutable) return false return variable !is KtProperty || !variable.isVar } override fun getPsiElement(): KtCallableDeclaration = variable override fun getDfType(qualifier: DfaVariableValue?): DfType = variable.type().toDfType() override fun equals(other: Any?): Boolean = other is KtVariableDescriptor && other.variable == variable override fun hashCode(): Int = variable.hashCode() override fun toString(): String = variable.name ?: "<unknown>" companion object { fun getSingleLambdaParameter(factory: DfaValueFactory, lambda: KtLambdaExpression): DfaVariableValue? { val parameters = lambda.valueParameters if (parameters.size > 1) return null if (parameters.size == 1) { return if (parameters[0].destructuringDeclaration == null) factory.varFactory.createVariableValue(KtVariableDescriptor(parameters[0])) else null } val kotlinType = lambda.resolveType()?.getValueParameterTypesFromFunctionType()?.singleOrNull()?.type ?: return null return factory.varFactory.createVariableValue(KtItVariableDescriptor(lambda.functionLiteral, kotlinType)) } fun createFromQualified(factory: DfaValueFactory, expr: KtExpression?): DfaVariableValue? { var selector = expr while (selector is KtQualifiedExpression) { selector = selector.selectorExpression } return createFromSimpleName(factory, selector) } fun createFromSimpleName(factory: DfaValueFactory, expr: KtExpression?): DfaVariableValue? { val varFactory = factory.varFactory if (expr is KtSimpleNameExpression) { val target = expr.mainReference.resolve() if (target is KtCallableDeclaration) { if (target is KtParameter && target.ownerFunction !is KtPrimaryConstructor || target is KtProperty && target.isLocal || target is KtDestructuringDeclarationEntry ) { return varFactory.createVariableValue(KtVariableDescriptor(target)) } if (isTrackableProperty(target)) { val parent = expr.parent var qualifier: DfaVariableValue? = null if (target.parent is KtClassBody && target.parent.parent is KtObjectDeclaration) { // property in object: singleton, can track return varFactory.createVariableValue(KtVariableDescriptor(target), null) } if (parent is KtQualifiedExpression && parent.selectorExpression == expr) { val receiver = parent.receiverExpression qualifier = createFromSimpleName(factory, receiver) } else { if (target.parent is KtFile) { // top-level declaration return varFactory.createVariableValue(KtVariableDescriptor(target), null) } val classOrObject = target.containingClassOrObject?.resolveToDescriptorIfAny() if (classOrObject != null) { val dfType = classOrObject.defaultType.toDfType() qualifier = varFactory.createVariableValue(KtThisDescriptor(classOrObject, dfType)) } } if (qualifier != null) { return varFactory.createVariableValue(KtVariableDescriptor(target), qualifier) } } } if (expr.textMatches("it")) { val descriptor = expr.resolveMainReferenceToDescriptors().singleOrNull() if (descriptor is ValueParameterDescriptor) { val fn = ((descriptor.containingDeclaration as? DeclarationDescriptorWithSource)?.source as? KotlinSourceElement)?.psi if (fn != null) { val type = descriptor.type return varFactory.createVariableValue(KtItVariableDescriptor(fn, type)) } } } } return null } private fun isTrackableProperty(target: PsiElement?) = target is KtParameter && target.ownerFunction is KtPrimaryConstructor || target is KtProperty && !target.hasDelegate() && target.getter == null && target.setter == null && !target.hasModifier(KtTokens.ABSTRACT_KEYWORD) && target.findAnnotation(VOLATILE_ANNOTATION_FQ_NAME) == null && target.containingClass()?.isInterface() != true && !target.isExtensionDeclaration() } } class KtItVariableDescriptor(val lambda: KtElement, val type: KotlinType): JvmVariableDescriptor() { override fun getDfType(qualifier: DfaVariableValue?): DfType = type.toDfType() override fun isStable(): Boolean = true override fun equals(other: Any?): Boolean = other is KtItVariableDescriptor && other.lambda == lambda override fun hashCode(): Int = lambda.hashCode() override fun toString(): String = "it" }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KtVariableDescriptor.kt
3574608066
package org.gittner.osmbugs.keepright import org.gittner.osmbugs.ui.ErrorMarker import org.osmdroid.views.MapView class KeeprightMarker(error: KeeprightError, map: MapView) : ErrorMarker<KeeprightError>(error, map) { init { icon = KeeprightError.GetZapIconFor(error.State, error.Type) } }
app/src/main/java/org/gittner/osmbugs/keepright/KeeprightMarker.kt
899290041
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui.colorpicker import com.intellij.ui.JBColor import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.* import java.awt.event.* import javax.swing.AbstractAction import javax.swing.JComponent import javax.swing.KeyStroke import kotlin.math.max private val DEFAULT_HORIZONTAL_PADDING = JBUI.scale(5) private val DEFAULT_VERTICAL_PADDING = JBUI.scale(5) private val KNOB_COLOR = Color(255, 255, 255) private val KNOB_BORDER_COLOR = JBColor(Color(100, 100, 100), Color(64, 64, 64)) private val KNOB_BORDER_STROKE = BasicStroke(1.5f) private const val KNOB_WIDTH = 5 private const val KNOB_CORNER_ARC = 5 private const val FOCUS_BORDER_CORNER_ARC = 5 private const val FOCUS_BORDER_WIDTH = 3 private const val ACTION_SLIDE_LEFT = "actionSlideLeft" private const val ACTION_SLIDE_LEFT_STEP = "actionSlideLeftStep" private const val ACTION_SLIDE_RIGHT = "actionSlideRight" private const val ACTION_SLIDE_RIGHT_STEP = "actionSlideRightStep" abstract class SliderComponent<T: Number>(initialValue: T) : JComponent() { protected val leftPadding = DEFAULT_HORIZONTAL_PADDING protected val rightPadding = DEFAULT_HORIZONTAL_PADDING protected val topPadding = DEFAULT_VERTICAL_PADDING protected val bottomPadding = DEFAULT_VERTICAL_PADDING private var _knobPosition: Int = 0 private var knobPosition: Int get() = _knobPosition set(newPointerValue) { _knobPosition = newPointerValue _value = knobPositionToValue(newPointerValue) } private var _value: T = initialValue var value: T get() = _value set(newValue) { _value = newValue _knobPosition = valueToKnobPosition(newValue) } private val polygonToDraw = Polygon() private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<(T) -> Unit>() /** * @return size of slider, must be positive value or zero. */ val sliderWidth get() = max(0, width - leftPadding - rightPadding) init { this.addMouseMotionListener(object : MouseAdapter() { override fun mouseDragged(e: MouseEvent) { processMouse(e) e.consume() } }) this.addMouseListener(object : MouseAdapter() { override fun mousePressed(e: MouseEvent) { processMouse(e) e.consume() } }) addMouseWheelListener { e -> runAndUpdateIfNeeded { value = slide(-e.preciseWheelRotation.toInt()) } e.consume() } this.addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent?) { repaint() } override fun focusLost(e: FocusEvent?) { repaint() } }) this.addComponentListener(object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { repaint() } }) with (actionMap) { put(ACTION_SLIDE_LEFT, object : AbstractAction() { override fun actionPerformed(e: ActionEvent) = runAndUpdateIfNeeded { doSlide(-1) } }) put(ACTION_SLIDE_LEFT_STEP, object : AbstractAction() { override fun actionPerformed(e: ActionEvent) = runAndUpdateIfNeeded { doSlide(-10) } }) put(ACTION_SLIDE_RIGHT, object : AbstractAction() { override fun actionPerformed(e: ActionEvent) = runAndUpdateIfNeeded { doSlide(1) } }) put(ACTION_SLIDE_RIGHT_STEP, object : AbstractAction() { override fun actionPerformed(e: ActionEvent) = runAndUpdateIfNeeded { doSlide(10) } }) } with (getInputMap(WHEN_FOCUSED)) { put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), ACTION_SLIDE_LEFT) put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.SHIFT_DOWN_MASK), ACTION_SLIDE_LEFT_STEP) put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), ACTION_SLIDE_RIGHT) put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.SHIFT_DOWN_MASK), ACTION_SLIDE_RIGHT_STEP) } } /** * Helper function to execute the code and check if needs to invoke [repaint] and/or [fireValueChanged] */ private fun runAndUpdateIfNeeded(task: () -> Unit) { val oldValue = value task() repaint() if (oldValue != value) { fireValueChanged() } } private fun processMouse(e: MouseEvent) = runAndUpdateIfNeeded { val newKnobPosition = Math.max(0, Math.min(e.x - leftPadding, sliderWidth)) knobPosition = newKnobPosition } fun addListener(listener: (T) -> Unit) { listeners.add(listener) } private fun fireValueChanged() = listeners.forEach { it.invoke(value) } protected abstract fun knobPositionToValue(knobPosition: Int): T protected abstract fun valueToKnobPosition(value: T): Int private fun doSlide(shift: Int) { value = slide(shift) } /** * return the new value after sliding. The [shift] is the amount of sliding. */ protected abstract fun slide(shift: Int): T override fun getPreferredSize(): Dimension = JBUI.size(100, 22) override fun getMinimumSize(): Dimension = JBUI.size(50, 22) override fun getMaximumSize(): Dimension = Dimension(Integer.MAX_VALUE, preferredSize.height) override fun isFocusable() = true override fun setToolTipText(text: String) = Unit override fun paintComponent(g: Graphics) { val g2d = g as Graphics2D if (isFocusOwner) { g2d.color = UIUtil.getFocusedFillColor() ?: Color.BLUE.brighter() val left = leftPadding - FOCUS_BORDER_WIDTH val top = topPadding - FOCUS_BORDER_WIDTH val width = width - left - rightPadding + FOCUS_BORDER_WIDTH val height = height - top - bottomPadding + FOCUS_BORDER_WIDTH g2d.fillRoundRect(left, top, width, height, FOCUS_BORDER_CORNER_ARC, FOCUS_BORDER_CORNER_ARC) } paintSlider(g2d) drawKnob(g2d, leftPadding + valueToKnobPosition(value)) } protected abstract fun paintSlider(g2d: Graphics2D) private fun drawKnob(g2d: Graphics2D, x: Int) { val originalAntialiasing = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING) val originalStroke = g2d.stroke g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) val knobLeft = x - KNOB_WIDTH / 2 val knobTop = topPadding / 2 val knobWidth = KNOB_WIDTH val knobHeight = height - (topPadding + bottomPadding) / 2 g2d.color = KNOB_COLOR g2d.fillRoundRect(knobLeft, knobTop, knobWidth, knobHeight, KNOB_CORNER_ARC, KNOB_CORNER_ARC) g2d.color = KNOB_BORDER_COLOR g2d.stroke = KNOB_BORDER_STROKE g2d.drawRoundRect(knobLeft, knobTop, knobWidth, knobHeight, KNOB_CORNER_ARC, KNOB_CORNER_ARC) g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, originalAntialiasing) g2d.stroke = originalStroke } }
platform/platform-impl/src/com/intellij/ui/colorpicker/SliderComponent.kt
3570386413
// 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.testFramework.assertions import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtilRt import com.intellij.rt.execution.junit.FileComparisonFailure import com.intellij.testFramework.UsefulTestCase import com.intellij.util.io.readChars import com.intellij.util.io.write import org.assertj.core.api.ListAssert import org.yaml.snakeyaml.DumperOptions import org.yaml.snakeyaml.Yaml import org.yaml.snakeyaml.nodes.Node import org.yaml.snakeyaml.nodes.Tag import org.yaml.snakeyaml.representer.Represent import org.yaml.snakeyaml.representer.Representer import java.nio.file.NoSuchFileException import java.nio.file.Path import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.regex.Pattern internal interface SnapshotFileUsageListener { fun beforeMatch(file: Path) } internal val snapshotFileUsageListeners = Collections.newSetFromMap<SnapshotFileUsageListener>(ConcurrentHashMap()) class ListAssertEx<ELEMENT>(actual: List<ELEMENT>?) : ListAssert<ELEMENT>(actual) { fun toMatchSnapshot(snapshotFile: Path) { snapshotFileUsageListeners.forEach { it.beforeMatch(snapshotFile) } isNotNull compareFileContent(actual, snapshotFile) } } fun dumpData(data: Any): String { val dumperOptions = DumperOptions() dumperOptions.isAllowReadOnlyProperties = true dumperOptions.lineBreak = DumperOptions.LineBreak.UNIX val yaml = Yaml(DumpRepresenter(), dumperOptions) return yaml.dump(data) } private class DumpRepresenter : Representer() { init { representers.put(Pattern::class.java, RepresentDump()) } private inner class RepresentDump : Represent { override fun representData(data: Any): Node = representScalar(Tag.STR, data.toString()) } } internal fun loadSnapshotContent(snapshotFile: Path, convertLineSeparators: Boolean = SystemInfo.isWindows): CharSequence { // because developer can open file and depending on editor settings, newline maybe added to the end of file var content = snapshotFile.readChars().trimEnd() if (convertLineSeparators) { content = StringUtilRt.convertLineSeparators(content, "\n") } return content } @Throws(FileComparisonFailure::class) fun compareFileContent(actual: Any, snapshotFile: Path, updateIfMismatch: Boolean = isUpdateSnapshotIfMismatch(), writeIfNotFound: Boolean = true) { val actualContent = if (actual is CharSequence) getNormalizedActualContent(actual) else dumpData(actual).trimEnd() val expected = try { loadSnapshotContent(snapshotFile) } catch (e: NoSuchFileException) { if (!writeIfNotFound || UsefulTestCase.IS_UNDER_TEAMCITY) { throw e } println("Write a new snapshot: ${snapshotFile.fileName}") snapshotFile.write(actualContent) return } if (StringUtil.equal(actualContent, expected, true)) { return } if (updateIfMismatch) { println("UPDATED snapshot ${snapshotFile.fileName}") snapshotFile.write(actualContent) } else { val firstMismatch = StringUtil.commonPrefixLength(actualContent, expected) @Suppress("SpellCheckingInspection") val message = "Received value does not match stored snapshot '${snapshotFile.fileName}' at ${firstMismatch}.\n" + "Expected: '${expected.contextAround(firstMismatch, 10)}'\n" + "Actual : '${actualContent.contextAround(firstMismatch, 10)}'\n" + "Inspect your code changes or run with `-Dtest.update.snapshots` to update" throw FileComparisonFailure(message, expected.toString(), actualContent.toString(), snapshotFile.toString()) } } internal fun getNormalizedActualContent(actual: CharSequence): CharSequence { var actualContent = actual if (SystemInfo.isWindows) { actualContent = StringUtilRt.convertLineSeparators(actualContent, "\n") } return actualContent.trimEnd() } private fun isUpdateSnapshotIfMismatch(): Boolean { if (UsefulTestCase.IS_UNDER_TEAMCITY) { return false } val value = System.getProperty("test.update.snapshots") return value != null && (value.isEmpty() || value.toBoolean()) } private fun CharSequence.contextAround(offset: Int, context: Int): String = substring((offset - context).coerceAtLeast(0), (offset + context).coerceAtMost(length))
platform/testFramework/extensions/src/com/intellij/testFramework/assertions/snapshot.kt
2951222441
// "Add 'abstract fun f()' to 'Iterable'" "false" // ACTION: Make internal // ACTION: Make private // ACTION: Make protected // ACTION: Remove 'override' modifier // ERROR: 'f' overrides nothing // ERROR: Class 'B' is not abstract and does not implement abstract member public abstract operator fun iterator(): Iterator<Int> defined in kotlin.collections.Iterable // WITH_STDLIB class B : Iterable<Int> { <caret>override fun f() {} }
plugins/kotlin/idea/tests/testData/quickfix/override/nothingToOverride/addFunctionToReadOnlySupertype.kt
1304589481
package html import java.util.* interface Factory<T> { fun create() : T } interface Element class TextElement(val text : String) : Element abstract class Tag(val name : String) : Element { val children = ArrayList<Element>() val attributes = HashMap<String, String>() protected fun <T : Element> initTag(init : T.() -> Unit) : T { val tag = <error descr="[TYPE_PARAMETER_ON_LHS_OF_DOT] Type parameter 'T' cannot have or inherit a companion object, so it cannot be on the left hand side of dot">T</error>.<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: create">create</error>() tag.init() children.add(tag) return tag } } abstract class TagWithText(name : String) : Tag(name) { operator fun String.unaryPlus() { children.add(TextElement(this)) } } class HTML() : TagWithText("html") { companion object : Factory<HTML> { override fun create() = HTML() } fun head(init : Head.() -> Unit) = initTag<Head>(init) fun body(init : Body.() -> Unit) = initTag<Body>(init) } class Head() : TagWithText("head") { companion object : Factory<Head> { override fun create() = Head() } fun title(init : Title.() -> Unit) = initTag<Title>(init) } class Title() : TagWithText("title") abstract class BodyTag(name : String) : TagWithText(name) { } class Body() : BodyTag("body") { companion object : Factory<Body> { override fun create() = Body() } fun b(init : B.() -> Unit) = initTag<B>(init) fun p(init : P.() -> Unit) = initTag<P>(init) fun h1(init : H1.() -> Unit) = initTag<H1>(init) fun a(href : String, init : A.() -> Unit) { val a = initTag<A>(init) a.href = href } } class B() : BodyTag("b") class P() : BodyTag("p") class H1() : BodyTag("h1") class A() : BodyTag("a") { var href : String? get() = attributes["href"] set(value) { if (value != null) attributes["href"] = value } } operator fun MutableMap<String, String>.set(key : String, value : String) = this.put(key, value) fun html(init : HTML.() -> Unit) : HTML { val html = HTML() html.init() return html } fun result(args : Array<String>) = html { head { title {+"XML encoding with Groovy"} } body { h1 {+"XML encoding with Groovy"} p {+"this format can be used as an alternative markup to XML"} // an element with attributes and text content a(href = "https://groovy.codehaus.org") {+"Groovy"} // mixed content p { +"This is some" b {+"mixed"} +"text. For more see the" a(href = "https://groovy.codehaus.org") {+"Groovy"} +"project" } p {+"some text"} // content generated by p { for (arg in args) +arg } } }
plugins/kotlin/idea/tests/testData/checker/Builders.fir.kt
1741571864
package org.thoughtcrime.securesms.stories.settings.select import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy import io.reactivex.rxjava3.subjects.PublishSubject import org.thoughtcrime.securesms.database.model.DistributionListId import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.util.livedata.Store class BaseStoryRecipientSelectionViewModel( private val distributionListId: DistributionListId?, private val repository: BaseStoryRecipientSelectionRepository ) : ViewModel() { private val store = Store(emptySet<RecipientId>()) private val subject = PublishSubject.create<Action>() private val disposable = CompositeDisposable() var actionObservable: Observable<Action> = subject var state: LiveData<Set<RecipientId>> = store.stateLiveData init { if (distributionListId != null) { disposable += repository.getListMembers(distributionListId) .subscribe { members -> store.update { it + members } } } } override fun onCleared() { disposable.clear() } fun toggleSelectAll() { disposable += repository.getAllSignalContacts().subscribeBy { allSignalRecipients -> store.update { allSignalRecipients } } } fun addRecipient(recipientId: RecipientId) { store.update { it + recipientId } } fun removeRecipient(recipientId: RecipientId) { store.update { it - recipientId } } fun onAction() { if (distributionListId != null) { repository.updateDistributionListMembership(distributionListId, store.state) subject.onNext(Action.ExitFlow) } else { subject.onNext(Action.GoToNextScreen(store.state)) } } sealed class Action { data class GoToNextScreen(val recipients: Set<RecipientId>) : Action() object ExitFlow : Action() } class Factory( private val distributionListId: DistributionListId?, private val repository: BaseStoryRecipientSelectionRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.cast(BaseStoryRecipientSelectionViewModel(distributionListId, repository)) as T } } }
app/src/main/java/org/thoughtcrime/securesms/stories/settings/select/BaseStoryRecipientSelectionViewModel.kt
941494326
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("GitTestUtil") package git4idea.test import com.intellij.dvcs.push.PushSpec import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.Executor.* import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.VcsLogObjectsFactory import com.intellij.vcs.log.VcsLogProvider import com.intellij.vcs.log.VcsRef import git4idea.GitRemoteBranch import git4idea.GitStandardRemoteBranch import git4idea.GitUtil import git4idea.GitVcs import git4idea.config.GitVersionSpecialty import git4idea.log.GitLogProvider import git4idea.push.GitPushSource import git4idea.push.GitPushTarget import git4idea.repo.GitRepository import org.junit.Assert.* import org.junit.Assume.assumeTrue import java.io.File const val USER_NAME = "John Doe" const val USER_EMAIL = "[email protected]" /** * * Creates file structure for given paths. Path element should be a relative (from project root) * path to a file or a directory. All intermediate paths will be created if needed. * To create a dir without creating a file pass "dir/" as a parameter. * * Usage example: * `createFileStructure("a.txt", "b.txt", "dir/c.txt", "dir/subdir/d.txt", "anotherdir/");` * * This will create files a.txt and b.txt in the project dir, create directories dir, dir/subdir and anotherdir, * and create file c.txt in dir and d.txt in dir/subdir. * * Note: use forward slash to denote directories, even if it is backslash that separates dirs in your system. * * All files are populated with "initial content" string. */ fun createFileStructure(rootDir: VirtualFile, vararg paths: String) { for (path in paths) { cd(rootDir) val dir = path.endsWith("/") if (dir) { mkdir(path) } else { touch(path, "initial_content_" + Math.random()) } } } fun initRepo(project: Project, repoRoot: String, makeInitialCommit: Boolean) { cd(repoRoot) git(project, "init") setupDefaultUsername(project) if (makeInitialCommit) { touch("initial.txt") git(project, "add initial.txt") git(project, "commit -m initial") } } fun GitPlatformTest.cloneRepo(source: String, destination: String, bare: Boolean) { cd(source) if (bare) { git("clone --bare -- . $destination") } else { git("clone -- . $destination") } cd(destination) setupDefaultUsername() } fun setupDefaultUsername(project: Project) = setupUsername(project, USER_NAME, USER_EMAIL) fun GitPlatformTest.setupDefaultUsername() = setupDefaultUsername(project) fun setupUsername(project: Project, name: String, email: String) { assertFalse("Can not set empty user name ", name.isEmpty()) assertFalse("Can not set empty user email ", email.isEmpty()) git(project, "config user.name '$name'") git(project, "config user.email '$email'") } /** * Creates a Git repository in the given root directory; * registers it in the Settings; * return the [GitRepository] object for this newly created repository. */ fun createRepository(project: Project, root: String) = createRepository(project, root, true) fun createRepository(project: Project, root: String, makeInitialCommit: Boolean): GitRepository { initRepo(project, root, makeInitialCommit) val gitDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(File(root, GitUtil.DOT_GIT)) assertNotNull(gitDir) return registerRepo(project, root) } fun registerRepo(project: Project, root: String): GitRepository { val vcsManager = ProjectLevelVcsManager.getInstance(project) as ProjectLevelVcsManagerImpl vcsManager.setDirectoryMapping(root, GitVcs.NAME) val file = LocalFileSystem.getInstance().findFileByIoFile(File(root)) assertFalse(vcsManager.allVcsRoots.isEmpty()) val repository = GitUtil.getRepositoryManager(project).getRepositoryForRoot(file) assertNotNull("Couldn't find repository for root " + root, repository) return repository!! } fun assumeSupportedGitVersion(vcs: GitVcs) { val version = vcs.version assumeTrue("Unsupported Git version: " + version, version.isSupported) } fun GitPlatformTest.readAllRefs(root: VirtualFile, objectsFactory: VcsLogObjectsFactory): Set<VcsRef> { val refs = git("log --branches --tags --no-walk --format=%H%d --decorate=full").lines() val result = mutableSetOf<VcsRef>() for (ref in refs) { result.addAll(RefParser(objectsFactory).parseCommitRefs(ref, root)) } return result } fun GitPlatformTest.makeCommit(file: String): String { append(file, "some content") addCommit("some message") return last() } fun findGitLogProvider(project: Project): GitLogProvider { val providers = Extensions.getExtensions(VcsLogProvider.LOG_PROVIDER_EP, project) .filter { provider -> provider.supportedVcs == GitVcs.getKey() } assertEquals("Incorrect number of GitLogProviders", 1, providers.size) return providers[0] as GitLogProvider } fun makePushSpec(repository: GitRepository, from: String, to: String): PushSpec<GitPushSource, GitPushTarget> { val source = repository.branches.findLocalBranch(from)!! var target: GitRemoteBranch? = repository.branches.findBranchByName(to) as GitRemoteBranch? val newBranch: Boolean if (target == null) { val firstSlash = to.indexOf('/') val remote = GitUtil.findRemoteByName(repository, to.substring(0, firstSlash))!! target = GitStandardRemoteBranch(remote, to.substring(firstSlash + 1)) newBranch = true } else { newBranch = false } return PushSpec(GitPushSource.create(source), GitPushTarget(target, newBranch)) } fun GitRepository.resolveConflicts() { cd(this) this.git("add -u .") } fun getPrettyFormatTagForFullCommitMessage(project: Project) = if (GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(project)) "%B" else "%s%n%n%-b"
plugins/git4idea/tests/git4idea/test/GitTestUtil.kt
2597361299
package nz.co.cic.ble.scanner import com.beust.klaxon.* import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import org.json.JSONObject import java.util.* /** * Created by dipshit on 10/03/17. */ class ScanFilter(val name: String, val messageKeys: Array<String>) { private var uuid: UUID? = null private var messageUuids: Map<UUID, String>? = null private val parser: Parser = Parser() init { this.uuid = UUID.nameUUIDFromBytes(name.toByteArray()) this.messageUuids = this.messageKeys.associateBy { keySelector -> UUID.nameUUIDFromBytes(keySelector.toByteArray()) } } fun filter(radioFlow: Flowable<JSONObject>?): Flowable<JsonObject> { return Flowable.create({ subscriber -> radioFlow?.subscribe({ jsonInfo -> var json = parser.parse(StringBuilder(jsonInfo.toString())) as JsonObject var filteredReturn = runFilter(json) filteredReturn.set("deviceAddress", json.get("deviceAddress")) subscriber.onNext(filteredReturn) }, { err -> subscriber.onError(err) }, { subscriber.onComplete() }) }, BackpressureStrategy.BUFFER) } private fun runFilter(json: JsonObject): JsonObject { var filtered = getServiceById(json) filtered?.set("id", this.name) filtered?.set("messages", nameMessages(filtered.array<JsonObject>("messages"))) return filtered!! } private fun nameMessages(json: JsonArray<JsonObject>?): JsonArray<JsonObject>? { var it = json?.iterator() while (it!!.hasNext()) { var message = it.next() var id = UUID.fromString(message.get("id") as String) var name = this.messageUuids?.get(id) message.set("id", name) } return json } private fun getServiceById(json: JsonObject): JsonObject? { var prefiltered = json.array<JsonObject>("messages") var filtered = prefiltered?.filter { it.string("id") == this.uuid.toString() } return filtered?.get(0) } }
library/src/main/java/nz/co/cic/ble/scanner/ScanFilter.kt
16892249
package org.kethereum.erc961 import org.kethereum.model.Token fun Token.generateURL(): String { val params = mutableListOf<String>() params.add("symbol=$symbol") if (decimals != 18) { params.add("decimals=$decimals") } name?.let { params.add("name=$it") } type?.let { params.add("type=$it") } return "ethereum:token_info-$address@${chain.value}?" + params.joinToString("&") }
erc961/src/main/kotlin/org/kethereum/erc961/ERC961Generator.kt
3163120652
package org.dvbviewer.controller.data.api.handler import org.apache.commons.lang3.StringUtils import org.dvbviewer.controller.data.entities.FFMpegPresetList import org.dvbviewer.controller.data.entities.Preset import org.dvbviewer.controller.utils.INIParser import org.dvbviewer.controller.utils.StreamUtils class FFMPEGPrefsHandler { @Throws(Exception::class) fun parse(ffmpegprefs: String?): FFMpegPresetList { val ffPrefs = FFMpegPresetList() if (StringUtils.isBlank(ffmpegprefs)) { return ffPrefs } val iniParser = INIParser(ffmpegprefs) ffPrefs.version = iniParser.getString("Version", "Version") val sectionIterator = iniParser.sections while (sectionIterator.hasNext()) { val sectionName = sectionIterator.next() if (isPreset(iniParser, sectionName)) { val preset = Preset() preset.title = sectionName val mimeType = iniParser.getString(sectionName, "MimeType") if (StringUtils.isEmpty(mimeType)) { preset.mimeType = StreamUtils.M3U8_MIME_TYPE } else { preset.mimeType = mimeType } preset.extension = iniParser.getString(sectionName, "Ext") ffPrefs.presets.add(preset) } } return ffPrefs } private fun isPreset(iniParser: INIParser, sectionName: String): Boolean { val keysIterator = iniParser.getKeys(sectionName) var isPreset = false while (keysIterator!!.hasNext()) { val keyName = keysIterator.next() if ("Cmd" == keyName) { isPreset = true } } return isPreset } }
dvbViewerController/src/main/java/org/dvbviewer/controller/data/api/handler/FFMPEGPrefsHandler.kt
1760398969
package com.darrenatherton.droidcommunity.data.subscription.mapper import com.darrenatherton.droidcommunity.data.subscription.SubscriptionData import com.google.firebase.database.DataSnapshot /** * Functions used to transform data from Firebase responses to valid data layer objects. */ internal fun convertSubscriptionsResponseToData(dataSnapshot: DataSnapshot): List<SubscriptionData> { return dataSnapshot.children.map { val subscription = it.getValue(SubscriptionData::class.java) SubscriptionData(it.key, subscription.readable, subscription.type, subscription.order) } }
app/src/main/kotlin/com/darrenatherton/droidcommunity/data/subscription/mapper/SubscriptionResponseMapper.kt
1600947565
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.util.* import io.ktor.utils.io.* import io.ktor.utils.io.charsets.* import io.ktor.utils.io.core.* import kotlin.math.* /** * [HttpClient] plugin that encodes [String] request bodies to [TextContent] * and processes the response body as [String]. * * To configure charsets set following properties in [HttpPlainText.Config]. */ public class HttpPlainText internal constructor( charsets: Set<Charset>, charsetQuality: Map<Charset, Float>, sendCharset: Charset?, private val responseCharsetFallback: Charset ) { private val requestCharset: Charset private val acceptCharsetHeader: String init { val withQuality = charsetQuality.toList().sortedByDescending { it.second } val withoutQuality = charsets.filter { !charsetQuality.containsKey(it) }.sortedBy { it.name } acceptCharsetHeader = buildString { withoutQuality.forEach { if (isNotEmpty()) append(",") append(it.name) } withQuality.forEach { (charset, quality) -> if (isNotEmpty()) append(",") check(quality in 0.0..1.0) val truncatedQuality = (100 * quality).roundToInt() / 100.0 append("${charset.name};q=$truncatedQuality") } if (isEmpty()) { append(responseCharsetFallback.name) } } requestCharset = sendCharset ?: withoutQuality.firstOrNull() ?: withQuality.firstOrNull()?.first ?: Charsets.UTF_8 } /** * Charset configuration for [HttpPlainText] plugin. */ @KtorDsl public class Config { internal val charsets: MutableSet<Charset> = mutableSetOf() internal val charsetQuality: MutableMap<Charset, Float> = mutableMapOf() /** * Add [charset] to allowed list with selected [quality]. */ public fun register(charset: Charset, quality: Float? = null) { quality?.let { check(it in 0.0..1.0) } charsets.add(charset) if (quality == null) { charsetQuality.remove(charset) } else { charsetQuality[charset] = quality } } /** * Explicit [Charset] for sending content. * * Use first with the highest quality from [register] charset if null. */ public var sendCharset: Charset? = null /** * Fallback charset for the response. * Use it if no charset specified. */ public var responseCharsetFallback: Charset = Charsets.UTF_8 } @Suppress("KDocMissingDocumentation") public companion object Plugin : HttpClientPlugin<Config, HttpPlainText> { override val key: AttributeKey<HttpPlainText> = AttributeKey("HttpPlainText") override fun prepare(block: Config.() -> Unit): HttpPlainText { val config = Config().apply(block) with(config) { return HttpPlainText( charsets, charsetQuality, sendCharset, responseCharsetFallback ) } } override fun install(plugin: HttpPlainText, scope: HttpClient) { scope.requestPipeline.intercept(HttpRequestPipeline.Render) { content -> plugin.addCharsetHeaders(context) if (content !is String) return@intercept val contentType = context.contentType() if (contentType != null && contentType.contentType != ContentType.Text.Plain.contentType) { return@intercept } proceedWith(plugin.wrapContent(content, contentType)) } scope.responsePipeline.intercept(HttpResponsePipeline.Transform) { (info, body) -> if (info.type != String::class || body !is ByteReadChannel) return@intercept val bodyBytes = body.readRemaining() val content = plugin.read(context, bodyBytes) proceedWith(HttpResponseContainer(info, content)) } } } private fun wrapContent(content: String, requestContentType: ContentType?): Any { val contentType: ContentType = requestContentType ?: ContentType.Text.Plain val charset = requestContentType?.charset() ?: requestCharset return TextContent(content, contentType.withCharset(charset)) } internal fun read(call: HttpClientCall, body: Input): String { val actualCharset = call.response.charset() ?: responseCharsetFallback return body.readText(charset = actualCharset) } internal fun addCharsetHeaders(context: HttpRequestBuilder) { if (context.headers[HttpHeaders.AcceptCharset] != null) return context.headers[HttpHeaders.AcceptCharset] = acceptCharsetHeader } } /** * Configure client charsets. * * ```kotlin * val client = HttpClient { * Charsets { * register(Charsets.UTF_8) * register(Charsets.ISO_8859_1, quality = 0.1) * } * } * ``` */ @Suppress("FunctionName") public fun HttpClientConfig<*>.Charsets(block: HttpPlainText.Config.() -> Unit) { install(HttpPlainText, block) }
ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpPlainText.kt
767007507
package net.monarezio.domain.common.extension import java.util.concurrent.ThreadLocalRandom /** * Created by monarezio on 08/07/2017. */ /** * Returns a random int between var lower and upper (both including) */ fun Int.Companion.random (lower: Int , upper: Int) = ThreadLocalRandom.current().nextInt(lower, upper + 2);
src/main/kotlin/net/monarezio/domain/common/extension/Int.kt
4030122555
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import vulkan.* val AMD_shader_core_properties = "AMDShaderCoreProperties".nativeClassVK("AMD_shader_core_properties", type = "device", postfix = "AMD") { documentation = """ This extension exposes shader core properties for a target physical device through the {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} extension. Please refer to the example below for proper usage. <h5>Examples</h5> This example retrieves the shader core properties for a physical device. <pre><code> ￿extern VkInstance instance; ￿ ￿PFN_vkGetPhysicalDeviceProperties2 pfnVkGetPhysicalDeviceProperties2 = ￿ reinterpret_cast&lt;PFN_vkGetPhysicalDeviceProperties2&gt; ￿ (vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2") ); ￿ ￿VkPhysicalDeviceProperties2 general_props; ￿VkPhysicalDeviceShaderCorePropertiesAMD shader_core_properties; ￿ ￿shader_core_properties.pNext = nullptr; ￿shader_core_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_AMD; ￿ ￿general_props.pNext = &amp;shader_core_properties; ￿general_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; ￿ ￿// After this call, shader_core_properties has been populated ￿pfnVkGetPhysicalDeviceProperties2(device, &amp;general_props); ￿ ￿printf("Number of shader engines: %d\n", ￿ m_shader_core_properties.shader_engine_count = ￿ shader_core_properties.shaderEngineCount; ￿printf("Number of shader arrays: %d\n", ￿ m_shader_core_properties.shader_arrays_per_engine_count = ￿ shader_core_properties.shaderArraysPerEngineCount; ￿printf("Number of CUs per shader array: %d\n", ￿ m_shader_core_properties.compute_units_per_shader_array = ￿ shader_core_properties.computeUnitsPerShaderArray; ￿printf("Number of SIMDs per compute unit: %d\n", ￿ m_shader_core_properties.simd_per_compute_unit = ￿ shader_core_properties.simdPerComputeUnit; ￿printf("Number of wavefront slots in each SIMD: %d\n", ￿ m_shader_core_properties.wavefronts_per_simd = ￿ shader_core_properties.wavefrontsPerSimd; ￿printf("Number of threads per wavefront: %d\n", ￿ m_shader_core_properties.wavefront_size = ￿ shader_core_properties.wavefrontSize; ￿printf("Number of physical SGPRs per SIMD: %d\n", ￿ m_shader_core_properties.sgprs_per_simd = ￿ shader_core_properties.sgprsPerSimd; ￿printf("Minimum number of SGPRs that can be allocated by a wave: %d\n", ￿ m_shader_core_properties.min_sgpr_allocation = ￿ shader_core_properties.minSgprAllocation; ￿printf("Number of available SGPRs: %d\n", ￿ m_shader_core_properties.max_sgpr_allocation = ￿ shader_core_properties.maxSgprAllocation; ￿printf("SGPRs are allocated in groups of this size: %d\n", ￿ m_shader_core_properties.sgpr_allocation_granularity = ￿ shader_core_properties.sgprAllocationGranularity; ￿printf("Number of physical VGPRs per SIMD: %d\n", ￿ m_shader_core_properties.vgprs_per_simd = ￿ shader_core_properties.vgprsPerSimd; ￿printf("Minimum number of VGPRs that can be allocated by a wave: %d\n", ￿ m_shader_core_properties.min_vgpr_allocation = ￿ shader_core_properties.minVgprAllocation; ￿printf("Number of available VGPRs: %d\n", ￿ m_shader_core_properties.max_vgpr_allocation = ￿ shader_core_properties.maxVgprAllocation; ￿printf("VGPRs are allocated in groups of this size: %d\n", ￿ m_shader_core_properties.vgpr_allocation_granularity = ￿ shader_core_properties.vgprAllocationGranularity;</code></pre> <h5>VK_AMD_shader_core_properties</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_AMD_shader_core_properties}</dd> <dt><b>Extension Type</b></dt> <dd>Device extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>186</dd> <dt><b>Revision</b></dt> <dd>2</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> <li>Requires {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} to be enabled for any device-level functionality</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Martin Dinkov <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_AMD_shader_core_properties]%20@mdinkov%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_AMD_shader_core_properties%20extension*">mdinkov</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2019-06-25</dd> <dt><b>IP Status</b></dt> <dd>No known IP claims.</dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Martin Dinkov, AMD</li> <li>Matthaeus G. Chajdas, AMD</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "AMD_SHADER_CORE_PROPERTIES_SPEC_VERSION".."2" ) StringConstant( "The extension name.", "AMD_SHADER_CORE_PROPERTIES_EXTENSION_NAME".."VK_AMD_shader_core_properties" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_AMD".."1000185000" ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/AMD_shader_core_properties.kt
4143088349
package imgui.demo import gli_.has import glm_.L import glm_.f import glm_.i import glm_.vec2.Vec2 import glm_.vec4.Vec4 import imgui.* import imgui.ImGui.alignTextToFramePadding import imgui.ImGui.begin import imgui.ImGui.beginChild import imgui.ImGui.beginGroup import imgui.ImGui.beginMenu import imgui.ImGui.beginMenuBar import imgui.ImGui.beginTabBar import imgui.ImGui.beginTabItem import imgui.ImGui.beginTable import imgui.ImGui.bulletText import imgui.ImGui.button import imgui.ImGui.checkbox import imgui.ImGui.collapsingHeader import imgui.ImGui.columns import imgui.ImGui.combo import imgui.ImGui.contentRegionAvail import imgui.ImGui.cursorScreenPos import imgui.ImGui.cursorStartPos import imgui.ImGui.dragFloat import imgui.ImGui.dragInt import imgui.ImGui.dragVec2 import imgui.ImGui.dummy import imgui.ImGui.end import imgui.ImGui.endChild import imgui.ImGui.endGroup import imgui.ImGui.endMenu import imgui.ImGui.endMenuBar import imgui.ImGui.endTabBar import imgui.ImGui.endTabItem import imgui.ImGui.endTable import imgui.ImGui.getColumnWidth import imgui.ImGui.getID import imgui.ImGui.invisibleButton import imgui.ImGui.io import imgui.ImGui.isItemActive import imgui.ImGui.isItemHovered import imgui.ImGui.itemRectMax import imgui.ImGui.itemRectSize import imgui.ImGui.listBox import imgui.ImGui.listBoxFooter import imgui.ImGui.listBoxHeader import imgui.ImGui.nextColumn import imgui.ImGui.plotHistogram import imgui.ImGui.popID import imgui.ImGui.popItemWidth import imgui.ImGui.popStyleColor import imgui.ImGui.popStyleVar import imgui.ImGui.pushID import imgui.ImGui.pushItemWidth import imgui.ImGui.pushStyleColor import imgui.ImGui.pushStyleVar import imgui.ImGui.sameLine import imgui.ImGui.scrollMaxX import imgui.ImGui.scrollMaxY import imgui.ImGui.scrollX import imgui.ImGui.scrollY import imgui.ImGui.selectable import imgui.ImGui.separator import imgui.ImGui.setNextItemWidth import imgui.ImGui.setNextWindowContentSize import imgui.ImGui.setScrollFromPosX import imgui.ImGui.setScrollFromPosY import imgui.ImGui.setScrollHereX import imgui.ImGui.setScrollHereY import imgui.ImGui.setTooltip import imgui.ImGui.sliderFloat import imgui.ImGui.sliderInt import imgui.ImGui.smallButton import imgui.ImGui.spacing import imgui.ImGui.style import imgui.ImGui.tableNextColumn import imgui.ImGui.text import imgui.ImGui.textColored import imgui.ImGui.textLineHeight import imgui.ImGui.textUnformatted import imgui.ImGui.textWrapped import imgui.ImGui.treeNode import imgui.ImGui.treePop import imgui.ImGui.windowContentRegionMax import imgui.ImGui.windowContentRegionWidth import imgui.ImGui.windowDrawList import imgui.ImGui.windowPos import imgui.api.demoDebugInformations.Companion.helpMarker import imgui.classes.Color import imgui.demo.showExampleApp.MenuFile import imgui.dsl.child import imgui.dsl.group import imgui.dsl.indent import imgui.dsl.menuBar import imgui.dsl.treeNode import imgui.dsl.withClipRect import imgui.dsl.withID import imgui.dsl.withItemWidth import imgui.dsl.withStyleColor import imgui.dsl.withStyleVar import kotlin.math.sin import imgui.WindowFlag as Wf object ShowDemoWindowLayout { operator fun invoke() { if (!collapsingHeader("Layout & Scrolling")) return `Child Windows`() `Widgets Width`() `Basic Horizontal SimpleLayout`() treeNode("Groups") { helpMarker( "BeginGroup() basically locks the horizontal position for new line. " + "EndGroup() bundles the whole group so that you can use \"item\" functions such as " + "IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group.") beginGroup() group { button("AAA") sameLine() button("BBB") sameLine() group { button("CCC") button("DDD") } sameLine() button("EEE") } if (isItemHovered()) setTooltip("First group hovered") // Capture the group size and create widgets using the same size val size = Vec2(itemRectSize) val values = floatArrayOf(0.5f, 0.2f, 0.8f, 0.6f, 0.25f) plotHistogram("##values", values, 0, "", 0f, 1f, size) button("ACTION", Vec2((size.x - style.itemSpacing.x) * 0.5f, size.y)) sameLine() button("REACTION", Vec2((size.x - style.itemSpacing.x) * 0.5f, size.y)) endGroup() sameLine() button("LEVERAGE\nBUZZWORD", size) sameLine() if (listBoxHeader("List", size)) { selectable("Selected", true) selectable("Not Selected", false) listBoxFooter() } } treeNode("Text Baseline Alignment") { run { bulletText("Text baseline:") sameLine(); helpMarker( "This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. " + "Lines only composed of text or \"small\" widgets use less vertical space than lines with framed widgets.") indent { text("KO Blahblah"); sameLine() button("Some framed item"); sameLine() helpMarker("Baseline of button will look misaligned with text..") // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. // (because we don't know what's coming after the Text() statement, we need to move the text baseline // down by FramePadding.y ahead of time) alignTextToFramePadding() text("OK Blahblah"); sameLine() button("Some framed item"); sameLine() helpMarker("We call AlignTextToFramePadding() to vertically align the text baseline by +FramePadding.y") // SmallButton() uses the same vertical padding as Text button("TEST##1"); sameLine() text("TEST"); sameLine() smallButton("TEST##2") // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. alignTextToFramePadding() text("Text aligned to framed item"); sameLine() button("Item##1"); sameLine() text("Item"); sameLine() smallButton("Item##2"); sameLine() button("Item##3") } } spacing() run { bulletText("Multi-line text:") indent { text("One\nTwo\nThree"); sameLine() text("Hello\nWorld"); sameLine() text("Banana") text("Banana"); sameLine() text("Hello\nWorld"); sameLine() text("One\nTwo\nThree") button("HOP##1"); sameLine() text("Banana"); sameLine() text("Hello\nWorld"); sameLine() text("Banana") button("HOP##2"); sameLine() text("Hello\nWorld"); sameLine() text("Banana") } } spacing() run { bulletText("Misc items:") indent { // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. button("80x80", Vec2(80)) sameLine() button("50x50", Vec2(50)) sameLine() button("Button()") sameLine() smallButton("SmallButton()") // Tree val spacing = style.itemInnerSpacing.x button("Button##1") sameLine(0f, spacing) treeNode("Node##1") { // Placeholder tree data for (i in 0..5) bulletText("Item $i..") } // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. // Otherwise you can use SmallButton() (smaller fit). alignTextToFramePadding() // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add // other contents below the node. val nodeOpen = treeNode("Node##2") sameLine(0f, spacing); button("Button##2") if (nodeOpen) { // Placeholder tree data for (i in 0..5) bulletText("Item $i..") treePop() } // Bullet button("Button##3") sameLine(0f, spacing) bulletText("Bullet text") alignTextToFramePadding() bulletText("Node") sameLine(0f, spacing); button("Button##4") } } } Scrolling() Clipping() } object `Child Windows` { var disableMouseWheel = false var disableMenu = false var offsetX = 0 operator fun invoke() { treeNode("Child Windows") { helpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window.") checkbox("Disable Mouse Wheel", ::disableMouseWheel) checkbox("Disable Menu", ::disableMenu) // Child 1: no border, enable horizontal scrollbar run { var windowFlags = Wf.HorizontalScrollbar.i if (disableMouseWheel) windowFlags = windowFlags or Wf.NoScrollWithMouse child("ChildL", Vec2(windowContentRegionWidth * 0.5f, 260), false, windowFlags) { for (i in 0..99) text("%04d: scrollable region", i) } } sameLine() // Child 2: rounded border run { var windowFlags = Wf.None.i if (disableMouseWheel) windowFlags = windowFlags or Wf.NoScrollWithMouse if (!disableMenu) windowFlags = windowFlags or Wf.MenuBar withStyleVar(StyleVar.ChildRounding, 5f) { child("ChildR", Vec2(0, 260), true, windowFlags) { if (!disableMenu && beginMenuBar()) { if (beginMenu("Menu")) { MenuFile() endMenu() } endMenuBar() } columns(2) if (beginTable("split", 2, TableFlag.Resizable or TableFlag.NoSavedSettings)) { for (i in 0..99) { val text = "%03d".format(style.locale, i) tableNextColumn() button(text, Vec2(-Float.MIN_VALUE, 0f)) } } endTable() } } } separator() // Demonstrate a few extra things // - Changing ImGuiCol_ChildBg (which is transparent black in default styles) // - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window) // You can also call SetNextWindowPos() to position the child window. The parent window will effectively // layout from this position. // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from // the POV of the parent window). See 'Demo->Querying Status (Active/Focused/Hovered etc.)' for details. run { setNextItemWidth(100f) dragInt("Offset X", ::offsetX, 1f, -1000, 1000) ImGui.cursorPosX += offsetX withStyleColor(Col.ChildBg, COL32(255, 0, 0, 100)) { beginChild("Red", Vec2(200, 100), true, Wf.None.i) for (n in 0..49) text("Some test $n") endChild() } val childIsHovered = ImGui.isItemHovered() val childRectMin = ImGui.itemRectMin val childRectMax = ImGui.itemRectMax text("Hovered: ${childIsHovered.i}") text("Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)", childRectMin.x, childRectMin.y, childRectMax.x, childRectMax.y) } } } } object `Widgets Width` { var f = 0f var showIndentedItems = true operator fun invoke() { treeNode("Widgets Width") { // Use SetNextItemWidth() to set the width of a single upcoming item. // Use PushItemWidth()/PopItemWidth() to set the width of a group of items. // In real code use you'll probably want to choose width values that are proportional to your font size // e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc. checkbox("Show indented items", ::showIndentedItems) text("SetNextItemWidth/PushItemWidth(100)") sameLine(); helpMarker("Fixed width.") pushItemWidth(100) dragFloat("float##1b", ::f) if (showIndentedItems) indent { dragFloat("float (indented)##1b", ::f) } popItemWidth() text("SetNextItemWidth/PushItemWidth(-100)") sameLine(); helpMarker("Align to right edge minus 100") pushItemWidth(-100) dragFloat("float##2a", ::f) if (showIndentedItems) indent { dragFloat("float (indented)##2b", ::f) } popItemWidth() text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)") sameLine(); helpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)") pushItemWidth(contentRegionAvail.x * 0.5f) dragFloat("float##3a", ::f) if (showIndentedItems) indent { dragFloat("float (indented)##3b", ::f) } popItemWidth() text("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)") sameLine(); helpMarker("Align to right edge minus half") pushItemWidth(-ImGui.contentRegionAvail.x * 0.5f) dragFloat("float##4a", ::f) if (showIndentedItems) indent { dragFloat("float (indented)##4b", ::f) } popItemWidth() // Demonstrate using PushItemWidth to surround three items. // Calling SetNextItemWidth() before each of them would have the same effect. text("SetNextItemWidth/PushItemWidth(-FLT_MIN)") sameLine(); helpMarker("Align to right edge") pushItemWidth(-Float.MIN_VALUE) dragFloat("##float5a", ::f) if (showIndentedItems) indent { dragFloat("float (indented)##5b", ::f) } popItemWidth() } } } object `Basic Horizontal SimpleLayout` { var c1 = false var c2 = false var c3 = false var c4 = false var f0 = 1f var f1 = 2f var f2 = 3f var item = -1 val selection = intArrayOf(0, 1, 2, 3) operator fun invoke() { treeNode("Basic Horizontal SimpleLayout") { textWrapped("(Use SameLine() to keep adding items to the right of the preceding item)") // Text text("Two items: Hello"); sameLine() textColored(Vec4(1, 1, 0, 1), "Sailor") // Adjust spacing text("More spacing: Hello"); sameLine(0, 20) textColored(Vec4(1, 1, 0, 1), "Sailor") // Button alignTextToFramePadding() text("Normal buttons"); sameLine() button("Banana"); sameLine() button("Apple"); sameLine() button("Corniflower") // Button text("Small buttons"); sameLine() smallButton("Like this one"); sameLine() text("can fit within a text block.") // Aligned to arbitrary position. Easy/cheap column. text("Aligned") sameLine(150); text("x=150") sameLine(300); text("x=300") text("Aligned") sameLine(150); smallButton("x=150") sameLine(300); smallButton("x=300") // Checkbox checkbox("My", ::c1); sameLine() checkbox("Tailor", ::c2); sameLine() checkbox("Is", ::c3); sameLine() checkbox("Rich", ::c4) // Various val items = arrayOf("AAAA", "BBBB", "CCCC", "DDDD") withItemWidth(80f) { combo("Combo", ::item, items); sameLine() sliderFloat("X", ::f0, 0f, 5f); sameLine() sliderFloat("Y", ::f1, 0f, 5f); sameLine() sliderFloat("Z", ::f2, 0f, 5f) } withItemWidth(80f) { text("Lists:") for (i in 0..3) { if (i > 0) sameLine() withID(i) { withInt(selection, i) { listBox("", it, items) } } //if (IsItemHovered()) SetTooltip("ListBox %d hovered", i); } } // Dummy val buttonSz = Vec2(40) button("A", buttonSz); sameLine() dummy(buttonSz); sameLine() button("B", buttonSz) // Manually wrapping // (we should eventually provide this as an automatic layout feature, but for now you can do it manually) text("Manually wrapping:") val buttonsCount = 20 val windowVisibleX2 = windowPos.x + windowContentRegionMax.x for (n in 0 until buttonsCount) { pushID(n) button("Box", buttonSz) val lastButtonX2 = itemRectMax.x val nextButtonX2 = lastButtonX2 + style.itemSpacing.x + buttonSz.x // Expected position if next button was on same line if (n + 1 < buttonsCount && nextButtonX2 < windowVisibleX2) sameLine() popID() } } } } object Scrolling { var enableTrack = true var enableExtraDecorations = false var trackItem = 50 val names = arrayOf("Left", "25%%", "Center", "75%%", "Right") var scrollToOffPx = 0f var scrollToPosPx = 200f var lines = 7 var showHorizontalContentsSizeDemoWindow = false var showHscrollbar = true var showButton = true var showTreeNodes = true var showTextWrapped = false var open = true var showColumns = true var showTabBar = true var showChild = false var explicitContentSize = false var contentsSizeX = 300f operator fun invoke() { treeNode("Scrolling") { // Vertical scroll functions helpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position.") checkbox("Decoration", ::enableExtraDecorations) checkbox("Track", ::enableTrack) pushItemWidth(100) sameLine(140); enableTrack = dragInt("##item", ::trackItem, 0.25f, 0, 99, "Item = %d") or enableTrack var scrollToOff = button("Scroll Offset") sameLine(140); scrollToOff = dragFloat("##off", ::scrollToOffPx, 1f, 0f, Float.MAX_VALUE, "+%.0f px") or scrollToOff var scrollToPos = button("Scroll To Pos") sameLine(140); scrollToPos = dragFloat("##pos", ::scrollToPosPx, 1f, -10f, Float.MAX_VALUE, "X/Y = %.0f px") or scrollToPos popItemWidth() if (scrollToOff || scrollToPos) enableTrack = false var childW = (contentRegionAvail.x - 4 * style.itemSpacing.x) / 5 if (childW < 1f) childW = 1f pushID("##VerticalScrolling") for (i in 0..4) { if (i > 0) sameLine() group { val names = arrayOf("Top", "25%%", "Center", "75%%", "Bottom") // double quote for ::format escaping textUnformatted(names[i]) val childFlags = if (enableExtraDecorations) Wf.MenuBar else Wf.None val childId = getID(i.L) val childIsVisible = beginChild(childId, Vec2(childW, 200f), true, childFlags.i) menuBar { textUnformatted("abc") } if (scrollToOff) scrollY = scrollToOffPx if (scrollToPos) setScrollFromPosY(cursorStartPos.y + scrollToPosPx, i * 0.25f) // Avoid calling SetScrollHereY when running with culled items if (childIsVisible) for (item in 0..99) if (enableTrack && item == trackItem) { textColored(Vec4(1, 1, 0, 1), "Item %d", item) setScrollHereY(i * 0.25f) // 0.0f:top, 0.5f:center, 1.0f:bottom } else text("Item $item") val scrollY = scrollY val scrollMaxY = scrollMaxY endChild() text("%.0f/%.0f", scrollY, scrollMaxY) } } popID() // Horizontal scroll functions spacing() helpMarker( "Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n" + "Because the clipping rectangle of most window hides half worth of WindowPadding on the " + "left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the " + "equivalent SetScrollFromPosY(+1) wouldn't.") pushID("##HorizontalScrolling") for (i in 0..4) { val childHeight = textLineHeight + style.scrollbarSize + style.windowPadding.y * 2f val childFlags = Wf.HorizontalScrollbar or if (enableExtraDecorations) Wf.AlwaysVerticalScrollbar else Wf.None val childId = getID(i.L) val childIsVisible = beginChild(childId, Vec2(-100f, childHeight), true, childFlags) if (scrollToOff) scrollX = scrollToOffPx if (scrollToPos) setScrollFromPosX(cursorStartPos.x + scrollToPosPx, i * 0.25f) if (childIsVisible) // Avoid calling SetScrollHereY when running with culled items for (item in 0..99) { if (enableTrack && item == trackItem) { textColored(Vec4(1, 1, 0, 1), "Item $item") setScrollHereX(i * 0.25f) // 0.0f:left, 0.5f:center, 1.0f:right } else text("Item $item") sameLine() } endChild() sameLine() text("${names[i]}\n%.0f/%.0f", scrollX, scrollMaxX) spacing() } popID() // Miscellaneous Horizontal Scrolling Demo helpMarker( "Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\n" + "You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin().") sliderInt("Lines", ::lines, 1, 15) pushStyleVar(StyleVar.FrameRounding, 3f) pushStyleVar(StyleVar.FramePadding, Vec2(2f, 1f)) val scrollingChildSize = Vec2(0f, ImGui.frameHeightWithSpacing * 7 + 30) beginChild("scrolling", scrollingChildSize, true, Wf.HorizontalScrollbar.i) for (line in 0 until lines) { // Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine() // If you want to create your own time line for a real application you may be better off manipulating // the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets // yourself. You may also want to use the lower-level ImDrawList API. val numButtons = 10 + (line * if (line has 1) 9 else 3) for (n in 0 until numButtons) { if (n > 0) sameLine() pushID(n + line * 1000) val label = if (n % 15 == 0) "FizzBuzz" else if (n % 3 == 0) "Fizz" else if (n % 5 == 0) "Buzz" else "$n" val hue = n * 0.05f pushStyleColor(Col.Button, Color.hsv(hue, 0.6f, 0.6f)) pushStyleColor(Col.ButtonHovered, Color.hsv(hue, 0.7f, 0.7f)) pushStyleColor(Col.ButtonActive, Color.hsv(hue, 0.8f, 0.8f)) button(label, Vec2(40f + sin((line + n).f) * 20f, 0f)) popStyleColor(3) popID() } } val _scrollX = scrollX val scrollMaxX = scrollMaxX endChild() popStyleVar(2) var scrollXDelta = 0f smallButton("<<") if (isItemActive) scrollXDelta = -io.deltaTime * 1000f sameLine() text("Scroll from code"); sameLine() smallButton(">>") if (isItemActive) scrollXDelta = io.deltaTime * 1000f sameLine() text("%.0f/%.0f", _scrollX, scrollMaxX) if (scrollXDelta != 0f) { // Demonstrate a trick: you can use Begin to set yourself in the context of another window // (here we are already out of your child window) beginChild("scrolling") scrollX += scrollXDelta endChild() } spacing() checkbox("Show Horizontal contents size demo window", ::showHorizontalContentsSizeDemoWindow) if (showHorizontalContentsSizeDemoWindow) { if (explicitContentSize) setNextWindowContentSize(Vec2(contentsSizeX, 0f)) begin("Horizontal contents size demo window", ::showHorizontalContentsSizeDemoWindow, if (showHscrollbar) Wf.HorizontalScrollbar.i else Wf.None.i) pushStyleVar(StyleVar.ItemSpacing, Vec2(2, 0)) pushStyleVar(StyleVar.FramePadding, Vec2(2, 0)) helpMarker("Test of different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\nUse 'Metrics->Tools->Show windows rectangles' to visualize rectangles.") checkbox("H-scrollbar", ::showHscrollbar) checkbox("Button", ::showButton) // Will grow contents size (unless explicitly overwritten) checkbox("Tree nodes", ::showTreeNodes) // Will grow contents size and display highlight over full width checkbox("Text wrapped", ::showTextWrapped) // Will grow and use contents size checkbox("Columns", ::showColumns) // Will use contents size checkbox("Tab bar", ::showTabBar) // Will use contents size checkbox("Child", ::showChild) // Will grow and use contents size checkbox("Explicit content size", ::explicitContentSize) text("Scroll %.1f/%.1f %.1f/%.1f", scrollX, scrollMaxX, scrollY, scrollMaxY) if (explicitContentSize) { sameLine() setNextItemWidth(100f) dragFloat("##csx", ::contentsSizeX) val p = cursorScreenPos windowDrawList.addRectFilled(p, Vec2(p.x + 10, p.y + 10), COL32_WHITE) windowDrawList.addRectFilled(Vec2(p.x + contentsSizeX - 10, p.y), Vec2(p.x + contentsSizeX, p.y + 10), COL32_WHITE) dummy(Vec2(0, 10)) } popStyleVar(2) separator() if (showButton) button("this is a 300-wide button", Vec2(300, 0)) if (showTreeNodes) { open = true treeNode("this is a tree node") { treeNode("another one of those tree node...") { text("Some tree contents") } } collapsingHeader("CollapsingHeader", ::open) } if (showTextWrapped) textWrapped("This text should automatically wrap on the edge of the work rectangle.") if (showColumns) { text("Tables:") if (beginTable("table", 4, TableFlag.Borders.i)) { for (n in 0..3) { tableNextColumn() text("Width %.2f", ImGui.contentRegionAvail.x) } endTable() } text("Columns:") columns(4) for (n in 0..3) { text("Width %.2f", getColumnWidth()) nextColumn() } columns(1) } if (showTabBar && beginTabBar("Hello")) { if (beginTabItem("OneOneOne")) endTabItem() if (beginTabItem("TwoTwoTwo")) endTabItem() if (beginTabItem("ThreeThreeThree")) endTabItem() if (beginTabItem("FourFourFour")) endTabItem() endTabBar() } if (showChild) { beginChild("child", Vec2(), true) endChild() } end() } } } } object Clipping { val size = Vec2(100f) val offset = Vec2(30) operator fun invoke() { treeNode("Clipping") { dragVec2("size", size, 0.5f, 1f, 200f, "%.0f") textWrapped("(Click and drag to scroll)") for (n in 0..2) { if (n > 0) sameLine() pushID(n) group { // Lock X position invisibleButton("##empty", size) if (ImGui.isItemActive && ImGui.isMouseDragging(MouseButton.Left)) offset += io.mouseDelta val p0 = Vec2(ImGui.itemRectMin) val p1 = Vec2(ImGui.itemRectMax) val textStr = "Line 1 hello\nLine 2 clip me!" val textPos = p0 + offset val drawList = ImGui.windowDrawList when (n) { 0 -> { helpMarker(""" Using ImGui::PushClipRect(): Will alter ImGui hit-testing logic + ImDrawList rendering. (use this if you want your clipping rectangle to affect interactions)""".trimIndent()) withClipRect(p0, p1, true) { drawList.addRectFilled(p0, p1, COL32(90, 90, 120, 255)) drawList.addText(textPos, COL32_WHITE, textStr) } } 1 -> { helpMarker(""" Using ImDrawList::PushClipRect(): Will alter ImDrawList rendering only. (use this as a shortcut if you are only using ImDrawList calls)""".trimIndent()) drawList.withClipRect(p0, p1, true) { addRectFilled(p0, p1, COL32(90, 90, 120, 255)) addText(textPos, COL32_WHITE, textStr) } } 2 -> { helpMarker(""" Using ImDrawList::AddText() with a fine ClipRect: Will alter only this specific ImDrawList::AddText() rendering. (this is often used internally to avoid altering the clipping rectangle and minimize draw calls)""".trimIndent()) val clipRect = Vec4(p0, p1) // AddText() takes a ImVec4* here so let's convert. drawList.addRectFilled(p0, p1, COL32(90, 90, 120, 255)) drawList.addText(ImGui.font, ImGui.fontSize, textPos, COL32_WHITE, textStr, 0f, clipRect) } } } popID() } } } } }
core/src/main/kotlin/imgui/demo/ShowDemoWindowLayout.kt
2840327565
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import vulkan.* val GOOGLE_display_timing = "GOOGLEDisplayTiming".nativeClassVK("GOOGLE_display_timing", type = "device", postfix = "GOOGLE") { documentation = """ This device extension allows an application that uses the {@link KHRSwapchain VK_KHR_swapchain} extension to obtain information about the presentation engine’s display, to obtain timing information about each present, and to schedule a present to happen no earlier than a desired time. An application can use this to minimize various visual anomalies (e.g. stuttering). Traditional game and real-time animation applications need to correctly position their geometry for when the presentable image will be presented to the user. To accomplish this, applications need various timing information about the presentation engine’s display. They need to know when presentable images were actually presented, and when they could have been presented. Applications also need to tell the presentation engine to display an image no sooner than a given time. This allows the application to avoid stuttering, so the animation looks smooth to the user. This extension treats variable-refresh-rate (VRR) displays as if they are fixed-refresh-rate (FRR) displays. <h5>Examples</h5> <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5> The example code for the this extension (like the {@link KHRSurface VK_KHR_surface} and {@code VK_GOOGLE_display_timing} extensions) is contained in the cube demo that is shipped with the official Khronos SDK, and is being kept up-to-date in that location (see: <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Tools/blob/master/cube/cube.c">https://github.com/KhronosGroup/Vulkan-Tools/blob/master/cube/cube.c</a> ). </div> <h5>VK_GOOGLE_display_timing</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_GOOGLE_display_timing}</dd> <dt><b>Extension Type</b></dt> <dd>Device extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>93</dd> <dt><b>Revision</b></dt> <dd>1</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> <li>Requires {@link KHRSwapchain VK_KHR_swapchain} to be enabled for any device-level functionality</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Ian Elliott <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_GOOGLE_display_timing]%20@ianelliottus%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_GOOGLE_display_timing%20extension*">ianelliottus</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2017-02-14</dd> <dt><b>IP Status</b></dt> <dd>No known IP claims.</dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Ian Elliott, Google</li> <li>Jesse Hall, Google</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "GOOGLE_DISPLAY_TIMING_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "GOOGLE_DISPLAY_TIMING_EXTENSION_NAME".."VK_GOOGLE_display_timing" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE".."1000092000" ) VkResult( "GetRefreshCycleDurationGOOGLE", """ Obtain the RC duration of the PE’s display. <h5>C Specification</h5> To query the duration of a refresh cycle (RC) for the presentation engine’s display, call: <pre><code> ￿VkResult vkGetRefreshCycleDurationGOOGLE( ￿ VkDevice device, ￿ VkSwapchainKHR swapchain, ￿ VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties);</code></pre> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code swapchain} <b>must</b> be a valid {@code VkSwapchainKHR} handle</li> <li>{@code pDisplayTimingProperties} <b>must</b> be a valid pointer to a ##VkRefreshCycleDurationGOOGLE structure</li> <li>Both of {@code device}, and {@code swapchain} <b>must</b> have been created, allocated, or retrieved from the same {@code VkInstance}</li> </ul> <h5>Host Synchronization</h5> <ul> <li>Host access to {@code swapchain} <b>must</b> be externally synchronized</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_OUT_OF_HOST_MEMORY</li> <li>#ERROR_DEVICE_LOST</li> <li>#ERROR_SURFACE_LOST_KHR</li> </ul></dd> </dl> <h5>See Also</h5> ##VkRefreshCycleDurationGOOGLE """, VkDevice("device", "the device associated with {@code swapchain}."), VkSwapchainKHR("swapchain", "the swapchain to obtain the refresh duration for."), VkRefreshCycleDurationGOOGLE.p("pDisplayTimingProperties", "a pointer to a ##VkRefreshCycleDurationGOOGLE structure.") ) VkResult( "GetPastPresentationTimingGOOGLE", """ Obtain timing of a previously-presented image. <h5>C Specification</h5> The implementation will maintain a limited amount of history of timing information about previous presents. Because of the asynchronous nature of the presentation engine, the timing information for a given #QueuePresentKHR() command will become available some time later. These time values can be asynchronously queried, and will be returned if available. All time values are in nanoseconds, relative to a monotonically-increasing clock (e.g. {@code CLOCK_MONOTONIC} (see clock_gettime(2)) on Android and Linux). To asynchronously query the presentation engine, for newly-available timing information about one or more previous presents to a given swapchain, call: <pre><code> ￿VkResult vkGetPastPresentationTimingGOOGLE( ￿ VkDevice device, ￿ VkSwapchainKHR swapchain, ￿ uint32_t* pPresentationTimingCount, ￿ VkPastPresentationTimingGOOGLE* pPresentationTimings);</code></pre> <h5>Description</h5> If {@code pPresentationTimings} is {@code NULL}, then the number of newly-available timing records for the given {@code swapchain} is returned in {@code pPresentationTimingCount}. Otherwise, {@code pPresentationTimingCount} <b>must</b> point to a variable set by the user to the number of elements in the {@code pPresentationTimings} array, and on return the variable is overwritten with the number of structures actually written to {@code pPresentationTimings}. If the value of {@code pPresentationTimingCount} is less than the number of newly-available timing records, at most {@code pPresentationTimingCount} structures will be written, and #INCOMPLETE will be returned instead of #SUCCESS, to indicate that not all the available timing records were returned. <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code swapchain} <b>must</b> be a valid {@code VkSwapchainKHR} handle</li> <li>{@code pPresentationTimingCount} <b>must</b> be a valid pointer to a {@code uint32_t} value</li> <li>If the value referenced by {@code pPresentationTimingCount} is not 0, and {@code pPresentationTimings} is not {@code NULL}, {@code pPresentationTimings} <b>must</b> be a valid pointer to an array of {@code pPresentationTimingCount} ##VkPastPresentationTimingGOOGLE structures</li> <li>Both of {@code device}, and {@code swapchain} <b>must</b> have been created, allocated, or retrieved from the same {@code VkInstance}</li> </ul> <h5>Host Synchronization</h5> <ul> <li>Host access to {@code swapchain} <b>must</b> be externally synchronized</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> <li>#INCOMPLETE</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_OUT_OF_HOST_MEMORY</li> <li>#ERROR_DEVICE_LOST</li> <li>#ERROR_OUT_OF_DATE_KHR</li> <li>#ERROR_SURFACE_LOST_KHR</li> </ul></dd> </dl> <h5>See Also</h5> ##VkPastPresentationTimingGOOGLE """, VkDevice("device", "the device associated with {@code swapchain}."), VkSwapchainKHR("swapchain", "the swapchain to obtain presentation timing information duration for."), AutoSize("pPresentationTimings")..Check(1)..uint32_t.p("pPresentationTimingCount", "a pointer to an integer related to the number of ##VkPastPresentationTimingGOOGLE structures to query, as described below."), nullable..VkPastPresentationTimingGOOGLE.p("pPresentationTimings", "either {@code NULL} or a pointer to an array of ##VkPastPresentationTimingGOOGLE structures.") ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/GOOGLE_display_timing.kt
2409361656
package net.pureal.traits.graphics import net.pureal.traits.math.* import net.pureal.traits.* import net.pureal.traits.interaction.KeysElement import net.pureal.traits.interaction.PointersElement trait TextElement : ColoredElement<String> { val font: Font val size: Number override val shape: Shape get() = font.shape(content).transformed(Transforms2.scale(size)) } fun textElement(content: String, font: Font, size: Number, fill: Fill) = object : TextElement { override val content = content override val font = font override val size = size override val fill = fill } trait Font { fun shape(text: String): Shape } trait TextInput : Composed<String>, KeysElement<String>, PointersElement<String> { var text: String override val content: String get() = text var cursorPosition: Int val textChanged: Observable<String> } fun textInput(text: String = "", bound: Rectangle, font: Font, fontFill: Fill, size: Number, backgroundFill: Fill) = object : TextInput { override val shape: Shape = null!! override val textChanged: Observable<String> = null!! override var cursorPosition: Int = null!! override var text = text private fun textElement() = textElement(text, font, size, fontFill) private fun cursor() = coloredElement(rectangle(vector(0,0)), fontFill) private fun background() = coloredElement(bound, backgroundFill) override val elements = observableList<TransformedElement<*>>() private fun refresh() { //elements.setTo(textElement(), cursor(), background()) } }
traits/src/net/pureal/traits/graphics/TextElement.kt
3114220826
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val EXT_direct_state_access = "EXTDirectStateAccess".nativeClassGL("EXT_direct_state_access", postfix = EXT) { documentation = """ Native bindings to the $registryLink extension. This extension introduces a set of new "direct state access" commands (meaning no selector is involved) to access (update and query) OpenGL state that previously depended on the OpenGL state selectors for access. These new commands supplement the existing selector-based OpenGL commands to access the same state. The intent of this extension is to make it more efficient for libraries to avoid disturbing selector and latched state. The extension also allows more efficient command usage by eliminating the need for selector update commands. Two derivative advantages of this extension are 1) display lists can be executed using these commands that avoid disturbing selectors that subsequent commands may depend on, and 2) drivers implemented with a dual-thread partitioning with OpenGL command buffering from an application thread and then OpenGL command dispatching in a concurrent driver thread can avoid thread synchronization created by selector saving, setting, command execution, and selector restoration. This extension does not itself add any new OpenGL state. We call a state variable in OpenGL an "OpenGL state selector" or simply a "selector" if OpenGL commands depend on the state variable to determine what state to query or update. The matrix mode and active texture are both selectors. Object bindings for buffers, programs, textures, and framebuffer objects are also selectors. We call OpenGL state "latched" if the state is set by one OpenGL command but then that state is saved by a subsequent command or the state determines how client memory or buffer object memory is accessed by a subsequent command. The array and element array buffer bindings are latched by vertex array specification commands to determine which buffer a given vertex array uses. Vertex array state and pixel pack/unpack state decides how client memory or buffer object memory is accessed by subsequent vertex pulling or image specification commands. The existence of selectors and latched state in the OpenGL API reduces the number of parameters to various sets of OpenGL commands but complicates the access to state for layered libraries which seek to access state without disturbing other state, namely the state of state selectors and latched state. In many cases, selectors and latched state were introduced by extensions as OpenGL evolved to minimize the disruption to the OpenGL API when new functionality, particularly the pluralization of existing functionality as when texture objects and later multiple texture units, was introduced. The OpenGL API involves several selectors (listed in historical order of introduction): ${ul( "The matrix mode.", "The current bound texture for each supported texture target.", "The active texture.", "The active client texture.", "The current bound program for each supported program target.", "The current bound buffer for each supported buffer target.", "The current GLSL program.", "The current framebuffer object." )} The new selector-free update commands can be compiled into display lists. The OpenGL API has latched state for vertex array buffer objects and pixel store state. When an application issues a GL command to unpack or pack pixels (for example, glTexImage2D or glReadPixels respectively), the current unpack and pack pixel store state determines how the pixels are unpacked from/packed to client memory or pixel buffer objects. For example, consider: ${codeBlock(""" glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_TRUE); glPixelStorei(GL_UNPACK_ROW_LENGTH, 640); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 47); glDrawPixels(100, 100, GL_RGB, GL_FLOAT, pixels);""")} The unpack swap bytes and row length state set by the preceding glPixelStorei commands (as well as the 6 other unpack pixel store state variables) control how data is read (unpacked) from buffer of data pointed to by pixels. The glBindBuffer command also specifies an unpack buffer object (47) so the pixel pointer is actually treated as a byte offset into buffer object 47. When an application issues a command to configure a vertex array, the current array buffer state is latched as the binding for the particular vertex array being specified. For example, consider: ${codeBlock(""" glBindBuffer(GL_ARRAY_BUFFER, 23); glVertexPointer(3, GL_FLOAT, 12, pointer);""")} The glBindBuffer command updates the array buffering binding (GL_ARRAY_BUFFER_BINDING) to the buffer object named 23. The subsequent glVertexPointer command specifies explicit parameters for the size, type, stride, and pointer to access the position vertex array BUT ALSO latches the current array buffer binding for the vertex array buffer binding (GL_VERTEX_ARRAY_BUFFER_BINDING). Effectively the current array buffer binding buffer object becomes an implicit fifth parameter to glVertexPointer and this applies to all the gl*Pointer vertex array specification commands. Selectors and latched state create problems for layered libraries using OpenGL because selectors require the selector state to be modified to update some other state and latched state means implicit state can affect the operation of commands specifying, packing, or unpacking data through pointers/offsets. For layered libraries, a state update performed by the library may attempt to save the selector state, set the selector, update/query some state the selector controls, and then restore the selector to its saved state. Layered libraries can skip the selector save/restore but this risks introducing uncertainty about the state of a selector after calling layered library routines. Such selector side-effects are difficult to document and lead to compatibility issues as the layered library evolves or its usage varies. For latched state, layered libraries may find commands such as glDrawPixels do not work as expected because latched pixel store state is not what the library expects. Querying or pushing the latched state, setting the latched state explicitly, performing the operation involving latched state, and then restoring or popping the latched state avoids entanglements with latched state but at considerable cost. <h3>EXAMPLE USAGE OF THIS EXTENSION'S FUNCTIONALITY</h3> Consider the following routine to set the modelview matrix involving the matrix mode selector: ${codeBlock(""" void setModelviewMatrix(const GLfloat matrix[16]) { GLenum savedMatrixMode; glGetIntegerv(GL_MATRIX_MODE, &savedMatrixMode); glMatrixMode(GL_MODELVIEW); glLoadMatrixf(matrix); glMatrixMode(savedMatrixMode); }""")} Notice that four OpenGL commands are required to update the current modelview matrix without disturbing the matrix mode selector. OpenGL query commands can also substantially reduce the performance of modern OpenGL implementations which may off-load OpenGL state processing to another CPU core/thread or to the GPU itself. An alternative to querying the selector is to use the glPushAttrib/glPopAttrib commands. However this approach typically involves pushing far more state than simply the one or two selectors that need to be saved and restored. Because so much state is associated with a given push/pop attribute bit, the glPushAttrib and glPopAttrib commands are considerably more costly than the save/restore approach. Additionally glPushAttrib risks overflowing the attribute stack. The reliability and performance of layered libraries and applications can be improved by adding to the OpenGL API a new set of commands to access directly OpenGL state that otherwise involves selectors to access. The above example can be reimplemented more efficiently and without selector side-effects: ${codeBlock(""" void setModelviewMatrix(const GLfloat matrix[16]) { glMatrixLoadfEXT(GL_MODELVIEW, matrix); }""")} Consider a layered library seeking to load a texture: ${codeBlock(""" void loadTexture(GLint texobj, GLint width, GLint height, void *data) { glBindTexture(GL_TEXTURE_2D, texobj); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, GL_RGB, GL_FLOAT, data); }""")} The library expects the data to be packed into the buffer pointed to by data. But what if the current pixel unpack buffer binding is not zero so the current pixel unpack buffer, rather than client memory, will be read? Or what if the application has modified the GL_UNPACK_ROW_LENGTH pixel store state before loadTexture is called? We can fix the routine by calling glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0) and setting all the pixel store unpack state to the initial state the loadTexture routine expects, but this is expensive. It also risks disturbing the state so when loadTexture returns to the application, the application doesn't realize the current texture object (for whatever texture unit the current active texture happens to be) and pixel store state has changed. We can more efficiently implement this routine without disturbing selector or latched state as follows: ${codeBlock(""" void loadTexture(GLint texobj, GLint width, GLint height, void *data) { glPushClientAttribDefaultEXT(GL_CLIENT_PIXEL_STORE_BIT); glTextureImage2D(texobj, GL_TEXTURE_2D, 0, GL_RGB8, width, height, GL_RGB, GL_FLOAT, data); glPopClientAttrib(); }""")} Now loadTexture does not have to worry about inappropriately configured pixel store state or a non-zero pixel unpack buffer binding. And loadTexture has no unintended side-effects for selector or latched state (assuming the client attrib state does not overflow). """ IntConstant( "GetBooleani_v, GetIntegeri_v, GetFloati_vEXT, GetDoublei_vEXT.", "PROGRAM_MATRIX_EXT"..0x8E2D, "TRANSPOSE_PROGRAM_MATRIX_EXT"..0x8E2E, "PROGRAM_MATRIX_STACK_DEPTH_EXT"..0x8E2F ) // OpenGL 1.1: New client commands void( "ClientAttribDefaultEXT", "", GLbitfield("mask", "") ) void( "PushClientAttribDefaultEXT", "", GLbitfield("mask", "") ) /* OpenGL 1.0: New matrix commands add "Matrix" prefix to name, drops "Matrix" suffix from name, and add initial "enum matrixMode" parameter */ void( "MatrixLoadfEXT", "", GLenum("matrixMode", ""), Check(16)..GLfloat.const.p("m", "") ) void( "MatrixLoaddEXT", "", GLenum("matrixMode", ""), Check(16)..GLdouble.const.p("m", "") ) void( "MatrixMultfEXT", "", GLenum("matrixMode", ""), Check(16)..GLfloat.const.p("m", "") ) void( "MatrixMultdEXT", "", GLenum("matrixMode", ""), Check(16)..GLdouble.const.p("m", "") ) void( "MatrixLoadIdentityEXT", "", GLenum("matrixMode", "") ) void( "MatrixRotatefEXT", "", GLenum("matrixMode", ""), GLfloat("angle", ""), GLfloat("x", ""), GLfloat("y", ""), GLfloat("z", "") ) void( "MatrixRotatedEXT", "", GLenum("matrixMode", ""), GLdouble("angle", ""), GLdouble("x", ""), GLdouble("y", ""), GLdouble("z", "") ) void( "MatrixScalefEXT", "", GLenum("matrixMode", ""), GLfloat("x", ""), GLfloat("y", ""), GLfloat("z", "") ) void( "MatrixScaledEXT", "", GLenum("matrixMode", ""), GLdouble("x", ""), GLdouble("y", ""), GLdouble("z", "") ) void( "MatrixTranslatefEXT", "", GLenum("matrixMode", ""), GLfloat("x", ""), GLfloat("y", ""), GLfloat("z", "") ) void( "MatrixTranslatedEXT", "", GLenum("matrixMode", ""), GLdouble("x", ""), GLdouble("y", ""), GLdouble("z", "") ) void( "MatrixOrthoEXT", "", GLenum("matrixMode", ""), GLdouble("l", ""), GLdouble("r", ""), GLdouble("b", ""), GLdouble("t", ""), GLdouble("n", ""), GLdouble("f", "") ) void( "MatrixFrustumEXT", "", GLenum("matrixMode", ""), GLdouble("l", ""), GLdouble("r", ""), GLdouble("b", ""), GLdouble("t", ""), GLdouble("n", ""), GLdouble("f", "") ) void( "MatrixPushEXT", "", GLenum("matrixMode", "") ) void( "MatrixPopEXT", "", GLenum("matrixMode", "") ) /* OpenGL 1.1: New texture object commands and queries replace "Tex" in name with "Texture" and add initial "uint texture" parameter */ void( "TextureParameteriEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("pname", ""), GLint("param", "") ) void( "TextureParameterivEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("pname", ""), Check(4)..GLint.const.p("param", "") ) void( "TextureParameterfEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("pname", ""), GLfloat("param", "") ) void( "TextureParameterfvEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("pname", ""), Check(4)..GLfloat.const.p("param", "") ) void( "TextureImage1DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("internalformat", ""), GLsizei("width", ""), GLint("border", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..nullable..void.const.p("pixels", "") ) void( "TextureImage2DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("internalformat", ""), GLsizei("width", ""), GLsizei("height", ""), GLint("border", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..nullable..void.const.p("pixels", "") ) void( "TextureSubImage1DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLsizei("width", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..void.const.p("pixels", "") ) void( "TextureSubImage2DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLsizei("width", ""), GLsizei("height", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..void.const.p("pixels", "") ) void( "CopyTextureImage1DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLenum("internalformat", ""), GLint("x", ""), GLint("y", ""), GLsizei("width", ""), GLint("border", "") ) void( "CopyTextureImage2DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLenum("internalformat", ""), GLint("x", ""), GLint("y", ""), GLsizei("width", ""), GLsizei("height", ""), GLint("border", "") ) void( "CopyTextureSubImage1DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("x", ""), GLint("y", ""), GLsizei("width", "") ) void( "CopyTextureSubImage2DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLint("x", ""), GLint("y", ""), GLsizei("width", ""), GLsizei("height", "") ) void( "GetTextureImageEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..void.p("pixels", "") ) void( "GetTextureParameterfvEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLfloat.p("params", "") ) void( "GetTextureParameterivEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) void( "GetTextureLevelParameterfvEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLfloat.p("params", "") ) void( "GetTextureLevelParameterivEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) /* OpenGL 1.2: New 3D texture object commands replace "Tex" in name with "Texture" and adds initial "uint texture" parameter */ DependsOn("OpenGL12")..void( "TextureImage3DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("internalformat", ""), GLsizei("width", ""), GLsizei("height", ""), GLsizei("depth", ""), GLint("border", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..nullable..RawPointer..void.const.p("pixels", "") ) DependsOn("OpenGL12")..void( "TextureSubImage3DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLint("zoffset", ""), GLsizei("width", ""), GLsizei("height", ""), GLsizei("depth", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..void.const.p("pixels", "") ) DependsOn("OpenGL12")..void( "CopyTextureSubImage3DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLint("zoffset", ""), GLint("x", ""), GLint("y", ""), GLsizei("width", ""), GLsizei("height", "") ) /* OpenGL 1.2.1: New multitexture commands and queries prefix "Multi" before "Tex" and add an initial "enum texunit" parameter (to identify the texture unit). */ DependsOn("OpenGL13")..void( "BindMultiTextureEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLuint("texture", "") ) DependsOn("OpenGL13")..void( "MultiTexCoordPointerEXT", "", GLenum("texunit", ""), GLint("size", ""), GLenum("type", ""), GLsizei("stride", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT )..Unsafe..RawPointer..void.const.p("pointer", "") ) DependsOn("OpenGL13")..void( "MultiTexEnvfEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), GLfloat("param", "") ) DependsOn("OpenGL13")..void( "MultiTexEnvfvEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(4)..GLfloat.const.p("params", "") ) DependsOn("OpenGL13")..void( "MultiTexEnviEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), GLint("param", "") ) DependsOn("OpenGL13")..void( "MultiTexEnvivEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(4)..GLint.const.p("params", "") ) DependsOn("OpenGL13")..void( "MultiTexGendEXT", "", GLenum("texunit", ""), GLenum("coord", ""), GLenum("pname", ""), GLdouble("param", "") ) DependsOn("OpenGL13")..void( "MultiTexGendvEXT", "", GLenum("texunit", ""), GLenum("coord", ""), GLenum("pname", ""), Check(4)..GLdouble.const.p("params", "") ) DependsOn("OpenGL13")..void( "MultiTexGenfEXT", "", GLenum("texunit", ""), GLenum("coord", ""), GLenum("pname", ""), GLfloat("param", "") ) DependsOn("OpenGL13")..void( "MultiTexGenfvEXT", "", GLenum("texunit", ""), GLenum("coord", ""), GLenum("pname", ""), Check(4)..GLfloat.const.p("params", "") ) DependsOn("OpenGL13")..void( "MultiTexGeniEXT", "", GLenum("texunit", ""), GLenum("coord", ""), GLenum("pname", ""), GLint("param", "") ) DependsOn("OpenGL13")..void( "MultiTexGenivEXT", "", GLenum("texunit", ""), GLenum("coord", ""), GLenum("pname", ""), Check(4)..GLint.const.p("params", "") ) DependsOn("OpenGL13")..void( "GetMultiTexEnvfvEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLfloat.p("params", "") ) DependsOn("OpenGL13")..void( "GetMultiTexEnvivEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) DependsOn("OpenGL13")..void( "GetMultiTexGendvEXT", "", GLenum("texunit", ""), GLenum("coord", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLdouble.p("params", "") ) DependsOn("OpenGL13")..void( "GetMultiTexGenfvEXT", "", GLenum("texunit", ""), GLenum("coord", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLfloat.p("params", "") ) DependsOn("OpenGL13")..void( "GetMultiTexGenivEXT", "", GLenum("texunit", ""), GLenum("coord", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) DependsOn("OpenGL13")..void( "MultiTexParameteriEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), GLint("param", "") ) DependsOn("OpenGL13")..void( "MultiTexParameterivEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(4)..GLint.const.p("param", "") ) DependsOn("OpenGL13")..void( "MultiTexParameterfEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), GLfloat("param", "") ) DependsOn("OpenGL13")..void( "MultiTexParameterfvEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(4)..GLfloat.const.p("param", "") ) DependsOn("OpenGL13")..void( "MultiTexImage1DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("internalformat", ""), GLsizei("width", ""), GLint("border", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..nullable..void.const.p("pixels", "") ) DependsOn("OpenGL13")..void( "MultiTexImage2DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("internalformat", ""), GLsizei("width", ""), GLsizei("height", ""), GLint("border", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..nullable..void.const.p("pixels", "") ) DependsOn("OpenGL13")..void( "MultiTexSubImage1DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLsizei("width", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..void.const.p("pixels", "") ) DependsOn("OpenGL13")..void( "MultiTexSubImage2DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLsizei("width", ""), GLsizei("height", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..void.const.p("pixels", "") ) DependsOn("OpenGL13")..void( "CopyMultiTexImage1DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLenum("internalformat", ""), GLint("x", ""), GLint("y", ""), GLsizei("width", ""), GLint("border", "") ) DependsOn("OpenGL13")..void( "CopyMultiTexImage2DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLenum("internalformat", ""), GLint("x", ""), GLint("y", ""), GLsizei("width", ""), GLsizei("height", ""), GLint("border", "") ) DependsOn("OpenGL13")..void( "CopyMultiTexSubImage1DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("x", ""), GLint("y", ""), GLsizei("width", "") ) DependsOn("OpenGL13")..void( "CopyMultiTexSubImage2DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLint("x", ""), GLint("y", ""), GLsizei("width", ""), GLsizei("height", "") ) DependsOn("OpenGL13")..void( "GetMultiTexImageEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..void.p("pixels", "") ) DependsOn("OpenGL13")..void( "GetMultiTexParameterfvEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLfloat.p("params", "") ) DependsOn("OpenGL13")..void( "GetMultiTexParameterivEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) DependsOn("OpenGL13")..void( "GetMultiTexLevelParameterfvEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLfloat.p("params", "") ) DependsOn("OpenGL13")..void( "GetMultiTexLevelParameterivEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) DependsOn("OpenGL13")..void( "MultiTexImage3DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("internalformat", ""), GLsizei("width", ""), GLsizei("height", ""), GLsizei("depth", ""), GLint("border", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..nullable..RawPointer..void.const.p("pixels", "") ) DependsOn("OpenGL13")..void( "MultiTexSubImage3DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLint("zoffset", ""), GLsizei("width", ""), GLsizei("height", ""), GLsizei("depth", ""), GLenum("format", ""), GLenum("type", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..Unsafe..RawPointer..void.const.p("pixels", "") ) DependsOn("OpenGL13")..void( "CopyMultiTexSubImage3DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLint("zoffset", ""), GLint("x", ""), GLint("y", ""), GLsizei("width", ""), GLsizei("height", "") ) /* OpenGL 1.2.1: New indexed texture commands and queries append "Indexed" to name and add "uint index" parameter (to identify the texture unit index) after state name parameters (if any) and before state value parameters */ DependsOn("OpenGL13")..void( "EnableClientStateIndexedEXT", "", GLenum("array", ""), GLuint("index", "") ) DependsOn("OpenGL13")..void( "DisableClientStateIndexedEXT", "", GLenum("array", ""), GLuint("index", "") ) /* OpenGL 3.0: New indexed texture commands and queries append "i" to name and add "uint index" parameter (to identify the texture unit index) after state name parameters (if any) and before state value parameters */ DependsOn("OpenGL30")..IgnoreMissing..void( "EnableClientStateiEXT", "", GLenum("array", ""), GLuint("index", "") ) DependsOn("OpenGL30")..IgnoreMissing..void( "DisableClientStateiEXT", "", GLenum("array", ""), GLuint("index", "") ) /* OpenGL 1.2.1: New indexed generic queries (added for indexed texture state) append "Indexed" to name and add "uint index" parameter (to identify the texture unit) after state name parameters (if any) and before state value parameters */ DependsOn("OpenGL13")..void( "GetFloatIndexedvEXT", "", GLenum("target", ""), GLuint("index", ""), Check(1)..ReturnParam..GLfloat.p("params", "") ) DependsOn("OpenGL13")..void( "GetDoubleIndexedvEXT", "", GLenum("target", ""), GLuint("index", ""), Check(1)..ReturnParam..GLdouble.p("params", "") ) DependsOn("OpenGL13")..void( "GetPointerIndexedvEXT", "", GLenum("target", ""), GLuint("index", ""), Check(1)..ReturnParam..void.p.p("params", "") ) /* OpenGL 3.0: New indexed generic queries (added for indexed texture state) replace "v" for "i_v" to name and add "uint index" parameter (to identify the texture unit) after state name parameters (if any) and before state value parameters */ DependsOn("OpenGL30")..IgnoreMissing..void( "GetFloati_vEXT", "", GLenum("pname", ""), GLuint("index", ""), Check(1)..ReturnParam..GLfloat.p("params", "") ) DependsOn("OpenGL30")..IgnoreMissing..void( "GetDoublei_vEXT", "", GLenum("pname", ""), GLuint("index", ""), Check(1)..ReturnParam..GLdouble.p("params", "") ) DependsOn("OpenGL30")..IgnoreMissing..void( "GetPointeri_vEXT", "", GLenum("pname", ""), GLuint("index", ""), Check(1)..ReturnParam..void.p.p("params", "") ) /* OpenGL 1.2.1: Extend the functionality of these EXT_draw_buffers2 commands and queries for multitexture */ DependsOn("OpenGL13")..(reuse(EXT_draw_buffers2, "EnableIndexedEXT")) DependsOn("OpenGL13")..(reuse(EXT_draw_buffers2, "DisableIndexedEXT")) DependsOn("OpenGL13")..(reuse(EXT_draw_buffers2, "IsEnabledIndexedEXT")) DependsOn("OpenGL13")..(reuse(EXT_draw_buffers2, "GetIntegerIndexedvEXT")) DependsOn("OpenGL13")..(reuse(EXT_draw_buffers2, "GetBooleanIndexedvEXT")) /* ARB_vertex_program: New program commands and queries add "Named" prefix to name and adds initial "uint program" parameter */ DependsOn("GL_ARB_vertex_program")..void( "NamedProgramStringEXT", "", GLuint("program", ""), GLenum("target", ""), GLenum("format", ""), AutoSize("string")..GLsizei("len", ""), void.const.p("string", "") ) DependsOn("GL_ARB_vertex_program")..void( "NamedProgramLocalParameter4dEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), GLdouble("x", ""), GLdouble("y", ""), GLdouble("z", ""), GLdouble("w", "") ) DependsOn("GL_ARB_vertex_program")..void( "NamedProgramLocalParameter4dvEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), Check(4)..GLdouble.const.p("params", "") ) DependsOn("GL_ARB_vertex_program")..void( "NamedProgramLocalParameter4fEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), GLfloat("x", ""), GLfloat("y", ""), GLfloat("z", ""), GLfloat("w", "") ) DependsOn("GL_ARB_vertex_program")..void( "NamedProgramLocalParameter4fvEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), Check(4)..GLfloat.const.p("params", "") ) DependsOn("GL_ARB_vertex_program")..void( "GetNamedProgramLocalParameterdvEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), Check(4)..GLdouble.p("params", "") ) DependsOn("GL_ARB_vertex_program")..void( "GetNamedProgramLocalParameterfvEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), Check(4)..GLfloat.p("params", "") ) DependsOn("GL_ARB_vertex_program")..void( "GetNamedProgramivEXT", "", GLuint("program", ""), GLenum("target", ""), GLenum("pname", ""), ReturnParam..Check(1)..GLint.p("params", "") ) DependsOn("GL_ARB_vertex_program")..void( "GetNamedProgramStringEXT", "", GLuint("program", ""), GLenum("target", ""), GLenum("pname", ""), Check("glGetNamedProgramiEXT(program, target, ARBVertexProgram.GL_PROGRAM_LENGTH_ARB)", debug = true)..void.p("string", "") ) /* OpenGL 1.3: New compressed texture object commands replace "Tex" in name with "Texture" and add initial "uint texture" parameter */ DependsOn("OpenGL13")..void( "CompressedTextureImage3DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLenum("internalformat", ""), GLsizei("width", ""), GLsizei("height", ""), GLsizei("depth", ""), GLint("border", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..nullable..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "CompressedTextureImage2DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLenum("internalformat", ""), GLsizei("width", ""), GLsizei("height", ""), GLint("border", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..nullable..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "CompressedTextureImage1DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLenum("internalformat", ""), GLsizei("width", ""), GLint("border", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..nullable..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "CompressedTextureSubImage3DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLint("zoffset", ""), GLsizei("width", ""), GLsizei("height", ""), GLsizei("depth", ""), GLenum("format", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "CompressedTextureSubImage2DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLsizei("width", ""), GLsizei("height", ""), GLenum("format", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "CompressedTextureSubImage1DEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLsizei("width", ""), GLenum("format", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "GetCompressedTextureImageEXT", "", GLuint("texture", ""), GLenum("target", ""), GLint("level", ""), Check( expression = "glGetTextureLevelParameteriEXT(texture, target, level, GL13.GL_TEXTURE_COMPRESSED_IMAGE_SIZE)", debug = true )..RawPointer..void.p("img", "") ) /* OpenGL 1.3: New multitexture compressed texture commands and queries prefix "Multi" before "Tex" and add an initial "enum texunit" parameter (to identify the texture unit). */ DependsOn("OpenGL13")..void( "CompressedMultiTexImage3DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLenum("internalformat", ""), GLsizei("width", ""), GLsizei("height", ""), GLsizei("depth", ""), GLint("border", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..nullable..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "CompressedMultiTexImage2DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLenum("internalformat", ""), GLsizei("width", ""), GLsizei("height", ""), GLint("border", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..nullable..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "CompressedMultiTexImage1DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLenum("internalformat", ""), GLsizei("width", ""), GLint("border", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..nullable..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "CompressedMultiTexSubImage3DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLint("zoffset", ""), GLsizei("width", ""), GLsizei("height", ""), GLsizei("depth", ""), GLenum("format", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "CompressedMultiTexSubImage2DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLint("yoffset", ""), GLsizei("width", ""), GLsizei("height", ""), GLenum("format", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "CompressedMultiTexSubImage1DEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), GLint("xoffset", ""), GLsizei("width", ""), GLenum("format", ""), AutoSize("data")..GLsizei("imageSize", ""), RawPointer..void.const.p("data", "") ) DependsOn("OpenGL13")..void( "GetCompressedMultiTexImageEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLint("level", ""), Check( expression = "glGetMultiTexLevelParameteriEXT(texunit, target, level, GL13.GL_TEXTURE_COMPRESSED_IMAGE_SIZE)", debug = true )..RawPointer..void.p("img", "") ) /* <OpenGL 1.3: New transpose matrix commands add "Matrix" suffix to name, drops "Matrix" suffix from name, and add initial "enum matrixMode" parameter */ DependsOn("OpenGL13")..void( "MatrixLoadTransposefEXT", "", GLenum("matrixMode", ""), Check(16)..GLfloat.const.p("m", "") ) DependsOn("OpenGL13")..void( "MatrixLoadTransposedEXT", "", GLenum("matrixMode", ""), Check(16)..GLdouble.const.p("m", "") ) DependsOn("OpenGL13")..void( "MatrixMultTransposefEXT", "", GLenum("matrixMode", ""), Check(16)..GLfloat.const.p("m", "") ) DependsOn("OpenGL13")..void( "MatrixMultTransposedEXT", "", GLenum("matrixMode", ""), Check(16)..GLdouble.const.p("m", "") ) /* OpenGL 1.5: New buffer commands and queries replace "Buffer" with "NamedBuffer" in name and replace "enum target" parameter with "uint buffer" */ DependsOn("OpenGL15")..void( "NamedBufferDataEXT", "", GLuint("buffer", ""), AutoSize("data")..GLsizeiptr("size", ""), optional..MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..void.const.p("data", ""), GLenum("usage", "") ) DependsOn("OpenGL15")..void( "NamedBufferSubDataEXT", "", GLuint("buffer", ""), GLintptr("offset", ""), AutoSize("data")..GLsizeiptr("size", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..void.const.p("data", "") ) DependsOn("OpenGL15")..MapPointer("glGetNamedBufferParameteriEXT(buffer, GL15.GL_BUFFER_SIZE)", oldBufferOverloads = true)..void.p( "MapNamedBufferEXT", "", GLuint("buffer", ""), GLenum("access", "") ) DependsOn("OpenGL15")..GLboolean( "UnmapNamedBufferEXT", "", GLuint("buffer", "") ) DependsOn("OpenGL15")..void( "GetNamedBufferParameterivEXT", "", GLuint("buffer", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) DependsOn("OpenGL15")..void( "GetNamedBufferSubDataEXT", "", GLuint("buffer", ""), GLintptr("offset", ""), AutoSize("data")..GLsizeiptr("size", ""), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..void.p("data", "") ) /* OpenGL 2.0: New uniform commands add "Program" prefix to name and add initial "uint program" parameter */ DependsOn("OpenGL20")..void( "ProgramUniform1fEXT", "", GLuint("program", ""), GLint("location", ""), GLfloat("v0", "") ) DependsOn("OpenGL20")..void( "ProgramUniform2fEXT", "", GLuint("program", ""), GLint("location", ""), GLfloat("v0", ""), GLfloat("v1", "") ) DependsOn("OpenGL20")..void( "ProgramUniform3fEXT", "", GLuint("program", ""), GLint("location", ""), GLfloat("v0", ""), GLfloat("v1", ""), GLfloat("v2", "") ) DependsOn("OpenGL20")..void( "ProgramUniform4fEXT", "", GLuint("program", ""), GLint("location", ""), GLfloat("v0", ""), GLfloat("v1", ""), GLfloat("v2", ""), GLfloat("v3", "") ) DependsOn("OpenGL20")..void( "ProgramUniform1iEXT", "", GLuint("program", ""), GLint("location", ""), GLint("v0", "") ) DependsOn("OpenGL20")..void( "ProgramUniform2iEXT", "", GLuint("program", ""), GLint("location", ""), GLint("v0", ""), GLint("v1", "") ) DependsOn("OpenGL20")..void( "ProgramUniform3iEXT", "", GLuint("program", ""), GLint("location", ""), GLint("v0", ""), GLint("v1", ""), GLint("v2", "") ) DependsOn("OpenGL20")..void( "ProgramUniform4iEXT", "", GLuint("program", ""), GLint("location", ""), GLint("v0", ""), GLint("v1", ""), GLint("v2", ""), GLint("v3", "") ) DependsOn("OpenGL20")..void( "ProgramUniform1fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize("value")..GLsizei("count", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL20")..void( "ProgramUniform2fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(2, "value")..GLsizei("count", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL20")..void( "ProgramUniform3fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(3, "value")..GLsizei("count", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL20")..void( "ProgramUniform4fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(4, "value")..GLsizei("count", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL20")..void( "ProgramUniform1ivEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize("value")..GLsizei("count", ""), GLint.const.p("value", "") ) DependsOn("OpenGL20")..void( "ProgramUniform2ivEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(2, "value")..GLsizei("count", ""), GLint.const.p("value", "") ) DependsOn("OpenGL20")..void( "ProgramUniform3ivEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(3, "value")..GLsizei("count", ""), GLint.const.p("value", "") ) DependsOn("OpenGL20")..void( "ProgramUniform4ivEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(4, "value")..GLsizei("count", ""), GLint.const.p("value", "") ) DependsOn("OpenGL20")..void( "ProgramUniformMatrix2fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(2 x 2, "value")..GLsizei("count", ""), GLboolean("transpose", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL20")..void( "ProgramUniformMatrix3fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(3 x 3, "value")..GLsizei("count", ""), GLboolean("transpose", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL20")..void( "ProgramUniformMatrix4fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(4 x 4, "value")..GLsizei("count", ""), GLboolean("transpose", ""), GLfloat.const.p("value", "") ) /* OpenGL 2.1: New uniform matrix commands add "Program" prefix to name and add initial "uint program" parameter */ DependsOn("OpenGL21")..void( "ProgramUniformMatrix2x3fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(2 x 3, "value")..GLsizei("count", ""), GLboolean("transpose", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL21")..void( "ProgramUniformMatrix3x2fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(3 x 2, "value")..GLsizei("count", ""), GLboolean("transpose", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL21")..void( "ProgramUniformMatrix2x4fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(2 x 4, "value")..GLsizei("count", ""), GLboolean("transpose", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL21")..void( "ProgramUniformMatrix4x2fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(4 x 2, "value")..GLsizei("count", ""), GLboolean("transpose", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL21")..void( "ProgramUniformMatrix3x4fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(3 x 4, "value")..GLsizei("count", ""), GLboolean("transpose", ""), GLfloat.const.p("value", "") ) DependsOn("OpenGL21")..void( "ProgramUniformMatrix4x3fvEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(4 x 3, "value")..GLsizei("count", ""), GLboolean("transpose", ""), GLfloat.const.p("value", "") ) /* EXT_texture_buffer_object: New texture buffer object command replaces "Tex" in name with "Texture" and adds initial "uint texture" parameter */ DependsOn("GL_EXT_texture_buffer_object")..void( "TextureBufferEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("internalformat", ""), GLuint("buffer", "") ) /* EXT_texture_buffer_object: New multitexture texture buffer command prefixes "Multi" before "Tex" and add an initial "enum texunit" parameter (to identify the texture unit). */ DependsOn("GL_EXT_texture_buffer_object")..void( "MultiTexBufferEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("internalformat", ""), GLuint("buffer", "") ) /* EXT_texture_integer: New integer texture object commands and queries replace "Tex" in name with "Texture" and add initial "uint texture" parameter */ DependsOn("GL_EXT_texture_integer")..void( "TextureParameterIivEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("pname", ""), Check(4)..GLint.const.p("params", "") ) DependsOn("GL_EXT_texture_integer")..void( "TextureParameterIuivEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("pname", ""), Check(4)..GLuint.const.p("params", "") ) DependsOn("GL_EXT_texture_integer")..void( "GetTextureParameterIivEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) DependsOn("GL_EXT_texture_integer")..void( "GetTextureParameterIuivEXT", "", GLuint("texture", ""), GLenum("target", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLuint.p("params", "") ) /* EXT_texture_integer: New multitexture integer texture commands and queries prefix "Multi" before "Tex" and add an initial "enum texunit" parameter (to identify the texture unit). */ DependsOn("GL_EXT_texture_integer")..void( "MultiTexParameterIivEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(4)..GLint.const.p("params", "") ) DependsOn("GL_EXT_texture_integer")..void( "MultiTexParameterIuivEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(4)..GLuint.const.p("params", "") ) DependsOn("GL_EXT_texture_integer")..void( "GetMultiTexParameterIivEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) DependsOn("GL_EXT_texture_integer")..void( "GetMultiTexParameterIuivEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLuint.p("params", "") ) /* EXT_gpu_shader4: New integer uniform commands add "Program" prefix to name and add initial "uint program" parameter */ DependsOn("GL_EXT_gpu_shader4")..void( "ProgramUniform1uiEXT", "", GLuint("program", ""), GLint("location", ""), GLuint("v0", "") ) DependsOn("GL_EXT_gpu_shader4")..void( "ProgramUniform2uiEXT", "", GLuint("program", ""), GLint("location", ""), GLuint("v0", ""), GLuint("v1", "") ) DependsOn("GL_EXT_gpu_shader4")..void( "ProgramUniform3uiEXT", "", GLuint("program", ""), GLint("location", ""), GLuint("v0", ""), GLuint("v1", ""), GLuint("v2", "") ) DependsOn("GL_EXT_gpu_shader4")..void( "ProgramUniform4uiEXT", "", GLuint("program", ""), GLint("location", ""), GLuint("v0", ""), GLuint("v1", ""), GLuint("v2", ""), GLuint("v3", "") ) DependsOn("GL_EXT_gpu_shader4")..void( "ProgramUniform1uivEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize("value")..GLsizei("count", ""), GLuint.const.p("value", "") ) DependsOn("GL_EXT_gpu_shader4")..void( "ProgramUniform2uivEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(2, "value")..GLsizei("count", ""), GLuint.const.p("value", "") ) DependsOn("GL_EXT_gpu_shader4")..void( "ProgramUniform3uivEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(3, "value")..GLsizei("count", ""), GLuint.const.p("value", "") ) DependsOn("GL_EXT_gpu_shader4")..void( "ProgramUniform4uivEXT", "", GLuint("program", ""), GLint("location", ""), AutoSize(4, "value")..GLsizei("count", ""), GLuint.const.p("value", "") ) /* EXT_gpu_program_parameters: New program command adds "Named" prefix to name and adds "uint program" parameter */ DependsOn("GL_EXT_gpu_program_parameters")..void( "NamedProgramLocalParameters4fvEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), AutoSize(4, "params")..GLsizei("count", ""), GLfloat.const.p("params", "") ) /* NV_gpu_program4: New program commands and queries add "Named" prefix to name and replace "enum target" with "uint program" */ DependsOn("GL_NV_gpu_program4")..void( "NamedProgramLocalParameterI4iEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), GLint("x", ""), GLint("y", ""), GLint("z", ""), GLint("w", "") ) DependsOn("GL_NV_gpu_program4")..void( "NamedProgramLocalParameterI4ivEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), Check(4)..GLint.const.p("params", "") ) DependsOn("GL_NV_gpu_program4")..void( "NamedProgramLocalParametersI4ivEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), AutoSize(4, "params")..GLsizei("count", ""), GLint.const.p("params", "") ) DependsOn("GL_NV_gpu_program4")..void( "NamedProgramLocalParameterI4uiEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), GLuint("x", ""), GLuint("y", ""), GLuint("z", ""), GLuint("w", "") ) DependsOn("GL_NV_gpu_program4")..void( "NamedProgramLocalParameterI4uivEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), Check(4)..GLuint.const.p("params", "") ) DependsOn("GL_NV_gpu_program4")..void( "NamedProgramLocalParametersI4uivEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), AutoSize(4, "params")..GLsizei("count", ""), GLuint.const.p("params", "") ) DependsOn("GL_NV_gpu_program4")..void( "GetNamedProgramLocalParameterIivEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), Check(4)..GLint.p("params", "") ) DependsOn("GL_NV_gpu_program4")..void( "GetNamedProgramLocalParameterIuivEXT", "", GLuint("program", ""), GLenum("target", ""), GLuint("index", ""), Check(4)..GLuint.p("params", "") ) /* OpenGL 3.0: New renderbuffer commands add "Named" prefix to name and replace "enum target" with "uint renderbuffer" */ DependsOn("OpenGL30")..void( "NamedRenderbufferStorageEXT", "", GLuint("renderbuffer", ""), GLenum("internalformat", ""), GLsizei("width", ""), GLsizei("height", "") ) DependsOn("OpenGL30")..void( "GetNamedRenderbufferParameterivEXT", "", GLuint("renderbuffer", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) /* OpenGL 3.0: New renderbuffer commands add "Named" prefix to name and replace "enum target" with "uint renderbuffer" */ DependsOn("OpenGL30")..void( "NamedRenderbufferStorageMultisampleEXT", "", GLuint("renderbuffer", ""), GLsizei("samples", ""), GLenum("internalformat", ""), GLsizei("width", ""), GLsizei("height", "") ) /* NV_framebuffer_multisample_coverage: New renderbuffer commands add "Named" prefix to name and replace "enum target" with "uint renderbuffer" */ DependsOn("GL_NV_framebuffer_multisample_coverage")..void( "NamedRenderbufferStorageMultisampleCoverageEXT", "", GLuint("renderbuffer", ""), GLsizei("coverageSamples", ""), GLsizei("colorSamples", ""), GLenum("internalformat", ""), GLsizei("width", ""), GLsizei("height", "") ) /* OpenGL 3.0: New framebuffer commands add "Named" prefix to name and replace "enum target" with "uint framebuffer" */ DependsOn("OpenGL30")..GLenum( "CheckNamedFramebufferStatusEXT", "", GLuint("framebuffer", ""), GLenum("target", "") ) DependsOn("OpenGL30")..void( "NamedFramebufferTexture1DEXT", "", GLuint("framebuffer", ""), GLenum("attachment", ""), GLenum("textarget", ""), GLuint("texture", ""), GLint("level", "") ) DependsOn("OpenGL30")..void( "NamedFramebufferTexture2DEXT", "", GLuint("framebuffer", ""), GLenum("attachment", ""), GLenum("textarget", ""), GLuint("texture", ""), GLint("level", "") ) DependsOn("OpenGL30")..void( "NamedFramebufferTexture3DEXT", "", GLuint("framebuffer", ""), GLenum("attachment", ""), GLenum("textarget", ""), GLuint("texture", ""), GLint("level", ""), GLint("zoffset", "") ) DependsOn("OpenGL30")..void( "NamedFramebufferRenderbufferEXT", "", GLuint("framebuffer", ""), GLenum("attachment", ""), GLenum("renderbuffertarget", ""), GLuint("renderbuffer", "") ) DependsOn("OpenGL30")..void( "GetNamedFramebufferAttachmentParameterivEXT", "", GLuint("framebuffer", ""), GLenum("attachment", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("params", "") ) /* OpenGL 3.0: New texture commands add "Texture" within name and replace "enum target" with "uint texture" */ DependsOn("OpenGL30")..void( "GenerateTextureMipmapEXT", "", GLuint("texture", ""), GLenum("target", "") ) /* OpenGL 3.0: New texture commands add "MultiTex" within name and replace "enum target" with "enum texunit" */ DependsOn("OpenGL30")..void( "GenerateMultiTexMipmapEXT", "", GLenum("texunit", ""), GLenum("target", "") ) // OpenGL 3.0: New framebuffer commands DependsOn("OpenGL30")..void( "FramebufferDrawBufferEXT", "", GLuint("framebuffer", ""), GLenum("mode", "") ) DependsOn("OpenGL30")..void( "FramebufferDrawBuffersEXT", "", GLuint("framebuffer", ""), AutoSize("bufs")..GLsizei("n", ""), GLenum.const.p("bufs", "") ) DependsOn("OpenGL30")..void( "FramebufferReadBufferEXT", "", GLuint("framebuffer", ""), GLenum("mode", "") ) // OpenGL 3.0: New framebuffer query DependsOn("OpenGL30")..void( "GetFramebufferParameterivEXT", "", GLuint("framebuffer", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("param", "") ) // OpenGL 3.0: New buffer data copy command DependsOn("OpenGL30")..void( "NamedCopyBufferSubDataEXT", "", GLuint("readBuffer", ""), GLuint("writeBuffer", ""), GLintptr("readOffset", ""), GLintptr("writeOffset", ""), GLsizeiptr("size", "") ) /* EXT_geometry_shader4 or NV_gpu_program4: New framebuffer commands add "Named" prefix to name and replace "enum target" with "uint framebuffer" */ DependsOn("ext.contains(\"GL_EXT_geometry_shader4\") || ext.contains(\"GL_NV_gpu_program4\")")..void( "NamedFramebufferTextureEXT", "", GLuint("framebuffer", ""), GLenum("attachment", ""), GLuint("texture", ""), GLint("level", "") ) DependsOn("ext.contains(\"GL_EXT_geometry_shader4\") || ext.contains(\"GL_NV_gpu_program4\")")..void( "NamedFramebufferTextureLayerEXT", "", GLuint("framebuffer", ""), GLenum("attachment", ""), GLuint("texture", ""), GLint("level", ""), GLint("layer", "") ) DependsOn("ext.contains(\"GL_EXT_geometry_shader4\") || ext.contains(\"GL_NV_gpu_program4\")")..void( "NamedFramebufferTextureFaceEXT", "", GLuint("framebuffer", ""), GLenum("attachment", ""), GLuint("texture", ""), GLint("level", ""), GLenum("face", "") ) /* NV_explicit_multisample: New texture renderbuffer object command replaces "Tex" in name with "Texture" and add initial "uint texture" parameter */ DependsOn("GL_NV_explicit_multisample")..void( "TextureRenderbufferEXT", "", GLuint("texture", ""), GLenum("target", ""), GLuint("renderbuffer", "") ) /* NV_explicit_multisample: New multitexture texture renderbuffer command prefixes "Multi" before "Tex" and add an initial "enum texunit" parameter (to identify the texture unit) */ DependsOn("GL_NV_explicit_multisample")..void( "MultiTexRenderbufferEXT", "", GLenum("texunit", ""), GLenum("target", ""), GLuint("renderbuffer", "") ) /* OpenGL 3.0: New vertex array specification commands for vertex array objects prefix "VertexArray", add initial "uint vaobj" and "uint buffer" parameters, change "Pointer" suffix to "Offset", and change the final parameter from "const void *" to "intptr offset" */ DependsOn("OpenGL30")..void( "VertexArrayVertexOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLint("size", ""), GLenum("type", ""), GLsizei("stride", ""), GLintptr("offset", "") ) DependsOn("OpenGL30")..void( "VertexArrayColorOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLint("size", ""), GLenum("type", ""), GLsizei("stride", ""), GLintptr("offset", "") ) DependsOn("OpenGL30")..void( "VertexArrayEdgeFlagOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLsizei("stride", ""), GLintptr("offset", "") ) DependsOn("OpenGL30")..void( "VertexArrayIndexOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLenum("type", ""), GLsizei("stride", ""), GLintptr("offset", "") ) DependsOn("OpenGL30")..void( "VertexArrayNormalOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLenum("type", ""), GLsizei("stride", ""), GLintptr("offset", "") ) DependsOn("OpenGL30")..void( "VertexArrayTexCoordOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLint("size", ""), GLenum("type", ""), GLsizei("stride", ""), GLintptr("offset", "") ) DependsOn("OpenGL30")..void( "VertexArrayMultiTexCoordOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLenum("texunit", ""), GLint("size", ""), GLenum("type", ""), GLsizei("stride", ""), GLintptr("offset", "") ) DependsOn("OpenGL30")..void( "VertexArrayFogCoordOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLenum("type", ""), GLsizei("stride", ""), GLintptr("offset", "") ) DependsOn("OpenGL30")..void( "VertexArraySecondaryColorOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLint("size", ""), GLenum("type", ""), GLsizei("stride", ""), GLintptr("offset", "") ) DependsOn("OpenGL30")..void( "VertexArrayVertexAttribOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLuint("index", ""), GLint("size", ""), GLenum("type", ""), GLboolean("normalized", ""), GLsizei("stride", ""), GLintptr("offset", "") ) DependsOn("OpenGL30")..void( "VertexArrayVertexAttribIOffsetEXT", "", GLuint("vaobj", ""), GLuint("buffer", ""), GLuint("index", ""), GLint("size", ""), GLenum("type", ""), GLsizei("stride", ""), GLintptr("offset", "") ) /* OpenGL 3.0: New vertex array enable commands for vertex array objects change "ClientState" to "VertexArray" and add an initial "uint vaobj" parameter */ DependsOn("OpenGL30")..void( "EnableVertexArrayEXT", "", GLuint("vaobj", ""), GLenum("array", "") ) DependsOn("OpenGL30")..void( "DisableVertexArrayEXT", "", GLuint("vaobj", ""), GLenum("array", "") ) /* OpenGL 3.0: New vertex attrib array enable commands for vertex array objects change "VertexAttribArray" to "VertexArrayAttrib" and add an initial "uint vaobj" parameter */ DependsOn("OpenGL30")..void( "EnableVertexArrayAttribEXT", "", GLuint("vaobj", ""), GLuint("index", "") ) DependsOn("OpenGL30")..void( "DisableVertexArrayAttribEXT", "", GLuint("vaobj", ""), GLuint("index", "") ) // OpenGL 3.0: New queries for vertex array objects DependsOn("OpenGL30")..void( "GetVertexArrayIntegervEXT", "", GLuint("vaobj", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("param", "") ) DependsOn("OpenGL30")..void( "GetVertexArrayPointervEXT", "", GLuint("vaobj", ""), GLenum("pname", ""), Check(1)..ReturnParam..void.p.p("param", "") ) DependsOn("OpenGL30")..void( "GetVertexArrayIntegeri_vEXT", "", GLuint("vaobj", ""), GLuint("index", ""), GLenum("pname", ""), Check(1)..ReturnParam..GLint.p("param", "") ) DependsOn("OpenGL30")..void( "GetVertexArrayPointeri_vEXT", "", GLuint("vaobj", ""), GLuint("index", ""), GLenum("pname", ""), Check(1)..ReturnParam..void.p.p("param", "") ) /* OpenGL 3.0: New buffer commands replace "Buffer" with "NamedBuffer" in name and replace "enum target" parameter with "uint buffer" */ DependsOn("OpenGL30")..MapPointer("length", oldBufferOverloads = true)..void.p( "MapNamedBufferRangeEXT", "", GLuint("buffer", ""), GLintptr("offset", ""), GLsizeiptr("length", ""), GLbitfield("access", "") ) DependsOn("OpenGL30")..void( "FlushMappedNamedBufferRangeEXT", "", GLuint("buffer", ""), GLintptr("offset", ""), GLsizeiptr("length", "") ) }
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/EXT_direct_state_access.kt
2899534464
package rynkbit.tk.coffeelist.db.converter import androidx.room.TypeConverter import rynkbit.tk.coffeelist.contract.entity.InvoiceState class InvoiceStateConverter { @TypeConverter fun nameToState(name: String): InvoiceState { return InvoiceState.valueOf(name) } @TypeConverter fun stateToName(state: InvoiceState): String{ return state.name } }
app/src/main/java/rynkbit/tk/coffeelist/db/converter/InvoiceStateConverter.kt
3830589610
package org.wikipedia.suggestededits import android.content.res.ColorStateList import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.HapticFeedbackConstants import android.view.LayoutInflater import android.view.View import android.view.View.* import android.view.ViewGroup import android.widget.CompoundButton import android.widget.Toast import androidx.core.view.children import com.google.android.material.chip.Chip import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.Constants import org.wikipedia.Constants.InvokeSource import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.activity.FragmentUtil import org.wikipedia.analytics.EditFunnel import org.wikipedia.analytics.SuggestedEditsFunnel import org.wikipedia.csrf.CsrfTokenClient import org.wikipedia.databinding.FragmentSuggestedEditsImageTagsItemBinding import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.dataclient.mwapi.media.MediaHelper import org.wikipedia.descriptions.DescriptionEditActivity.Action.ADD_IMAGE_TAGS import org.wikipedia.page.PageTitle import org.wikipedia.settings.Prefs import org.wikipedia.suggestededits.provider.EditingSuggestionsProvider import org.wikipedia.util.* import org.wikipedia.util.L10nUtil.setConditionalLayoutDirection import org.wikipedia.util.log.L import org.wikipedia.views.ImageZoomHelper import org.wikipedia.views.ViewUtil import java.util.* import kotlin.collections.ArrayList class SuggestedEditsImageTagsFragment : SuggestedEditsItemFragment(), CompoundButton.OnCheckedChangeListener, OnClickListener, SuggestedEditsImageTagDialog.Callback { private var _binding: FragmentSuggestedEditsImageTagsItemBinding? = null private val binding get() = _binding!! var publishing: Boolean = false var publishSuccess: Boolean = false private var page: MwQueryPage? = null private val tagList: MutableList<MwQueryPage.ImageLabel> = ArrayList() private var wasCaptionLongClicked: Boolean = false private var lastSearchTerm: String = "" var invokeSource: InvokeSource = InvokeSource.SUGGESTED_EDITS private var funnel: EditFunnel? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { super.onCreateView(inflater, container, savedInstanceState) _binding = FragmentSuggestedEditsImageTagsItemBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setConditionalLayoutDirection(binding.contentContainer, callback().getLangCode()) binding.cardItemErrorView.backClickListener = OnClickListener { requireActivity().finish() } binding.cardItemErrorView.retryClickListener = OnClickListener { binding.cardItemProgressBar.visibility = VISIBLE binding.cardItemErrorView.visibility = GONE getNextItem() } val transparency = 0xcc000000 binding.tagsContainer.setBackgroundColor(transparency.toInt() or (ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color) and 0xffffff)) binding.imageCaption.setBackgroundColor(transparency.toInt() or (ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color) and 0xffffff)) binding.publishOverlayContainer.setBackgroundColor(transparency.toInt() or (ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color) and 0xffffff)) binding.publishOverlayContainer.visibility = GONE val colorStateList = ColorStateList(arrayOf(intArrayOf()), intArrayOf(if (WikipediaApp.getInstance().currentTheme.isDark) Color.WHITE else ResourceUtil.getThemedColor(requireContext(), R.attr.colorAccent))) binding.publishProgressBar.progressTintList = colorStateList binding.publishProgressBarComplete.progressTintList = colorStateList binding.publishProgressCheck.imageTintList = colorStateList binding.publishProgressText.setTextColor(colorStateList) binding.tagsLicenseText.text = StringUtil.fromHtml(getString(R.string.suggested_edits_cc0_notice, getString(R.string.terms_of_use_url), getString(R.string.cc_0_url))) binding.tagsLicenseText.movementMethod = LinkMovementMethod.getInstance() binding.imageView.setOnClickListener { if (Prefs.shouldShowImageZoomTooltip()) { Prefs.setShouldShowImageZoomTooltip(false) FeedbackUtil.showToastOverView(binding.imageView, getString(R.string.suggested_edits_image_zoom_tooltip), Toast.LENGTH_LONG) } } if (callback().getSinglePage() != null) { page = callback().getSinglePage() } binding.imageCaption.setOnLongClickListener { wasCaptionLongClicked = true false } getNextItem() updateContents() updateTagChips() } override fun onStart() { super.onStart() callback().updateActionButton() } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun getNextItem() { if (page != null) { return } disposables.add(EditingSuggestionsProvider.getNextImageWithMissingTags() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ page -> this.page = page updateContents() updateTagChips() }, { this.setErrorState(it) })!!) } private fun setErrorState(t: Throwable) { L.e(t) binding.cardItemErrorView.setError(t) binding.cardItemErrorView.visibility = VISIBLE binding.cardItemProgressBar.visibility = GONE binding.contentContainer.visibility = GONE } private fun updateContents() { binding.cardItemErrorView.visibility = GONE binding.contentContainer.visibility = if (page != null) VISIBLE else GONE binding.cardItemProgressBar.visibility = if (page != null) GONE else VISIBLE if (page == null) { return } funnel = EditFunnel(WikipediaApp.getInstance(), PageTitle(page!!.title(), WikiSite(Service.COMMONS_URL))) binding.tagsLicenseText.visibility = GONE binding.tagsHintText.visibility = VISIBLE ImageZoomHelper.setViewZoomable(binding.imageView) ViewUtil.loadImage(binding.imageView, ImageUrlUtil.getUrlForPreferredSize(page!!.imageInfo()!!.thumbUrl, Constants.PREFERRED_CARD_THUMBNAIL_SIZE)) disposables.add(MediaHelper.getImageCaptions(page!!.title()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { captions -> if (captions.containsKey(callback().getLangCode())) { binding.imageCaption.text = captions[callback().getLangCode()] binding.imageCaption.visibility = VISIBLE } else { if (page!!.imageInfo() != null && page!!.imageInfo()!!.metadata != null) { binding.imageCaption.text = StringUtil.fromHtml(page!!.imageInfo()!!.metadata!!.imageDescription()).toString().trim() binding.imageCaption.visibility = VISIBLE } else { binding.imageCaption.visibility = GONE } } }) updateLicenseTextShown() callback().updateActionButton() } private fun updateTagChips() { val typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) binding.tagsChipGroup.removeAllViews() if (!publishSuccess) { // add an artificial chip for adding a custom tag addChip(null, typeface) } for (label in tagList) { val chip = addChip(label, typeface) chip.isChecked = label.isSelected if (publishSuccess) { chip.isEnabled = false if (chip.isChecked) { chip.setChipBackgroundColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.color_group_57)) chip.setChipStrokeColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.color_group_58)) } else { chip.setChipBackgroundColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color)) chip.setChipStrokeColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color)) } } } updateLicenseTextShown() callback().updateActionButton() } private fun addChip(label: MwQueryPage.ImageLabel?, typeface: Typeface): Chip { val chip = Chip(requireContext()) chip.text = label?.label ?: getString(R.string.suggested_edits_image_tags_add_tag) chip.textAlignment = TEXT_ALIGNMENT_CENTER chip.setChipBackgroundColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color)) chip.chipStrokeWidth = DimenUtil.dpToPx(1f) chip.setChipStrokeColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color)) chip.setTextColor(ResourceUtil.getThemedColor(requireContext(), R.attr.material_theme_primary_color)) chip.typeface = typeface chip.isCheckable = true chip.setChipIconResource(R.drawable.ic_chip_add_24px) chip.iconEndPadding = 0f chip.textStartPadding = DimenUtil.dpToPx(2f) chip.chipIconSize = DimenUtil.dpToPx(24f) chip.chipIconTint = ColorStateList.valueOf(ResourceUtil.getThemedColor(requireContext(), R.attr.material_theme_de_emphasised_color)) chip.setCheckedIconResource(R.drawable.ic_chip_check_24px) chip.setOnCheckedChangeListener(this) chip.setOnClickListener(this) chip.setEnsureMinTouchTargetSize(true) chip.ensureAccessibleTouchTarget(DimenUtil.dpToPx(48f).toInt()) chip.tag = label if (label != null) { chip.isChecked = label.isSelected } // add some padding to the Chip, since our container view doesn't support item spacing yet. val params = ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) val margin = DimenUtil.roundedDpToPx(8f) params.setMargins(margin, 0, margin, 0) chip.layoutParams = params binding.tagsChipGroup.addView(chip) return chip } companion object { fun newInstance(): SuggestedEditsItemFragment { return SuggestedEditsImageTagsFragment() } } override fun onClick(v: View?) { val chip = v as Chip if (chip.tag == null) { // they clicked the chip to add a new tag, so cancel out the check changing... chip.isChecked = !chip.isChecked // and launch the selection dialog for the custom tag. SuggestedEditsImageTagDialog.newInstance(wasCaptionLongClicked, lastSearchTerm).show(childFragmentManager, null) } } override fun onCheckedChanged(button: CompoundButton?, isChecked: Boolean) { val chip = button as Chip if (chip.isChecked) { chip.setChipBackgroundColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.color_group_55)) chip.setChipStrokeColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.color_group_56)) chip.isChipIconVisible = false } else { chip.setChipBackgroundColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color)) chip.setChipStrokeColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color)) chip.isChipIconVisible = true } if (chip.tag != null) { (chip.tag as MwQueryPage.ImageLabel).isSelected = chip.isChecked } updateLicenseTextShown() callback().updateActionButton() } override fun onSearchSelect(item: MwQueryPage.ImageLabel) { var exists = false for (tag in tagList) { if (tag.wikidataId == item.wikidataId) { exists = true tag.isSelected = true break } } if (!exists) { item.isSelected = true tagList.add(item) } updateTagChips() } override fun onSearchDismiss(searchTerm: String) { lastSearchTerm = searchTerm } override fun publish() { if (publishing || publishSuccess || binding.tagsChipGroup.childCount == 0) { return } val acceptedLabels = ArrayList<MwQueryPage.ImageLabel>() val iterator = tagList.iterator() while (iterator.hasNext()) { val tag = iterator.next() if (tag.isSelected) { acceptedLabels.add(tag) } else { iterator.remove() } } if (acceptedLabels.isEmpty()) { return } // -- point of no return -- publishing = true publishSuccess = false funnel?.logSaveAttempt() binding.publishProgressText.setText(R.string.suggested_edits_image_tags_publishing) binding.publishProgressCheck.visibility = GONE binding.publishOverlayContainer.visibility = VISIBLE binding.publishProgressBarComplete.visibility = GONE binding.publishProgressBar.visibility = VISIBLE val commonsSite = WikiSite(Service.COMMONS_URL) disposables.add(CsrfTokenClient(WikiSite(Service.COMMONS_URL)).token .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ token -> val mId = "M" + page!!.pageId() var claimStr = "{\"claims\":[" var commentStr = "/* add-depicts: " var first = true for (label in acceptedLabels) { if (!first) { claimStr += "," } if (!first) { commentStr += "," } first = false claimStr += "{\"mainsnak\":" + "{\"snaktype\":\"value\",\"property\":\"P180\"," + "\"datavalue\":{\"value\":" + "{\"entity-type\":\"item\",\"id\":\"${label.wikidataId}\"}," + "\"type\":\"wikibase-entityid\"},\"datatype\":\"wikibase-item\"}," + "\"type\":\"statement\"," + "\"id\":\"${mId}\$${UUID.randomUUID()}\"," + "\"rank\":\"normal\"}" commentStr += label.wikidataId + "|" + label.label.replace("|", "").replace(",", "") } claimStr += "]}" commentStr += " */" disposables.add(ServiceFactory.get(commonsSite).postEditEntity(mId, token, claimStr, commentStr, null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate { publishing = false } .subscribe({ if (it.entity != null) { funnel?.logSaved(it.entity!!.lastRevId, invokeSource.getName()) } publishSuccess = true onSuccess() }, { caught -> onError(caught) }) ) }, { onError(it) })) } private fun onSuccess() { SuggestedEditsFunnel.get()!!.success(ADD_IMAGE_TAGS) val duration = 500L binding.publishProgressBar.alpha = 1f binding.publishProgressBar.animate() .alpha(0f) .duration = duration / 2 binding.publishProgressBarComplete.alpha = 0f binding.publishProgressBarComplete.visibility = VISIBLE binding.publishProgressBarComplete.animate() .alpha(1f) .withEndAction { binding.publishProgressText.setText(R.string.suggested_edits_image_tags_published) playSuccessVibration() } .duration = duration / 2 binding.publishProgressCheck.alpha = 0f binding.publishProgressCheck.visibility = VISIBLE binding.publishProgressCheck.animate() .alpha(1f) .duration = duration binding.publishProgressBar.postDelayed({ if (isAdded) { updateLicenseTextShown() binding.publishOverlayContainer.visibility = GONE callback().nextPage(this) callback().logSuccess() updateTagChips() } }, duration * 3) } private fun onError(caught: Throwable) { // TODO: expand this a bit. SuggestedEditsFunnel.get()!!.failure(ADD_IMAGE_TAGS) funnel?.logError(caught.localizedMessage) binding.publishOverlayContainer.visibility = GONE FeedbackUtil.showError(requireActivity(), caught) } private fun playSuccessVibration() { binding.imageView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) } private fun updateLicenseTextShown() { when { publishSuccess -> { binding.tagsLicenseText.visibility = GONE binding.tagsHintText.setText(R.string.suggested_edits_image_tags_published_list) binding.tagsHintText.visibility = VISIBLE } atLeastOneTagChecked() -> { binding.tagsLicenseText.visibility = VISIBLE binding.tagsHintText.visibility = GONE } else -> { binding.tagsLicenseText.visibility = GONE binding.tagsHintText.visibility = GONE } } } private fun atLeastOneTagChecked(): Boolean { return binding.tagsChipGroup.children.filterIsInstance<Chip>().any { it.isChecked } } override fun publishEnabled(): Boolean { return !publishSuccess && atLeastOneTagChecked() } override fun publishOutlined(): Boolean { if (_binding == null) { return false } return !atLeastOneTagChecked() } private fun callback(): Callback { return FragmentUtil.getCallback(this, Callback::class.java)!! } }
app/src/main/java/org/wikipedia/suggestededits/SuggestedEditsImageTagsFragment.kt
3242692663
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.core.ui.screens.habits.show.views import org.isoron.platform.time.DayOfWeek import org.isoron.platform.time.LocalDate import org.isoron.uhabits.core.commands.CommandRunner import org.isoron.uhabits.core.commands.CreateRepetitionCommand import org.isoron.uhabits.core.models.Entry import org.isoron.uhabits.core.models.Entry.Companion.SKIP import org.isoron.uhabits.core.models.Entry.Companion.YES_AUTO import org.isoron.uhabits.core.models.Entry.Companion.YES_MANUAL import org.isoron.uhabits.core.models.Habit import org.isoron.uhabits.core.models.HabitList import org.isoron.uhabits.core.models.NumericalHabitType.AT_LEAST import org.isoron.uhabits.core.models.NumericalHabitType.AT_MOST import org.isoron.uhabits.core.models.PaletteColor import org.isoron.uhabits.core.models.Timestamp import org.isoron.uhabits.core.preferences.Preferences import org.isoron.uhabits.core.ui.screens.habits.list.ListHabitsBehavior import org.isoron.uhabits.core.ui.views.HistoryChart import org.isoron.uhabits.core.ui.views.HistoryChart.Square.DIMMED import org.isoron.uhabits.core.ui.views.HistoryChart.Square.GREY import org.isoron.uhabits.core.ui.views.HistoryChart.Square.HATCHED import org.isoron.uhabits.core.ui.views.HistoryChart.Square.OFF import org.isoron.uhabits.core.ui.views.HistoryChart.Square.ON import org.isoron.uhabits.core.ui.views.OnDateClickedListener import org.isoron.uhabits.core.ui.views.Theme import org.isoron.uhabits.core.utils.DateUtils import kotlin.math.roundToInt data class HistoryCardState( val color: PaletteColor, val firstWeekday: DayOfWeek, val series: List<HistoryChart.Square>, val defaultSquare: HistoryChart.Square, val notesIndicators: List<Boolean>, val theme: Theme, val today: LocalDate, ) class HistoryCardPresenter( val commandRunner: CommandRunner, val habit: Habit, val habitList: HabitList, val preferences: Preferences, val screen: Screen, ) : OnDateClickedListener { override fun onDateLongPress(date: LocalDate) { val timestamp = Timestamp.fromLocalDate(date) screen.showFeedback() if (habit.isNumerical) { showNumberPopup(timestamp) } else { if (preferences.isShortToggleEnabled) showCheckmarkPopup(timestamp) else toggle(timestamp) } } override fun onDateShortPress(date: LocalDate) { val timestamp = Timestamp.fromLocalDate(date) screen.showFeedback() if (habit.isNumerical) { showNumberPopup(timestamp) } else { if (preferences.isShortToggleEnabled) toggle(timestamp) else showCheckmarkPopup(timestamp) } } private fun showCheckmarkPopup(timestamp: Timestamp) { val entry = habit.computedEntries.get(timestamp) screen.showCheckmarkPopup( entry.value, entry.notes, preferences, habit.color, ) { newValue, newNotes -> commandRunner.run( CreateRepetitionCommand( habitList, habit, timestamp, newValue, newNotes, ), ) } } private fun toggle(timestamp: Timestamp) { val entry = habit.computedEntries.get(timestamp) val nextValue = Entry.nextToggleValue( value = entry.value, isSkipEnabled = preferences.isSkipEnabled, areQuestionMarksEnabled = preferences.areQuestionMarksEnabled ) commandRunner.run( CreateRepetitionCommand( habitList, habit, timestamp, nextValue, entry.notes, ), ) } private fun showNumberPopup(timestamp: Timestamp) { val entry = habit.computedEntries.get(timestamp) val oldValue = entry.value screen.showNumberPopup( value = oldValue / 1000.0, notes = entry.notes, preferences = preferences, ) { newValue: Double, newNotes: String -> val thousands = (newValue * 1000).roundToInt() commandRunner.run( CreateRepetitionCommand( habitList, habit, timestamp, thousands, newNotes, ), ) } } fun onClickEditButton() { screen.showHistoryEditorDialog(this) } companion object { fun buildState( habit: Habit, firstWeekday: DayOfWeek, theme: Theme, ): HistoryCardState { val today = DateUtils.getTodayWithOffset() val oldest = habit.computedEntries.getKnown().lastOrNull()?.timestamp ?: today val entries = habit.computedEntries.getByInterval(oldest, today) val series = if (habit.isNumerical) { entries.map { when { it.value == Entry.UNKNOWN -> OFF it.value == SKIP -> HATCHED (habit.targetType == AT_MOST) && (it.value / 1000.0 <= habit.targetValue) -> ON (habit.targetType == AT_LEAST) && (it.value / 1000.0 >= habit.targetValue) -> ON else -> GREY } } } else { entries.map { when (it.value) { YES_MANUAL -> ON YES_AUTO -> DIMMED SKIP -> HATCHED else -> OFF } } } val notesIndicators = entries.map { when (it.notes) { "" -> false else -> true } } return HistoryCardState( color = habit.color, firstWeekday = firstWeekday, today = today.toLocalDate(), theme = theme, series = series, defaultSquare = OFF, notesIndicators = notesIndicators, ) } } interface Screen { fun showHistoryEditorDialog(listener: OnDateClickedListener) fun showFeedback() fun showNumberPopup( value: Double, notes: String, preferences: Preferences, callback: ListHabitsBehavior.NumberPickerCallback, ) fun showCheckmarkPopup( selectedValue: Int, notes: String, preferences: Preferences, color: PaletteColor, callback: ListHabitsBehavior.CheckMarkDialogCallback, ) } }
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/screens/habits/show/views/HistoryCard.kt
3035311920
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.arch.storage.internal import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import net.openid.appauth.AuthState import org.hisp.dhis.android.core.utils.runner.D2JunitRunner import org.junit.Test import org.junit.runner.RunWith @RunWith(D2JunitRunner::class) class CredentialsSecureStorageMockIntegrationShould { private fun instantiateStore(): CredentialsSecureStoreImpl = CredentialsSecureStoreImpl( ChunkedSecureStore( AndroidSecureStore(InstrumentationRegistry.getInstrumentation().context) ) ) @Test fun credentials_are_correctly_stored_for_regular_password() { setAndVerify(Credentials("username", "serverUrl", "password", null)) } @Test fun credentials_are_correctly_stored_for_really_log_password() { val pw = (0 until 1000).joinToString { it.toString() } setAndVerify(Credentials("username", "serverUrl", pw, null)) } @Test fun credentials_are_correctly_stored_for_open_id_connect_config() { val authState = AuthState() setAndVerify(Credentials("username", "serverUrl", null, authState)) } private fun setAndVerify(credentials: Credentials) { val store1 = instantiateStore() store1.set(credentials) val extractedCredentials1 = store1.get() assertThat(extractedCredentials1).isEqualTo(credentials) // Instantiating a second store ensure credentials are not retrieved from the cache val store2 = instantiateStore() val extractedCredentials2 = store2.get() assertThat(extractedCredentials2).isEqualTo(credentials) } @Test fun credentials_are_correctly_removed() { val store1 = instantiateStore() val credentials = Credentials("username", "serverUrl", "password", null) store1.set(credentials) store1.remove() val retrievedCredentials1 = store1.get() assertThat(retrievedCredentials1).isNull() val store2 = instantiateStore() val retrievedCredentials2 = store2.get() assertThat(retrievedCredentials2).isNull() } }
core/src/androidTest/java/org/hisp/dhis/android/core/arch/storage/internal/CredentialsSecureStorageMockIntegrationShould.kt
4257566721
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.ClearableLazyValue import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.DIRECTORY_GROUPING import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.MODULE_GROUPING import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.REPOSITORY_GROUPING import org.jetbrains.annotations.NonNls import java.beans.PropertyChangeListener import java.beans.PropertyChangeSupport import javax.swing.tree.DefaultTreeModel private val PREDEFINED_PRIORITIES = mapOf(DIRECTORY_GROUPING to 10, MODULE_GROUPING to 20, REPOSITORY_GROUPING to 30) open class ChangesGroupingSupport(val project: Project, source: Any, val showConflictsNode: Boolean) { private val changeSupport = PropertyChangeSupport(source) private val _groupingKeys = mutableSetOf<String>() val groupingKeys get() = _groupingKeys.toSet() operator fun get(groupingKey: @NonNls String): Boolean { if (!isAvailable(groupingKey)) return false return _groupingKeys.contains(groupingKey) } operator fun set(groupingKey: String, state: Boolean) { if (!isAvailable(groupingKey)) throw IllegalArgumentException("Unknown grouping $groupingKey") // NON-NLS val currentState = _groupingKeys.contains(groupingKey) if (currentState == state) return val oldGroupingKeys = _groupingKeys.toSet() if (state) { _groupingKeys += groupingKey } else { _groupingKeys -= groupingKey } changeSupport.firePropertyChange(PROP_GROUPING_KEYS, oldGroupingKeys, _groupingKeys.toSet()) } val grouping: ChangesGroupingPolicyFactory get() = CombinedGroupingPolicyFactory() val isNone: Boolean get() = _groupingKeys.isEmpty() val isDirectory: Boolean get() = this[DIRECTORY_GROUPING] fun setGroupingKeysOrSkip(newGroupingKeys: Set<String>) { _groupingKeys.clear() _groupingKeys += newGroupingKeys.filter { groupingKey -> isAvailable(groupingKey) } } open fun isAvailable(groupingKey: String) = findFactory(groupingKey) != null fun addPropertyChangeListener(listener: PropertyChangeListener) { changeSupport.addPropertyChangeListener(listener) } fun removePropertyChangeListener(listener: PropertyChangeListener) { changeSupport.removePropertyChangeListener(listener) } private inner class CombinedGroupingPolicyFactory : ChangesGroupingPolicyFactory() { override fun createGroupingPolicy(project: Project, model: DefaultTreeModel): ChangesGroupingPolicy { var result = DefaultChangesGroupingPolicy.Factory(showConflictsNode).createGroupingPolicy(project, model) _groupingKeys.sortedByDescending { PREDEFINED_PRIORITIES[it] }.forEach { groupingKey -> val factory = findFactory(groupingKey) ?: throw IllegalArgumentException("Unknown grouping $groupingKey") // NON-NLS result = factory.createGroupingPolicy(project, model).apply { setNextGroupingPolicy(result) } } return result } } companion object { @JvmField val KEY = DataKey.create<ChangesGroupingSupport>("ChangesTree.GroupingSupport") const val PROP_GROUPING_KEYS = "ChangesGroupingKeys" // NON-NLS const val DIRECTORY_GROUPING = "directory" // NON-NLS const val MODULE_GROUPING = "module" // NON-NLS const val REPOSITORY_GROUPING = "repository" // NON-NLS const val NONE_GROUPING = "none" // NON-NLS private val FACTORIES = ClearableLazyValue.create { buildFactories() } init { ChangesGroupingPolicyFactory.EP_NAME.addChangeListener({ FACTORIES.drop() }, null) } @JvmStatic fun getFactory(key: String): ChangesGroupingPolicyFactory { return findFactory(key) ?: NoneChangesGroupingFactory } @JvmStatic fun findFactory(key: String): ChangesGroupingPolicyFactory? { return FACTORIES.value[key] } private fun buildFactories(): Map<String, ChangesGroupingPolicyFactory> { val result = mutableMapOf<String, ChangesGroupingPolicyFactory>() for (bean in ChangesGroupingPolicyFactory.EP_NAME.extensionList) { val key = bean.key ?: continue val clazz = bean.implementationClass ?: continue try { result[key] = ApplicationManager.getApplication().instantiateClass(clazz, bean.pluginDescriptor) } catch (e: Throwable) { logger<ChangesGroupingSupport>().error(e) } } return result } } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesGroupingSupport.kt
3316156546
package soutvoid.com.DsrWeatherApp.domain import com.google.gson.annotations.SerializedName import soutvoid.com.DsrWeatherApp.domain.temp.Temperature import soutvoid.com.DsrWeatherApp.domain.weather.Weather data class OneDayForecast( @SerializedName("dt") val dateTime: Long, @SerializedName("temp") val temperature: Temperature, @SerializedName("pressure") val pressure: Double, @SerializedName("humidity") val humidity: Int, @SerializedName("weather") val weather: List<Weather>, @SerializedName("speed") val windSpeed: Double, @SerializedName("deg") val windDegrees: Double, @SerializedName("clouds") val clouds: Double, @SerializedName("snow") val snow: Double, @SerializedName("rain") val rain: Double )
app/src/main/java/soutvoid/com/DsrWeatherApp/domain/OneDayForecast.kt
1280472213
package com.intellij.laf.macos import com.intellij.ide.ui.LafProvider import com.intellij.ide.ui.laf.PluggableLafInfo import com.intellij.ide.ui.laf.darcula.ui.DarculaEditorTextFieldBorder import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.util.NlsSafe import com.intellij.ui.EditorTextField import javax.swing.LookAndFeel internal class MacLafProvider : LafProvider { override fun getLookAndFeelInfo() = instance private class MacOsLookAndFeelInfo : PluggableLafInfo(LAF_NAME, MacIntelliJLaf::class.java.name) { override fun createLookAndFeel(): LookAndFeel = MacIntelliJLaf() override fun createSearchAreaPainter(context: SearchAreaContext) = MacSearchPainter(context) override fun createEditorTextFieldBorder(editorTextField: EditorTextField, editor: EditorEx): DarculaEditorTextFieldBorder { return MacEditorTextFieldBorder(editorTextField, editor) } } companion object { @NlsSafe const val LAF_NAME = "macOS Light" private val instance: PluggableLafInfo = MacOsLookAndFeelInfo() } }
plugins/laf/macos/src/com/intellij/laf/macos/MacLafProvider.kt
1664737411
fun box() { renamed.foo() } // MAIN_CLASS: LibrarySources4Kt // FILE: jvmClassNameSameName.kt // LINE: 5
plugins/kotlin/jvm-debugger/test/testData/exceptionFilter/librarySources4/librarySources4.kt
1496568673
// 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.findusages import com.intellij.navigation.ChooseByNameContributorEx import com.intellij.navigation.NavigationItem import com.intellij.psi.PsiManager import com.intellij.psi.SyntaxTraverser import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.Processor import com.intellij.util.indexing.FileBasedIndex import com.intellij.util.indexing.FindSymbolParameters import com.intellij.util.indexing.IdFilter import org.editorconfig.language.index.EditorConfigIdentifierIndex import org.editorconfig.language.psi.interfaces.EditorConfigDescribableElement class EditorConfigGoToSymbolContributor : ChooseByNameContributorEx { override fun processNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?) { FileBasedIndex.getInstance().processAllKeys(EditorConfigIdentifierIndex.id, processor, scope, filter) } override fun processElementsWithName(name: String, processor: Processor<in NavigationItem>, parameters: FindSymbolParameters) { val psiManager = PsiManager.getInstance(parameters.project) FileBasedIndex.getInstance().getFilesWithKey( EditorConfigIdentifierIndex.id, setOf(name), { file -> SyntaxTraverser.psiTraverser(psiManager.findFile(file)) .filter(EditorConfigDescribableElement::class.java) .processEach(processor) }, parameters.searchScope) } }
plugins/editorconfig/src/org/editorconfig/language/codeinsight/findusages/EditorConfigGoToSymbolContributor.kt
2378730289
/* * *************************************************************************** * Copyright 2014-2018 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.dsbrowser.gui.services.jobService.data import com.spectralogic.ds3client.Ds3Client import com.spectralogic.ds3client.commands.spectrads3.GetActiveJobSpectraS3Request import com.spectralogic.ds3client.commands.spectrads3.GetJobSpectraS3Request import com.spectralogic.ds3client.commands.spectrads3.PutBulkJobSpectraS3Request import com.spectralogic.ds3client.helpers.Ds3ClientHelpers import com.spectralogic.ds3client.helpers.FileObjectPutter import com.spectralogic.ds3client.helpers.WriteJobImpl import com.spectralogic.ds3client.helpers.events.ConcurrentEventRunner import com.spectralogic.ds3client.helpers.strategy.blobstrategy.BlackPearlChunkAttemptRetryDelayBehavior import com.spectralogic.ds3client.helpers.strategy.blobstrategy.MaxChunkAttemptsRetryBehavior import com.spectralogic.ds3client.helpers.strategy.blobstrategy.PutSequentialBlobStrategy import com.spectralogic.ds3client.helpers.strategy.transferstrategy.EventDispatcherImpl import com.spectralogic.ds3client.helpers.strategy.transferstrategy.TransferStrategyBuilder import com.spectralogic.ds3client.models.JobStatus import com.spectralogic.ds3client.models.Priority import com.spectralogic.ds3client.models.bulk.Ds3Object import com.spectralogic.dsbrowser.api.services.logging.LogType import com.spectralogic.dsbrowser.api.services.logging.LoggingService import com.spectralogic.dsbrowser.gui.services.jobService.JobTaskElement import com.spectralogic.dsbrowser.gui.services.jobService.util.EmptyChannelBuilder import com.spectralogic.dsbrowser.gui.util.DateTimeUtils import com.spectralogic.dsbrowser.gui.util.ParseJobInterruptionMap import javafx.beans.property.BooleanProperty import java.io.File import java.lang.RuntimeException import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.time.Instant import java.util.UUID data class PutJobData( private val items: List<Pair<String, Path>>, private val targetDir: String, override val bucket: String, private val jobTaskElement: JobTaskElement ) : JobData { override fun runningTitle(): String { val transferringPut = jobTaskElement.resourceBundle.getString("transferringPut") val jobId = job.jobId val startedAt = jobTaskElement.resourceBundle.getString("startedAt") val started = jobTaskElement.dateTimeUtils.format(getStartTime()) return "$transferringPut $jobId $startedAt $started" } override val jobId: UUID by lazy { job.jobId } override fun client(): Ds3Client = jobTaskElement.client override fun internationalize(labelName: String): String = jobTaskElement.resourceBundle.getString(labelName) override fun modifyJob(job: Ds3ClientHelpers.Job) { job.withMaxParallelRequests(jobTaskElement.settingsStore.processSettings.maximumNumberOfParallelThreads) } override val job: Ds3ClientHelpers.Job by lazy { val ds3Objects = items.map { pathToDs3Object(it.second) }.flatten() ds3Objects.map { pair: Pair<Ds3Object, Path> -> Pair<String, Path>(pair.first.name, pair.second) } .forEach { prefixMap.put(it.first, it.second) } if (ds3Objects.isEmpty()) { loggingService().logMessage("File list is empty, cannot create job", LogType.ERROR) throw RuntimeException("File list is empty") } val priority = if (jobTaskElement.savedJobPrioritiesStore.jobSettings.putJobPriority.equals("Data Policy Default (no change)")) { null } else { Priority.valueOf(jobTaskElement.savedJobPrioritiesStore.jobSettings.putJobPriority) } val request = PutBulkJobSpectraS3Request( bucket, ds3Objects.map { it.first } ).withPriority(priority) val response = jobTaskElement.client.putBulkJobSpectraS3(request) val eventDispatcher = EventDispatcherImpl(ConcurrentEventRunner()) val blobStrategy = PutSequentialBlobStrategy( jobTaskElement.client, response.masterObjectList, eventDispatcher, MaxChunkAttemptsRetryBehavior(1), BlackPearlChunkAttemptRetryDelayBehavior(eventDispatcher) ) val transferStrategyBuilder = TransferStrategyBuilder() .withDs3Client(jobTaskElement.client) .withMasterObjectList(response.masterObjectList) .withBlobStrategy(blobStrategy) .withChannelBuilder(null) .withNumConcurrentTransferThreads(jobTaskElement.settingsStore.processSettings.maximumNumberOfParallelThreads) WriteJobImpl(transferStrategyBuilder) } override var prefixMap: MutableMap<String, Path> = mutableMapOf() override fun showCachedJobProperty(): BooleanProperty = jobTaskElement.settingsStore.showCachedJobSettings.showCachedJobEnableProperty() override fun loggingService(): LoggingService = jobTaskElement.loggingService override fun targetPath(): String = targetDir override fun dateTimeUtils(): DateTimeUtils = jobTaskElement.dateTimeUtils private var startTime: Instant = Instant.now() override fun getStartTime(): Instant = startTime override fun setStartTime(): Instant { startTime = Instant.now() return startTime } override fun getObjectChannelBuilder(prefix: String): Ds3ClientHelpers.ObjectChannelBuilder = EmptyChannelBuilder(FileObjectPutter(prefixMap.get(prefix)!!.parent), prefixMap.get(prefix)!!) private fun pathToDs3Object(path: Path): List<Pair<Ds3Object, Path>> { val parent = path.parent return path .toFile() .walk(FileWalkDirection.TOP_DOWN) .filter(::rejectEmptyDirectory) .filter(::rejectDeadLinks) .map(::addSize) .map { convertToDs3Object(it, parent) } .map { Pair(it, path) } .distinct() .toList() } private fun addSize(file: File): Pair<File, Long> = Pair(file, if (Files.isDirectory(file.toPath())) 0L else file.length()) private fun rejectEmptyDirectory(file: File) = !(file.isDirectory && Files.list(file.toPath()).use { f -> f.findAny().isPresent }) private fun convertToDs3Object(fileParts: Pair<File, Long>, parent: Path): Ds3Object { val (file, size) = fileParts val pathBuilder = StringBuilder(targetDir) val localDelim = file.toPath().fileSystem.separator pathBuilder.append(parent.relativize(file.toPath()).toString().replace(localDelim, "/")) if (file.isDirectory) { pathBuilder.append("/") } return Ds3Object(pathBuilder.toString(), size) } private fun rejectDeadLinks(file: File): Boolean { return try { file.toPath().toRealPath() true } catch (e: NoSuchFileException) { loggingService().logMessage("Could not resolve link " + file, LogType.ERROR) false } } override fun jobSize() = jobTaskElement.client.getActiveJobSpectraS3(GetActiveJobSpectraS3Request(job.jobId)).activeJobResult.originalSizeInBytes override fun shouldRestoreFileAttributes(): Boolean = jobTaskElement.settingsStore.filePropertiesSettings.isFilePropertiesEnabled override fun isCompleted() = jobTaskElement.client.getJobSpectraS3(GetJobSpectraS3Request(job.jobId)).masterObjectListResult.status == JobStatus.COMPLETED override fun removeJob() { ParseJobInterruptionMap.removeJobIdFromFile(jobTaskElement.jobInterruptionStore, job.jobId.toString(), jobTaskElement.client.connectionDetails.endpoint) } override fun saveJob(jobSize: Long) { ParseJobInterruptionMap.saveValuesToFiles(jobTaskElement.jobInterruptionStore, prefixMap, mapOf(), jobTaskElement.client.connectionDetails.endpoint, job.jobId, jobSize, targetPath(), jobTaskElement.dateTimeUtils, "PUT", bucket) } }
dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/services/jobService/data/PutJobData.kt
2954988940
package co.smartreceipts.android.sync.drive.managers import co.smartreceipts.automatic_backups.drive.managers.DriveDatabaseManager interface GoogleDriveTableManager { fun initializeListeners( driveDatabaseManager: DriveDatabaseManager, driveReceiptsManager: DriveReceiptsManager ) fun deinitializeListeners() }
app/src/main/java/co/smartreceipts/android/sync/drive/managers/GoogleDriveTableManager.kt
331059174
package co.smartreceipts.android.workers import android.content.Context import android.content.Intent import co.smartreceipts.android.DefaultObjects import co.smartreceipts.android.R import co.smartreceipts.android.date.DateFormatter import co.smartreceipts.android.model.Distance import co.smartreceipts.android.model.Receipt import co.smartreceipts.android.model.factory.ReceiptBuilderFactory import co.smartreceipts.android.persistence.DatabaseHelper import co.smartreceipts.android.persistence.database.tables.DistanceTable import co.smartreceipts.android.persistence.database.tables.ReceiptsTable import co.smartreceipts.android.settings.UserPreferenceManager import co.smartreceipts.android.settings.catalog.UserPreference import co.smartreceipts.android.utils.IntentUtils import co.smartreceipts.android.workers.EmailAssistant.EmailOptions import co.smartreceipts.android.workers.widget.EmailResult import co.smartreceipts.android.workers.widget.GenerationErrors import com.nhaarman.mockitokotlin2.* import io.reactivex.Single import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import java.io.File import java.util.* @RunWith(RobolectricTestRunner::class) class EmailAssistantTest { // Class under test private lateinit var emailAssistant: EmailAssistant private val context = mock<Context>() private val databaseHelper = mock<DatabaseHelper>() private val preferenceManager = mock<UserPreferenceManager>() private val attachmentFilesWriter = mock<AttachmentFilesWriter>() private val dateFormatter = mock<DateFormatter>() private val intentUtils = mock<IntentUtils>() private val trip = DefaultObjects.newDefaultTrip() private val receiptsTable = mock<ReceiptsTable>() private val distancesTable = mock<DistanceTable>() private val to = "to" private val cc = "cc" private val bcc = "bcc" private val subject = "subject" @Before fun setUp() { whenever(databaseHelper.receiptsTable).thenReturn(receiptsTable) whenever(databaseHelper.distanceTable).thenReturn(distancesTable) whenever(receiptsTable.get(trip, true)).thenReturn(Single.just(emptyList())) whenever(distancesTable.get(trip, true)).thenReturn(Single.just(emptyList())) whenever(preferenceManager.get(UserPreference.Email.ToAddresses)).thenReturn(to) whenever(preferenceManager.get(UserPreference.Email.CcAddresses)).thenReturn(cc) whenever(preferenceManager.get(UserPreference.Email.BccAddresses)).thenReturn(bcc) whenever(preferenceManager.get(UserPreference.Email.Subject)).thenReturn(subject) whenever(preferenceManager.get(UserPreference.Receipts.OnlyIncludeReimbursable)).thenReturn(false) whenever(preferenceManager.get(UserPreference.Receipts.UsePreTaxPrice)).thenReturn(false) whenever(preferenceManager.get(UserPreference.ReportOutput.UserId)).thenReturn("") whenever(context.getString(R.string.report_attached)).thenReturn("1 report attached") whenever(context.packageName).thenReturn("") whenever(dateFormatter.getFormattedDate(trip.startDisplayableDate)).thenReturn("") whenever(dateFormatter.getFormattedDate(trip.endDisplayableDate)).thenReturn("") emailAssistant = EmailAssistant(context, databaseHelper, preferenceManager, attachmentFilesWriter, dateFormatter, intentUtils) } @Test fun emailTripErrorNoOptionsTest() { val options = EnumSet.noneOf(EmailOptions::class.java) val result = emailAssistant.emailTrip(trip, options).blockingGet() assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_NO_SELECTION) verifyZeroInteractions(databaseHelper, preferenceManager, attachmentFilesWriter, dateFormatter) } @Test fun emailTripErrorNoReceiptsNoDistancesTest() { // user wants to create report but there are no receipts and no distances val options = EnumSet.allOf(EmailOptions::class.java) val result = emailAssistant.emailTrip(trip, options).blockingGet() assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_NO_RECEIPTS) verify(databaseHelper).receiptsTable verify(databaseHelper).distanceTable verifyNoMoreInteractions(databaseHelper) verifyZeroInteractions(preferenceManager, attachmentFilesWriter, dateFormatter) } @Test fun emailTripErrorNoReceiptsDistancesNotPdfNotCsvTest() { // user wants to create report (not PDF or CSV) with just distances val options = EnumSet.of(EmailOptions.ZIP, EmailOptions.ZIP_WITH_METADATA, EmailOptions.PDF_IMAGES_ONLY) whenever(distancesTable.get(trip, true)).thenReturn(Single.just(listOf(mock()))) val result = emailAssistant.emailTrip(trip, options).blockingGet() assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_NO_RECEIPTS) verify(databaseHelper).receiptsTable verify(databaseHelper).distanceTable verifyNoMoreInteractions(databaseHelper) verifyZeroInteractions(preferenceManager, attachmentFilesWriter, dateFormatter) } @Test fun emailTripErrorNoReceiptsDisabledDistancesPdfTest() { // user wants to create PDF report with just distances but this option is disabled val optionsPdf = EnumSet.of(EmailOptions.PDF_FULL) whenever(distancesTable.get(trip, true)).thenReturn(Single.just(listOf(mock()))) whenever(preferenceManager.get(UserPreference.Distance.PrintDistanceTableInReports)).thenReturn(false) val result = emailAssistant.emailTrip(trip, optionsPdf).blockingGet() assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_DISABLED_DISTANCES) verify(databaseHelper).receiptsTable verify(databaseHelper).distanceTable verifyNoMoreInteractions(databaseHelper) verify(preferenceManager).get(UserPreference.Distance.PrintDistanceTableInReports) verifyNoMoreInteractions(preferenceManager) verifyZeroInteractions(attachmentFilesWriter, dateFormatter) } @Test fun emailTripErrorNoReceiptsDisabledDistancesCsvTest() { // user wants to create CSV report with just distances but this option is disabled val optionsCsv = EnumSet.of(EmailOptions.CSV) whenever(distancesTable.get(trip, true)).thenReturn(Single.just(listOf(mock()))) whenever(preferenceManager.get(UserPreference.Distance.PrintDistanceTableInReports)).thenReturn(false) val result = emailAssistant.emailTrip(trip, optionsCsv).blockingGet() assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_DISABLED_DISTANCES) verify(databaseHelper).receiptsTable verify(databaseHelper).distanceTable verifyNoMoreInteractions(databaseHelper) verify(preferenceManager).get(UserPreference.Distance.PrintDistanceTableInReports) verifyNoMoreInteractions(preferenceManager) verifyZeroInteractions(attachmentFilesWriter, dateFormatter) } @Test fun emailTripErrorMemoryTest() { val options = EnumSet.allOf(EmailOptions::class.java) val distancesList: List<Distance> = emptyList() val receiptsList: List<Receipt> = listOf(mock()) val writerResults = AttachmentFilesWriter.WriterResults() writerResults.didMemoryErrorOccure = true whenever(receiptsTable.get(trip, true)).thenReturn(Single.just(receiptsList)) whenever(attachmentFilesWriter.write(trip, receiptsList, distancesList, options)).thenReturn(writerResults) val result = emailAssistant.emailTrip(trip, options).blockingGet() assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_MEMORY) verify(databaseHelper).receiptsTable verify(databaseHelper).distanceTable verify(attachmentFilesWriter).write(trip, receiptsList, distancesList, options) verifyNoMoreInteractions(databaseHelper, attachmentFilesWriter) } @Test fun emailTripErrorTooManyColumns() { val options = EnumSet.of(EmailOptions.PDF_FULL) val distancesList: List<Distance> = emptyList() val receiptsList: List<Receipt> = listOf(mock()) val writerResults = AttachmentFilesWriter.WriterResults() writerResults.didPDFFailCompletely = true writerResults.didPDFFailTooManyColumns = true whenever(receiptsTable.get(trip, true)).thenReturn(Single.just(receiptsList)) whenever(attachmentFilesWriter.write(trip, receiptsList, distancesList, options)).thenReturn(writerResults) val result = emailAssistant.emailTrip(trip, options).blockingGet() assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_TOO_MANY_COLUMNS) verify(databaseHelper).receiptsTable verify(databaseHelper).distanceTable verify(attachmentFilesWriter).write(trip, receiptsList, distancesList, options) verifyNoMoreInteractions(databaseHelper, attachmentFilesWriter) } @Test fun emailTripErrorPdfGeneration() { val options = EnumSet.of(EmailOptions.PDF_FULL) val distancesList: List<Distance> = emptyList() val receiptsList: List<Receipt> = listOf(mock()) val writerResults = AttachmentFilesWriter.WriterResults() writerResults.didPDFFailCompletely = true whenever(receiptsTable.get(trip, true)).thenReturn(Single.just(receiptsList)) whenever(attachmentFilesWriter.write(trip, receiptsList, distancesList, options)).thenReturn(writerResults) val result = emailAssistant.emailTrip(trip, options).blockingGet() assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_PDF_GENERATION) verify(databaseHelper).receiptsTable verify(databaseHelper).distanceTable verify(attachmentFilesWriter).write(trip, receiptsList, distancesList, options) verifyNoMoreInteractions(databaseHelper, attachmentFilesWriter) } @Test fun emailTripSuccess() { val options = EnumSet.of(EmailOptions.PDF_FULL, EmailOptions.CSV) val distancesList: List<Distance> = emptyList() val receiptsList: List<Receipt> = listOf(ReceiptBuilderFactory().setTrip(trip).build()) val filesList: Array<File?> = arrayOf(mock()) val sendIntent = Intent() val writerResults = mock<AttachmentFilesWriter.WriterResults>() whenever(writerResults.didPDFFailCompletely).thenReturn(false) whenever(writerResults.didMemoryErrorOccure).thenReturn(false) whenever(writerResults.files).thenReturn(filesList) whenever(receiptsTable.get(trip, true)).thenReturn(Single.just(receiptsList)) whenever(attachmentFilesWriter.write(trip, receiptsList, distancesList, options)).thenReturn(writerResults) whenever(intentUtils.getSendIntent(context, filesList.filterNotNull())).thenReturn(sendIntent) val result = emailAssistant.emailTrip(trip, options).blockingGet() assert(result is EmailResult.Success) val intent = (result as EmailResult.Success).intent val ccExtra = intent.getStringArrayExtra(Intent.EXTRA_CC) assert(ccExtra.size == 1 && ccExtra[0] == cc) val bccExtra = intent.getStringArrayExtra(Intent.EXTRA_BCC) assert(bccExtra.size == 1 && bccExtra[0] == bcc) val toExtra = intent.getStringArrayExtra(Intent.EXTRA_EMAIL) assert(toExtra.size == 1 && toExtra[0] == to) val subjectExtra = intent.getStringExtra(Intent.EXTRA_SUBJECT) assertEquals(subject, subjectExtra) val bodyExtra = intent.getStringExtra(Intent.EXTRA_TEXT) assertEquals("1 report attached", bodyExtra) verify(databaseHelper).receiptsTable verify(databaseHelper).distanceTable verify(attachmentFilesWriter).write(trip, receiptsList, distancesList, options) verify(intentUtils).getSendIntent(context, filesList.filterNotNull()) } }
app/src/test/java/co/smartreceipts/android/workers/EmailAssistantTest.kt
3989264894
package com.airbnb.epoxy.processor import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.asClassName object KClassNames { // Annotations val DEPRECATED = Deprecated::class.asClassName() val KOTLIN_UNIT = ClassName.bestGuess("kotlin.Unit") }
epoxy-processor/src/main/java/com/airbnb/epoxy/processor/KClassNames.kt
4001616198
package com.mgaetan89.showsrage.extension.realm import android.support.test.runner.AndroidJUnit4 import com.mgaetan89.showsrage.extension.deleteShow import com.mgaetan89.showsrage.extension.getShow import com.mgaetan89.showsrage.extension.getShowStat import com.mgaetan89.showsrage.model.Episode import com.mgaetan89.showsrage.model.Quality import com.mgaetan89.showsrage.model.RealmShowStat import com.mgaetan89.showsrage.model.Schedule import com.mgaetan89.showsrage.model.Show import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class RealmExtension_DeleteShowTest : RealmTest() { @Before fun before() { this.validateInitialState() } @Test fun deleteShow() { this.realm.deleteShow(INDEXER_ID) assertThat(this.getAllEpisodes()).hasSize(1594) assertThat(this.getAllQualities()).hasSize(82) assertThat(this.getAllScheduled()).hasSize(35) assertThat(this.getAllShows()).hasSize(82) assertThat(this.getAllShowStats()).hasSize(82) assertThat(this.getEpisodes()).hasSize(0) assertThat(this.getQuality()).isNull() assertThat(this.getSchedule()).hasSize(0) assertThat(this.getShow()).isNull() assertThat(this.getShowStat()).isNull() } @Test fun deleteShow_unknown() { this.realm.deleteShow(-1) this.validateInitialState() } private fun getAllEpisodes() = this.realm.where(Episode::class.java).findAll() private fun getAllQualities() = this.realm.where(Quality::class.java).findAll() private fun getAllScheduled() = this.realm.where(Schedule::class.java).findAll() private fun getAllShows() = this.realm.where(Show::class.java).findAll() private fun getAllShowStats() = this.realm.where(RealmShowStat::class.java).findAll() private fun getEpisodes() = this.realm.where(Episode::class.java).equalTo("indexerId", INDEXER_ID).findAll() private fun getQuality() = this.realm.where(Quality::class.java).equalTo("indexerId", INDEXER_ID).findFirst() private fun getSchedule() = this.realm.where(Schedule::class.java).equalTo("indexerId", INDEXER_ID).findAll() private fun getShow() = this.realm.getShow(INDEXER_ID) private fun getShowStat() = this.realm.getShowStat(INDEXER_ID) private fun validateInitialState() { assertThat(this.getAllEpisodes()).hasSize(1647) assertThat(this.getAllQualities()).hasSize(83) assertThat(this.getAllScheduled()).hasSize(36) assertThat(this.getAllShows()).hasSize(83) assertThat(this.getAllShowStats()).hasSize(83) assertThat(this.getEpisodes()).hasSize(53) assertThat(this.getQuality()).isNotNull() assertThat(this.getSchedule()).hasSize(1) assertThat(this.getShow()).isNotNull() assertThat(this.getShowStat()).isNotNull() } companion object { private const val INDEXER_ID = 257655 } }
app/src/androidTest/kotlin/com/mgaetan89/showsrage/extension/realm/RealmExtension_DeleteShowTest.kt
3677328500
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.framework import com.intellij.openapi.util.Ref import com.intellij.testFramework.runInEdtAndWait import java.lang.reflect.Method import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.api.extension.InvocationInterceptor import org.junit.jupiter.api.extension.ReflectiveInvocationContext class EdtInterceptor : InvocationInterceptor { override fun interceptBeforeEachMethod( invocation: InvocationInterceptor.Invocation<Void>, invocationContext: ReflectiveInvocationContext<Method>, extensionContext: ExtensionContext ) { exec(invocation, invocationContext) } override fun interceptAfterEachMethod( invocation: InvocationInterceptor.Invocation<Void>, invocationContext: ReflectiveInvocationContext<Method>, extensionContext: ExtensionContext ) { exec(invocation, invocationContext) } override fun interceptTestMethod( invocation: InvocationInterceptor.Invocation<Void>, invocationContext: ReflectiveInvocationContext<Method>, extensionContext: ExtensionContext ) { exec(invocation, invocationContext) } private fun exec( invocation: InvocationInterceptor.Invocation<Void>, invocationContext: ReflectiveInvocationContext<Method> ) { if (invocationContext.executable.getAnnotation(NoEdt::class.java) != null) { invocation.proceed() return } val ref = Ref<Throwable>() runInEdtAndWait { try { invocation.proceed() } catch (t: Throwable) { ref.set(t) } } val thrown = ref.get() if (thrown != null) { throw thrown } } }
src/test/kotlin/com/demonwav/mcdev/framework/EdtInterceptor.kt
2294055856
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.codeInspection.enhancedSwitch import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.enhancedSwitch.RedundantLabeledSwitchRuleCodeBlockInspection import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase /** * @author Pavel.Dolgov */ class RedundantLabeledSwitchRuleCodeBlockFixTest : LightQuickFixParameterizedTestCase() { override fun configureLocalInspectionTools(): Array<LocalInspectionTool> = arrayOf(RedundantLabeledSwitchRuleCodeBlockInspection()) override fun getProjectDescriptor(): LightProjectDescriptor = LightCodeInsightFixtureTestCase.JAVA_12 override fun getBasePath() = "/inspection/redundantLabeledSwitchRuleCodeBlockFix" }
java/java-tests/testSrc/com/intellij/java/codeInspection/enhancedSwitch/RedundantLabeledSwitchRuleCodeBlockFixTest.kt
2463639085
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.* import com.intellij.psi.infos.CandidateInfo import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* class JavaUSimpleNameReferenceExpression( override val psi: PsiElement?, override val identifier: String, givenParent: UElement?, val reference: PsiReference? = null ) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable { override fun resolve(): PsiElement? = (reference ?: psi as? PsiReference)?.resolve() override fun multiResolve(): Iterable<ResolveResult> = (reference as? PsiPolyVariantReference ?: psi as? PsiPolyVariantReference)?.multiResolve(false)?.asIterable() ?: listOfNotNull(resolve()?.let { CandidateInfo(it, PsiSubstitutor.EMPTY) }) override val resolvedName: String? get() = ((reference ?: psi as? PsiReference)?.resolve() as? PsiNamedElement)?.name override fun getPsiParentForLazyConversion(): PsiElement? { val parent = super.getPsiParentForLazyConversion() if (parent is PsiReferenceExpression && parent.parent is PsiMethodCallExpression) { return parent.parent } return parent } override fun convertParent(): UElement? = super.convertParent().let(this::unwrapCompositeQualifiedReference) override val referenceNameElement: UElement? get() = when (psi) { is PsiJavaCodeReferenceElement -> psi.referenceNameElement.toUElement() else -> this } } class JavaUTypeReferenceExpression( override val psi: PsiTypeElement, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UTypeReferenceExpression { override val type: PsiType get() = psi.type } class LazyJavaUTypeReferenceExpression( override val psi: PsiElement, givenParent: UElement?, private val typeSupplier: () -> PsiType ) : JavaAbstractUExpression(givenParent), UTypeReferenceExpression { override val type: PsiType by lz { typeSupplier() } } @Deprecated("no known usages, to be removed in IDEA 2019.2") @ApiStatus.ScheduledForRemoval(inVersion = "2019.2") class JavaClassUSimpleNameReferenceExpression( override val identifier: String, val ref: PsiJavaReference, override val psi: PsiElement, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable { override fun resolve(): PsiElement? = ref.resolve() override fun multiResolve(): Iterable<ResolveResult> = ref.multiResolve(false).asIterable() override val resolvedName: String? get() = (ref.resolve() as? PsiNamedElement)?.name }
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUSimpleNameReferenceExpression.kt
996452817
import pkg.<warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning> import pkg.<warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning>.NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS import pkg.<warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning>.staticNonAnnotatedMethodInAnnotatedClass import pkg.<warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning>.<warning descr="'ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is scheduled for removal in 123.456">ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</warning> import pkg.<warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning>.<warning descr="'staticAnnotatedMethodInAnnotatedClass()' is scheduled for removal in 123.456">staticAnnotatedMethodInAnnotatedClass</warning> import pkg.NonAnnotatedClass import pkg.NonAnnotatedClass.NON_ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS import pkg.NonAnnotatedClass.staticNonAnnotatedMethodInNonAnnotatedClass import pkg.NonAnnotatedClass.<warning descr="'ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS' is scheduled for removal in 123.456">ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS</warning> import pkg.NonAnnotatedClass.<warning descr="'staticAnnotatedMethodInNonAnnotatedClass()' is scheduled for removal in 123.456">staticAnnotatedMethodInNonAnnotatedClass</warning> import pkg.<warning descr="'pkg.AnnotatedEnum' is scheduled for removal in 123.456">AnnotatedEnum</warning> import pkg.NonAnnotatedEnum import pkg.<warning descr="'pkg.AnnotatedEnum' is scheduled for removal in 123.456">AnnotatedEnum</warning>.NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM import pkg.<warning descr="'pkg.AnnotatedEnum' is scheduled for removal in 123.456">AnnotatedEnum</warning>.<warning descr="'ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is scheduled for removal in 123.456">ANNOTATED_VALUE_IN_ANNOTATED_ENUM</warning> import pkg.NonAnnotatedEnum.NON_ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM import pkg.NonAnnotatedEnum.<warning descr="'ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM' is scheduled for removal in 123.456">ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM</warning> import pkg.<warning descr="'pkg.AnnotatedAnnotation' is scheduled for removal in 123.456">AnnotatedAnnotation</warning> import pkg.NonAnnotatedAnnotation import <warning descr="'annotatedPkg' is scheduled for removal in 123.456">annotatedPkg</warning>.ClassInAnnotatedPkg @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE", "UNUSED_VALUE") class ScheduledForRemovalElementsTest { fun test() { var s = <warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning>.NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS <warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning>.staticNonAnnotatedMethodInAnnotatedClass() val annotatedClassInstanceViaNonAnnotatedConstructor : <warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning> = AnnotatedClass() s = annotatedClassInstanceViaNonAnnotatedConstructor.nonAnnotatedFieldInAnnotatedClass annotatedClassInstanceViaNonAnnotatedConstructor.nonAnnotatedMethodInAnnotatedClass() s = NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS staticNonAnnotatedMethodInAnnotatedClass() s = <warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning>.<warning descr="'ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is scheduled for removal in 123.456">ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</warning> <warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning>.<warning descr="'staticAnnotatedMethodInAnnotatedClass()' is scheduled for removal in 123.456">staticAnnotatedMethodInAnnotatedClass</warning>() val annotatedClassInstanceViaAnnotatedConstructor : <warning descr="'pkg.AnnotatedClass' is scheduled for removal in 123.456">AnnotatedClass</warning> = <warning descr="'AnnotatedClass(java.lang.String)' is scheduled for removal in 123.456">AnnotatedClass</warning>("") s = annotatedClassInstanceViaAnnotatedConstructor.<warning descr="'annotatedFieldInAnnotatedClass' is scheduled for removal in 123.456">annotatedFieldInAnnotatedClass</warning> annotatedClassInstanceViaAnnotatedConstructor.<warning descr="'annotatedMethodInAnnotatedClass()' is scheduled for removal in 123.456">annotatedMethodInAnnotatedClass</warning>() s = <warning descr="'ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is scheduled for removal in 123.456">ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</warning> <warning descr="'staticAnnotatedMethodInAnnotatedClass()' is scheduled for removal in 123.456">staticAnnotatedMethodInAnnotatedClass</warning>() // --------------------------------- s = NonAnnotatedClass.NON_ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS NonAnnotatedClass.staticNonAnnotatedMethodInNonAnnotatedClass() val nonAnnotatedClassInstanceViaNonAnnotatedConstructor = NonAnnotatedClass() s = nonAnnotatedClassInstanceViaNonAnnotatedConstructor.nonAnnotatedFieldInNonAnnotatedClass nonAnnotatedClassInstanceViaNonAnnotatedConstructor.nonAnnotatedMethodInNonAnnotatedClass() s = NON_ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS staticNonAnnotatedMethodInNonAnnotatedClass() s = NonAnnotatedClass.<warning descr="'ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS' is scheduled for removal in 123.456">ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS</warning> NonAnnotatedClass.<warning descr="'staticAnnotatedMethodInNonAnnotatedClass()' is scheduled for removal in 123.456">staticAnnotatedMethodInNonAnnotatedClass</warning>() val nonAnnotatedClassInstanceViaAnnotatedConstructor = <warning descr="'NonAnnotatedClass(java.lang.String)' is scheduled for removal in 123.456">NonAnnotatedClass</warning>("") s = nonAnnotatedClassInstanceViaAnnotatedConstructor.<warning descr="'annotatedFieldInNonAnnotatedClass' is scheduled for removal in 123.456">annotatedFieldInNonAnnotatedClass</warning> nonAnnotatedClassInstanceViaAnnotatedConstructor.<warning descr="'annotatedMethodInNonAnnotatedClass()' is scheduled for removal in 123.456">annotatedMethodInNonAnnotatedClass</warning>() s = <warning descr="'ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS' is scheduled for removal in 123.456">ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS</warning> <warning descr="'staticAnnotatedMethodInNonAnnotatedClass()' is scheduled for removal in 123.456">staticAnnotatedMethodInNonAnnotatedClass</warning>() // --------------------------------- var nonAnnotatedValueInAnnotatedEnum : <warning descr="'pkg.AnnotatedEnum' is scheduled for removal in 123.456">AnnotatedEnum</warning> = <warning descr="'pkg.AnnotatedEnum' is scheduled for removal in 123.456">AnnotatedEnum</warning>.NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM nonAnnotatedValueInAnnotatedEnum = NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM var annotatedValueInAnnotatedEnum : <warning descr="'pkg.AnnotatedEnum' is scheduled for removal in 123.456">AnnotatedEnum</warning> = <warning descr="'pkg.AnnotatedEnum' is scheduled for removal in 123.456">AnnotatedEnum</warning>.<warning descr="'ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is scheduled for removal in 123.456">ANNOTATED_VALUE_IN_ANNOTATED_ENUM</warning> annotatedValueInAnnotatedEnum = <warning descr="'ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is scheduled for removal in 123.456">ANNOTATED_VALUE_IN_ANNOTATED_ENUM</warning> var nonAnnotatedValueInNonAnnotatedEnum = NonAnnotatedEnum.NON_ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM nonAnnotatedValueInNonAnnotatedEnum = NON_ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM var annotatedValueInNonAnnotatedEnum = NonAnnotatedEnum.<warning descr="'ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM' is scheduled for removal in 123.456">ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM</warning> annotatedValueInNonAnnotatedEnum = <warning descr="'ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM' is scheduled for removal in 123.456">ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM</warning> // --------------------------------- @<warning descr="'pkg.AnnotatedAnnotation' is scheduled for removal in 123.456">AnnotatedAnnotation</warning> class C1 @<warning descr="'pkg.AnnotatedAnnotation' is scheduled for removal in 123.456">AnnotatedAnnotation</warning>(nonAnnotatedAttributeInAnnotatedAnnotation = "123") class C2 @<warning descr="'pkg.AnnotatedAnnotation' is scheduled for removal in 123.456">AnnotatedAnnotation</warning>(<warning descr="'annotatedAttributeInAnnotatedAnnotation' is scheduled for removal in 123.456">annotatedAttributeInAnnotatedAnnotation</warning> = "123") class C3 @NonAnnotatedAnnotation class C4 @NonAnnotatedAnnotation(nonAnnotatedAttributeInNonAnnotatedAnnotation = "123") class C5 @NonAnnotatedAnnotation(<warning descr="'annotatedAttributeInNonAnnotatedAnnotation' is scheduled for removal in 123.456">annotatedAttributeInNonAnnotatedAnnotation</warning> = "123") class C6 } }
jvm/jvm-analysis-kotlin-tests/testData/codeInspection/scheduledForRemoval/ScheduledForRemovalElementsTest.kt
3123470615