content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.renderscript_test import android.graphics.Bitmap import android.renderscript.Allocation import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.Script import android.renderscript.ScriptIntrinsicBlend import android.renderscript.Type import com.google.android.renderscript.BlendingMode import com.google.android.renderscript.Range2d /** * Does a Blend operation using the RenderScript Intrinsics. */ fun intrinsicBlend( context: RenderScript, mode: BlendingMode, sourceArray: ByteArray, destArray: ByteArray, sizeX: Int, sizeY: Int, restriction: Range2d? ) { val scriptBlend = ScriptIntrinsicBlend.create(context, Element.U8_4(context)) val builder = Type.Builder(context, Element.U8_4(context)) builder.setX(sizeX) builder.setY(sizeY) val arrayType = builder.create() val sourceAllocation = Allocation.createTyped(context, arrayType) val destAllocation = Allocation.createTyped(context, arrayType) sourceAllocation.copyFrom(sourceArray) destAllocation.copyFrom(destArray) callBlendForEach(scriptBlend, sourceAllocation, destAllocation, mode, restriction) destAllocation.copyTo(destArray) sourceAllocation.destroy() destAllocation.destroy() arrayType.destroy() scriptBlend.destroy() } fun intrinsicBlend( context: RenderScript, mode: BlendingMode, sourceBitmap: Bitmap, destBitmap: Bitmap, restriction: Range2d? ) { val scriptBlend = ScriptIntrinsicBlend.create(context, Element.U8_4(context)) val sourceAllocation = Allocation.createFromBitmap(context, sourceBitmap) val destAllocation = Allocation.createFromBitmap(context, destBitmap) sourceAllocation.copyFrom(sourceBitmap) destAllocation.copyFrom(destBitmap) callBlendForEach(scriptBlend, sourceAllocation, destAllocation, mode, restriction) destAllocation.copyTo(destBitmap) sourceAllocation.destroy() destAllocation.destroy() scriptBlend.destroy() } private fun callBlendForEach( scriptBlend: ScriptIntrinsicBlend, sourceAllocation: Allocation, destAllocation: Allocation, mode: BlendingMode, restriction: Range2d? ) { if (restriction != null) { val options = Script.LaunchOptions() options.setX(restriction.startX, restriction.endX) options.setY(restriction.startY, restriction.endY) when (mode) { BlendingMode.CLEAR -> scriptBlend.forEachClear( sourceAllocation, destAllocation, options ) BlendingMode.SRC -> scriptBlend.forEachSrc( sourceAllocation, destAllocation, options ) BlendingMode.DST -> scriptBlend.forEachDst( sourceAllocation, destAllocation, options ) BlendingMode.SRC_OVER -> scriptBlend.forEachSrcOver( sourceAllocation, destAllocation, options ) BlendingMode.DST_OVER -> scriptBlend.forEachDstOver( sourceAllocation, destAllocation, options ) BlendingMode.SRC_IN -> scriptBlend.forEachSrcIn( sourceAllocation, destAllocation, options ) BlendingMode.DST_IN -> scriptBlend.forEachDstIn( sourceAllocation, destAllocation, options ) BlendingMode.SRC_OUT -> scriptBlend.forEachSrcOut( sourceAllocation, destAllocation, options ) BlendingMode.DST_OUT -> scriptBlend.forEachDstOut( sourceAllocation, destAllocation, options ) BlendingMode.SRC_ATOP -> scriptBlend.forEachSrcAtop( sourceAllocation, destAllocation, options ) BlendingMode.DST_ATOP -> scriptBlend.forEachDstAtop( sourceAllocation, destAllocation, options ) BlendingMode.XOR -> scriptBlend.forEachXor( sourceAllocation, destAllocation, options ) BlendingMode.MULTIPLY -> scriptBlend.forEachMultiply( sourceAllocation, destAllocation, options ) BlendingMode.ADD -> scriptBlend.forEachAdd( sourceAllocation, destAllocation, options ) BlendingMode.SUBTRACT -> scriptBlend.forEachSubtract( sourceAllocation, destAllocation, options ) } } else { when (mode) { BlendingMode.CLEAR -> scriptBlend.forEachClear( sourceAllocation, destAllocation ) BlendingMode.SRC -> scriptBlend.forEachSrc( sourceAllocation, destAllocation ) BlendingMode.DST -> scriptBlend.forEachDst( sourceAllocation, destAllocation ) BlendingMode.SRC_OVER -> scriptBlend.forEachSrcOver( sourceAllocation, destAllocation ) BlendingMode.DST_OVER -> scriptBlend.forEachDstOver( sourceAllocation, destAllocation ) BlendingMode.SRC_IN -> scriptBlend.forEachSrcIn( sourceAllocation, destAllocation ) BlendingMode.DST_IN -> scriptBlend.forEachDstIn( sourceAllocation, destAllocation ) BlendingMode.SRC_OUT -> scriptBlend.forEachSrcOut( sourceAllocation, destAllocation ) BlendingMode.DST_OUT -> scriptBlend.forEachDstOut( sourceAllocation, destAllocation ) BlendingMode.SRC_ATOP -> scriptBlend.forEachSrcAtop( sourceAllocation, destAllocation ) BlendingMode.DST_ATOP -> scriptBlend.forEachDstAtop( sourceAllocation, destAllocation ) BlendingMode.XOR -> scriptBlend.forEachXor( sourceAllocation, destAllocation ) BlendingMode.MULTIPLY -> scriptBlend.forEachMultiply( sourceAllocation, destAllocation ) BlendingMode.ADD -> scriptBlend.forEachAdd( sourceAllocation, destAllocation ) BlendingMode.SUBTRACT -> scriptBlend.forEachSubtract( sourceAllocation, destAllocation ) } } }
test-app/src/main/java/com/google/android/renderscript_test/IntrinsicBlend.kt
2743234614
package org.hexworks.zircon.api.dsl.component import org.hexworks.zircon.api.component.AttachedComponent import org.hexworks.zircon.api.component.Component import org.hexworks.zircon.api.component.Container import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer operator fun ComponentDecorationRenderer.plus( other: ComponentDecorationRenderer ): List<ComponentDecorationRenderer> { return listOf(this, other) } operator fun <T : Component> T.plus(other: T): List<T> { return listOf(this, other) } operator fun Container.plus(other: Component): AttachedComponent { return this.addComponent(other) }
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/dsl/component/DSLExtensions.kt
3015497882
package org.hexworks.zircon.internal.tileset.transformer import com.badlogic.gdx.graphics.g2d.TextureRegion import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.api.tileset.TextureTransformer import org.hexworks.zircon.api.tileset.TileTexture import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture class LibgdxTextureCloner : TextureTransformer<TextureRegion> { override val targetType = TextureRegion::class override fun transform(texture: TileTexture<TextureRegion>, tile: Tile): TileTexture<TextureRegion> { return DefaultTileTexture( width = texture.width, height = texture.height, texture = TextureRegion(texture.texture), cacheKey = tile.cacheKey ) } }
zircon.jvm.libgdx/src/main/kotlin/org/hexworks/zircon/internal/tileset/transformer/LibgdxTextureCloner.kt
2846314231
package org.ligi.passandroid.functions import android.content.ActivityNotFoundException import android.content.Intent import android.provider.CalendarContract import androidx.annotation.VisibleForTesting import com.google.android.material.snackbar.Snackbar import androidx.appcompat.app.AlertDialog import android.view.View import org.ligi.passandroid.R import org.ligi.passandroid.model.pass.Pass import org.ligi.passandroid.model.pass.PassImpl const val DEFAULT_EVENT_LENGTH_IN_HOURS = 8L fun tryAddDateToCalendar(pass: Pass, contextView: View, timeSpan: PassImpl.TimeSpan) { if (pass.calendarTimespan == null) { AlertDialog.Builder(contextView.context).setMessage(R.string.expiration_date_to_calendar_warning_message) .setTitle(R.string.expiration_date_to_calendar_warning_title) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok) { _, _ -> reallyAddToCalendar(pass, contextView, timeSpan) } .show() } else { reallyAddToCalendar(pass, contextView, timeSpan) } } private fun reallyAddToCalendar(pass: Pass, contextView: View, timeSpan: PassImpl.TimeSpan) = try { val intent = createIntent(pass, timeSpan) contextView.context.startActivity(intent) } catch (exception: ActivityNotFoundException) { // TODO maybe action to install calendar app Snackbar.make(contextView, R.string.no_calendar_app_found, Snackbar.LENGTH_LONG).show() } @VisibleForTesting fun createIntent(pass: Pass, timeSpan: PassImpl.TimeSpan) = Intent(Intent.ACTION_EDIT).apply { if (timeSpan.from == null && timeSpan.to == null) { throw IllegalArgumentException("span must have either a to or a from") } type = "vnd.android.cursor.item/event" val from = timeSpan.from ?: timeSpan.to!!.minusHours(DEFAULT_EVENT_LENGTH_IN_HOURS) putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, from.toEpochSecond() * 1000) val to = timeSpan.to ?: timeSpan.from!!.plusHours(DEFAULT_EVENT_LENGTH_IN_HOURS) putExtra(CalendarContract.EXTRA_EVENT_END_TIME, to.toEpochSecond() * 1000) putExtra("title", pass.description) pass.locations.firstOrNull()?.name?.let { putExtra("eventLocation", it) } }
android/src/main/java/org/ligi/passandroid/functions/AddToCalendar.kt
3237532384
package org.wordpress.android.ui.stats.refresh.lists.widget.today import org.wordpress.android.modules.AppComponent import org.wordpress.android.ui.stats.refresh.lists.widget.StatsWidget import org.wordpress.android.ui.stats.refresh.lists.widget.WidgetUpdater import javax.inject.Inject class StatsTodayWidget : StatsWidget() { @Inject lateinit var todayWidgetUpdater: TodayWidgetUpdater override val widgetUpdater: WidgetUpdater get() = todayWidgetUpdater override fun inject(appComponent: AppComponent) { appComponent.inject(this) } }
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/widget/today/StatsTodayWidget.kt
3177713534
package com.edwardharker.aircraftrecognition.repository.retrofit import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.Type object UnitConverterFactory : Converter.Factory() { override fun responseBodyConverter( type: Type, annotations: Array<out Annotation>, retrofit: Retrofit ): Converter<ResponseBody, *>? { return if (type == Unit::class.java) UnitConverter else null } private object UnitConverter : Converter<ResponseBody, Unit> { override fun convert(value: ResponseBody) { value.close() } } }
androidcommon/src/main/kotlin/com/edwardharker/aircraftrecognition/repository/retrofit/UnitConverterFactory.kt
3241406460
package org.wordpress.android.ui.stats object StatsConstants { const val ITEM_TYPE_POST = "post" const val ITEM_TYPE_HOME_PAGE = "homepage" const val ITEM_TYPE_ATTACHMENT = "attachment" }
WordPress/src/main/java/org/wordpress/android/ui/stats/StatsConstants.kt
4145882527
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.merge.mergeconfig import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction import com.kotlinnlp.simplednn.core.layers.LayerType /** * The Biaffine merge layer configuration. * * @property outputSize the size of the merged output * @property activationFunction the output activation function */ class BiaffineMerge( outputSize: Int, activationFunction: ActivationFunction? = null ) : VariableOutputMergeConfig( type = LayerType.Connection.Biaffine, outputSize = outputSize, activationFunction = activationFunction )
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/merge/mergeconfig/BiaffineMerge.kt
2286397088
// IS_APPLICABLE: false interface MyInterface { val <caret>prop5: Int }
plugins/kotlin/idea/tests/testData/intentions/movePropertyToConstructor/declaredInInterface.kt
2259572001
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.statistic.libraryUsage import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase import com.intellij.util.xmlb.XmlSerializer class LibraryUsageStatisticStorageTest : LightJavaCodeInsightFixtureTestCase() { fun testFiles() { val txtFile = myFixture.addFileToProject("Text.txt", "").virtualFile val javaFile = myFixture.addFileToProject("JavaFile.java", "").virtualFile val filesStorageService = ProcessedFilesStorageService.getInstance(project) val state = filesStorageService.state val timestamps = state.timestamps assertFalse(filesStorageService.isVisited(txtFile)) assertTrue(filesStorageService.visit(txtFile)) assertTrue(filesStorageService.isVisited(txtFile)) assertFalse(filesStorageService.visit(txtFile)) assertTrue(filesStorageService.isVisited(txtFile)) filesStorageService.visit(txtFile) assertTrue(filesStorageService.isVisited(txtFile)) assertFalse(filesStorageService.isVisited(javaFile)) assertTrue(filesStorageService.visit(javaFile)) assertTrue(filesStorageService.isVisited(javaFile)) assertTrue(timestamps.isNotEmpty()) val serializedState = XmlSerializer.serialize(state) val deserializedState = XmlSerializer.deserialize( serializedState, ProcessedFilesStorageService.MyState::class.java, ) assertEquals(timestamps, deserializedState.timestamps) filesStorageService.loadState(deserializedState) assertEquals(timestamps, filesStorageService.state.timestamps) } fun testLibraries() { val txtFile = myFixture.addFileToProject("Text.txt", "").virtualFile val javaFile = myFixture.addFileToProject("JavaFile.java", "").virtualFile val storageService = LibraryUsageStatisticsStorageService.getInstance(project) val txtLib = createLib(txtFile) storageService.increaseUsage(txtLib) storageService.increaseUsage(txtLib) storageService.increaseUsage(createLib(javaFile)) storageService.increaseUsages(listOf(txtLib, createLib(txtFile, version = "1.0.0"), createLib(txtFile, name = "otherName"))) val copyOfState = storageService.state assertTrue(copyOfState.statistics.isNotEmpty()) assertEquals(copyOfState.statistics, storageService.state.statistics) val expectedSet = mapOf( LibraryUsage("myLibName", "1.1.1", "PLAIN_TEXT") to 3, LibraryUsage("myLibName", "1.0.0", "PLAIN_TEXT") to 1, LibraryUsage("myLibName", "1.1.1", "JAVA") to 1, LibraryUsage("otherName", "1.1.1", "PLAIN_TEXT") to 1, ) assertEquals(expectedSet, copyOfState.statistics) assertEquals(expectedSet, storageService.getStatisticsAndResetState()) assertTrue(storageService.state.statistics.isEmpty()) storageService.loadState(copyOfState) val state = storageService.state val statistics = storageService.getStatisticsAndResetState() assertEquals(expectedSet, statistics) assertTrue(storageService.state.statistics.isEmpty()) val serializedState = XmlSerializer.serialize(state) val deserializedState = XmlSerializer.deserialize( serializedState, LibraryUsageStatisticsStorageService.LibraryUsageStatisticsState::class.java, ) assertEquals(expectedSet, deserializedState.statistics) storageService.loadState(deserializedState) assertEquals(expectedSet, storageService.state.statistics) } } private fun LibraryUsageStatisticsStorageService.increaseUsage(lib: LibraryUsage) { increaseUsages(listOf(lib)) } private fun createLib( vFile: VirtualFile, name: String = "myLibName", version: String = "1.1.1", ): LibraryUsage = LibraryUsage(name = name, version = version, fileType = vFile.fileType)
java/java-tests/testSrc/com/intellij/internal/statistic/libraryUsage/LibraryUsageStatisticStorageTest.kt
4251917026
package com.jlangen.vaultbox.vaults.vault import android.os.Bundle import android.support.v7.widget.Toolbar import com.jlangen.vaultbox.R import com.jlangen.vaultbox.architecture.BaseActivity import com.jlangen.vaultbox.architecture.DaggerCoordinatorProvider import com.jlangen.vaultbox.architecture.coordinators.Coordinators class VaultActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_vault) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) supportActionBar?.setDefaultDisplayHomeAsUpEnabled(true) supportActionBar?.title = getString(R.string.app_name) Coordinators.bind(findViewById(R.id.vault_view), DaggerCoordinatorProvider()) } }
app/src/main/java/com/jlangen/vaultbox/vaults/vault/VaultActivity.kt
3505334184
package de.schooltec.datapass.datasupplier import android.content.Context import java.util.* /** * DummyDataSupplier which simply says that it can't retrieve any data. * * @author Martin Hellwig */ internal class DummyDataSupplier : DataSupplier { override val isRealDataSupplier: Boolean get() = false override val trafficWasted: Long get() = 0 override val trafficAvailable: Long get() = 0 override val lastUpdate: Date get() = Date() override fun fetchData(context: Context): DataSupplier.ReturnCode { return DataSupplier.ReturnCode.CARRIER_UNAVAILABLE } }
app/src/main/java/de/schooltec/datapass/datasupplier/DummyDataSupplier.kt
3964170403
// WITH_STDLIB fun test() { <selection>1 to 2</selection> }
plugins/kotlin/idea/tests/testData/refactoring/introduceVariable/multiDeclarations/unusedExpr.kt
2124951668
/** * Copyright 2018 Google LLC. 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.example.subscriptions.ui import android.util.Log import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.LinearLayout import android.widget.ProgressBar import android.widget.TextView import androidx.databinding.BindingAdapter import com.bumptech.glide.Glide import com.bumptech.glide.request.target.Target import com.example.subscriptions.Constants import com.example.subscriptions.R import com.example.subscriptions.billing.isAccountHold import com.example.subscriptions.billing.isBasicContent import com.example.subscriptions.billing.isGracePeriod import com.example.subscriptions.billing.isPaused import com.example.subscriptions.billing.isPremiumContent import com.example.subscriptions.billing.isPrepaid import com.example.subscriptions.billing.isSubscriptionRestore import com.example.subscriptions.billing.isTransferRequired import com.example.subscriptions.data.ContentResource import com.example.subscriptions.data.SubscriptionStatus import com.example.subscriptions.utils.basicTextForSubscription import com.example.subscriptions.utils.premiumTextForSubscription import java.text.SimpleDateFormat import java.util.Calendar private const val TAG = "BindingAdapter" /** * Update a loading progress bar when the status changes. * * When the network state changes, the binding adapter triggers this view in the layout XML. * See the layout XML files for the app:loadingProgressBar attribute. */ @BindingAdapter("loadingProgressBar") fun ProgressBar.loadingProgressBar(loading: Boolean?) { visibility = if (loading == true) View.VISIBLE else View.GONE } /** * Load image with original size. If url is null, hide [ImageView] */ @BindingAdapter("loadImageOrHide") fun ImageView.loadImageOrHide(url: String?) { if (url != null) { Log.d(TAG, "Loading image for content: $url") visibility = View.VISIBLE Glide.with(context) .load(url) .override(Target.SIZE_ORIGINAL) .into(this) } else { visibility = View.GONE } } /** * Update basic content when the URL changes. */ @BindingAdapter("basicContent") fun TextView.updateBasicContent(basicContent: ContentResource?) { text = if (basicContent?.url != null) resources.getString(R.string.basic_auto_message) else resources.getString(R.string.no_basic_content) } /** * Update premium content on the Premium fragment when the URL changes. */ @BindingAdapter("premiumContent") fun TextView.updatePremiumContent(premiumContent: ContentResource?) { text = if (premiumContent?.url != null) resources.getString(R.string.premium_content_text) else resources.getString(R.string.no_premium_content) } /** * Update subscription views on the Home fragment when the subscription changes. * * When the subscription changes, the binding adapter triggers this view in the layout XML. * See the layout XML files for the app:updateHomeViews attribute. */ @BindingAdapter("updateHomeViews") fun LinearLayout.updateHomeViews(subscriptions: List<SubscriptionStatus>?) { val paywallMessage = findViewById<View>(R.id.home_paywall_message) val restoreMessage = findViewById<TextView>(R.id.home_restore_message) val gracePeriodMessage = findViewById<View>(R.id.home_grace_period_message) val transferMessage = findViewById<View>(R.id.home_transfer_message) val accountHoldMessage = findViewById<View>(R.id.home_account_hold_message) val accountPausedMessage = findViewById<View>(R.id.home_account_paused_message) val basicMessage = findViewById<View>(R.id.home_basic_message) val downgradeMessage = findViewById<View>(R.id.basic_downgrade_message) val prepaidMessage = findViewById<View>(R.id.prepaid_basic_content) val accountPausedMessageText = findViewById<TextView>(R.id.home_account_paused_message_text) // Set visibility assuming no subscription is available. // If a subscription is found that meets certain criteria, then the visibility of the paywall // will be changed to View.GONE. paywallMessage.visibility = View.VISIBLE // The remaining views start hidden. If a subscription is found that meets each criteria, // then the visibility will be changed to View.VISIBLE. listOf( restoreMessage, gracePeriodMessage, transferMessage, accountHoldMessage, accountPausedMessage, basicMessage, prepaidMessage, downgradeMessage ).forEach { it.visibility = View.GONE } // Update based on subscription information. subscriptions?.forEach { subscription -> if (subscription.isBasicContent && isSubscriptionRestore(subscription) && !subscription.isPrepaid) { Log.d(TAG, "restore VISIBLE") restoreMessage.run { visibility = View.VISIBLE val expiryDate = getHumanReadableDate(subscription.activeUntilMillisec) text = resources.getString(R.string.restore_message_with_date, expiryDate) } paywallMessage.visibility = View.GONE // Paywall gone. } if (isGracePeriod(subscription)) { Log.d(TAG, "grace period VISIBLE") gracePeriodMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE // Paywall gone. } if (isTransferRequired(subscription) && subscription.product == Constants.BASIC_PRODUCT) { Log.d(TAG, "transfer VISIBLE") transferMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE // Paywall gone. } if (isAccountHold(subscription)) { Log.d(TAG, "account hold VISIBLE") accountHoldMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE // Paywall gone. } if (isPaused(subscription)) { Log.d(TAG, "account paused VISIBLE") accountPausedMessageText.run { val autoResumeDate = getHumanReadableDate(subscription.autoResumeTimeMillis) text = resources.getString(R.string.account_paused_message, autoResumeDate) } accountPausedMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE // Paywall gone. } if (subscription.isBasicContent && !isPremiumContent(subscription) && !subscription.isPrepaid) { Log.d(TAG, "Downgrade VISIBLE") basicMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE // Paywall gone. } if (subscription.isPrepaid && subscription.isBasicContent && !isPremiumContent(subscription)) { Log.d(TAG, "Basic Prepaid VISIBLE") prepaidMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE } if (!subscription.isBasicContent && isPremiumContent(subscription)) { Log.d(TAG, "Downgrade VISIBLE") downgradeMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE } } } /** * Update subscription views on the Premium fragment when the subscription changes. * * When the subscription changes, the binding adapter triggers this view in the layout XML. * See the layout XML files for the app:updatePremiumViews attribute. */ @BindingAdapter("updatePremiumViews") fun LinearLayout.updatePremiumViews(subscriptions: List<SubscriptionStatus>?) { val paywallMessage = findViewById<View>(R.id.premium_paywall_message) val restoreMessage = findViewById<TextView>(R.id.premium_restore_message) val gracePeriodMessage = findViewById<TextView>(R.id.premium_grace_period_message) val transferMessage = findViewById<View>(R.id.premium_transfer_message) val accountHoldMessage = findViewById<View>(R.id.premium_account_hold_message) val accountPausedMessage = findViewById<View>(R.id.premium_account_paused_message) val premiumContent = findViewById<View>(R.id.premium_premium_content) val upgradeMessage = findViewById<View>(R.id.premium_upgrade_message) val prepaidMessage = findViewById<View>(R.id.prepaid_premium_content) val accountPausedMessageText = findViewById<TextView>(R.id.premium_account_paused_message_text) // Set visibility assuming no subscription is available. // If a subscription is found that meets certain criteria, then the visibility of the paywall // will be changed to View.GONE. paywallMessage.visibility = View.VISIBLE // The remaining views start hidden. If a subscription is found that meets each criteria, // then the visibility will be changed to View.VISIBLE. listOf( restoreMessage, gracePeriodMessage, transferMessage, accountHoldMessage, accountPausedMessage, premiumContent, upgradeMessage, prepaidMessage ).forEach { it.visibility = View.GONE } // The Upgrade button should appear if the user has a basic subscription, but does not // have a premium subscription. This variable keeps track of whether a premium subscription // has been found when looking through the list of subscriptions. // Update based on subscription information. subscriptions?.let { for (subscription in subscriptions) { if (isPremiumContent(subscription) && isSubscriptionRestore(subscription) && !subscription.isPrepaid) { Log.d(TAG, "restore VISIBLE") restoreMessage.run { visibility = View.VISIBLE val expiryDate = getHumanReadableDate(subscription.activeUntilMillisec) text = resources.getString(R.string.restore_message_with_date, expiryDate) } paywallMessage.visibility = View.GONE // Paywall gone. } if (isGracePeriod(subscription)) { Log.d(TAG, "grace period VISIBLE") gracePeriodMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE // Paywall gone. } if (isTransferRequired(subscription) && subscription.product == Constants.PREMIUM_PRODUCT) { Log.d(TAG, "transfer VISIBLE") transferMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE // Paywall gone. } if (isAccountHold(subscription)) { Log.d(TAG, "account hold VISIBLE") accountHoldMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE // Paywall gone. } if (isPaused(subscription)) { Log.d(TAG, "account paused VISIBLE") accountPausedMessageText.run { val autoResumeDate = getHumanReadableDate(subscription.autoResumeTimeMillis) text = resources.getString(R.string.account_paused_message, autoResumeDate) } accountPausedMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE // Paywall gone. } // The upgrade message must be shown if there is a basic subscription // and there are zero premium subscriptions. We need to keep track of the premium // subscriptions and hide the upgrade message if we find any. if (isPremiumContent(subscription) && !subscription.isPrepaid && !subscription.isBasicContent) { Log.d(TAG, "premium VISIBLE") premiumContent.visibility = View.VISIBLE paywallMessage.visibility = View.GONE // Paywall gone. } if (isPremiumContent(subscription) && !subscription.isBasicContent && subscription.isPrepaid) { Log.d(TAG, "Premium Prepaid VISIBLE") prepaidMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE } if (!isPremiumContent(subscription) && subscription.isBasicContent) { Log.d(TAG, "Upgrade VISIBLE") upgradeMessage.visibility = View.VISIBLE paywallMessage.visibility = View.GONE } } } } /** * Update views on the Settings fragment when the subscription changes. * * When the subscription changes, the binding adapter triggers this view in the layout XML. * See the layout XML files for the app:updateSettingsViews attribute. * TODO(232165789): update method to update settings view */ @BindingAdapter("updateSettingsViews") fun LinearLayout.updateSettingsViews(subscriptions: List<SubscriptionStatus>?) { } /** * Get a readable date from the time in milliseconds. */ fun getHumanReadableDate(milliSeconds: Long): String { val formatter = SimpleDateFormat.getDateInstance() val calendar = Calendar.getInstance() calendar.timeInMillis = milliSeconds if (milliSeconds == 0L) { Log.d(TAG, "Suspicious time: 0 milliseconds.") } else { Log.d(TAG, "Milliseconds: $milliSeconds") } return formatter.format(calendar.time) }
ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/ui/SubscriptionBindingAdapter.kt
959241330
package i_introduction._0_Hello_World import util.TODO import util.doc0 fun todoTask0(): Nothing = TODO( """ Task 0. Read README.md to learn how to work with this project and check your solutions. Using 'documentation =' below the task description you can open the related part of the online documentation. Press 'Ctrl+Q'(Windows) or 'F1'(Mac OS) on 'doc0()' to call the "Quick Documentation" action; "See also" section gives you a link. You can see the shortcut for the "Quick Documentation" action used in your IntelliJ IDEA by choosing "Help -> Find Action..." (in the top menu), and typing the action name ("Quick Documentation"). The shortcut in use will be written next to the action name. Using 'references =' you can navigate to the code mentioned in the task description. Let's start! Make the function 'task0' return "OK". Note that you can return expression directly. """, documentation = doc0(), references = { task0(); "OK" } ) fun task0(): String { return "OK" }
src/i_introduction/_0_Hello_World/n00Start.kt
3152210419
package me.aberrantfox.hotbot.commandframework.commands.permissions import me.aberrantfox.hotbot.commandframework.parsing.ArgumentType import me.aberrantfox.hotbot.dsls.command.Command import me.aberrantfox.hotbot.dsls.command.CommandSet import me.aberrantfox.hotbot.dsls.command.commands import me.aberrantfox.hotbot.dsls.embed.embed import me.aberrantfox.hotbot.extensions.stdlib.sanitiseMentions import me.aberrantfox.hotbot.permissions.PermissionLevel import me.aberrantfox.hotbot.services.CommandDescriptor import me.aberrantfox.hotbot.services.HelpConf import net.dv8tion.jda.core.entities.Role import java.awt.Color @CommandSet fun permissionCommands() = commands { command("setPermission") { expect(ArgumentType.Command, ArgumentType.PermissionLevel) execute { val command = it.args.component1() as Command val level = it.args.component2() as PermissionLevel it.manager.setPermission(command.name, level) it.safeRespond("${command.name} is now accessible to ${level.name} and higher") } } command("getPermission") { expect(ArgumentType.Command) execute { val name = (it.args.component1() as Command).name it.safeRespond("The required role is: ${it.manager.roleRequired(name).name}") } } command("listcommandperms") { execute { it.respond(it.manager.listAvailableCommands(it.author)) } } command("roleids") { execute { it.safeRespond(it.guild.roles.joinToString("\n") { role -> "${role.name} :: ${role.id}" }) } } command("setallPermissions") { expect(ArgumentType.PermissionLevel) execute { val level = it.args.component1() as PermissionLevel if (it.config.serverInformation.ownerID != it.author.id) { it.respond("Sorry, this command can only be run by the owner marked in the configuration file.") return@execute } it.container.listCommands().forEach { command -> it.manager.setPermission(command, level) } } } command("setPermissions") { expect(ArgumentType.Category, ArgumentType.PermissionLevel) execute { val category = it.args.component1() as String val level = it.args.component2() as PermissionLevel val commands = HelpConf.listCommandsinCategory(category).map { it.name } if (commands.isEmpty()) { it.respond("Either this category ($category) contains 0 commands, or it is not a real category :thinking:") return@execute } commands.forEach { command -> it.manager.setPermission(command, level) } it.safeRespond("${level.name} now has access to: ${commands.joinToString(prefix = "`", postfix = "`")}") } } command("viewpermissions") { execute { it.respond(embed { title("Command Permissions") description("Below you can see all of the different command categories, along with all of their " + "respective commands and the associated permission required to use those commands.") HelpConf.listCategories() .map { cat -> val commandsInCategory = HelpConf.listCommandsinCategory(cat) val text = commandsInCategory.joinToString("\n") { cmd -> "${cmd.name} -- ${it.manager.roleRequired(cmd.name)}" } Pair(cat, text) } .forEach { field { name = it.first value = it.second.sanitiseMentions() inline = false } } }) } } command("listavailable") { execute { val available = HelpConf.listCategories().map { cat -> val cmds = HelpConf.listCommandsinCategory(cat) .filter { cmd -> it.manager.canUseCommand(it.author, cmd.name) } .map(CommandDescriptor::name) .joinToString() Pair(cat, cmds) }.filter { it.second.isNotEmpty() } it.respond(embed { title("Commands available to you") setColor(Color.green) setThumbnail(it.author.effectiveAvatarUrl) available.forEach { field { name = it.first value = it.second inline = false } } }) } } command("setRoleLevel") { expect(ArgumentType.Role, ArgumentType.PermissionLevel) execute { val role = it.args.component1() as Role val level = it.args.component2() as PermissionLevel it.manager.assignRoleLevel(role, level) it.respond("${role.name} is now assigned the permission level ${level.name}") } } command("viewRoleAssignments") { execute { it.respond(embed { title("Role Assignments") description("Below you can see what roles have been assigned what permission levels") val assignments = it.manager.roleAssignemts() val assignmentsText = if(assignments.isEmpty()) { "None" } else { assignments.joinToString("\n") { pair -> val roleName = it.guild.getRoleById(pair.key).name "$roleName :: PermissionLevel.${pair.value}" } } field { this.name = "Assignments" this.value = assignmentsText inline = false } }) } } }
src/main/kotlin/me/aberrantfox/hotbot/commandframework/commands/permissions/PermissionsCommands.kt
2024351516
package com.emberjs.configuration.serve import com.emberjs.configuration.EmberCommandLineState import com.emberjs.configuration.EmberConfigurationBase import com.emberjs.configuration.serve.ui.EmberServeSettingsEditor import com.intellij.execution.ExecutionException import com.intellij.execution.Executor import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import org.jetbrains.annotations.NotNull import org.jetbrains.annotations.Nullable class EmberServeConfiguration(project: Project, factory: ConfigurationFactory, name: String) : EmberConfigurationBase(project, factory, name) { override val options = EmberServeOptions() override val command: String = "serve" @NotNull override fun getConfigurationEditor(): SettingsEditor<out RunConfiguration> { return EmberServeSettingsEditor(project) } @Nullable @Throws(ExecutionException::class) override fun getState(@NotNull executor: Executor, @NotNull executionEnvironment: ExecutionEnvironment): RunProfileState? { return EmberCommandLineState(executionEnvironment) } }
src/main/kotlin/com/emberjs/configuration/serve/EmberServeConfiguration.kt
544957923
package id.kotlin.sample.room.data import android.arch.persistence.room.Dao import android.arch.persistence.room.Delete import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy import android.arch.persistence.room.Query import android.arch.persistence.room.Update @Dao interface UserDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun createUser(user: User) @Query("SELECT * FROM User") fun findAll(): List<User> @Update fun updateUser(user: User) @Delete fun deleteUser(user: User) }
app/src/main/java/id/kotlin/sample/room/data/UserDao.kt
571284375
// "Convert string to character literal" "true" fun test(c: Char): Boolean { return <caret>c == "'" }
plugins/kotlin/idea/tests/testData/quickfix/equalityNotApplicable/charLiteralConversion/charEqStringSingleQuote.kt
1304149261
package org.jetbrains.completion.full.line.settings.ui.panels import com.intellij.lang.Language import com.intellij.ui.components.JBPasswordField import com.intellij.ui.layout.* import org.jetbrains.completion.full.line.models.ModelType import org.jetbrains.completion.full.line.settings.state.MLServerCompletionSettings import org.jetbrains.completion.full.line.settings.ui.components.LoadingComponent import org.jetbrains.completion.full.line.settings.ui.components.languageCheckBox import org.jetbrains.completion.full.line.settings.ui.components.loadingStatus import org.jetbrains.completion.full.line.settings.ui.components.pingButton import org.jetbrains.completion.full.line.settings.ui.fullRow class LanguageCloudModelPanel( languages: Collection<Language>, private val flccEnabled: ComponentPredicate, authTokenTextField: JBPasswordField? = null, ) : ComplexPanel { private val rows = languages.map { LanguageRow( it, authTokenTextField, MLServerCompletionSettings.getInstance().state.langStates.keys.maxByOrNull { it.length }, ) } override val panel = panel { rows.forEach { it.row(this).enableIf(flccEnabled) } }.apply { name = ModelType.Cloud.name } private class LanguageRow(val language: Language, val authTokenTextField: JBPasswordField?, biggestLang: String?) : ComplexRow { private val checkBox = languageCheckBox(language, biggestLang) private val loadingIcon = LoadingComponent() override fun row(builder: LayoutBuilder) = builder.fullRow { component(checkBox) .withSelectedBinding(MLServerCompletionSettings.getInstance().getLangState(language)::enabled.toBinding()) component(pingButton(language, loadingIcon, authTokenTextField)) .enableIf(checkBox.selected) loadingStatus(loadingIcon) .forEach { it.enableIf(checkBox.selected) } } } }
plugins/full-line/src/org/jetbrains/completion/full/line/settings/ui/panels/LanguageCloudModelPanel.kt
3158135763
fun foo( x: Int ) { } // SET_TRUE: CONTINUATION_INDENT_IN_PARAMETER_LISTS
plugins/kotlin/idea/tests/testData/formatter/ContinuationIndentInParameterLists.inv.kt
1451059952
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.j2k.ast import com.intellij.psi.PsiTypeParameter import com.intellij.psi.PsiTypeParameterList import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.j2k.Converter import org.jetbrains.kotlin.j2k.append import org.jetbrains.kotlin.j2k.buildList class TypeParameter(val name: Identifier, private val extendsTypes: List<Type>) : Element() { fun hasWhere(): Boolean = extendsTypes.size > 1 fun whereToKotlin(builder: CodeBuilder) { if (hasWhere()) { builder append name append " : " append extendsTypes[1] } } override fun generateCode(builder: CodeBuilder) { builder append name if (extendsTypes.isNotEmpty()) { builder append " : " append extendsTypes[0] } } } class TypeParameterList(val parameters: List<TypeParameter>) : Element() { override fun generateCode(builder: CodeBuilder) { if (parameters.isNotEmpty()) builder.append(parameters, ", ", "<", ">") } fun appendWhere(builder: CodeBuilder): CodeBuilder { if (hasWhere()) { builder.buildList(generators = parameters.map { { it.whereToKotlin(builder) } }, separator = ", ", prefix = " where ", suffix = "") } return builder } override val isEmpty: Boolean get() = parameters.isEmpty() private fun hasWhere(): Boolean = parameters.any { it.hasWhere() } companion object { val Empty = TypeParameterList(listOf()) } } private fun Converter.convertTypeParameter(typeParameter: PsiTypeParameter): TypeParameter { return TypeParameter(typeParameter.declarationIdentifier(), typeParameter.extendsListTypes.map { typeConverter.convertType(it) }).assignPrototype(typeParameter) } fun Converter.convertTypeParameterList(typeParameterList: PsiTypeParameterList?): TypeParameterList { return if (typeParameterList != null) TypeParameterList(typeParameterList.typeParameters.toList().map { convertTypeParameter(it) }).assignPrototype(typeParameterList) else TypeParameterList.Empty }
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/TypeParameters.kt
2021747612
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection.test.junit import com.intellij.analysis.JvmAnalysisBundle import com.intellij.codeInsight.TestFrameworks import com.intellij.codeInspection.* import com.intellij.codeInspection.test.junit.HamcrestCommonClassNames.ORG_HAMCREST_MATCHER_ASSERT import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdkVersion import com.intellij.openapi.projectRoots.JavaVersionService import com.intellij.psi.* import com.intellij.uast.UastHintedVisitorAdapter import com.siyeh.ig.junit.JUnitCommonClassNames.ORG_JUNIT_JUPITER_API_ASSERTIONS import com.siyeh.ig.junit.JUnitCommonClassNames.ORG_JUNIT_JUPITER_API_ASSUMPTIONS import com.siyeh.ig.testFrameworks.AbstractAssertHint import com.siyeh.ig.testFrameworks.UAssertHint import org.jetbrains.annotations.NonNls import org.jetbrains.uast.* import org.jetbrains.uast.generate.getUastElementFactory import org.jetbrains.uast.generate.replace import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor class JUnit5AssertionsConverterInspection(val frameworkName: @NonNls String = "JUnit5") : AbstractBaseUastLocalInspectionTool() { private fun shouldInspect(file: PsiFile): Boolean = JavaVersionService.getInstance().isAtLeast(file, JavaSdkVersion.JDK_1_8) && isJUnit4InScope(file) && isJUnit5InScope(file) && (file as? PsiClassOwner)?.classes?.all { TestFrameworks.detectFramework(it)?.name != frameworkName } == false override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { if (!shouldInspect(holder.file)) return PsiElementVisitor.EMPTY_VISITOR return UastHintedVisitorAdapter.create( holder.file.language, JUnit5AssertionsConverterVisitor(holder), arrayOf(UCallExpression::class.java, UCallableReferenceExpression::class.java), true ) } private fun getNewAssertClassName(methodName: @NonNls String): String = when { methodName == "assertThat" -> ORG_HAMCREST_MATCHER_ASSERT methodName.startsWith("assume") -> ORG_JUNIT_JUPITER_API_ASSUMPTIONS else -> ORG_JUNIT_JUPITER_API_ASSERTIONS } inner class JUnit5AssertionsConverterVisitor(private val holder: ProblemsHolder) : AbstractUastNonRecursiveVisitor() { override fun visitCallExpression(node: UCallExpression): Boolean { if (node.methodIdentifier == null) return true doCheck(node, { node.methodIdentifier?.sourcePsi }) { UAssertHint.create(node) { AbstractAssertHint.ASSERT_METHOD_2_PARAMETER_COUNT[it] } } return true } override fun visitCallableReferenceExpression(node: UCallableReferenceExpression): Boolean { doCheck(node, { node.sourcePsi }) { UAssertHint.create(node) { AbstractAssertHint.ASSERT_METHOD_2_PARAMETER_COUNT[it] } } return true } private fun doCheck(node: UExpression, toHighlight: () -> PsiElement?, createHint: () -> AbstractAssertHint<UExpression>?) { val sourcePsi = node.sourcePsi ?: return val hint = createHint() ?: return val psiMethod = hint.method if (!psiMethod.hasModifierProperty(PsiModifier.STATIC)) return if (!hint.isMessageOnFirstPosition) return val file = sourcePsi.containingFile as PsiClassOwner for (psiClass in file.classes) { val testFramework = TestFrameworks.detectFramework(psiClass) ?: continue if (frameworkName == testFramework.name) { val highlight = toHighlight() ?: return registerError(psiMethod, highlight) break } } } private fun registerError(psiMethod: PsiMethod, toHighlight: PsiElement) { val containingClass = psiMethod.containingClass ?: return val methodName = psiMethod.name val assertClassName = getNewAssertClassName(methodName) val message = JvmAnalysisBundle.message("jvm.inspections.junit5.assertions.converter.problem.descriptor", containingClass.name, assertClassName) if (!absentInJUnit5(psiMethod, methodName)) holder.registerProblem( toHighlight, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ReplaceObsoleteAssertsFix(getNewAssertClassName(methodName)) ) else holder.registerProblem(toHighlight, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } private fun absentInJUnit5(psiMethod: PsiMethod, methodName: @NonNls String): Boolean { if ("assertNotEquals" == methodName) { val parameters = psiMethod.parameterList.parameters if (parameters.isNotEmpty()) { val lastParamIdx = if (parameters.first().type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) 3 else 2 if (parameters.size > lastParamIdx && parameters[lastParamIdx].type is PsiPrimitiveType) return true } } return false } } inner class ReplaceObsoleteAssertsFix(private val baseClassName: String) : LocalQuickFix { override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement when (val uElement = element.toUElement()) { is UCallableReferenceExpression -> { val methodName = uElement.callableName val newClassName = JavaPsiFacade.getInstance(project).findClass( getNewAssertClassName(methodName), element.resolveScope )?.qualifiedName ?: return val psiFactory = uElement.getUastElementFactory(project) ?: return val newQualifier = psiFactory.createQualifiedReference(newClassName, element) ?: return val newCallableReferences = psiFactory.createCallableReferenceExpression(newQualifier, methodName, null) ?: return uElement.replace(newCallableReferences) ?: return } is UIdentifier -> { // UCallExpression val methodCall = uElement.getParentOfType<UCallExpression>() ?: return val methodName = methodCall.methodName ?: return val assertHint = UAssertHint.create(methodCall) { AbstractAssertHint.ASSERT_METHOD_2_PARAMETER_COUNT[it] } ?: return val arguments = methodCall.valueArguments.toMutableList() if ("assertThat" != methodName) { assertHint.message?.let { arguments.remove(it) arguments.add(it) } } val psiFactory = methodCall.getUastElementFactory(project) ?: return val clazz = JavaPsiFacade.getInstance(project).findClass( getNewAssertClassName(methodName), element.resolveScope ) ?: return val newClassName = clazz.qualifiedName ?: return val newReceiver = psiFactory.createQualifiedReference(newClassName, methodCall.sourcePsi) val newCall = psiFactory.createCallExpression( newReceiver, methodName, arguments, null, methodCall.kind, null ) ?: return val qualifiedCall = methodCall.getQualifiedParentOrThis() qualifiedCall.replace(newCall) } } } override fun getName(): String = JvmAnalysisBundle.message("jvm.inspections.junit5.assertions.converter.quickfix", baseClassName) override fun getFamilyName(): String = JvmAnalysisBundle.message("jvm.inspections.junit5.assertions.converter.familyName") } }
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnit5AssertionsConverterInspection.kt
1895150035
package org.kethereum.functions.rlp import org.kethereum.extensions.removeLeadingZero import org.kethereum.extensions.toMinimalByteArray import java.math.BigInteger import java.math.BigInteger.ZERO /** RLP as of Appendix B. Recursive Length Prefix at https://github.com/ethereum/yellowpaper */ // to RLP fun String.toRLP() = RLPElement(toByteArray()) fun Int.toRLP() = RLPElement(toMinimalByteArray()) fun BigInteger.toRLP() = RLPElement(toByteArray().removeLeadingZero()) fun ByteArray.toRLP() = RLPElement(this) fun Byte.toRLP() = RLPElement(kotlin.ByteArray(1) { this }) // from RLP fun RLPElement.toIntFromRLP() = if (bytes.isEmpty()) { 0 } else { bytes.mapIndexed { index, byte -> (byte.toInt() and 0xff).shl((bytes.size - 1 - index) * 8) } .reduce { acc, i -> acc + i } } fun RLPElement.toUnsignedBigIntegerFromRLP(): BigInteger = if (bytes.isEmpty()) ZERO else BigInteger(1, bytes) fun RLPElement.toByteFromRLP(): Byte { require(bytes.size == 1) { "trying to convert RLP with != 1 byte to Byte" } return bytes.first() } fun RLPElement.toStringFromRLP() = String(bytes)
rlp/src/main/kotlin/org/kethereum/functions/rlp/RLPTypeConverter.kt
3733369369
package com.devbrackets.android.playlistcore.components.mediasession import android.app.PendingIntent import android.app.Service import android.content.ComponentName import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.os.Build import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaSessionCompat import android.util.Log import com.devbrackets.android.playlistcore.data.MediaInfo import com.devbrackets.android.playlistcore.data.RemoteActions open class DefaultMediaSessionProvider( val context: Context, val serviceClass: Class<out Service> ) : MediaSessionCompat.Callback(), MediaSessionProvider { companion object { const val SESSION_TAG = "DefaultMediaSessionProvider.Session" const val RECEIVER_EXTRA_CLASS = "com.devbrackets.android.playlistcore.RECEIVER_EXTRA_CLASS" } @Deprecated("These class level intents are no-longer used. If you need to override these values use the onPlay()/onPause()") protected var playPausePendingIntent = createPendingIntent(RemoteActions.ACTION_PLAY_PAUSE, serviceClass) @Deprecated("These class level intents are no-longer used. If you need to override these values use the onSkipToNext()") protected var nextPendingIntent = createPendingIntent(RemoteActions.ACTION_NEXT, serviceClass) @Deprecated("These class level intents are no-longer used. If you need to override these values use the onSkipToPrevious()") protected var previousPendingIntent = createPendingIntent(RemoteActions.ACTION_PREVIOUS, serviceClass) protected val mediaSession: MediaSessionCompat by lazy { val componentName = ComponentName(context, DefaultMediaSessionControlsReceiver::class.java.name) MediaSessionCompat(context, SESSION_TAG, componentName, getMediaButtonReceiverPendingIntent(componentName)) } override fun get(): MediaSessionCompat { return mediaSession } override fun update(mediaInfo: MediaInfo) { mediaSession.setCallback(this) // Updates the current media MetaData val builder = MediaMetadataCompat.Builder() builder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, mediaInfo.title) builder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, mediaInfo.album) builder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, mediaInfo.artist) builder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, mediaInfo.playbackDurationMs) // Updates the icon BitmapFactory.decodeResource(context.resources, mediaInfo.appIcon)?.let { builder.putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, it) } // Updates the artwork if (mediaInfo.artwork != null) { builder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, mediaInfo.artwork) } mediaSession.setMetadata(builder.build()) } override fun onPlay() { val intent = createPendingIntent(RemoteActions.ACTION_PLAY_PAUSE, serviceClass) sendPendingIntent(intent) } override fun onPause() { val intent = createPendingIntent(RemoteActions.ACTION_PLAY_PAUSE, serviceClass) sendPendingIntent(intent) } override fun onSkipToNext() { val intent = createPendingIntent(RemoteActions.ACTION_NEXT, serviceClass) sendPendingIntent(intent) } override fun onSkipToPrevious() { val intent = createPendingIntent(RemoteActions.ACTION_PREVIOUS, serviceClass) sendPendingIntent(intent) } override fun onSeekTo(pos: Long) { val intent = Intent(context, serviceClass) intent.action = RemoteActions.ACTION_SEEK_ENDED intent.putExtra(RemoteActions.ACTION_EXTRA_SEEK_POSITION, pos) val pi = PendingIntent.getService(context, 0, intent, getIntentFlags()) sendPendingIntent(pi) } /** * Creates a PendingIntent for the given action to the specified service * * @param action The action to use * @param serviceClass The service class to notify of intents * @return The resulting PendingIntent */ protected open fun createPendingIntent(action: String, serviceClass: Class<out Service>): PendingIntent { val intent = Intent(context, serviceClass) intent.action = action return PendingIntent.getService(context, 0, intent, getIntentFlags()) } protected open fun getMediaButtonReceiverPendingIntent(componentName: ComponentName): PendingIntent { val mediaButtonIntent = Intent(Intent.ACTION_MEDIA_BUTTON) mediaButtonIntent.component = componentName mediaButtonIntent.putExtra(RECEIVER_EXTRA_CLASS, serviceClass.name) return PendingIntent.getBroadcast(context, 0, mediaButtonIntent, getIntentFlags()) } protected open fun sendPendingIntent(pi: PendingIntent) { try { pi.send() } catch (e: Exception) { Log.d("DefaultMediaSessionPro", "Error sending media controls pending intent", e) } } protected open fun getIntentFlags(): Int { return when { Build.VERSION.SDK_INT < Build.VERSION_CODES.M -> PendingIntent.FLAG_UPDATE_CURRENT else -> PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE } } }
library/src/main/kotlin/com/devbrackets/android/playlistcore/components/mediasession/DefaultMediaSessionProvider.kt
2383912876
/* * Ad Free * Copyright (c) 2017 by abertschi, www.abertschi.ch * See the file "LICENSE" for the full license governing this code. */ package ch.abertschi.adfree.plugin import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity /** * Created by abertschi on 30.08.17. */ interface PluginActivityAction { fun startActivityForResult(intent: Intent?, requestCode: Int, options: Bundle?); fun addOnActivityResult(callable: (requestCode: Int, resultCode: Int, data: Intent?) -> Unit) fun activity(): Activity }
app/src/main/java/ch/abertschi/adfree/plugin/PluginActivityAction.kt
3826454877
package quanti.com.kotlinlog.file.file import android.content.Context import quanti.com.kotlinlog.android.MetadataLogger import quanti.com.kotlinlog.utils.openLogFileOutput import java.io.FileOutputStream class MetadataFile(appCtx: Context) { private val fileName = "PhoneMetadata.log" private var fos: FileOutputStream = appCtx.openLogFileOutput(fileName, false) private val metadata = MetadataLogger.getLogStrings(appCtx.applicationContext) fun write(){ fos.write(metadata.toByteArray()) } fun closeOutputStream() = fos.close() }
kotlinlog/src/main/kotlin/quanti/com/kotlinlog/file/file/MetadataFile.kt
4227114993
package com.winterbe.expekt import org.junit.Test class ExpectCollectionTest { @Test fun elementsHaveAny() { passes { expect(listOf(1, 2, 3)).to.contain.any.elements(1, 2, 3) } passes { expect(listOf(1, 2, 3)).to.contain.any.elements(1, 4) } fails("expect [1, 2, 3] to contain any elements [4, 5]") { expect(listOf(1, 2, 3)).to.contain.any.elements(4, 5) } } @Test fun elementsHaveAll() { passes { expect(listOf(1, 2, 3)).to.have.all.elements(1, 2, 3) } fails("expect [1, 2, 3] to have all elements [1, 2]") { expect(listOf(1, 2, 3)).to.have.all.elements(1, 2) } fails { expect(listOf(1, 2, 3)).to.have.all.elements(1) } fails { expect(listOf(1, 2, 3)).to.have.all.elements(1, 2, 3, 4) } } @Test fun elementsHaveImplicitAll() { passes { expect(listOf(1, 2, 3)).to.have.elements(1, 2, 3) } fails("expect [1, 2, 3] to have elements [1, 2]") { expect(listOf(1, 2, 3)).to.have.elements(1, 2) } fails { expect(listOf(1, 2, 3)).to.have.elements(1) } fails { expect(listOf(1, 2, 3)).to.have.elements(1, 2, 3, 4) } } @Test fun elementsContainAny() { passes { expect(listOf(1, 2, 3)).to.contain.any.elements(1, 2, 3) } passes { expect(listOf(1, 2, 3)).to.contain.any.elements(1, 4) } fails("expect [1, 2, 3] to contain any elements [4, 5]") { expect(listOf(1, 2, 3)).to.contain.any.elements(4, 5) } } @Test fun elementsContainAll() { passes { expect(listOf(1, 2, 3)).to.contain.all.elements(1, 2, 3) } passes { expect(listOf(1, 2, 3)).to.contain.all.elements(1, 2) } passes { expect(listOf(1, 2, 3)).to.contain.all.elements(1) } fails("expect [1, 2, 3] to contain all elements [1, 2, 4]") { expect(listOf(1, 2, 3)).to.contain.all.elements(1, 2, 4) } } @Test fun elementsContainImplicitAll() { passes { expect(listOf(1, 2, 3)).to.contain.elements(1, 2, 3) } passes { expect(listOf(1, 2, 3)).to.contain.elements(1, 2) } passes { expect(listOf(1, 2, 3)).to.contain.elements(1) } fails("expect [1, 2, 3] to contain elements [1, 2, 4]") { expect(listOf(1, 2, 3)).to.contain.elements(1, 2, 4) } } @Test fun containsLength() { passes { expect(listOf(1, 2, 3)).to.contain(3).and.to.have.size.above(2) } } @Test fun notContain() { passes { expect(listOf(1, 2, 3)).not.to.contain(4) } fails("expect [1, 2, 3] not to contain 3") { expect(listOf(1, 2, 3)).not.to.contain(3) } } @Test fun contain() { passes { expect(listOf(1, 2, 3)).to.contain(1) } fails("expect [1, 2, 3] to contain 4") { expect(listOf(1, 2, 3)).to.contain(4) } } @Test fun notSizeProp() { passes { expect(listOf(1, 2, 3)).not.to.have.size.above(3) } fails("expect [1, 2, 3] not to have size below 4") { expect(listOf(1, 2, 3)).not.to.have.size.below(4) } } @Test fun sizeProp() { passes { expect(listOf(1, 2, 3)).to.have.size.above(2) } fails("expect [1, 2, 3] to have size equal 4") { expect(listOf(1, 2, 3)).to.have.size.equal(4) } } @Test fun notSize() { passes { expect(listOf(1, 2, 3)).not.to.have.size(4) } fails("expect [1, 2, 3] not to have size 3") { expect(listOf(1, 2, 3)).not.to.have.size(3) } } @Test fun size() { passes { expect(listOf(1, 2, 3)).to.have.size(3) } fails("expect [1, 2, 3] to have size 4") { expect(listOf(1, 2, 3)).to.have.size(4) } } @Test fun notEmpty() { passes { expect(listOf(1, 2, 3)).not.to.be.empty } fails("expect [] not to be empty") { expect(listOf<Int>()).not.to.be.empty } } @Test fun empty() { passes { expect(listOf<Int>()).to.be.empty } fails("expect [1, 2, 3] to be empty") { expect(listOf(1, 2, 3)).to.be.empty } } @Test fun notEquals() { passes { expect(listOf(1, 2, 3)).not.to.equal(listOf(1, 2, 3, 4)) } fails("expect [1, 2, 3] not to equal [1, 2, 3]") { expect(listOf(1, 2, 3)).not.to.equal(listOf(1, 2, 3)) } } @Test fun equals() { passes { expect(listOf(1, 2, 3)).to.equal(listOf(1, 2, 3)) } fails("expect [1, 2, 3] to equal [1, 2, 3, 4]") { expect(listOf(1, 2, 3)).to.equal(listOf(1, 2, 3, 4)) } } @Test fun `null`() { passes { expect(null as Collection<Int>?).to.be.`null` } fails("expect [1, 2, 3] to be null") { expect(listOf(1, 2, 3)).to.be.`null` } } @Test fun should() { listOf(1, 2, 3).should.contain.all.elements(1, 2) } }
src/test/kotlin/com/winterbe/expekt/ExpectCollectionTest.kt
3188109149
/* * 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.network.tls import io.ktor.network.sockets.* import io.ktor.network.util.* import io.ktor.utils.io.* import io.ktor.utils.io.core.* import io.ktor.utils.io.pool.* import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import java.nio.* import kotlin.coroutines.* internal actual suspend fun openTLSSession( socket: Socket, input: ByteReadChannel, output: ByteWriteChannel, config: TLSConfig, context: CoroutineContext ): Socket { val handshake = TLSClientHandshake(input, output, config, context) try { handshake.negotiate() } catch (cause: ClosedSendChannelException) { throw TLSException("Negotiation failed due to EOS", cause) } return TLSSocket(handshake.input, handshake.output, socket, context) } private class TLSSocket( private val input: ReceiveChannel<TLSRecord>, private val output: SendChannel<TLSRecord>, private val socket: Socket, override val coroutineContext: CoroutineContext ) : CoroutineScope, Socket by socket { override fun attachForReading(channel: ByteChannel): WriterJob = writer(coroutineContext + CoroutineName("cio-tls-input-loop"), channel) { appDataInputLoop(this.channel) } override fun attachForWriting(channel: ByteChannel): ReaderJob = reader(coroutineContext + CoroutineName("cio-tls-output-loop"), channel) { appDataOutputLoop(this.channel) } @OptIn(ExperimentalCoroutinesApi::class) private suspend fun appDataInputLoop(pipe: ByteWriteChannel) { try { input.consumeEach { record -> val packet = record.packet val length = packet.remaining when (record.type) { TLSRecordType.ApplicationData -> { pipe.writePacket(record.packet) pipe.flush() } else -> throw TLSException("Unexpected record ${record.type} ($length bytes)") } } } catch (cause: Throwable) { } finally { pipe.close() } } private suspend fun appDataOutputLoop( pipe: ByteReadChannel ): Unit = DefaultByteBufferPool.useInstance { buffer: ByteBuffer -> try { while (true) { buffer.clear() val rc = pipe.readAvailable(buffer) if (rc == -1) break buffer.flip() output.send(TLSRecord(TLSRecordType.ApplicationData, packet = buildPacket { writeFully(buffer) })) } } finally { output.close() } } override fun dispose() { socket.dispose() } }
ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientSessionJvm.kt
3902313027
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val ARB_enhanced_layouts = "ARBEnhancedLayouts".nativeClassGL("ARB_enhanced_layouts") { documentation = """ Native bindings to the $registryLink extension. This extension adds the following functionality to layout qualifiers, including broadening the API where this functionality is reflected. The following are added: ${ol( "Use compile-time constant expressions.", "Specify explicit byte offsets within a uniform or shader storage block.", "Force alignment within a uniform or shader storage block.", "Specify component numbers to more fully utilize the vec4-slot interfaces between shader outputs and shader inputs.", "Specify transform/feedback buffers, locations, and widths.", "Allow locations on input and output blocks for SSO interface matching." )} Requires ${GL31.core} and GLSL 1.40. ${GL44.promoted} """ IntConstant( "Accepted in the {@code props} array of #GetProgramResourceiv().", "LOCATION_COMPONENT"..0x934A, "TRANSFORM_FEEDBACK_BUFFER_INDEX"..0x934B, "TRANSFORM_FEEDBACK_BUFFER_STRIDE"..0x934C ) }
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_enhanced_layouts.kt
2270811402
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package egl.templates import egl.* import org.lwjgl.generator.* val KHR_stream_cross_process_fd = "KHRStreamCrossProcessFD".nativeClassEGL("KHR_stream_cross_process_fd", postfix = KHR) { documentation = """ Native bindings to the $registryLink extension. This extension allows an EGLStreamKHR object handle to be duplicated into another process so that the EGLStream producer can be in one process while the EGLStream consumer can be in another process. Duplicating the EGLStreamKHR object handle into another process is peformed in 3 steps ${ol( "Get a file descriptor associated with the EGLStream.", "Duplicate the file descriptor into another process.", "Create an EGLStreamKHR from the duplicated file descriptor in the other process." )} The file descriptor is obtained by calling eglGetStreamFileDescriptorKHR(). Duplicating the file descriptor into another process is outside the scope of this extension. See issue \\#1 for an example of how to do this on a Linux system. The EGLStreamKHR object handle is created in the second process by passing the file descriptor to the eglCreateStreamFromFileDescriptorKHR() function. This must be done while the EGLStream is in the EGL_STREAM_STATE_CREATED_KHR state. Once the EGLStreamKHR object handle is created in the second process, it refers to the same EGLStream as the EGLStreamKHR object handle in the original process. A consumer can be associated with the EGLStream from either process. A producer can be associated with the EGLStream from either process. Requires ${EGL12.core} and ${KHR_stream.link}. """ IntConstant( "", "NO_FILE_DESCRIPTOR_KHR".."-1" ) EGLNativeFileDescriptorKHR( "GetStreamFileDescriptorKHR", "", EGLDisplay("dpy", ""), EGLStreamKHR("stream", "") ) EGLStreamKHR( "CreateStreamFromFileDescriptorKHR", "", EGLDisplay("dpy", ""), EGLNativeFileDescriptorKHR("file_descriptor", "") ) }
modules/lwjgl/egl/src/templates/kotlin/egl/templates/KHR_stream_cross_process_fd.kt
2335842340
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.at import com.demonwav.mcdev.framework.toSnakeCase import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.testFramework.LexerTestCase import com.intellij.testFramework.UsefulTestCase import java.io.File import java.io.IOException class AtLexerTest : LexerTestCase() { override fun getDirPath() = "src/test/resources/com/demonwav/mcdev/platform/mcp/at/lexer/fixtures" override fun createLexer() = AtLexerAdapter() override fun getTestName(lowercaseFirstLetter: Boolean) = super.getTestName(lowercaseFirstLetter).substring(1).toSnakeCase("_at") // Copied because it wasn't handling the paths correctly private fun doTest() { val fileName = dirPath + "/" + getTestName(true) + ".cfg" var text = "" try { val fileText = FileUtil.loadFile(File(fileName)) text = StringUtil.convertLineSeparators(if (shouldTrim()) fileText.trim() else fileText) } catch (e: IOException) { fail("can't load file " + fileName + ": " + e.message) } val result = printTokens(text, 0, createLexer()) UsefulTestCase.assertSameLinesWithFile(dirPath + "/" + getTestName(true) + ".txt", result) } fun `test spigot mapped srg`() = doTest() }
src/test/kotlin/com/demonwav/mcdev/platform/mcp/at/AtLexerTest.kt
4223289156
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.insight import com.demonwav.mcdev.platform.mixin.util.findFirstOverwriteTarget import com.demonwav.mcdev.platform.mixin.util.findOverwriteTargets import com.intellij.codeHighlighting.Pass import com.intellij.codeInsight.daemon.GutterIconNavigationHandler import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProviderDescriptor import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator import com.intellij.icons.AllIcons import com.intellij.ide.util.MethodCellRenderer import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiElement import com.intellij.psi.PsiIdentifier import com.intellij.psi.PsiMethod import com.intellij.util.FunctionUtil import java.awt.event.MouseEvent class OverwriteLineMarkerProvider : LineMarkerProviderDescriptor(), GutterIconNavigationHandler<PsiIdentifier> { companion object { private val ICON = AllIcons.Gutter.OverridingMethod!! private val TOOLTIP_FUNCTION = FunctionUtil.constant<Any, String>("Go to target method") } override fun getName() = "Mixin @Overwrite line marker" override fun getIcon() = ICON override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiIdentifier>? { if (element !is PsiMethod) { return null } val identifier = element.nameIdentifier ?: return null // Check if @Overwrite actually has a target element.findFirstOverwriteTarget() ?: return null return LineMarker(identifier, this) } override fun collectSlowLineMarkers(elements: List<PsiElement>, result: Collection<LineMarkerInfo<PsiElement>>) { } override fun navigate(e: MouseEvent, elt: PsiIdentifier) { val method = elt.parent as? PsiMethod ?: return val targets = method.findOverwriteTargets() ?: return if (targets.isNotEmpty()) { PsiElementListNavigator.openTargets(e, targets.toTypedArray(), "Choose target method of ${method.name}", null, MethodCellRenderer(false)) } } private class LineMarker(identifier: PsiIdentifier, navHandler: GutterIconNavigationHandler<PsiIdentifier>) : MergeableLineMarkerInfo<PsiIdentifier>(identifier, identifier.textRange, ICON, Pass.LINE_MARKERS, TOOLTIP_FUNCTION, navHandler, GutterIconRenderer.Alignment.LEFT) { override fun canMergeWith(info: MergeableLineMarkerInfo<*>) = info is LineMarker override fun getCommonTooltip(infos: List<MergeableLineMarkerInfo<PsiElement>>) = TOOLTIP_FUNCTION override fun getCommonIcon(infos: List<MergeableLineMarkerInfo<PsiElement>>) = ICON } }
src/main/kotlin/com/demonwav/mcdev/platform/mixin/insight/OverwriteLineMarkerProvider.kt
211755206
package com.talentica.androidkotlin.networking.repoui import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.View import android.widget.ProgressBar import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.talentica.androidkotlin.networking.R import com.talentica.androidkotlin.networking.dto.Repository class UserRepositories : AppCompatActivity(), RepositoryContract.View { val progressBar: ProgressBar by lazy { findViewById<ProgressBar>(R.id.progress_bar) } val repoList: RecyclerView by lazy { findViewById<RecyclerView>(R.id.rv_repo_list) } val mPresenter: RepositoryContract.Presenter by lazy { RepoPresenter(this, this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user_repositories) repoList.layoutManager = LinearLayoutManager(this) if (!intent.hasExtra("username")) { finish() } val username = intent.getStringExtra("username") val libType = intent.getStringExtra("libraryType") if (libType != null && username != null) { mPresenter.start(libType, username) } } override fun onDestroy() { super.onDestroy() mPresenter.destroy() } override fun onReposAvailable(repos: Array<Repository>) { val handler = Handler(Looper.getMainLooper()) handler.post({ val repoAdapter = RepoAdapter(repos) repoList.adapter = repoAdapter }) } override fun showLoading() { val handler = Handler(Looper.getMainLooper()) handler.post({ progressBar.visibility = View.VISIBLE repoList.alpha = 0.4f }) } override fun hideLoading() { val handler = Handler(Looper.getMainLooper()) handler.post({ progressBar.visibility = View.GONE repoList.alpha = 1.0f }) } override fun displayError(message: String) { val handler = Handler(Looper.getMainLooper()) handler.post({ Toast.makeText(this, message, Toast.LENGTH_SHORT).show() }) } override fun destroy() { finish() } }
networking/src/main/java/com/talentica/androidkotlin/networking/repoui/UserRepositories.kt
365976680
/* * Copyright (C) 2016-Present The MoonLake (mcmoonlake@hotmail.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.packet data class PacketInPosition( var x: Double, var y: Double, var z: Double, var isOnGround: Boolean ) : PacketInBukkitAbstract("PacketPlayInFlying\$PacketPlayInPosition", "PacketPlayInPosition") { @Deprecated("") constructor() : this(.0, .0, .0, false) override fun read(data: PacketBuffer) { this.x = data.readDouble() this.y = data.readDouble() this.z = data.readDouble() this.isOnGround = data.readUnsignedByte().toInt() != 0 } override fun write(data: PacketBuffer) { data.writeDouble(x) data.writeDouble(y) data.writeDouble(z) data.writeByte(if(isOnGround) 1 else 0) } }
API/src/main/kotlin/com/mcmoonlake/api/packet/PacketInPosition.kt
1278784213
package com.talentica.androidkotlin.customcamera.utils import android.os.Environment import android.util.Log import java.io.File /** * Created by suyashg on 03/06/17. */ class Utils { val storageDir = File(Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CustomCamera") fun checkAndMakeDir():File? { val mediaStorageDir = storageDir if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("CustomCameraApp", "failed to create directory") return null } } return mediaStorageDir } }
customcamera/src/main/java/com/talentica/androidkotlin/customcamera/utils/Utils.kt
3430411629
package me.serce.solidity.lang.core.resolve import me.serce.solidity.lang.psi.SolNamedElement class SolImportResolveFoundryTest : SolResolveTestBase() { fun testImportPathResolveFoundryRemappings() { val testcases = arrayListOf<Pair<String, String>>( Pair("lib/forge-std/src/Test.sol","contracts/ImportUsageFoundryStd.sol"), Pair("lib/solmate/src/tokens/ERC721.sol","contracts/ImportUsageFoundrySolmate.sol"), Pair("lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol","contracts/ImportUsageFoundryOpenzeppelin.sol"), ); testcases.forEach { (targetFile, contractFile) -> val file1 = myFixture.configureByFile(targetFile) myFixture.configureByFile("remappings.txt") myFixture.configureByFile(contractFile) val (refElement) = findElementAndDataInEditor<SolNamedElement>("^") val resolved = checkNotNull(refElement.reference?.resolve()) { "Failed to resolve ${refElement.text}" } assertEquals(file1.name, resolved.containingFile.name) } } override fun getTestDataPath() = "src/test/resources/fixtures/importRemappings/" }
src/test/kotlin/me/serce/solidity/lang/core/resolve/SolImportResolveFoundryTest.kt
1408643356
package ee.mcdimus.matewp.service import junit.framework.Assert.assertEquals import junit.framework.Assert.assertTrue import org.junit.jupiter.api.assertThrows import org.spekframework.spek2.Spek import org.spekframework.spek2.style.gherkin.Feature /** * @author Dmitri Maksimov */ object OpSysServiceFactorySpec : Spek({ Feature("OpSysServiceFactory") { val subject by memoized { OpSysServiceFactory } Scenario("running on Linux") { Given("os.name == Linux") { System.setProperty("os.name", "Linux") } Then("should return instance of LinuxMateService") { assertTrue(subject.get() is LinuxMateService) } } Scenario("guessing that running on any Linux") { Given("os.name == Linux") { System.setProperty("os.name", "SomeLinuxDistro") } Then("should return instance of LinuxMateService") { assertTrue(subject.get() is LinuxMateService) } } Scenario("running on Windows 7") { Given("os.name == Windows 7") { System.setProperty("os.name", "Windows 7") } Then("should return instance of LinuxMateService") { assertTrue(subject.get() is WindowsService) } } Scenario("guessing that running on any Linux") { Given("os.name == Linux") { System.setProperty("os.name", "AnyOtherWindows") } Then("should return instance of WindowsService") { assertTrue(subject.get() is WindowsService) } } Scenario("running on unsupported OS") { Given("os.name == FreeBSD") { System.setProperty("os.name", "FreeBSD") } Then("should throw IllegalStateException") { assertThrows<IllegalStateException> { subject.get() }.also { assertEquals("unsupported operating system: FreeBSD", it.message) } } } } })
src/test/kotlin/ee/mcdimus/matewp/service/OpSysServiceFactorySpec.kt
3468668830
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.compiler.artifacts import com.intellij.openapi.Disposable import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.packaging.artifacts.ArtifactManager import com.intellij.packaging.artifacts.ArtifactPropertiesProvider import com.intellij.packaging.elements.PackagingElementFactory import com.intellij.packaging.impl.artifacts.PlainArtifactType import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.rules.ProjectModelRule import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.storage.bridgeEntities.api.ArtifactEntity import org.junit.Assert.* import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.io.File class ArtifactLoadingTest { @Rule @JvmField val projectModel = ProjectModelRule(true) @Rule @JvmField var disposableRule = DisposableRule() companion object { @JvmField @ClassRule val appRule = ApplicationRule() } @Test fun `loading of default artifact properties`() { runWithRegisteredExtension(MockArtifactPropertiesProvider(), ArtifactPropertiesProvider.EP_NAME) { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) WriteAction.runAndWait<RuntimeException> { artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), PackagingElementFactory.getInstance().createArtifactRootElement()) } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root" /> | </artifact> |</component>""".trimMargin()) val project1 = PlatformTestUtil.loadAndOpenProject(projectModel.baseProjectDir.rootPath, disposableRule.disposable) val defaultProperty = runReadAction { ArtifactManager.getInstance(project1).artifacts.single().getProperties(MockArtifactPropertiesProvider.getInstance()) } assertNotNull(defaultProperty) } } @Test fun `loading of properties with changes`() { runWithRegisteredExtension(MockArtifactPropertiesProvider(), ArtifactPropertiesProvider.EP_NAME) { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) WriteAction.runAndWait<RuntimeException> { val addArtifact = artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), PackagingElementFactory.getInstance().createArtifactRootElement()) val modifiableModel = ArtifactManager.getInstance(project).createModifiableModel() val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(addArtifact) modifiableArtifact.setProperties(MockArtifactPropertiesProvider.getInstance(), MockArtifactProperties().also { it.data = "123" }) modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <properties id="mock-properties"> | <options> | <option name="data" value="123" /> | </options> | </properties> | <root id="root" /> | </artifact> |</component>""".trimMargin()) val project1 = PlatformTestUtil.loadAndOpenProject(projectModel.baseProjectDir.rootPath, disposableRule.disposable) val defaultProperty = WorkspaceModel.getInstance(project1).entityStorage.current .entities(ArtifactEntity::class.java) .single() .customProperties .filter { it.providerType == MockArtifactPropertiesProvider.getInstance().id } .single() assertTrue("123" in defaultProperty.propertiesXmlTag!!) val properties = runReadAction { ArtifactManager.getInstance(project).artifacts.single().getProperties(MockArtifactPropertiesProvider.getInstance()) } assertEquals("123", (properties as MockArtifactProperties).data) } } private fun assertArtifactFileTextEquals(expectedText: String) { assertEquals(StringUtil.convertLineSeparators(expectedText), StringUtil.convertLineSeparators(File(projectModel.baseProjectDir.root, ".idea/artifacts/Artifact.xml").readText())) } private inline fun <T> runWithRegisteredExtension(extension: T, extensionPoint: ExtensionPointName<T>, action: () -> Unit) { val disposable = Disposer.newDisposable() runInEdt { runWriteAction { registerExtension(extension, extensionPoint, disposable) } } try { action() } finally { Disposer.dispose(disposable) } } private fun <T> registerExtension(type: T, extensionPointName: ExtensionPointName<T>, disposable: Disposable) { val artifactTypeDisposable = Disposer.newDisposable() Disposer.register(disposable, Disposable { runInEdt { runWriteAction { Disposer.dispose(artifactTypeDisposable) } } }) extensionPointName.point.registerExtension(type, artifactTypeDisposable) } }
java/compiler/tests/com/intellij/compiler/artifacts/ArtifactLoadingTest.kt
173923007
// ACTION_CLASS: org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateTestSupportActionBase$SetUp // CONFIGURE_LIBRARY: JUnit // TEST_FRAMEWORK: JUnit4 open class A { open fun setUp() { } } class B : A() {<caret> }
plugins/kotlin/idea/tests/testData/codeInsight/generate/testFrameworkSupport/jUnit4/setUpOverrides.kt
1506541
// "Replace with safe (?.) call" "false" // ACTION: Add non-null asserted (!!) call // ACTION: Enable a trailing comma by default in the formatter // ACTION: Expand boolean expression to 'if else' // ACTION: Flip '<=' // ACTION: Replace overloaded operator with function call // ERROR: Operator call corresponds to a dot-qualified call 'w?.x.compareTo(42)' which is not allowed on a nullable receiver 'w?.x'. class Wrapper(val x: Int) fun test(w: Wrapper?) { when { w?.x <caret><= 42 -> {} } }
plugins/kotlin/idea/tests/testData/quickfix/nullables/unsafeInfixCall/unsafeComparisonInWhen.kt
1983992775
package klay.core /** * Contains info for laying out and drawing single- or multi-line text to a [Canvas]. */ open class TextFormat /** Creates a configured text format instance. */ constructor( /** The font in which to render the text (null indicates that the default font is used). */ open val font: Font? = null, /** Whether or not the text should be antialiased. Defaults to true. * NOTE: this is not supported by the HTML5 backend. */ open val antialias: Boolean = true) { /** Returns a clone of this text format with the font configured as specified. */ open fun withFont(font: Font): TextFormat { return TextFormat(font, this.antialias) } /** Returns a clone of this text format with the font configured as specified. */ fun withFont(name: String, style: Font.Style, size: Float): TextFormat { return withFont(Font(name, style, size)) } /** Returns a clone of this text format with the font configured as specified. */ fun withFont(name: String, size: Float): TextFormat { return withFont(Font(name, size)) } /** Returns a clone of this text format with [.antialias] configured as specified. */ open fun withAntialias(antialias: Boolean): TextFormat { return TextFormat(this.font, antialias) } override fun toString(): String { return "[font=$font, antialias=$antialias]" } override fun equals(other: Any?): Boolean { if (other is TextFormat) { val ofmt = other return (font === ofmt.font || font != null && font == ofmt.font) && antialias == ofmt.antialias } else { return false } } override fun hashCode(): Int { var hash = if (antialias) 1 else 0 if (font != null) hash = hash xor font!!.hashCode() return hash } } /** Creates a default text format instance. */ /** Creates a text format instance with the specified font. */
src/main/kotlin/klay/core/TextFormat.kt
2359976277
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.utils import androidx.core.util.Pair import de.dreier.mytargets.base.db.dao.EndDAO import de.dreier.mytargets.base.db.dao.RoundDAO import de.dreier.mytargets.shared.models.SelectableZone import de.dreier.mytargets.shared.models.Target import de.dreier.mytargets.shared.models.db.Round import de.dreier.mytargets.shared.models.db.Shot import de.dreier.mytargets.shared.targets.scoringstyle.ArrowAwareScoringStyle import java.util.* object ScoreUtils { fun getTopScoreDistribution(sortedScore: List<Map.Entry<SelectableZone, Int>>): List<Pair<String, Int>> { val result = sortedScore.map { Pair(it.key.text, it.value) }.toMutableList() // Collapse first two entries if they yield the same score points, // e.g. 10 and X => {X, 10+X, 9, ...} if (sortedScore.size > 1) { val first = sortedScore[0] val second = sortedScore[1] if (first.key.points == second.key.points) { val newTitle = second.key.text + "+" + first.key.text result[1] = Pair(newTitle, second.value + first.value) } } return result } /** * Compound 9ers are already collapsed to one SelectableZone. */ fun getSortedScoreDistribution( roundDAO: RoundDAO, endDAO: EndDAO, rounds: List<Round> ): List<Map.Entry<SelectableZone, Int>> { return getRoundScores(roundDAO, endDAO, rounds).entries.sortedBy { it.key } } private fun getRoundScores( roundDAO: RoundDAO, endDAO: EndDAO, rounds: List<Round> ): Map<SelectableZone, Int> { val t = rounds[0].target val scoreCount = getAllPossibleZones(t) rounds.flatMap { roundDAO.loadEnds(it.id) } .forEach { endDAO.loadShots(it.id).forEach { s -> if (s.scoringRing != Shot.NOTHING_SELECTED) { val tuple = SelectableZone( s.scoringRing, t.model.getZone(s.scoringRing), t.zoneToString(s.scoringRing, s.index), t.getScoreByZone(s.scoringRing, s.index) ) val integer = scoreCount[tuple] if (integer != null) { val count = integer + 1 scoreCount[tuple] = count } } } } return scoreCount } private fun getAllPossibleZones(t: Target): MutableMap<SelectableZone, Int> { val scoreCount = HashMap<SelectableZone, Int>() for (arrow in 0..2) { val zoneList = t.getSelectableZoneList(arrow) for (selectableZone in zoneList) { scoreCount[selectableZone] = 0 } if (t.getScoringStyle() !is ArrowAwareScoringStyle) { break } } return scoreCount } }
app/src/main/java/de/dreier/mytargets/utils/ScoreUtils.kt
69085573
package polaris.okapi.tests.teamdefense.gui import polaris.okapi.App import polaris.okapi.gui.Gui import polaris.okapi.tests.teamdefense.world.TTDWorld import polaris.okapi.world.World /** * Created by Killian Le Clainche on 4/4/2018. */ class TTDUI @JvmOverloads constructor(application: App, world: TTDWorld, parent: Gui? = null, ticksExisted: Double = 0.0) : Gui(application, parent, ticksExisted) { val minimap : Minimap = Minimap(world) override fun init() { super.init() minimap.init() } override fun render(delta: Double) { super.render(delta) minimap.render(delta) } }
tests/polaris/okapi/tests/teamdefense/gui/UI.kt
4136908224
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.shared.targets.decoration import android.graphics.Matrix import android.graphics.Paint import android.graphics.Path import android.graphics.RectF import android.text.TextPaint import de.dreier.mytargets.shared.targets.drawable.CanvasWrapper import de.dreier.mytargets.shared.targets.models.Beursault import de.dreier.mytargets.shared.utils.Color import de.dreier.mytargets.shared.utils.Color.DARK_GRAY class BeursaultDecorator(private val model: Beursault) : CenterMarkDecorator(DARK_GRAY, 500f, 6, false) { private val paintFill: Paint by lazy { val paintFill = Paint() paintFill.isAntiAlias = true paintFill.color = Color.WHITE paintFill } private val paintText: TextPaint by lazy { val paintText = TextPaint() paintText.isAntiAlias = true paintText.color = Color.BLACK paintText } override fun drawDecoration(canvas: CanvasWrapper) { super.drawDecoration(canvas) drawPathsForZone(canvas, 6, 6, 2.4f, one, oneBounds) drawPathsForZone(canvas, 4, 4, 2.4f, two, twoBounds) drawPathsForZone(canvas, 2, 3, 1.05f, three, threeBounds) } private fun drawPathsForZone(canvas: CanvasWrapper, innerZoneIndex: Int, outerZoneIndex: Int, scale: Float, path: Path, pathBounds: RectF) { val outerZone = model.getZone(outerZoneIndex) val innerZone = model.getZone(innerZoneIndex) val outerRadius = outerZone.radius - outerZone.strokeWidth * 0.5f val innerRadius = innerZone.radius + innerZone.strokeWidth * 0.5f val rel = (outerRadius + innerRadius) * 0.5f drawFilledPath(canvas, 0f, -rel, scale, path, pathBounds) // top drawFilledPath(canvas, -rel, 0f, scale, path, pathBounds) // left drawFilledPath(canvas, 0f, rel, scale, path, pathBounds) // bottom drawFilledPath(canvas, rel, 0f, scale, path, pathBounds) // right } private fun drawFilledPath(canvas: CanvasWrapper, x: Float, y: Float, scaleFactor: Float, path: Path, bounds: RectF) { var rectSize = 0.012f * 2f * scaleFactor val bgRect = RectF(x - rectSize, y - rectSize, x + rectSize, y + rectSize) canvas.drawRect(bgRect, paintFill) rectSize = 0.007f * 2f * scaleFactor val numberRect = RectF(x - rectSize, y - rectSize, x + rectSize, y + rectSize) val scaleMatrix = Matrix() scaleMatrix.setRectToRect(bounds, numberRect, Matrix.ScaleToFit.CENTER) val tmp = Path(path) tmp.transform(scaleMatrix) canvas.drawPath(tmp, paintText) } companion object { private val one = Path() private val two = Path() private val three = Path() private val oneBounds: RectF private val twoBounds: RectF private val threeBounds: RectF init { one.moveTo(-9.3f, 30.7f) one.lineTo(-11.9f, 30.7f) one.lineTo(-11.9f, 20.900002f) one.cubicTo(-12.9f, 21.800001f, -14.0f, 22.400002f, -15.299999f, 22.900002f) one.lineTo(-15.299999f, 20.500002f) one.cubicTo(-14.599999f, 20.300001f, -13.9f, 19.900002f, -13.099999f, 19.200003f) one.cubicTo(-12.299999f, 18.600002f, -11.799999f, 17.900003f, -11.499999f, 17.000002f) one.lineTo(-9.4f, 17.000002f) one.lineTo(-9.3f, 30.7f) one.lineTo(-9.3f, 30.7f) one.close() oneBounds = RectF() one.computeBounds(oneBounds, true) } init { two.moveTo(-5.2f, 28.4f) two.lineTo(-5.2f, 30.8f) two.lineTo(-14.3f, 30.8f) two.cubicTo(-14.2f, 29.9f, -13.900001f, 29.0f, -13.400001f, 28.199999f) two.cubicTo(-12.900001f, 27.4f, -11.900001f, 26.3f, -10.5f, 24.9f) two.cubicTo(-9.3f, 23.8f, -8.6f, 23.1f, -8.3f, 22.699999f) two.cubicTo(-7.9f, 22.199999f, -7.8f, 21.599998f, -7.8f, 21.099998f) two.cubicTo(-7.8f, 20.499998f, -8.0f, 20.099998f, -8.3f, 19.8f) two.cubicTo(-8.6f, 19.5f, -9.0f, 19.3f, -9.6f, 19.3f) two.cubicTo(-10.1f, 19.3f, -10.6f, 19.5f, -10.900001f, 19.8f) two.cubicTo(-11.200001f, 20.099998f, -11.400001f, 20.699999f, -11.500001f, 21.4f) two.lineTo(-14.000001f, 21.199999f) two.cubicTo(-13.800001f, 19.8f, -13.400001f, 18.699999f, -12.500001f, 18.099998f) two.cubicTo(-11.700001f, 17.499998f, -10.700001f, 17.199999f, -9.400002f, 17.199999f) two.cubicTo(-8.100001f, 17.199999f, -7.0000014f, 17.599998f, -6.2000017f, 18.3f) two.cubicTo(-5.4f, 19.0f, -5.0f, 19.9f, -5.0f, 21.0f) two.cubicTo(-5.0f, 21.6f, -5.1f, 22.2f, -5.3f, 22.7f) two.cubicTo(-5.5f, 23.300001f, -5.9f, 23.800001f, -6.3f, 24.400002f) two.cubicTo(-6.6000004f, 24.800001f, -7.2000003f, 25.400002f, -8.0f, 26.100002f) two.cubicTo(-8.8f, 26.900002f, -9.3f, 27.400002f, -9.6f, 27.600002f) two.cubicTo(-9.8f, 27.800003f, -10.0f, 28.100002f, -10.1f, 28.300003f) two.lineTo(-5.2f, 28.4f) two.lineTo(-5.2f, 28.4f) two.close() twoBounds = RectF() two.computeBounds(twoBounds, true) } init { three.moveTo(-14.1f, 26.8f) three.lineTo(-11.6f, 26.5f) three.cubicTo(-11.5f, 27.1f, -11.3f, 27.6f, -11.0f, 28.0f) three.cubicTo(-10.7f, 28.4f, -10.2f, 28.5f, -9.7f, 28.5f) three.cubicTo(-9.2f, 28.5f, -8.7f, 28.3f, -8.3f, 27.9f) three.cubicTo(-7.9f, 27.5f, -7.7000003f, 26.9f, -7.7000003f, 26.199999f) three.cubicTo(-7.7000003f, 25.499998f, -7.9f, 24.999998f, -8.200001f, 24.599998f) three.cubicTo(-8.6f, 24.2f, -9.0f, 24.0f, -9.5f, 24.0f) three.cubicTo(-9.8f, 24.0f, -10.2f, 24.1f, -10.7f, 24.2f) three.lineTo(-10.4f, 22.1f) three.cubicTo(-9.7f, 22.1f, -9.2f, 22.0f, -8.799999f, 21.6f) three.cubicTo(-8.4f, 21.300001f, -8.199999f, 20.800001f, -8.199999f, 20.300001f) three.cubicTo(-8.199999f, 19.800001f, -8.299999f, 19.500002f, -8.599998f, 19.2f) three.cubicTo(-8.899999f, 18.900002f, -9.199999f, 18.800001f, -9.699999f, 18.800001f) three.cubicTo(-10.099998f, 18.800001f, -10.499999f, 19.000002f, -10.799999f, 19.300001f) three.cubicTo(-11.099999f, 19.6f, -11.299999f, 20.1f, -11.4f, 20.7f) three.lineTo(-13.799999f, 20.300001f) three.cubicTo(-13.599999f, 19.500002f, -13.4f, 18.800001f, -12.999999f, 18.300001f) three.cubicTo(-12.699999f, 17.800001f, -12.199999f, 17.400002f, -11.599999f, 17.1f) three.cubicTo(-10.999999f, 16.800001f, -10.299999f, 16.7f, -9.599999f, 16.7f) three.cubicTo(-8.299999f, 16.7f, -7.299999f, 17.1f, -6.4999995f, 17.900002f) three.cubicTo(-5.8999996f, 18.600002f, -5.4999995f, 19.300001f, -5.4999995f, 20.2f) three.cubicTo(-5.4999995f, 21.400002f, -6.1999993f, 22.300001f, -7.4999995f, 23.1f) three.cubicTo(-6.6999993f, 23.300001f, -6.0999994f, 23.6f, -5.5999994f, 24.2f) three.cubicTo(-5.0999994f, 24.800001f, -4.8999996f, 25.5f, -4.8999996f, 26.300001f) three.cubicTo(-4.8999996f, 27.500002f, -5.2999997f, 28.500002f, -6.2f, 29.400002f) three.cubicTo(-7.1f, 30.300001f, -8.2f, 30.7f, -9.5f, 30.7f) three.cubicTo(-10.7f, 30.7f, -11.8f, 30.300001f, -12.6f, 29.6f) three.cubicTo(-13.5f, 28.9f, -13.9f, 28.0f, -14.1f, 26.8f) three.close() threeBounds = RectF() three.computeBounds(threeBounds, true) } } }
shared/src/main/java/de/dreier/mytargets/shared/targets/decoration/BeursaultDecorator.kt
2093716102
package co.smartreceipts.android.model.utils import android.content.Context import android.text.TextUtils import android.text.format.DateFormat import co.smartreceipts.android.date.DateUtils import co.smartreceipts.android.model.Price import co.smartreceipts.android.model.Price.Companion.moneyFormatter import org.joda.money.BigMoney import org.joda.money.CurrencyUnit import java.math.BigDecimal import java.math.RoundingMode import java.sql.Date import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.util.* object ModelUtils { private const val EPSILON = 0.0001f val decimalFormat: DecimalFormat get() { // check for the case when Locale has changed if (_decimalFormat.decimalFormatSymbols != DecimalFormatSymbols()) { _decimalFormat = initDecimalFormat() } return _decimalFormat } val decimalSeparator: Char get() = decimalFormat.decimalFormatSymbols.decimalSeparator private var _decimalFormat: DecimalFormat = initDecimalFormat() private fun initDecimalFormat(): DecimalFormat { val format = DecimalFormat() format.isParseBigDecimal = true format.isGroupingUsed = true return format } @JvmStatic fun getFormattedDate(date: java.util.Date, timeZone: TimeZone, context: Context, separator: String): String = getFormattedDate(Date(date.time), timeZone, context, separator) /** * Gets a formatted version of a date based on the timezone and locale for a given separator. In the US, * we might expect to see a result like "10/23/2014" returned if we set the separator as "/" * * @param date - the [Date] to format * @param timeZone - the [TimeZone] to use for this date * @param context - the current [Context] * @param separator - the date separator (e.g. "/", "-", ".") * @return the formatted date string for the start date */ fun getFormattedDate(date: Date, timeZone: TimeZone, context: Context, separator: String): String { val format = DateFormat.getDateFormat(context) format.timeZone = timeZone // Hack to shift the timezone appropriately val formattedDate = format.format(date) return formattedDate.replace(DateUtils.getDateSeparator(context), separator) } /** * Generates "decimal-formatted" value, which would appear to the end user as "25.20" or "25,20" instead of * showing naively as "25.2" or "25.2001910" * By default, this assumes a decimal precision of {@link PriceNew#TOTAL_DECIMAL_PRECISION} * * @param decimal - the [BigDecimal] to format * @param precision - the decimal places count * @return the decimal formatted price [String] */ @JvmStatic @JvmOverloads fun getDecimalFormattedValue(decimal: BigDecimal, precision: Int = Price.TOTAL_DECIMAL_PRECISION): String { val money = BigMoney.of(CurrencyUtils.getDefaultCurrency(), decimal) return moneyFormatter.print(money.withScale(precision, RoundingMode.HALF_EVEN)) } /** * The "currency-formatted" value, which would appear as "$25.20" or "$25,20" as determined by the user's locale. * * @param decimal - the [BigDecimal] to format * @param currency - the [CurrencyUnit] to use * @param precision - the desired decimal precision to use (eg 2 => "$25.20", 3 => "$25.200") * @return - the currency formatted price [String] */ @JvmStatic fun getCurrencyFormattedValue(decimal: BigDecimal, currency: CurrencyUnit, precision: Int = -1): String { val money = BigMoney.of(currency, decimal) val decimalPlaces = when (precision) { -1 -> currency.decimalPlaces else -> precision } return money.currencyUnit.symbol + moneyFormatter.print(money.withScale(decimalPlaces, RoundingMode.HALF_EVEN)) } /** * The "currency-code-formatted" value, which would appear as "USD 25.20" or "USD 25,20" as determined by the user's locale. * * @param decimal - the [BigDecimal] to format * @param currency - the [CurrencyUnit] to use. If this is {@code null}, return {@link #getDecimalFormattedValue(BigDecimal)} * @param precision - the desired decimal precision to use (eg 2 => "USD 25.20", 3 => "USD 25.200") * @return - the currency formatted price [String] */ @JvmStatic fun getCurrencyCodeFormattedValue(decimal: BigDecimal, currency: CurrencyUnit, precision: Int = -1): String { val money = BigMoney.of(currency, decimal) val decimalPlaces = when (precision) { -1 -> currency.decimalPlaces else -> precision } return currency.code + " " + moneyFormatter.print(money.withScale(decimalPlaces, RoundingMode.HALF_EVEN)) } /** * Tries to parse a string to find the underlying numerical value * * @param number the string containing a number (hopefully) * @return the [BigDecimal] value * @throws NumberFormatException if we cannot parse this number */ @JvmStatic @Throws(NumberFormatException::class) fun parseOrThrow(number: String?): BigDecimal { if (number == null || TextUtils.isEmpty(number)) { throw NumberFormatException("Cannot parse an empty string") } // Note: for some locales grouping separator symbol is non-breaking space (code = 160), // but incoming string may contain general space => need to prepare such string before parsing val groupingSeparator = decimalFormat.decimalFormatSymbols.groupingSeparator.toString() val nonBreakingSpace = ("\u00A0").toString() val parsedNumber = when (groupingSeparator) { nonBreakingSpace -> decimalFormat.parse(number.replace(" ", nonBreakingSpace)) else -> decimalFormat.parse(number) } return BigDecimal(parsedNumber.toString()) } /** * Tries to parse a string to find the underlying numerical value * * @param number the string containing a number (hopefully) * @return the [BigDecimal] value or "0" if it cannot be found */ @JvmStatic @JvmOverloads fun tryParse(number: String?, defaultValue: BigDecimal = BigDecimal.ZERO): BigDecimal { return try { parseOrThrow(number) } catch (e: NumberFormatException) { defaultValue } } @JvmStatic fun isPriceZero(price: Price): Boolean { return price.priceAsFloat < EPSILON && price.priceAsFloat > -1 * EPSILON } }
app/src/main/java/co/smartreceipts/android/model/utils/ModelUtils.kt
2454552952
package co.smartreceipts.android.apis.moshi.adapters import com.squareup.moshi.FromJson import com.squareup.moshi.JsonReader /** * This adapter works with different preference types: String, Int, Boolean, Float */ class PreferenceJsonAdapter { @FromJson fun fromJson(reader: JsonReader): Any? { return if (reader.peek() == JsonReader.Token.NUMBER) { val numberAsString = reader.nextString() numberAsString.toIntOrNull() ?: numberAsString.toFloatOrNull() } else { // reader.readJsonValue() } } }
app/src/main/java/co/smartreceipts/android/apis/moshi/adapters/PreferenceJsonAdapter.kt
919341855
package simyukkuri.gameobject.yukkuri.statistic.statistics /** ゆっくりの変化しないパラメータのインターフェース */ interface Attribute { val damageThreshold: Int val happySec: Int val angrySec: Int val scaredSec: Int val fullnessThresholds: List<Int> val maxFullness: Int val damagePerHunger: Int val nearThreshold: Int val eyesight: Int val speed: Int val jumpHeight: Int val unitPoo: Int val gestationSec: Int val bearingSec: Int val sleepyThreshold: Int val sexuallyExcitedSec: Int val fullnessConsumedBySukkiring: Int val fullnessConsumedByGettingSukkiried: Int val probabilityOfGettingSexuallyExcited: Float val probabilityOfGettingSexuallyExcitedOfRaper: Float val incubationSec: Float val probabilityOfInfectionByInsanitationPerSec: Float val probabilityOfInfectionByContact: Float val decreasingDamageByPeroperoedPerSec: Int }
subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/statistic/statistics/Attribute.kt
4226364391
package top.zbeboy.isy.web.internship.statistics import com.alibaba.fastjson.JSON import org.apache.commons.lang.StringUtils import org.slf4j.LoggerFactory import org.springframework.stereotype.Controller import org.springframework.ui.ModelMap import org.springframework.util.ObjectUtils import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import top.zbeboy.isy.config.Workbook import top.zbeboy.isy.domain.tables.pojos.* import top.zbeboy.isy.service.cache.CacheManageService import top.zbeboy.isy.service.common.UploadService import top.zbeboy.isy.service.export.* import top.zbeboy.isy.service.internship.* import top.zbeboy.isy.service.util.DateTimeUtils import top.zbeboy.isy.service.util.RequestUtils import top.zbeboy.isy.web.bean.export.ExportBean import top.zbeboy.isy.web.bean.internship.release.InternshipReleaseBean import top.zbeboy.isy.web.bean.internship.statistics.InternshipChangeCompanyHistoryBean import top.zbeboy.isy.web.bean.internship.statistics.InternshipChangeHistoryBean import top.zbeboy.isy.web.bean.internship.statistics.InternshipStatisticsBean import top.zbeboy.isy.web.common.MethodControllerCommon import top.zbeboy.isy.web.internship.common.InternshipMethodControllerCommon import top.zbeboy.isy.web.util.AjaxUtils import top.zbeboy.isy.web.util.DataTablesUtils import top.zbeboy.isy.web.util.PaginationUtils import java.io.IOException import java.util.* import javax.annotation.Resource import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Created by zbeboy 2017-12-28 . **/ @Controller open class InternshipStatisticsController { private val log = LoggerFactory.getLogger(InternshipStatisticsController::class.java) @Resource open lateinit var internshipReleaseService: InternshipReleaseService @Resource open lateinit var internshipTypeService: InternshipTypeService @Resource open lateinit var internshipStatisticsService: InternshipStatisticsService @Resource open lateinit var internshipCollegeService: InternshipCollegeService @Resource open lateinit var internshipCompanyService: InternshipCompanyService @Resource open lateinit var graduationPracticeCompanyService: GraduationPracticeCompanyService @Resource open lateinit var graduationPracticeCollegeService: GraduationPracticeCollegeService @Resource open lateinit var graduationPracticeUnifyService: GraduationPracticeUnifyService @Resource open lateinit var methodControllerCommon: MethodControllerCommon @Resource open lateinit var internshipChangeHistoryService: InternshipChangeHistoryService @Resource open lateinit var internshipChangeCompanyHistoryService: InternshipChangeCompanyHistoryService @Resource open lateinit var internshipMethodControllerCommon: InternshipMethodControllerCommon @Resource open lateinit var cacheManageService: CacheManageService @Resource open lateinit var uploadService: UploadService /** * 实习统计 * * @return 实习统计页面 */ @RequestMapping(value = ["/web/menu/internship/statistical"], method = [(RequestMethod.GET)]) fun internshipStatistical(): String { return "web/internship/statistics/internship_statistics::#page-wrapper" } /** * 已提交列表 * * @return 已提交列表 统计页面 */ @RequestMapping(value = ["/web/internship/statistical/submitted"], method = [(RequestMethod.GET)]) fun statisticalSubmitted(@RequestParam("id") internshipReleaseId: String, modelMap: ModelMap): String { modelMap.addAttribute("internshipReleaseId", internshipReleaseId) return "web/internship/statistics/internship_submitted::#page-wrapper" } /** * 申请记录列表 * * @return 申请记录列表页面 */ @RequestMapping(value = ["/web/internship/statistical/record/apply"], method = [(RequestMethod.GET)]) fun changeHistory(@RequestParam("id") internshipReleaseId: String, @RequestParam("studentId") studentId: Int, modelMap: ModelMap): String { modelMap.addAttribute("internshipReleaseId", internshipReleaseId) modelMap.addAttribute("studentId", studentId) return "web/internship/statistics/internship_change_history::#page-wrapper" } /** * 单位变更记录列表 * * @return 单位变更记录列表页面 */ @RequestMapping(value = ["/web/internship/statistical/record/company"], method = [(RequestMethod.GET)]) fun changeCompanyHistory(@RequestParam("id") internshipReleaseId: String, @RequestParam("studentId") studentId: Int, modelMap: ModelMap): String { modelMap.addAttribute("internshipReleaseId", internshipReleaseId) modelMap.addAttribute("studentId", studentId) return "web/internship/statistics/internship_change_company_history::#page-wrapper" } /** * 未提交列表 * * @return 未提交列表 统计页面 */ @RequestMapping(value = ["/web/internship/statistical/unsubmitted"], method = [(RequestMethod.GET)]) fun statisticalUnSubmitted(@RequestParam("id") internshipReleaseId: String, modelMap: ModelMap): String { modelMap.addAttribute("internshipReleaseId", internshipReleaseId) return "web/internship/statistics/internship_unsubmitted::#page-wrapper" } /** * 数据列表 * * @return 数据列表 统计页面 */ @RequestMapping(value = ["/web/internship/statistical/data_list"], method = [(RequestMethod.GET)]) fun statisticalDataList(@RequestParam("id") internshipReleaseId: String, modelMap: ModelMap): String { val internshipRelease = internshipReleaseService.findById(internshipReleaseId) return if (!ObjectUtils.isEmpty(internshipRelease)) { modelMap.addAttribute("internshipReleaseId", internshipReleaseId) val internshipType = internshipTypeService.findByInternshipTypeId(internshipRelease.internshipTypeId!!) when (internshipType.internshipTypeName) { Workbook.INTERNSHIP_COLLEGE_TYPE -> "web/internship/statistics/internship_college_data::#page-wrapper" Workbook.INTERNSHIP_COMPANY_TYPE -> "web/internship/statistics/internship_company_data::#page-wrapper" Workbook.GRADUATION_PRACTICE_COLLEGE_TYPE -> "web/internship/statistics/graduation_practice_college_data::#page-wrapper" Workbook.GRADUATION_PRACTICE_UNIFY_TYPE -> "web/internship/statistics/graduation_practice_unify_data::#page-wrapper" Workbook.GRADUATION_PRACTICE_COMPANY_TYPE -> "web/internship/statistics/graduation_practice_company_data::#page-wrapper" else -> methodControllerCommon.showTip(modelMap, "未找到相关实习类型页面") } } else { methodControllerCommon.showTip(modelMap, "您不符合进入条件") } } /** * 获取实习统计数据 * * @return 数据 */ @RequestMapping(value = ["/web/internship/statistical/internship/data"], method = [(RequestMethod.GET)]) @ResponseBody fun internshipListDatas(paginationUtils: PaginationUtils): AjaxUtils<InternshipReleaseBean> { val ajaxUtils = internshipMethodControllerCommon.internshipListDatas(paginationUtils) val internshipReleaseBeens = ajaxUtils.listResult internshipReleaseBeens!!.forEach { r -> val internshipStatisticsBean = InternshipStatisticsBean() internshipStatisticsBean.internshipReleaseId = r.internshipReleaseId r.submittedTotalData = internshipStatisticsService.submittedCountAll(internshipStatisticsBean) r.unsubmittedTotalData = internshipStatisticsService.unsubmittedCountAll(internshipStatisticsBean) } return ajaxUtils.listData(internshipReleaseBeens) } /** * 已提交列表 数据 * * @param request 请求 * @return 数据 */ @RequestMapping(value = ["/web/internship/statistical/submitted/data"], method = [(RequestMethod.GET)]) @ResponseBody fun submittedDatas(request: HttpServletRequest): DataTablesUtils<InternshipStatisticsBean> { // 前台数据标题 注:要和前台标题顺序一致,获取order用 val headers = ArrayList<String>() headers.add("student_name") headers.add("student_number") headers.add("science_name") headers.add("organize_name") headers.add("internship_apply_state") headers.add("operator") val dataTablesUtils = DataTablesUtils<InternshipStatisticsBean>(request, headers) val internshipStatisticsBean = InternshipStatisticsBean() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { internshipStatisticsBean.internshipReleaseId = request.getParameter("internshipReleaseId") val records = internshipStatisticsService.submittedFindAllByPage(dataTablesUtils, internshipStatisticsBean) var internshipStatisticsBeens: List<InternshipStatisticsBean> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { internshipStatisticsBeens = records.into(InternshipStatisticsBean::class.java) } dataTablesUtils.data = internshipStatisticsBeens dataTablesUtils.setiTotalRecords(internshipStatisticsService.submittedCountAll(internshipStatisticsBean).toLong()) dataTablesUtils.setiTotalDisplayRecords(internshipStatisticsService.submittedCountByCondition(dataTablesUtils, internshipStatisticsBean).toLong()) } return dataTablesUtils } /** * 申请变更记录数据 * * @param internshipReleaseId 实习发布id * @param studentId 学生id * @return 数据 */ @RequestMapping(value = ["/web/internship/statistical/record/apply/data"], method = [(RequestMethod.GET)]) @ResponseBody fun changeHistoryDatas(@RequestParam("internshipReleaseId") internshipReleaseId: String, @RequestParam("studentId") studentId: Int): AjaxUtils<InternshipChangeHistoryBean> { val ajaxUtils = AjaxUtils.of<InternshipChangeHistoryBean>() var internshipChangeHistoryBeans: List<InternshipChangeHistoryBean> = ArrayList() val records = internshipChangeHistoryService.findByInternshipReleaseIdAndStudentId(internshipReleaseId, studentId) if (records.isNotEmpty) { internshipChangeHistoryBeans = records.into(InternshipChangeHistoryBean::class.java) internshipChangeHistoryBeans.forEach { i -> i.applyTimeStr = DateTimeUtils.formatDate(i.applyTime) if (!ObjectUtils.isEmpty(i.changeFillStartTime)) { i.changeFillStartTimeStr = DateTimeUtils.formatDate(i.changeFillStartTime) } if (!ObjectUtils.isEmpty(i.changeFillEndTime)) { i.changeFillEndTimeStr = DateTimeUtils.formatDate(i.changeFillEndTime) } } } return ajaxUtils.success().msg("获取数据成功").listData(internshipChangeHistoryBeans) } /** * 单位变更记录数据 * * @param internshipReleaseId 实习发布id * @param studentId 学生id * @return 数据 */ @RequestMapping(value = ["/web/internship/statistical/record/company/data"], method = [(RequestMethod.GET)]) @ResponseBody fun changeCompanyDatas(@RequestParam("internshipReleaseId") internshipReleaseId: String, @RequestParam("studentId") studentId: Int): AjaxUtils<InternshipChangeCompanyHistoryBean> { val ajaxUtils = AjaxUtils.of<InternshipChangeCompanyHistoryBean>() var internshipChangeCompanyHistoryBeans: List<InternshipChangeCompanyHistoryBean> = ArrayList() val records = internshipChangeCompanyHistoryService.findByInternshipReleaseIdAndStudentId(internshipReleaseId, studentId) if (records.isNotEmpty) { internshipChangeCompanyHistoryBeans = records.into(InternshipChangeCompanyHistoryBean::class.java) internshipChangeCompanyHistoryBeans.forEach { i -> i.changeTimeStr = DateTimeUtils.formatDate(i.changeTime) } } return ajaxUtils.success().msg("获取数据成功").listData(internshipChangeCompanyHistoryBeans) } /** * 未提交列表 数据 * * @param request 请求 * @return 数据 */ @RequestMapping(value = ["/web/internship/statistical/unsubmitted/data"], method = [(RequestMethod.GET)]) @ResponseBody fun unsubmittedDatas(request: HttpServletRequest): DataTablesUtils<InternshipStatisticsBean> { // 前台数据标题 注:要和前台标题顺序一致,获取order用 val headers = ArrayList<String>() headers.add("student_name") headers.add("student_number") headers.add("science_name") headers.add("organize_name") headers.add("operator") val dataTablesUtils = DataTablesUtils<InternshipStatisticsBean>(request, headers) val internshipStatisticsBean = InternshipStatisticsBean() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { internshipStatisticsBean.internshipReleaseId = request.getParameter("internshipReleaseId") val records = internshipStatisticsService.unsubmittedFindAllByPage(dataTablesUtils, internshipStatisticsBean) var internshipStatisticsBeens: List<InternshipStatisticsBean> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { internshipStatisticsBeens = records.into(InternshipStatisticsBean::class.java) } dataTablesUtils.data = internshipStatisticsBeens dataTablesUtils.setiTotalRecords(internshipStatisticsService.unsubmittedCountAll(internshipStatisticsBean).toLong()) dataTablesUtils.setiTotalDisplayRecords(internshipStatisticsService.unsubmittedCountByCondition(dataTablesUtils, internshipStatisticsBean).toLong()) } return dataTablesUtils } /** * 数据列表 顶岗实习(留学院) 数据 * * @param request 请求 * @return 数据 */ @RequestMapping(value = ["/web/internship/statistical/college/data"], method = [(RequestMethod.GET)]) @ResponseBody fun collegeData(request: HttpServletRequest): DataTablesUtils<InternshipCollege> { // 前台数据标题 注:要和前台标题顺序一致,获取order用 val headers = ArrayList<String>() headers.add("student_name") headers.add("college_class") headers.add("student_sex") headers.add("student_number") headers.add("phone_number") headers.add("qq_mailbox") headers.add("parental_contact") headers.add("headmaster") headers.add("headmaster_contact") headers.add("internship_college_name") headers.add("internship_college_address") headers.add("internship_college_contacts") headers.add("internship_college_tel") headers.add("school_guidance_teacher") headers.add("school_guidance_teacher_tel") headers.add("start_time") headers.add("end_time") headers.add("commitment_book") headers.add("safety_responsibility_book") headers.add("practice_agreement") headers.add("internship_application") headers.add("practice_receiving") headers.add("security_education_agreement") headers.add("parental_consent") val dataTablesUtils = DataTablesUtils<InternshipCollege>(request, headers) val internshipCollege = InternshipCollege() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { internshipCollege.internshipReleaseId = request.getParameter("internshipReleaseId") val records = internshipCollegeService.findAllByPage(dataTablesUtils, internshipCollege) var internshipColleges: List<InternshipCollege> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { internshipColleges = records.into(InternshipCollege::class.java) internshipColleges.forEach { data -> val usersKey = cacheManageService.getUsersKey(data.studentUsername!!) data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey) data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey) } } dataTablesUtils.data = internshipColleges dataTablesUtils.setiTotalRecords(internshipCollegeService.countAll(internshipCollege).toLong()) dataTablesUtils.setiTotalDisplayRecords(internshipCollegeService.countByCondition(dataTablesUtils, internshipCollege).toLong()) } return dataTablesUtils } /** * 导出 顶岗实习(留学院) 数据 * * @param request 请求 */ @RequestMapping(value = ["/web/internship/statistical/college/data/export"], method = [(RequestMethod.GET)]) fun collegeDataExport(request: HttpServletRequest, response: HttpServletResponse) { try { var fileName: String? = "顶岗实习(留学院)" var ext: String? = Workbook.XLSX_FILE val exportBean = JSON.parseObject(request.getParameter("exportFile"), ExportBean::class.java) val extraSearchParam = request.getParameter("extra_search") val dataTablesUtils = DataTablesUtils.of<InternshipCollege>() if (StringUtils.isNotBlank(extraSearchParam)) { dataTablesUtils.search = JSON.parseObject(extraSearchParam) } val internshipCollege = InternshipCollege() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { internshipCollege.internshipReleaseId = request.getParameter("internshipReleaseId") val records = internshipCollegeService.exportData(dataTablesUtils, internshipCollege) var internshipColleges: List<InternshipCollege> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { internshipColleges = records.into(InternshipCollege::class.java) internshipColleges.forEach { data -> val usersKey = cacheManageService.getUsersKey(data.studentUsername!!) data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey) data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey) } } if (StringUtils.isNotBlank(exportBean.fileName)) { fileName = exportBean.fileName } if (StringUtils.isNotBlank(exportBean.ext)) { ext = exportBean.ext } val internshipRelease = internshipReleaseService.findById(internshipReleaseId) if (!ObjectUtils.isEmpty(internshipRelease)) { val export = InternshipCollegeExport(internshipColleges) val schoolInfoPath = cacheManageService.schoolInfoPath(internshipRelease.departmentId!!) val path = Workbook.internshipPath(schoolInfoPath) + fileName + "." + ext export.exportExcel(RequestUtils.getRealPath(request) + Workbook.internshipPath(schoolInfoPath), fileName!!, ext!!) uploadService.download(fileName, path, response, request) } } } catch (e: IOException) { log.error("Export file error, error is {}", e) } } /** * 数据列表 校外自主实习(去单位) 数据 * * @param request 请求 * @return 数据 */ @RequestMapping(value = ["/web/internship/statistical/company/data"], method = [(RequestMethod.GET)]) @ResponseBody fun companyData(request: HttpServletRequest): DataTablesUtils<InternshipCompany> { // 前台数据标题 注:要和前台标题顺序一致,获取order用 val headers = ArrayList<String>() headers.add("student_name") headers.add("college_class") headers.add("student_sex") headers.add("student_number") headers.add("phone_number") headers.add("qq_mailbox") headers.add("parental_contact") headers.add("headmaster") headers.add("headmaster_contact") headers.add("internship_company_name") headers.add("internship_company_address") headers.add("internship_company_contacts") headers.add("internship_company_tel") headers.add("school_guidance_teacher") headers.add("school_guidance_teacher_tel") headers.add("start_time") headers.add("end_time") headers.add("commitment_book") headers.add("safety_responsibility_book") headers.add("practice_agreement") headers.add("internship_application") headers.add("practice_receiving") headers.add("security_education_agreement") headers.add("parental_consent") val dataTablesUtils = DataTablesUtils<InternshipCompany>(request, headers) val internshipCompany = InternshipCompany() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { internshipCompany.internshipReleaseId = request.getParameter("internshipReleaseId") val records = internshipCompanyService.findAllByPage(dataTablesUtils, internshipCompany) var internshipCompanies: List<InternshipCompany> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { internshipCompanies = records.into(InternshipCompany::class.java) internshipCompanies.forEach { data -> val usersKey = cacheManageService.getUsersKey(data.studentUsername!!) data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey) data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey) } } dataTablesUtils.data = internshipCompanies dataTablesUtils.setiTotalRecords(internshipCompanyService.countAll(internshipCompany).toLong()) dataTablesUtils.setiTotalDisplayRecords(internshipCompanyService.countByCondition(dataTablesUtils, internshipCompany).toLong()) } return dataTablesUtils } /** * 导出 校外自主实习(去单位) 数据 * * @param request 请求 */ @RequestMapping(value = ["/web/internship/statistical/company/data/export"], method = [(RequestMethod.GET)]) fun companyDataExport(request: HttpServletRequest, response: HttpServletResponse) { try { var fileName: String? = "校外自主实习(去单位)" var ext: String? = Workbook.XLSX_FILE val exportBean = JSON.parseObject(request.getParameter("exportFile"), ExportBean::class.java) val extraSearchParam = request.getParameter("extra_search") val dataTablesUtils = DataTablesUtils.of<InternshipCompany>() if (StringUtils.isNotBlank(extraSearchParam)) { dataTablesUtils.search = JSON.parseObject(extraSearchParam) } val internshipCompany = InternshipCompany() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { internshipCompany.internshipReleaseId = request.getParameter("internshipReleaseId") val records = internshipCompanyService.exportData(dataTablesUtils, internshipCompany) var internshipCompanies: List<InternshipCompany> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { internshipCompanies = records.into(InternshipCompany::class.java) internshipCompanies.forEach { data -> val usersKey = cacheManageService.getUsersKey(data.studentUsername!!) data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey) data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey) } } if (StringUtils.isNotBlank(exportBean.fileName)) { fileName = exportBean.fileName } if (StringUtils.isNotBlank(exportBean.ext)) { ext = exportBean.ext } val internshipRelease = internshipReleaseService.findById(internshipReleaseId) if (!ObjectUtils.isEmpty(internshipRelease)) { val export = InternshipCompanyExport(internshipCompanies) val schoolInfoPath = cacheManageService.schoolInfoPath(internshipRelease.departmentId!!) val path = Workbook.internshipPath(schoolInfoPath) + fileName + "." + ext export.exportExcel(RequestUtils.getRealPath(request) + Workbook.internshipPath(schoolInfoPath), fileName!!, ext!!) uploadService.download(fileName, path, response, request) } } } catch (e: IOException) { log.error("Export file error, error is {}", e) } } /** * 数据列表 毕业实习(校外) 数据 * * @param request 请求 * @return 数据 */ @RequestMapping(value = ["/web/internship/statistical/graduation_practice_company/data"], method = [(RequestMethod.GET)]) @ResponseBody fun graduationPracticeCompanyData(request: HttpServletRequest): DataTablesUtils<GraduationPracticeCompany> { // 前台数据标题 注:要和前台标题顺序一致,获取order用 val headers = ArrayList<String>() headers.add("student_name") headers.add("college_class") headers.add("student_sex") headers.add("student_number") headers.add("phone_number") headers.add("qq_mailbox") headers.add("parental_contact") headers.add("headmaster") headers.add("headmaster_contact") headers.add("graduation_practice_company_name") headers.add("graduation_practice_company_address") headers.add("graduation_practice_company_contacts") headers.add("graduation_practice_company_tel") headers.add("school_guidance_teacher") headers.add("school_guidance_teacher_tel") headers.add("start_time") headers.add("end_time") headers.add("commitment_book") headers.add("safety_responsibility_book") headers.add("practice_agreement") headers.add("internship_application") headers.add("practice_receiving") headers.add("security_education_agreement") headers.add("parental_consent") val dataTablesUtils = DataTablesUtils<GraduationPracticeCompany>(request, headers) val graduationPracticeCompany = GraduationPracticeCompany() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { graduationPracticeCompany.internshipReleaseId = request.getParameter("internshipReleaseId") val records = graduationPracticeCompanyService.findAllByPage(dataTablesUtils, graduationPracticeCompany) var graduationPracticeCompanies: List<GraduationPracticeCompany> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { graduationPracticeCompanies = records.into(GraduationPracticeCompany::class.java) graduationPracticeCompanies.forEach { data -> val usersKey = cacheManageService.getUsersKey(data.studentUsername!!) data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey) data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey) } } dataTablesUtils.data = graduationPracticeCompanies dataTablesUtils.setiTotalRecords(graduationPracticeCompanyService.countAll(graduationPracticeCompany).toLong()) dataTablesUtils.setiTotalDisplayRecords(graduationPracticeCompanyService.countByCondition(dataTablesUtils, graduationPracticeCompany).toLong()) } return dataTablesUtils } /** * 导出 毕业实习(校外) 数据 * * @param request 请求 */ @RequestMapping(value = ["/web/internship/statistical/graduation_practice_company/data/export"], method = [(RequestMethod.GET)]) fun graduationPracticeCompanyDataExport(request: HttpServletRequest, response: HttpServletResponse) { try { var fileName: String? = "毕业实习(校外)" var ext: String? = Workbook.XLSX_FILE val exportBean = JSON.parseObject(request.getParameter("exportFile"), ExportBean::class.java) val extraSearchParam = request.getParameter("extra_search") val dataTablesUtils = DataTablesUtils.of<GraduationPracticeCompany>() if (StringUtils.isNotBlank(extraSearchParam)) { dataTablesUtils.search = JSON.parseObject(extraSearchParam) } val graduationPracticeCompany = GraduationPracticeCompany() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { graduationPracticeCompany.internshipReleaseId = request.getParameter("internshipReleaseId") val records = graduationPracticeCompanyService.exportData(dataTablesUtils, graduationPracticeCompany) var graduationPracticeCompanies: List<GraduationPracticeCompany> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { graduationPracticeCompanies = records.into(GraduationPracticeCompany::class.java) graduationPracticeCompanies.forEach { data -> val usersKey = cacheManageService.getUsersKey(data.studentUsername!!) data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey) data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey) } } if (StringUtils.isNotBlank(exportBean.fileName)) { fileName = exportBean.fileName } if (StringUtils.isNotBlank(exportBean.ext)) { ext = exportBean.ext } val internshipRelease = internshipReleaseService.findById(internshipReleaseId) if (!ObjectUtils.isEmpty(internshipRelease)) { val export = GraduationPracticeCompanyExport(graduationPracticeCompanies) val schoolInfoPath = cacheManageService.schoolInfoPath(internshipRelease.departmentId!!) val path = Workbook.internshipPath(schoolInfoPath) + fileName + "." + ext export.exportExcel(RequestUtils.getRealPath(request) + Workbook.internshipPath(schoolInfoPath), fileName!!, ext!!) uploadService.download(fileName, path, response, request) } } } catch (e: IOException) { log.error("Export file error, error is {}", e) } } /** * 数据列表 毕业实习(校内) 数据 * * @param request 请求 * @return 数据 */ @RequestMapping(value = ["/web/internship/statistical/graduation_practice_college/data"], method = [(RequestMethod.GET)]) @ResponseBody fun graduationPracticeCollegeData(request: HttpServletRequest): DataTablesUtils<GraduationPracticeCollege> { // 前台数据标题 注:要和前台标题顺序一致,获取order用 val headers = ArrayList<String>() headers.add("student_name") headers.add("college_class") headers.add("student_sex") headers.add("student_number") headers.add("phone_number") headers.add("qq_mailbox") headers.add("parental_contact") headers.add("headmaster") headers.add("headmaster_contact") headers.add("graduation_practice_college_name") headers.add("graduation_practice_college_address") headers.add("graduation_practice_college_contacts") headers.add("graduation_practice_college_tel") headers.add("school_guidance_teacher") headers.add("school_guidance_teacher_tel") headers.add("start_time") headers.add("end_time") headers.add("commitment_book") headers.add("safety_responsibility_book") headers.add("practice_agreement") headers.add("internship_application") headers.add("practice_receiving") headers.add("security_education_agreement") headers.add("parental_consent") val dataTablesUtils = DataTablesUtils<GraduationPracticeCollege>(request, headers) val graduationPracticeCollege = GraduationPracticeCollege() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { graduationPracticeCollege.internshipReleaseId = request.getParameter("internshipReleaseId") val records = graduationPracticeCollegeService.findAllByPage(dataTablesUtils, graduationPracticeCollege) var graduationPracticeColleges: List<GraduationPracticeCollege> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { graduationPracticeColleges = records.into(GraduationPracticeCollege::class.java) graduationPracticeColleges.forEach { data -> val usersKey = cacheManageService.getUsersKey(data.studentUsername!!) data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey) data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey) } } dataTablesUtils.data = graduationPracticeColleges dataTablesUtils.setiTotalRecords(graduationPracticeCollegeService.countAll(graduationPracticeCollege).toLong()) dataTablesUtils.setiTotalDisplayRecords(graduationPracticeCollegeService.countByCondition(dataTablesUtils, graduationPracticeCollege).toLong()) } return dataTablesUtils } /** * 导出 毕业实习(校内) 数据 * * @param request 请求 */ @RequestMapping(value = ["/web/internship/statistical/graduation_practice_college/data/export"], method = [(RequestMethod.GET)]) fun graduationPracticeCollegeDataExport(request: HttpServletRequest, response: HttpServletResponse) { try { var fileName: String? = "毕业实习(校内)" var ext: String? = Workbook.XLSX_FILE val exportBean = JSON.parseObject(request.getParameter("exportFile"), ExportBean::class.java) val extraSearchParam = request.getParameter("extra_search") val dataTablesUtils = DataTablesUtils.of<GraduationPracticeCollege>() if (StringUtils.isNotBlank(extraSearchParam)) { dataTablesUtils.search = JSON.parseObject(extraSearchParam) } val graduationPracticeCollege = GraduationPracticeCollege() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { graduationPracticeCollege.internshipReleaseId = request.getParameter("internshipReleaseId") val records = graduationPracticeCollegeService.exportData(dataTablesUtils, graduationPracticeCollege) var graduationPracticeColleges: List<GraduationPracticeCollege> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { graduationPracticeColleges = records.into(GraduationPracticeCollege::class.java) graduationPracticeColleges.forEach { data -> val usersKey = cacheManageService.getUsersKey(data.studentUsername!!) data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey) data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey) } } if (StringUtils.isNotBlank(exportBean.fileName)) { fileName = exportBean.fileName } if (StringUtils.isNotBlank(exportBean.ext)) { ext = exportBean.ext } val internshipRelease = internshipReleaseService.findById(internshipReleaseId) if (!ObjectUtils.isEmpty(internshipRelease)) { val export = GraduationPracticeCollegeExport(graduationPracticeColleges) val schoolInfoPath = cacheManageService.schoolInfoPath(internshipRelease.departmentId!!) val path = Workbook.internshipPath(schoolInfoPath) + fileName + "." + ext export.exportExcel(RequestUtils.getRealPath(request) + Workbook.internshipPath(schoolInfoPath), fileName!!, ext!!) uploadService.download(fileName, path, response, request) } } } catch (e: IOException) { log.error("Export file error, error is {}", e) } } /** * 数据列表 毕业实习(学校统一组织校外实习) 数据 * * @param request 请求 * @return 数据 */ @RequestMapping(value = ["/web/internship/statistical/graduation_practice_unify/data"], method = [(RequestMethod.GET)]) @ResponseBody fun graduationPracticeUnifyData(request: HttpServletRequest): DataTablesUtils<GraduationPracticeUnify> { // 前台数据标题 注:要和前台标题顺序一致,获取order用 val headers = ArrayList<String>() headers.add("student_name") headers.add("college_class") headers.add("student_sex") headers.add("student_number") headers.add("phone_number") headers.add("qq_mailbox") headers.add("parental_contact") headers.add("headmaster") headers.add("headmaster_contact") headers.add("graduation_practice_unify_name") headers.add("graduation_practice_unify_address") headers.add("graduation_practice_unify_contacts") headers.add("graduation_practice_unify_tel") headers.add("school_guidance_teacher") headers.add("school_guidance_teacher_tel") headers.add("start_time") headers.add("end_time") headers.add("commitment_book") headers.add("safety_responsibility_book") headers.add("practice_agreement") headers.add("internship_application") headers.add("practice_receiving") headers.add("security_education_agreement") headers.add("parental_consent") val dataTablesUtils = DataTablesUtils<GraduationPracticeUnify>(request, headers) val graduationPracticeUnify = GraduationPracticeUnify() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { graduationPracticeUnify.internshipReleaseId = request.getParameter("internshipReleaseId") val records = graduationPracticeUnifyService.findAllByPage(dataTablesUtils, graduationPracticeUnify) var graduationPracticeUnifies: List<GraduationPracticeUnify> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { graduationPracticeUnifies = records.into(GraduationPracticeUnify::class.java) graduationPracticeUnifies.forEach { data -> val usersKey = cacheManageService.getUsersKey(data.studentUsername!!) data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey) data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey) } } dataTablesUtils.data = graduationPracticeUnifies dataTablesUtils.setiTotalRecords(graduationPracticeUnifyService.countAll(graduationPracticeUnify).toLong()) dataTablesUtils.setiTotalDisplayRecords(graduationPracticeUnifyService.countByCondition(dataTablesUtils, graduationPracticeUnify).toLong()) } return dataTablesUtils } /** * 导出 毕业实习(学校统一组织校外实习) 数据 * * @param request 请求 */ @RequestMapping(value = ["/web/internship/statistical/graduation_practice_unify/data/export"], method = [(RequestMethod.GET)]) fun graduationPracticeUnifyDataExport(request: HttpServletRequest, response: HttpServletResponse) { try { var fileName: String? = "毕业实习(学校统一组织校外实习)" var ext: String? = Workbook.XLSX_FILE val exportBean = JSON.parseObject(request.getParameter("exportFile"), ExportBean::class.java) val extraSearchParam = request.getParameter("extra_search") val dataTablesUtils = DataTablesUtils.of<GraduationPracticeUnify>() if (StringUtils.isNotBlank(extraSearchParam)) { dataTablesUtils.search = JSON.parseObject(extraSearchParam) } val graduationPracticeUnify = GraduationPracticeUnify() val internshipReleaseId = request.getParameter("internshipReleaseId") if (!ObjectUtils.isEmpty(internshipReleaseId)) { graduationPracticeUnify.internshipReleaseId = request.getParameter("internshipReleaseId") val records = graduationPracticeUnifyService.exportData(dataTablesUtils, graduationPracticeUnify) var graduationPracticeUnifies: List<GraduationPracticeUnify> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { graduationPracticeUnifies = records.into(GraduationPracticeUnify::class.java) graduationPracticeUnifies.forEach { data -> val usersKey = cacheManageService.getUsersKey(data.studentUsername!!) data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey) data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey) } } if (StringUtils.isNotBlank(exportBean.fileName)) { fileName = exportBean.fileName } if (StringUtils.isNotBlank(exportBean.ext)) { ext = exportBean.ext } val internshipRelease = internshipReleaseService.findById(internshipReleaseId) if (!ObjectUtils.isEmpty(internshipRelease)) { val export = GraduationPracticeUnifyExport(graduationPracticeUnifies) val schoolInfoPath = cacheManageService.schoolInfoPath(internshipRelease.departmentId!!) val path = Workbook.internshipPath(schoolInfoPath) + fileName + "." + ext export.exportExcel(RequestUtils.getRealPath(request) + Workbook.internshipPath(schoolInfoPath), fileName!!, ext!!) uploadService.download(fileName, path, response, request) } } } catch (e: IOException) { log.error("Export file error, error is {}", e) } } }
src/main/java/top/zbeboy/isy/web/internship/statistics/InternshipStatisticsController.kt
59852331
package com.akhbulatov.wordkeeper.presentation.ui.global.base import android.app.Dialog import android.os.Bundle import androidx.annotation.StringRes import androidx.core.os.bundleOf import androidx.fragment.app.setFragmentResult import com.google.android.material.dialog.MaterialAlertDialogBuilder class ConfirmDialog : BaseDialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val args = requireArguments() return MaterialAlertDialogBuilder(requireContext()) .setTitle(args.getInt(ARG_TITLE)) .setMessage(args.getInt(ARG_MESSAGE)) .setPositiveButton(args.getInt(ARG_POSITIVE_BUTTON)) { _, _ -> setFragmentResult(REQUEST_OK, bundleOf()) } .setNegativeButton(args.getInt(ARG_NEGATIVE_BUTTON)) { _, _ -> dismiss() } .create() } companion object { const val REQUEST_OK = "request_ok" private const val ARG_TITLE = "title" private const val ARG_MESSAGE = "message" private const val ARG_POSITIVE_BUTTON = "positive_button" private const val ARG_NEGATIVE_BUTTON = "negative_button" fun newInstance( @StringRes title: Int, @StringRes message: Int, @StringRes positiveButton: Int = android.R.string.ok, @StringRes negativeButton: Int = android.R.string.cancel ) = ConfirmDialog().apply { arguments = bundleOf( ARG_TITLE to title, ARG_MESSAGE to message, ARG_POSITIVE_BUTTON to positiveButton, ARG_NEGATIVE_BUTTON to negativeButton ) } } }
app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/global/base/ConfirmDialog.kt
3397045260
package com.alexstyl.specialdates.addevent.operations import java.net.URI data class InsertImage(val imageUri: URI) : ContactOperation
memento/src/main/java/com/alexstyl/specialdates/addevent/operations/InsertImage.kt
2005169721
/* * 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.PsiForStatement import com.intellij.psi.impl.source.tree.ChildRole import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.UForExpression import org.jetbrains.uast.UIdentifier class JavaUForExpression( override val psi: PsiForStatement, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UForExpression { override val declaration: UExpression? by lz { psi.initialization?.let { JavaConverter.convertStatement(it, this) } } override val condition: UExpression? by lz { psi.condition?.let { JavaConverter.convertExpression(it, this) } } override val update: UExpression? by lz { psi.update?.let { JavaConverter.convertStatement(it, this) } } override val body: UExpression by lz { JavaConverter.convertOrEmpty(psi.body, this) } override val forIdentifier: UIdentifier get() = UIdentifier(psi.getChildByRole(ChildRole.FOR_KEYWORD), this) }
uast/uast-java/src/org/jetbrains/uast/java/controlStructures/JavaUForExpression.kt
2143607313
package com.burrowsapps.gif.search.data.source.network import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class TenorResponseDtoTest { private val nextResponse = "1.0" private val results = listOf<ResultDto>() private var sutDefault = TenorResponseDto() private lateinit var sut: TenorResponseDto @Before fun setUp() { sut = TenorResponseDto(results, nextResponse) } @Test fun testGetResults() { assertThat(sutDefault.results).isEmpty() assertThat(sut.results).isEqualTo(results) } @Test fun testGetNext() { assertThat(sutDefault.next).isEqualTo("0.0") assertThat(sut.next).isEqualTo(nextResponse) } }
app/src/test/java/com/burrowsapps/gif/search/data/source/network/TenorResponseDtoTest.kt
4233321435
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Instruction2 import org.objectweb.asm.Opcodes.PUTFIELD @DependsOn(Node::class) class Inventory : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Node>() } .and { it.interfaces.isEmpty() } .and { it.instanceMethods.isEmpty() } .and { it.instanceFields.count { it.type == IntArray::class.type } == 2 } .and { it.instanceFields.size == 2 } class ids : OrderMapper.InConstructor.Field(Inventory::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class quantities : OrderMapper.InConstructor.Field(Inventory::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } }
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Inventory.kt
3473864445
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.resolve import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.test.withCustomCompilerOptions import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.junit.Assert import java.io.File abstract class AbstractPartialBodyResolveTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE fun doTest(unused: String) { val testPath = dataFilePath(fileName()) val dumpNormal = dump(testPath, BodyResolveMode.PARTIAL) val testPathNoExt = FileUtil.getNameWithoutExtension(testPath) KotlinTestUtils.assertEqualsToFile(File("$testPathNoExt.dump"), dumpNormal) val dumpForCompletion = dump(testPath, BodyResolveMode.PARTIAL_FOR_COMPLETION) val completionDump = File("$testPathNoExt.completion") if (dumpForCompletion != dumpNormal) { KotlinTestUtils.assertEqualsToFile(completionDump, dumpForCompletion) } else { Assert.assertFalse(completionDump.exists()) } } private fun dump(testPath: String, resolveMode: BodyResolveMode): String { myFixture.configureByText(KotlinFileType.INSTANCE, File(testPath).readText()) return withCustomCompilerOptions(myFixture.file.text, project, module) { val file = myFixture.file as KtFile val editor = myFixture.editor val selectionModel = editor.selectionModel val expression = if (selectionModel.hasSelection()) { PsiTreeUtil.findElementOfClassAtRange( file, selectionModel.selectionStart, selectionModel.selectionEnd, KtExpression::class.java ) ?: error("No KtExpression at selection range") } else { val offset = editor.caretModel.offset val element = file.findElementAt(offset)!! element.getNonStrictParentOfType<KtSimpleNameExpression>() ?: error("No KtSimpleNameExpression at caret") } val resolutionFacade = file.getResolutionFacade() // optimized resolve val (target1, type1, processedStatements1) = doResolve(expression, resolutionFacade.analyze(expression, resolveMode)) // full body resolve val (target2, type2, processedStatements2) = doResolve(expression, resolutionFacade.analyze(expression)) val set = HashSet(processedStatements2) assert(set.containsAll(processedStatements1)) set.removeAll(processedStatements1) val builder = StringBuilder() if (expression is KtReferenceExpression) { builder.append("Resolve target: ${target2.presentation(type2)}\n") } else { builder.append("Expression type:${type2.presentation()}\n") } builder.append("----------------------------------------------\n") val skippedStatements = set .filter { !it.parents.any { it in set } } // do not include skipped statements which are inside other skipped statement .sortedBy { it.textOffset } myFixture.project.executeWriteCommand("") { for (statement in skippedStatements) { statement.replace(KtPsiFactory(project).createComment("/* STATEMENT DELETED: ${statement.compactPresentation()} */")) } } val fileText = file.text if (selectionModel.hasSelection()) { val start = selectionModel.selectionStart val end = selectionModel.selectionEnd builder.append(fileText.substring(0, start)) builder.append("<selection>") builder.append(fileText.substring(start, end)) builder.append("<selection>") builder.append(fileText.substring(end)) } else { val newCaretOffset = editor.caretModel.offset builder.append(fileText.substring(0, newCaretOffset)) builder.append("<caret>") builder.append(fileText.substring(newCaretOffset)) } Assert.assertEquals(target2.presentation(null), target1.presentation(null)) Assert.assertEquals(type2.presentation(), type1.presentation()) builder.toString() } } private data class ResolveData( val target: DeclarationDescriptor?, val type: KotlinType?, val processedStatements: Collection<KtExpression> ) private fun doResolve(expression: KtExpression, bindingContext: BindingContext): ResolveData { val target = if (expression is KtReferenceExpression) bindingContext[BindingContext.REFERENCE_TARGET, expression] else null val processedStatements = bindingContext.getSliceContents(BindingContext.PROCESSED) .filter { it.value } .map { it.key } .filter { it.parent is KtBlockExpression } val receiver = (expression as? KtSimpleNameExpression)?.getReceiverExpression() val expressionWithType = if (receiver != null) { expression.parent as? KtExpression ?: expression } else { expression } val type = bindingContext.getType(expressionWithType) return ResolveData(target, type, processedStatements) } private fun DeclarationDescriptor?.presentation(type: KotlinType?): String { if (this == null) return "null" val s = DescriptorRenderer.COMPACT.render(this) val renderType = this is VariableDescriptor && type != this.returnType if (!renderType) return s return "$s smart-cast to ${type.presentation()}" } private fun KotlinType?.presentation() = if (this != null) DescriptorRenderer.COMPACT.renderType(this) else "unknown type" private fun KtExpression.compactPresentation(): String { val text = text val builder = StringBuilder() var dropSpace = false for (c in text) { when (c) { ' ', '\n', '\r' -> { if (!dropSpace) builder.append(' ') dropSpace = true } else -> { builder.append(c) dropSpace = false } } } return builder.toString() } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/resolve/AbstractPartialBodyResolveTest.kt
3902810048
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.wizard import com.intellij.icons.AllIcons import com.intellij.ide.plugins.PluginManagerConfigurable import com.intellij.ide.projectWizard.NewProjectWizardCollector import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.PlatformCoreDataKeys.CONTEXT_COMPONENT import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.IdeaActionButtonLook import com.intellij.openapi.application.ModalityState import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.InstallPluginTask import com.intellij.openapi.util.registry.Registry import com.intellij.ui.UIBundle import com.intellij.ui.awt.RelativePoint import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.components.SegmentedButtonBorder import java.util.function.Consumer import java.util.function.Supplier import javax.swing.JComponent abstract class AbstractNewProjectWizardMultiStepWithAddButton<S : NewProjectWizardStep, F: NewProjectWizardMultiStepFactory<S>>( parent: NewProjectWizardStep, epName: ExtensionPointName<F> ) : AbstractNewProjectWizardMultiStep<S, F>(parent, epName) { abstract var additionalStepPlugins: Map<String, String> override fun setupSwitcherUi(builder: Panel) { with(builder) { row(label) { createAndSetupSwitcher(this@row) if (additionalStepPlugins.isNotEmpty()) { val plus = AdditionalStepsAction() val actionButton = ActionButton( plus, plus.templatePresentation, ActionPlaces.getPopupPlace("NEW_PROJECT_WIZARD"), ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE ) actionButton.setLook(IdeaActionButtonLook()) actionButton.border = SegmentedButtonBorder() cell(actionButton) } }.bottomGap(BottomGap.SMALL) } } private inner class AdditionalStepsAction : DumbAwareAction(null, null, AllIcons.General.Add) { override fun actionPerformed(e: AnActionEvent) { NewProjectWizardCollector.logAddPlugin(context) val additionalSteps = (additionalStepPlugins.keys - steps.keys).sorted().map { OpenMarketPlaceAction(it) } JBPopupFactory.getInstance().createActionGroupPopup( UIBundle.message("new.project.wizard.popup.title.install.plugin"), DefaultActionGroup(additionalSteps), e.dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false ).show(RelativePoint.getSouthOf(e.getData(CONTEXT_COMPONENT) as JComponent)) } } private inner class OpenMarketPlaceAction(private val step: String) : DumbAwareAction(Supplier { step }) { override fun actionPerformed(e: AnActionEvent) { NewProjectWizardCollector.logPluginSelected(context, step) val pluginId = PluginId.getId(additionalStepPlugins[step]!!) val component = e.dataContext.getData(CONTEXT_COMPONENT)!! if (Registry.`is`("new.project.wizard.modal.plugin.install", false)) { ProgressManager.getInstance().run(InstallPluginTask(setOf(pluginId), ModalityState.stateForComponent(component))) } else { ShowSettingsUtil.getInstance().editConfigurable(null, PluginManagerConfigurable(), Consumer { it.openMarketplaceTab("/tag: \"Programming Language\" $step") }) } } } }
platform/platform-impl/src/com/intellij/ide/wizard/AbstractNewProjectWizardMultiStepWithAddButton.kt
1268315240
package org.runestar.client.updater.mapper import java.lang.reflect.Modifier abstract class StaticOrderMapper<T>(val position: Int) : Mapper<T>(), InstructionResolver<T> { override fun match(jar: Jar2): T { val n = position.takeUnless { it < 0 } ?: position * -1 - 1 val instructions = jar.classes.asSequence() .flatMap { it.methods.asSequence() } .filter { Modifier.isStatic(it.access) } .flatMap { it.instructions } val relativeInstructions = if (position >= 0) { instructions } else { instructions.toList().asReversed().asSequence() } val instructionMatches = relativeInstructions.filter(predicate).toList() instructionMatches.mapTo(HashSet()) { it.method }.single() return resolve(instructionMatches[n]) } abstract val predicate: Predicate<Instruction2> abstract class Class(position: Int) : StaticOrderMapper<Class2>(position), ElementMatcher.Class, InstructionResolver.Class abstract class Field(position: Int) : StaticOrderMapper<Field2>(position), ElementMatcher.Field, InstructionResolver.Field abstract class Method(position: Int) : StaticOrderMapper<Method2>(position), ElementMatcher.Method, InstructionResolver.Method }
updater-mapper/src/main/java/org/runestar/client/updater/mapper/StaticOrderMapper.kt
2354872873
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.k2.codeinsight.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicators.* import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset internal class UseExpressionBodyIntention : AbstractKotlinApplicatorBasedIntention<KtDeclarationWithBody, UseExpressionBodyIntention.Input>( KtDeclarationWithBody::class, ) { class Input : KotlinApplicatorInput override fun getApplicator() = applicator<KtDeclarationWithBody, Input> { familyAndActionName(KotlinBundle.lazyMessage(("convert.body.to.expression"))) isApplicableByPsi { declaration -> // Check if either property accessor or named function if (declaration !is KtNamedFunction && declaration !is KtPropertyAccessor) return@isApplicableByPsi false // Check if a named function has explicit type if (declaration is KtNamedFunction && !declaration.hasDeclaredReturnType()) return@isApplicableByPsi false // Check if function has block with single non-empty KtReturnExpression val returnedExpression = declaration.singleReturnedExpressionOrNull ?: return@isApplicableByPsi false // Check if the returnedExpression actually always returns (early return is possible) // TODO: take into consideration other cases (???) if (returnedExpression.anyDescendantOfType<KtReturnExpression>( canGoInside = { it !is KtFunctionLiteral && it !is KtNamedFunction && it !is KtPropertyAccessor }) ) return@isApplicableByPsi false true } applyToWithEditorRequired { declaration, _, _, editor -> val newFunctionBody = declaration.replaceWithPreservingComments() editor.correctRightMargin(declaration, newFunctionBody) if (declaration is KtNamedFunction) editor.selectFunctionColonType(declaration) } } override fun getApplicabilityRange() = applicabilityRanges { declaration: KtDeclarationWithBody -> val returnExpression = declaration.singleReturnExpressionOrNull ?: return@applicabilityRanges emptyList() val resultTextRanges = mutableListOf(TextRange(0, returnExpression.returnKeyword.endOffset - declaration.startOffset)) // Adding applicability to the end of the declaration block val rBraceTextRange = declaration.rBraceOffSetTextRange ?: return@applicabilityRanges resultTextRanges resultTextRanges.add(rBraceTextRange) resultTextRanges } override fun getInputProvider() = inputProvider<KtDeclarationWithBody, _> { Input() } override fun skipProcessingFurtherElementsAfter(element: PsiElement) = false } private fun KtDeclarationWithBody.replaceWithPreservingComments(): KtExpression { val bodyBlock = bodyBlockExpression ?: return this val returnedExpression = singleReturnedExpressionOrNull ?: return this val commentSaver = CommentSaver(bodyBlock) val factory = KtPsiFactory(this) val eq = addBefore(factory.createEQ(), bodyBlockExpression) addAfter(factory.createWhiteSpace(), eq) val newBody = bodyBlock.replaced(returnedExpression) commentSaver.restore(newBody) return newBody } /** * This function guarantees that the function with its old body replaced by returned expression * will have this expression placed on the next line to the function's signature or property accessor's 'get() =' statement * in case it goes beyond IDEA editor's right margin * @param[declaration] the PSI element used as an anchor, as no indexes are built for newly generated body yet * @param[newBody] the new "= <returnedExpression>" like body, which replaces the old one */ private fun Editor.correctRightMargin( declaration: KtDeclarationWithBody, newBody: KtExpression ) { val kotlinFactory = KtPsiFactory(declaration) val startOffset = newBody.startOffset val startLine = document.getLineNumber(startOffset) val rightMargin = settings.getRightMargin(project) if (document.getLineEndOffset(startLine) - document.getLineStartOffset(startLine) >= rightMargin) { declaration.addBefore(kotlinFactory.createNewLine(), newBody) } } private fun Editor.selectFunctionColonType(newFunctionBody: KtNamedFunction) { val colon = newFunctionBody.colon ?: return val typeReference = newFunctionBody.typeReference ?: return selectionModel.setSelection(colon.startOffset, typeReference.endOffset) caretModel.moveToOffset(typeReference.endOffset) } private val KtDeclarationWithBody.singleReturnExpressionOrNull: KtReturnExpression? get() = bodyBlockExpression?.statements?.singleOrNull() as? KtReturnExpression private val KtDeclarationWithBody.singleReturnedExpressionOrNull: KtExpression? get() = singleReturnExpressionOrNull?.returnedExpression private val KtDeclarationWithBody.rBraceOffSetTextRange: TextRange? get() { val rightBlockBodyBrace = bodyBlockExpression?.rBrace ?: return null return rightBlockBodyBrace.textRange.shiftLeft(startOffset) }
plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/UseExpressionBodyIntention.kt
2435694502
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.minimap.settings import com.intellij.ide.minimap.utils.MiniMessagesBundle import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.ui.ComboBox import com.intellij.ui.components.JBCheckBox import com.intellij.ui.dsl.builder.bind import com.intellij.ui.dsl.builder.bindSelected import com.intellij.ui.dsl.builder.panel import com.intellij.ui.layout.selected import java.awt.Component import javax.swing.BoxLayout import javax.swing.DefaultListCellRenderer import javax.swing.JList import javax.swing.JPanel class MinimapConfigurable : BoundConfigurable(MiniMessagesBundle.message("settings.name")) { companion object { const val ID = "com.intellij.minimap" } private val state = MinimapSettingsState() // todo remove private val fileTypes = mutableListOf<String>() private lateinit var fileTypeComboBox: ComboBox<FileType> override fun createPanel() = panel { MinimapSettings.getInstance().state.let { // todo remove except fileTypes state.enabled = it.enabled state.rightAligned = it.rightAligned state.width = it.width fileTypes.clear() fileTypes.addAll(it.fileTypes) } lateinit var enabled: JBCheckBox row { enabled = checkBox(MiniMessagesBundle.message("settings.enable")) .applyToComponent { toolTipText = MiniMessagesBundle.message("settings.enable.hint") } .bindSelected(state::enabled) .component } indent { buttonsGroup { row(MiniMessagesBundle.message("settings.alignment")) { radioButton(MiniMessagesBundle.message("settings.left"), false) radioButton(MiniMessagesBundle.message("settings.right"), true) } }.bind(state::rightAligned) row(MiniMessagesBundle.message("settings.file.types")) { val textFileTypes = (FileTypeManager.getInstance() as FileTypeManagerImpl).registeredFileTypes .filter { !it.isBinary && it.defaultExtension.isNotBlank() }.distinctBy { it.defaultExtension } .sortedBy { it.defaultExtension.lowercase() } .sortedBy { if (fileTypes.contains(it.defaultExtension)) 0 else 1 } fileTypeComboBox = comboBox(textFileTypes, FileTypeListCellRenderer()) .applyToComponent { isSwingPopup = false addActionListener { val fileType = fileTypeComboBox.item ?: return@addActionListener if (!fileTypes.remove(fileType.defaultExtension)) { fileTypes.add(fileType.defaultExtension) } fileTypeComboBox.repaint() } }.component } }.enabledIf(enabled.selected) } override fun isModified(): Boolean { return super.isModified() || fileTypes != MinimapSettings.getInstance().state.fileTypes } override fun apply() { if (!isModified) { return } super.apply() state.fileTypes = fileTypes.toList() val settings = MinimapSettings.getInstance() val currentState = settings.state val needToRebuildUI = currentState.rightAligned != state.rightAligned || currentState.enabled != state.enabled || currentState.fileTypes != state.fileTypes settings.state = state.copy() settings.settingsChangeCallback.notify(if (needToRebuildUI) MinimapSettings.SettingsChangeType.WithUiRebuild else MinimapSettings.SettingsChangeType.Normal) } override fun reset() { super.reset() fileTypes.clear() fileTypes.addAll(MinimapSettings.getInstance().state.fileTypes) fileTypeComboBox.repaint() } private inner class FileTypeListCellRenderer : DefaultListCellRenderer() { private val container = JPanel(null) private val checkBox = JBCheckBox() init { isOpaque = false container.isOpaque = false checkBox.isOpaque = false container.layout = BoxLayout(container, BoxLayout.X_AXIS) container.add(checkBox) container.add(this) } override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) if (index == -1) { checkBox.isVisible = false text = fileTypes.joinToString(",") return container } checkBox.isVisible = true val fileType = value as? FileType ?: return container text = fileType.defaultExtension icon = fileType.icon checkBox.isSelected = fileTypes.contains(fileType.defaultExtension) return container } } }
platform/platform-impl/src/com/intellij/ide/minimap/settings/MinimapConfigurable.kt
203247184
/* * Copyright 2020 Stéphane Baiget * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sbgapps.scoreit.core.widget import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.sbgapps.scoreit.core.ext.inflate class GenericRecyclerViewAdapter(initialItems: List<ItemAdapter> = emptyList()) : RecyclerView.Adapter<BaseViewHolder>() { var items: List<ItemAdapter> = initialItems private set fun updateItems(newItems: List<ItemAdapter>, diffResult: DiffUtil.DiffResult? = null) { items = newItems diffResult?.dispatchUpdatesTo(this) ?: notifyDataSetChanged() } override fun getItemCount(): Int = items.size override fun getItemViewType(position: Int): Int = items[position].layoutId override fun onCreateViewHolder(parent: ViewGroup, @LayoutRes layoutId: Int): BaseViewHolder { val itemView = parent.inflate(layoutId) return items.first { it.layoutId == layoutId }.onCreateViewHolder(itemView) } override fun onBindViewHolder(holder: BaseViewHolder, position: Int) = items[position].onBindViewHolder(holder) }
core/src/main/kotlin/com/sbgapps/scoreit/core/widget/GenericRecyclerViewAdapter.kt
2869261167
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.net.InetAddress import java.net.Socket import java.nio.channels.SocketChannel import javax.net.SocketFactory class ChannelSocketFactory : SocketFactory() { override fun createSocket(): Socket { return SocketChannel.open().socket() } override fun createSocket(host: String, port: Int): Socket = TODO("Not yet implemented") override fun createSocket( host: String, port: Int, localHost: InetAddress, localPort: Int ): Socket = TODO("Not yet implemented") override fun createSocket(host: InetAddress, port: Int): Socket = TODO("Not yet implemented") override fun createSocket( address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int ): Socket = TODO("Not yet implemented") }
okhttp/src/test/java/okhttp3/ChannelSocketFactory.kt
2633380318
package com.mikepenz.iconics.typeface.library.fontawesome import android.content.Context import com.mikepenz.iconics.typeface.ITypeface import com.mikepenz.iconics.typeface.IconicsHolder import com.mikepenz.iconics.typeface.IconicsInitializer class Initializer : androidx.startup.Initializer<ITypeface> { override fun create(context: Context): ITypeface { IconicsHolder.registerFont(FontAwesome) IconicsHolder.registerFont(FontAwesomeBrand) IconicsHolder.registerFont(FontAwesomeRegular) return FontAwesome } override fun dependencies(): List<Class<out androidx.startup.Initializer<*>>> { return listOf(IconicsInitializer::class.java) } }
fontawesome-typeface-library/src/main/java/com/mikepenz/iconics/typeface/library/fontawesome/Initializer.kt
3125831902
package io.fluidsonic.json import java.time.* public object LocalDateTimeJsonCodec : AbstractJsonCodec<LocalDateTime, JsonCodingContext>() { override fun JsonDecoder<JsonCodingContext>.decode(valueType: JsonCodingType<LocalDateTime>): LocalDateTime = readString().let { raw -> try { LocalDateTime.parse(raw) } catch (e: DateTimeException) { invalidValueError("date and time in ISO-8601 format expected, got '$raw'") } } override fun JsonEncoder<JsonCodingContext>.encode(value: LocalDateTime): Unit = writeString(value.toString()) }
coding-jdk8/sources-jvm/codecs/extended/LocalDateTimeJsonCodec.kt
2455695841
// 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.configurationStore import com.intellij.ide.IdeBundle import com.intellij.ide.actions.ImportSettingsFilenameFilter import com.intellij.ide.plugins.PluginManager import com.intellij.ide.startup.StartupActionScriptManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.showOkCancelDialog import com.intellij.openapi.updateSettings.impl.UpdateSettings import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtilRt import com.intellij.util.io.copy import com.intellij.util.io.exists import com.intellij.util.io.inputStream import com.intellij.util.io.isDirectory import java.io.IOException import java.io.InputStream import java.nio.file.Path import java.nio.file.Paths import java.util.zip.ZipException import java.util.zip.ZipInputStream // the class is open for Rider purpose open class ImportSettingsAction : AnAction(), DumbAware { override fun update(e: AnActionEvent) { e.presentation.isEnabled = true } override fun actionPerformed(e: AnActionEvent) { val dataContext = e.dataContext val component = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext) val descriptor = object : FileChooserDescriptor(true, true, true, true, false, false) { override fun isFileSelectable(file: VirtualFile?): Boolean { if (file?.isDirectory == true) { return file.fileSystem.getNioPath(file)?.let { path -> ConfigImportHelper.isConfigDirectory(path) } == true } return super.isFileSelectable(file) } }.apply { title = ConfigurationStoreBundle.message("title.import.file.location") description = ConfigurationStoreBundle.message("prompt.choose.import.file.path") isHideIgnored = false withFileFilter { ConfigImportHelper.isSettingsFile(it) } } chooseSettingsFile(descriptor, PathManager.getConfigPath(), component) { val saveFile = Paths.get(it.path) try { doImport(saveFile) } catch (e1: ZipException) { Messages.showErrorDialog( ConfigurationStoreBundle.message("error.reading.settings.file", saveFile, e1.message), ConfigurationStoreBundle.message("title.invalid.file")) } catch (e1: IOException) { Messages.showErrorDialog(ConfigurationStoreBundle.message("error.reading.settings.file.2", saveFile, e1.message), IdeBundle.message("title.error.reading.file")) } } } protected open fun getExportableComponents(relativePaths: Set<String>): Map<FileSpec, List<ExportableItem>> { return getExportableComponentsMap(true). filterKeys { relativePaths.contains(it.relativePath) } } protected open fun getMarkedComponents(components: Set<ExportableItem>): Set<ExportableItem> = components protected open fun doImport(saveFile: Path) { if (!saveFile.exists()) { Messages.showErrorDialog(ConfigurationStoreBundle.message("error.cannot.find.file", saveFile), ConfigurationStoreBundle.message("title.file.not.found")) return } if (saveFile.isDirectory()) { doImportFromDirectory(saveFile) return } val relativePaths = getPaths(saveFile.inputStream()) if (!relativePaths.contains(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER)) { Messages.showErrorDialog( ConfigurationStoreBundle.message("error.no.settings.to.import", saveFile), ConfigurationStoreBundle.message("title.invalid.file")) return } val configPath = Paths.get(PathManager.getConfigPath()) val dialog = ChooseComponentsToExportDialog( getExportableComponents(relativePaths), false, ConfigurationStoreBundle.message("title.select.components.to.import"), ConfigurationStoreBundle.message("prompt.check.components.to.import")) if (!dialog.showAndGet()) { return } val tempFile = Paths.get(PathManager.getPluginTempPath()).resolve(saveFile.fileName) saveFile.copy(tempFile) val filenameFilter = ImportSettingsFilenameFilter(getRelativeNamesToExtract(getMarkedComponents(dialog.exportableComponents))) StartupActionScriptManager.addActionCommands(listOf(StartupActionScriptManager.UnzipCommand(tempFile, configPath, filenameFilter), StartupActionScriptManager.DeleteCommand(tempFile))) UpdateSettings.getInstance().forceCheckForUpdateAfterRestart() if (confirmRestart(ConfigurationStoreBundle.message("message.settings.imported.successfully", getRestartActionName(), ApplicationNamesInfo.getInstance().fullProductName))) { restart() } } private fun restart() { invokeLater { (ApplicationManager.getApplication() as ApplicationEx).restart(true) } } private fun confirmRestart(@NlsContexts.DialogMessage message: String): Boolean = (Messages.OK == showOkCancelDialog( title = ConfigurationStoreBundle.message("import.settings.confirmation.title"), message = message, okText = getRestartActionName(), icon = Messages.getQuestionIcon() )) @NlsContexts.Button private fun getRestartActionName(): String = if (ApplicationManager.getApplication().isRestartCapable) ConfigurationStoreBundle.message("import.settings.confirmation.button.restart") else ConfigurationStoreBundle.message("import.default.settings.confirmation.button.shutdown") private fun doImportFromDirectory(saveFile: Path) { val confirmationMessage = ConfigurationStoreBundle.message("restore.default.settings.confirmation.message", ConfigBackup.getNextBackupPath(PathManager.getConfigDir())) if (confirmRestart(confirmationMessage)) { CustomConfigMigrationOption.MigrateFromCustomPlace(saveFile).writeConfigMarkerFile() restart() } } private fun getRelativeNamesToExtract(chosenComponents: Set<ExportableItem>): Set<String> { val result = HashSet<String>() for (item in chosenComponents) { result.add(item.fileSpec.relativePath) } result.add(PluginManager.INSTALLED_TXT) return result } } fun getPaths(input: InputStream): Set<String> { val result = mutableSetOf<String>() val zipIn = ZipInputStream(input) zipIn.use { while (true) { val entry = zipIn.nextEntry ?: break var path = entry.name.trimEnd('/') result.add(path) while (true) { path = PathUtilRt.getParentPath(path).takeIf { it.isNotEmpty() } ?: break result.add(path) } } } return result }
platform/configuration-store-impl/src/ImportSettingsAction.kt
3180244543
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.roots.ui.configuration import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.util.ProgressIndicatorBase import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider.SdkInfo import com.intellij.openapi.wm.ex.ProgressIndicatorEx import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import org.jetbrains.concurrency.AsyncPromise import java.util.concurrent.atomic.AtomicReference @ApiStatus.Internal class SdkLookupProviderImpl : SdkLookupProvider { @Volatile private var context: SdkLookupContext? = null override fun newLookupBuilder(): SdkLookupBuilder { return CommonSdkLookupBuilder(lookup = ::lookup) } @TestOnly fun getSdkPromiseForTests() = context?.getSdkPromiseForTests() override fun getSdkInfo(): SdkInfo { return context?.getSdkInfo() ?: SdkInfo.Undefined } override fun getSdk(): Sdk? { return context?.getSdk() } override fun blockingGetSdk(): Sdk? { return context?.blockingGetSdk() } override fun onProgress(progressIndicator: ProgressIndicator) { context?.onProgress(progressIndicator) } private fun lookup(builder: CommonSdkLookupBuilder) { val context = SdkLookupContext() this.context = context context.onProgress(builder.progressIndicator) val progressIndicator = context.progressIndicator ?: ProgressIndicatorBase() val parameters = builder .copy( progressIndicator = progressIndicator, //listeners are merged, so copy is the way to avoid chaining the listeners onSdkNameResolved = { sdk -> context.setSdkInfo(sdk) builder.onSdkNameResolved(sdk) }, onSdkResolved = { sdk -> context.setSdk(sdk) builder.onSdkResolved(sdk) } ) invokeAndWaitIfNeeded { service<SdkLookup>().lookup(parameters) } } private class SdkLookupContext { private val sdk = AsyncPromise<Sdk?>() private val sdkInfo = AtomicReference<SdkInfo>(SdkInfo.Unresolved) var progressIndicator : ProgressIndicator? = null @TestOnly fun getSdkPromiseForTests() = sdk fun getSdkInfo(): SdkInfo = sdkInfo.get() fun getSdk(): Sdk? = if (getSdkInfo() is SdkInfo.Resolved) sdk.get() else null fun blockingGetSdk(): Sdk? = sdk.get() fun onProgress(progressIndicator: ProgressIndicator?) { this.progressIndicator = progressIndicator } fun setSdkInfo(sdk: Sdk?) { when (sdk) { null -> sdkInfo.set(SdkInfo.Unresolved) else -> sdkInfo.set(SdkInfo.Resolving(sdk.name, sdk.versionString, sdk.homePath)) } } fun setSdk(sdk: Sdk?) { when (sdk) { null -> sdkInfo.set(SdkInfo.Undefined) else -> sdkInfo.set(SdkInfo.Resolved(sdk.name, sdk.versionString, sdk.homePath)) } this.sdk.setResult(sdk) } } }
platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/SdkLookupProviderImpl.kt
147431302
package com.masahirosaito.spigot.homes.commands.subcommands import com.masahirosaito.spigot.homes.commands.BaseCommand import com.masahirosaito.spigot.homes.commands.CommandUsage abstract class SubCommand(command: BaseCommand) : BaseCommand { override val name: String = command.name override val description: String = command.description override val commands: List<BaseCommand> = listOf() override val usage: CommandUsage = command.usage }
src/main/kotlin/com/masahirosaito/spigot/homes/commands/subcommands/SubCommand.kt
206427202
// 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.analysis.problemsView.toolWindow import com.intellij.analysis.problemsView.Problem import com.intellij.codeInsight.daemon.impl.SeverityRegistrar import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareToggleAction import com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel.renderSeverity import com.intellij.util.ui.tree.TreeUtil.promiseExpandAll import org.jetbrains.annotations.Nls internal class ProblemFilter(val state: ProblemsViewState) : (Problem) -> Boolean { override fun invoke(problem: Problem): Boolean { val highlighting = problem as? HighlightingProblem ?: return true return !(state.hideBySeverity.contains(highlighting.severity)) } } internal class SeverityFiltersActionGroup : DumbAware, ActionGroup() { override fun getChildren(event: AnActionEvent?): Array<AnAction> { val project = event?.project ?: return AnAction.EMPTY_ARRAY if (project.isDisposed) return AnAction.EMPTY_ARRAY val panel = ProblemsView.getSelectedPanel(project) as? HighlightingPanel ?: return AnAction.EMPTY_ARRAY return SeverityRegistrar.getSeverityRegistrar(project).allSeverities.reversed() .filter { it != HighlightSeverity.INFO && it > HighlightSeverity.INFORMATION && it < HighlightSeverity.ERROR } .map { SeverityFilterAction(ProblemsViewBundle.message("problems.view.highlighting.severity.show", renderSeverity(it)), it.myVal, panel) } .toTypedArray() } } private class SeverityFilterAction(@Nls name: String, val severity: Int, val panel: HighlightingPanel) : DumbAwareToggleAction(name) { override fun isSelected(event: AnActionEvent) = !panel.state.hideBySeverity.contains(severity) override fun setSelected(event: AnActionEvent, selected: Boolean) { val changed = with(panel.state.hideBySeverity) { if (selected) remove(severity) else add(severity) } if (changed) { val wasEmpty = panel.tree.isEmpty panel.state.intIncrementModificationCount() panel.treeModel.structureChanged(null) panel.powerSaveStateChanged() // workaround to expand a root without handle if (wasEmpty) promiseExpandAll(panel.tree) } } }
platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/ProblemFilter.kt
1864395460
// 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.codeInspection.tests.kotlin import com.intellij.codeInspection.UnstableApiUsageInspection import com.intellij.jvm.analysis.JvmAnalysisKtTestsUtil import com.intellij.openapi.vfs.VirtualFileFilter import com.intellij.testFramework.TestDataPath import com.intellij.testFramework.builders.JavaModuleFixtureBuilder import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl import com.intellij.util.PathUtil import org.jetbrains.annotations.ApiStatus @TestDataPath("\$CONTENT_ROOT/testData/codeInspection/unstableApiUsage/experimental") class UnstableApiUsageInspectionTest : JavaCodeInsightFixtureTestCase() { private val inspection = UnstableApiUsageInspection() override fun getBasePath() = "${JvmAnalysisKtTestsUtil.TEST_DATA_PROJECT_RELATIVE_BASE_PATH}/codeInspection/unstableApiUsage/experimental" override fun tuneFixture(moduleBuilder: JavaModuleFixtureBuilder<*>) { moduleBuilder.addLibrary("util", PathUtil.getJarPathForClass(ApiStatus::class.java)) } override fun setUp() { super.setUp() myFixture.enableInspections(inspection) // otherwise assertion in PsiFileImpl ("Access to tree elements not allowed") will not pass (myFixture as CodeInsightTestFixtureImpl).setVirtualFileFilter(VirtualFileFilter.NONE) configureAnnotatedFiles() } private fun configureAnnotatedFiles() { listOf( "annotatedPkg/ClassInAnnotatedPkg.java", "annotatedPkg/package-info.java", "pkg/AnnotatedAnnotation.java", "pkg/AnnotatedClass.java", "pkg/AnnotatedEnum.java", "pkg/NonAnnotatedAnnotation.java", "pkg/NonAnnotatedClass.java", "pkg/NonAnnotatedEnum.java", "pkg/ClassWithExperimentalTypeInSignature.java", "pkg/OwnerOfMembersWithExperimentalTypesInSignature.java" ).forEach { myFixture.copyFileToProject(it) } } fun `test java unstable api usages`() { inspection.myIgnoreInsideImports = false myFixture.testHighlighting("UnstableElementsTest.java") } fun `test java do not report unstable api usages inside import statements`() { inspection.myIgnoreInsideImports = true myFixture.testHighlighting("UnstableElementsIgnoreImportsTest.java") } fun `test java no warnings on access to members of the same file`() { myFixture.testHighlighting("NoWarningsMembersOfTheSameFile.java") } fun `test kotlin no warnings on access to members of the same file`() { myFixture.testHighlighting("NoWarningsMembersOfTheSameFile.kt") } fun `test kotlin unstable api usages`() { inspection.myIgnoreInsideImports = false myFixture.testHighlighting("UnstableElementsTest.kt") } fun `test kotlin do not report unstable api usages inside import statements`() { inspection.myIgnoreInsideImports = true myFixture.testHighlighting("UnstableElementsIgnoreImportsTest.kt") } } @TestDataPath("\$CONTENT_ROOT/testData/codeInspection/unstableApiUsage/scheduledForRemoval") class ScheduledForRemovalApiUsageTest: JavaCodeInsightFixtureTestCase() { private val inspection = UnstableApiUsageInspection() override fun getBasePath() = "${JvmAnalysisKtTestsUtil.TEST_DATA_PROJECT_RELATIVE_BASE_PATH}/codeInspection/unstableApiUsage/scheduledForRemoval" override fun tuneFixture(moduleBuilder: JavaModuleFixtureBuilder<*>) { moduleBuilder.addLibrary("util", PathUtil.getJarPathForClass(ApiStatus::class.java)) } override fun setUp() { super.setUp() // otherwise assertion in PsiFileImpl ("Access to tree elements not allowed") will not pass myFixture.enableInspections(inspection) (myFixture as CodeInsightTestFixtureImpl).setVirtualFileFilter(VirtualFileFilter.NONE) configureAnnotatedFiles() } private fun configureAnnotatedFiles() { listOf( "annotatedPkg/ClassInAnnotatedPkg.java", "annotatedPkg/package-info.java", "pkg/AnnotatedAnnotation.java", "pkg/AnnotatedClass.java", "pkg/AnnotatedEnum.java", "pkg/NonAnnotatedAnnotation.java", "pkg/NonAnnotatedClass.java", "pkg/NonAnnotatedEnum.java", "pkg/ClassWithScheduledForRemovalTypeInSignature.java", "pkg/OwnerOfMembersWithScheduledForRemovalTypesInSignature.java" ).forEach { myFixture.copyFileToProject(it) } } fun testKotlinInspection() { inspection.myIgnoreInsideImports = false myFixture.testHighlighting("ScheduledForRemovalElementsTest.kt") } fun testJavaInspection() { inspection.myIgnoreInsideImports = false myFixture.testHighlighting(true, false, false, "ScheduledForRemovalElementsTest.java") } }
jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/tests/kotlin/UnstableApiUsageInspectionTest.kt
3971360603
// 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 org.jetbrains.ide import com.google.gson.JsonElement import com.google.gson.JsonObject import com.intellij.openapi.Disposable internal class ToolboxUpdateNotificationHandler : ToolboxServiceHandler<ToolboxUpdateNotificationHandler.UpdateNotification> { data class UpdateNotification(val version: String, val build: String) override val requestName: String = "update-notification" override fun parseRequest(request: JsonElement): UpdateNotification { require(request.isJsonObject) { "JSON Object was expected" } val obj = request.asJsonObject val build = obj["build"]?.asString val version = obj["version"]?.asString require(!build.isNullOrBlank()) { "the `build` attribute must not be blank" } require(!version.isNullOrBlank()) { "the `version` attribute must not be blank" } return UpdateNotification(version = version, build = build) } override fun handleToolboxRequest(lifetime: Disposable, request: UpdateNotification, onResult: (JsonElement) -> Unit) { onResult(JsonObject().apply { addProperty("status", "not implemented") }) } }
platform/built-in-server/src/org/jetbrains/ide/ToolboxUpdateNotificationHandler.kt
874636163
package org.mrlem.happycows.ui.screens.splash import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType import org.mrlem.happycows.HappyCowsGame import org.mrlem.happycows.ui.Styles.BACKGROUND_COLOR import org.mrlem.happycows.ui.Styles.LIGHT_ORANGE_COLOR import org.mrlem.happycows.ui.Styles.MASK_COLOR import org.mrlem.happycows.ui.screens.AbstractScreen private const val GRADIENT_SIZE = 256 /** * @author Sébastien Guillemin <seb@mrlem.org> */ class SplashScreen(game: HappyCowsGame) : AbstractScreen(game), SplashNavigation { private val ui = SplashUi() private val animations = SplashAnimations(ui, this) init { stage = ui animations.play() } /////////////////////////////////////////////////////////////////////////// // Screen implementation /////////////////////////////////////////////////////////////////////////// override fun doUpdate(delta: Float) { ui.act(delta) } override fun doRender(delta: Float) { // render top/bottom gradient bars shapeRenderer.internalRenderer.apply { begin(ShapeType.Filled) rect(0f, ui.height / 2 + GRADIENT_SIZE, ui.width, ui.height / 2 - GRADIENT_SIZE, LIGHT_ORANGE_COLOR, LIGHT_ORANGE_COLOR, BACKGROUND_COLOR, BACKGROUND_COLOR) rect(0f, 0f, ui.width, ui.height / 2 - GRADIENT_SIZE, Color.WHITE, Color.WHITE, LIGHT_ORANGE_COLOR, LIGHT_ORANGE_COLOR) end() if (animations.uiAlpha < 1) { MASK_COLOR.a = 1 - animations.uiAlpha Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA) Gdx.gl.glEnable(GL20.GL_BLEND) begin(ShapeType.Filled) rect(0f, 0f, ui.width, ui.height, MASK_COLOR, MASK_COLOR, MASK_COLOR, MASK_COLOR) end() Gdx.gl.glDisable(GL20.GL_BLEND) } } ui.draw() } override fun resize(width: Int, height: Int) { ui.viewport.update(width, height, true) } override fun show() { Gdx.input.isCursorCatched = true } override fun hide() { Gdx.input.isCursorCatched = false } /////////////////////////////////////////////////////////////////////////// // Navigation implementation /////////////////////////////////////////////////////////////////////////// override fun gotoMenu() { game.screen = game.menuScreen } }
core/src/org/mrlem/happycows/ui/screens/splash/SplashScreen.kt
1447705188
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.reactor import kotlinx.coroutines.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.* import kotlinx.coroutines.reactive.* import org.junit.* import org.junit.Test import org.reactivestreams.* import reactor.core.publisher.* import reactor.util.context.* import java.time.Duration.* import java.util.function.* import kotlin.test.* class MonoTest : TestBase() { @Before fun setup() { ignoreLostThreads("timer-", "parallel-") Hooks.onErrorDropped { expectUnreached() } } @Test fun testBasicSuccess() = runBlocking { expect(1) val mono = mono(currentDispatcher()) { expect(4) "OK" } expect(2) mono.subscribe { value -> expect(5) assertEquals("OK", value) } expect(3) yield() // to started coroutine finish(6) } @Test fun testBasicFailure() = runBlocking { expect(1) val mono = mono(currentDispatcher()) { expect(4) throw RuntimeException("OK") } expect(2) mono.subscribe({ expectUnreached() }, { error -> expect(5) assertTrue(error is RuntimeException) assertEquals("OK", error.message) }) expect(3) yield() // to started coroutine finish(6) } @Test fun testBasicEmpty() = runBlocking { expect(1) val mono = mono(currentDispatcher()) { expect(4) null } expect(2) mono.subscribe({}, { throw it }, { expect(5) }) expect(3) yield() // to started coroutine finish(6) } @Test fun testBasicUnsubscribe() = runBlocking { expect(1) val mono = mono(currentDispatcher()) { expect(4) yield() // back to main, will get cancelled expectUnreached() } expect(2) // nothing is called on a disposed mono val sub = mono.subscribe({ expectUnreached() }, { expectUnreached() }) expect(3) yield() // to started coroutine expect(5) sub.dispose() // will cancel coroutine yield() finish(6) } @Test fun testMonoNoWait() { val mono = mono { "OK" } checkMonoValue(mono) { assertEquals("OK", it) } } @Test fun testMonoAwait() = runBlocking { assertEquals("OK", Mono.just("O").awaitSingle() + "K") assertEquals("OK", Mono.just("O").awaitSingleOrNull() + "K") assertFailsWith<NoSuchElementException>{ Mono.empty<String>().awaitSingle() } assertNull(Mono.empty<Int>().awaitSingleOrNull()) } /** Tests that calls to [awaitSingleOrNull] (and, thus, to the rest of such functions) throw [CancellationException] * and unsubscribe from the publisher when their [Job] is cancelled. */ @Test fun testAwaitCancellation() = runTest { expect(1) val mono = mono { delay(Long.MAX_VALUE) }.doOnSubscribe { expect(3) }.doOnCancel { expect(5) } val job = launch(start = CoroutineStart.UNDISPATCHED) { try { expect(2) mono.awaitSingleOrNull() } catch (e: CancellationException) { expect(6) throw e } } expect(4) job.cancelAndJoin() finish(7) } @Test fun testMonoEmitAndAwait() { val mono = mono { Mono.just("O").awaitSingle() + "K" } checkMonoValue(mono) { assertEquals("OK", it) } } @Test fun testMonoWithDelay() { val mono = mono { Flux.just("O").delayElements(ofMillis(50)).awaitSingle() + "K" } checkMonoValue(mono) { assertEquals("OK", it) } } @Test fun testMonoException() { val mono = mono { Flux.just("O", "K").awaitSingle() + "K" } checkErroneous(mono) { assert(it is IllegalArgumentException) } } @Test fun testAwaitFirst() { val mono = mono { Flux.just("O", "#").awaitFirst() + "K" } checkMonoValue(mono) { assertEquals("OK", it) } } @Test fun testAwaitLast() { val mono = mono { Flux.just("#", "O").awaitLast() + "K" } checkMonoValue(mono) { assertEquals("OK", it) } } @Test fun testExceptionFromFlux() { val mono = mono { try { Flux.error<String>(RuntimeException("O")).awaitFirst() } catch (e: RuntimeException) { Flux.just(e.message!!).awaitLast() + "K" } } checkMonoValue(mono) { assertEquals("OK", it) } } @Test fun testExceptionFromCoroutine() { val mono = mono<String> { throw IllegalStateException(Flux.just("O").awaitSingle() + "K") } checkErroneous(mono) { assert(it is IllegalStateException) assertEquals("OK", it.message) } } @Test fun testSuppressedException() = runTest { val mono = mono(currentDispatcher()) { launch(start = CoroutineStart.ATOMIC) { throw TestException() // child coroutine fails } try { delay(Long.MAX_VALUE) } finally { throw TestException2() // but parent throws another exception while cleaning up } } try { mono.awaitSingle() expectUnreached() } catch (e: TestException) { assertTrue(e.suppressed[0] is TestException2) } } @Test fun testUnhandledException() = runTest { expect(1) var subscription: Subscription? = null val handler = BiFunction<Throwable, Any?, Throwable> { t, _ -> assertTrue(t is TestException) expect(5) t } val mono = mono(currentDispatcher()) { expect(4) subscription!!.cancel() // cancel our own subscription, so that delay will get cancelled try { delay(Long.MAX_VALUE) } finally { throw TestException() // would not be able to handle it since mono is disposed } }.contextWrite { Context.of("reactor.onOperatorError.local", handler) } mono.subscribe(object : Subscriber<Unit> { override fun onSubscribe(s: Subscription) { expect(2) subscription = s } override fun onNext(t: Unit?) { expectUnreached() } override fun onComplete() { expectUnreached() } override fun onError(t: Throwable) { expectUnreached() } }) expect(3) yield() // run coroutine finish(6) } @Test fun testIllegalArgumentException() { assertFailsWith<IllegalArgumentException> { mono(Job()) { } } } @Test fun testExceptionAfterCancellation() = runTest { // Test exception is not reported to global handler Flux .interval(ofMillis(1)) .switchMap { mono(coroutineContext) { timeBomb().awaitSingle() } } .onErrorReturn({ expect(1) true }, 42) .blockLast() finish(2) } private fun timeBomb() = Mono.delay(ofMillis(1)).doOnSuccess { throw Exception("something went wrong") } @Test fun testLeakedException() = runBlocking { // Test exception is not reported to global handler val flow = mono<Unit> { throw TestException() }.toFlux().asFlow() repeat(10000) { combine(flow, flow) { _, _ -> } .catch {} .collect { } } } /** Test that cancelling a [mono] due to a timeout does throw an exception. */ @Test fun testTimeout() { val mono = mono { withTimeout(1) { delay(100) } } try { mono.doOnSubscribe { expect(1) } .doOnNext { expectUnreached() } .doOnSuccess { expectUnreached() } .doOnError { expect(2) } .doOnCancel { expectUnreached() } .block() } catch (e: CancellationException) { expect(3) } finish(4) } /** Test that when the reason for cancellation of a [mono] is that the downstream doesn't want its results anymore, * this is considered normal behavior and exceptions are not propagated. */ @Test fun testDownstreamCancellationDoesNotThrow() = runTest { var i = 0 /** Attach a hook that handles exceptions from publishers that are known to be disposed of. We don't expect it * to be fired in this case, as the reason for the publisher in this test to accept an exception is simply * cancellation from the downstream. */ Hooks.onOperatorError("testDownstreamCancellationDoesNotThrow") { t, a -> expectUnreached() t } /** A Mono that doesn't emit a value and instead waits indefinitely. */ val mono = mono(Dispatchers.Unconfined) { expect(5 * i + 3); delay(Long.MAX_VALUE) } .doOnSubscribe { expect(5 * i + 2) } .doOnNext { expectUnreached() } .doOnSuccess { expectUnreached() } .doOnError { expectUnreached() } .doOnCancel { expect(5 * i + 4) } val n = 1000 repeat(n) { i = it expect(5 * i + 1) mono.awaitCancelAndJoin() expect(5 * i + 5) } finish(5 * n + 1) Hooks.resetOnOperatorError("testDownstreamCancellationDoesNotThrow") } /** Test that, when [Mono] is cancelled by the downstream and throws during handling the cancellation, the resulting * error is propagated to [Hooks.onOperatorError]. */ @Test fun testRethrowingDownstreamCancellation() = runTest { var i = 0 /** Attach a hook that handles exceptions from publishers that are known to be disposed of. We expect it * to be fired in this case. */ Hooks.onOperatorError("testDownstreamCancellationDoesNotThrow") { t, a -> expect(i * 6 + 5) t } /** A Mono that doesn't emit a value and instead waits indefinitely, and, when cancelled, throws. */ val mono = mono(Dispatchers.Unconfined) { expect(i * 6 + 3) try { delay(Long.MAX_VALUE) } catch (e: CancellationException) { throw TestException() } } .doOnSubscribe { expect(i * 6 + 2) } .doOnNext { expectUnreached() } .doOnSuccess { expectUnreached() } .doOnError { expectUnreached() } .doOnCancel { expect(i * 6 + 4) } val n = 1000 repeat(n) { i = it expect(i * 6 + 1) mono.awaitCancelAndJoin() expect(i * 6 + 6) } finish(n * 6 + 1) Hooks.resetOnOperatorError("testDownstreamCancellationDoesNotThrow") } /** Run the given [Mono], cancel it, wait for the cancellation handler to finish, and return only then. * * Will not work in the general case, but here, when the publisher uses [Dispatchers.Unconfined], this seems to * ensure that the cancellation handler will have nowhere to execute but serially with the cancellation. */ private suspend fun <T> Mono<T>.awaitCancelAndJoin() = coroutineScope { async(start = CoroutineStart.UNDISPATCHED) { awaitSingleOrNull() }.cancelAndJoin() } }
reactive/kotlinx-coroutines-reactor/test/MonoTest.kt
2381583991
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow.internal import kotlinx.coroutines.* import kotlinx.coroutines.flow.* internal actual class AbortFlowException actual constructor( actual val owner: FlowCollector<*> ) : CancellationException("Flow was aborted, no more elements needed") internal actual class ChildCancelledException : CancellationException("Child of the scoped flow was cancelled")
kotlinx-coroutines-core/js/src/flow/internal/FlowExceptions.kt
66144458
package com.agoda.sample.screen import com.agoda.kakao.screen.Screen import com.agoda.kakao.web.KWebView import com.agoda.sample.R class TestWebScreen : Screen<TestWebScreen>() { val webView = KWebView { withId(R.id.webView) } }
sample/src/androidTest/kotlin/com/agoda/sample/screen/TestWebScreen.kt
2603944604
// 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.execution.configuration import com.intellij.execution.ExecutionException import com.intellij.execution.Executor import com.intellij.execution.Location import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.RunConfigurationBase import com.intellij.execution.configurations.RunnerSettings import com.intellij.execution.process.ProcessHandler import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.options.ExtendableSettingsEditor import com.intellij.openapi.options.ExtensionSettingsEditor import com.intellij.openapi.options.SettingsEditorGroup import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.Key import com.intellij.openapi.util.WriteExternalException import com.intellij.util.SmartList import gnu.trove.THashMap import org.jdom.Element import java.util.* private val RUN_EXTENSIONS = Key.create<List<Element>>("run.extension.elements") private const val EXT_ID_ATTR = "ID" private const val EXTENSION_ROOT_ATTR = "EXTENSION" open class RunConfigurationExtensionsManager<U : RunConfigurationBase<*>, T : RunConfigurationExtensionBase<U>>(val extensionPoint: ExtensionPointName<T>) { protected open val idAttrName = EXT_ID_ATTR protected open val extensionRootAttr = EXTENSION_ROOT_ATTR fun readExternal(configuration: U, parentNode: Element) { val children = parentNode.getChildren(extensionRootAttr) if (children.isEmpty()) { return } val extensions = THashMap<String, T>() processApplicableExtensions(configuration) { extensions.put(it.serializationId, it) } // if some of extensions settings weren't found we should just keep it because some plugin with extension // may be turned off var hasUnknownExtension = false for (element in children) { val extension = extensions.remove(element.getAttributeValue(idAttrName)) if (extension == null) { hasUnknownExtension = true } else { extension.readExternal(configuration, element) } } if (hasUnknownExtension) { val copy = SmartList<Element>() for (child in children) { copy.add(JDOMUtil.internElement(child)) } configuration.putCopyableUserData(RUN_EXTENSIONS, copy) } } fun writeExternal(configuration: U, parentNode: Element) { val map = TreeMap<String, Element>() val elements = configuration.getCopyableUserData(RUN_EXTENSIONS) if (elements != null) { for (element in elements) { map.put(element.getAttributeValue(idAttrName), element.clone()) } } processApplicableExtensions(configuration) { extension -> val element = Element(extensionRootAttr) element.setAttribute(idAttrName, extension.serializationId) try { extension.writeExternal(configuration, element) } catch (ignored: WriteExternalException) { return@processApplicableExtensions } if (element.content.isNotEmpty() || element.attributes.size > 1) { map.put(extension.serializationId, element) } } for (values in map.values) { parentNode.addContent(values) } } fun <V : U> appendEditors(configuration: U, group: SettingsEditorGroup<V>) { appendEditors(configuration, group, null) } /** * Appends {@code SettingsEditor} to group or to {@param mainEditor} (if editor implements marker interface {@code ExtensionSettingsEditor} */ fun <V : U> appendEditors(configuration: U, group: SettingsEditorGroup<V>, mainEditor: ExtendableSettingsEditor<V>?) { processApplicableExtensions(configuration) { @Suppress("UNCHECKED_CAST") val editor = it.createEditor(configuration as V) ?: return@processApplicableExtensions if (mainEditor != null && editor is ExtensionSettingsEditor) { mainEditor.addExtensionEditor(editor) } else { group.addEditor(it.editorTitle, editor) } } } @Throws(Exception::class) fun validateConfiguration(configuration: U, isExecution: Boolean) { // only for enabled extensions processEnabledExtensions(configuration, null) { it.validateConfiguration(configuration, isExecution) } } fun extendCreatedConfiguration(configuration: U, location: Location<*>) { processApplicableExtensions(configuration) { it.extendCreatedConfiguration(configuration, location) } } fun extendTemplateConfiguration(configuration: U) { processApplicableExtensions(configuration) { it.extendTemplateConfiguration(configuration) } } @Throws(ExecutionException::class) open fun patchCommandLine(configuration: U, runnerSettings: RunnerSettings?, cmdLine: GeneralCommandLine, runnerId: String, executor: Executor) { // only for enabled extensions processEnabledExtensions(configuration, runnerSettings) { it.patchCommandLine(configuration, runnerSettings, cmdLine, runnerId, executor) } } @Throws(ExecutionException::class) open fun patchCommandLine(configuration: U, runnerSettings: RunnerSettings?, cmdLine: GeneralCommandLine, runnerId: String) { // only for enabled extensions processEnabledExtensions(configuration, runnerSettings) { it.patchCommandLine(configuration, runnerSettings, cmdLine, runnerId) } } open fun attachExtensionsToProcess(configuration: U, handler: ProcessHandler, runnerSettings: RunnerSettings?) { // only for enabled extensions processEnabledExtensions(configuration, runnerSettings) { it.attachToProcess(configuration, handler, runnerSettings) } } /** * Consider to use processApplicableExtensions. */ protected fun getApplicableExtensions(configuration: U): MutableList<T> { val extensions = SmartList<T>() processApplicableExtensions(configuration) { extensions.add(it) } return extensions } protected inline fun processApplicableExtensions(configuration: U, handler: (T) -> Unit) { for (extension in extensionPoint.iterable) { if (extension.isApplicableFor(configuration)) { handler(extension) } } } protected inline fun processEnabledExtensions(configuration: U, runnerSettings: RunnerSettings?, handler: (T) -> Unit) { for (extension in extensionPoint.iterable) { if (extension.isApplicableFor(configuration) && extension.isEnabledFor(configuration, runnerSettings)) { handler(extension) } } } }
platform/lang-api/src/com/intellij/execution/configuration/RunConfigurationExtensionsManager.kt
1311083041
// 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.execution.target import com.intellij.execution.configurations.RuntimeConfigurationException import com.intellij.execution.target.ContributedConfigurationBase.Companion.getTypeImpl import com.intellij.execution.target.LanguageRuntimeType.Companion.EXTENSION_NAME import com.intellij.execution.target.LanguageRuntimeType.VolumeDescriptor import com.intellij.execution.target.LanguageRuntimeType.VolumeType import com.intellij.execution.target.TargetEnvironment.TargetPath import com.intellij.execution.target.TargetEnvironment.UploadRoot import com.intellij.execution.target.TargetEnvironmentType.TargetSpecificVolumeData import com.intellij.util.text.nullize import java.nio.file.Path /** * Base class for configuration instances contributed by the ["com.intellij.executionTargetLanguageRuntimeType"][EXTENSION_NAME] extension point. * <p/> * Language configurations may define separate volume types to group together several related file transfers, and allow user to configure the * target-specific remote paths for each group, along with the target-specific options for every transfer. */ abstract class LanguageRuntimeConfiguration(typeId: String) : ContributedConfigurationBase(typeId, EXTENSION_NAME) { private val volumeTargetSpecificBits = mutableMapOf<VolumeType, TargetSpecificVolumeData>() private val volumePaths = mutableMapOf<VolumeType, String>() fun createUploadRoot(descriptor: VolumeDescriptor, localRootPath: Path): UploadRoot { return UploadRoot(localRootPath, getTargetPath(descriptor)).also { it.volumeData = getTargetSpecificData(descriptor) } } fun getTargetSpecificData(volumeDescriptor: VolumeDescriptor): TargetSpecificVolumeData? { return volumeTargetSpecificBits[volumeDescriptor.type] } fun setTargetSpecificData(volumeDescriptor: VolumeDescriptor, data: TargetSpecificVolumeData?) { volumeTargetSpecificBits.putOrClear(volumeDescriptor.type, data) } fun getTargetPathValue(volumeDescriptor: VolumeDescriptor): String? = volumePaths[volumeDescriptor.type] fun getTargetPath(volumeDescriptor: VolumeDescriptor): TargetPath { return TargetPath.Temporary(hint = volumeDescriptor.type.id, parentDirectory = getTargetPathValue(volumeDescriptor)?.nullize() ?: volumeDescriptor.defaultPath.nullize()) } fun setTargetPath(volumeDescriptor: VolumeDescriptor, targetPath: String?) { volumePaths.putOrClear(volumeDescriptor.type, targetPath) } @Throws(RuntimeConfigurationException::class) open fun validateConfiguration() = Unit companion object { private fun <K, V> MutableMap<K, V>.putOrClear(key: K, value: V?) { if (value == null) { this.remove(key) } else { this[key] = value } } } } fun <C : LanguageRuntimeConfiguration, T : LanguageRuntimeType<C>> C.getRuntimeType(): T = this.getTypeImpl()
platform/lang-api/src/com/intellij/execution/target/LanguageRuntimeConfiguration.kt
84200783
// 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.codeInsight.hints.presentation import com.intellij.codeInsight.hints.dimension import com.intellij.openapi.editor.markup.TextAttributes import java.awt.Dimension import java.awt.Graphics2D import java.awt.Point import java.awt.Rectangle import java.awt.event.MouseEvent class SequencePresentation(val presentations: List<InlayPresentation>) : BasePresentation() { init { if (presentations.isEmpty()) throw IllegalArgumentException() for (presentation in presentations) { presentation.addListener(InternalListener(presentation)) } } fun calcDimensions() { width = presentations.sumBy { it.width } height = presentations.maxBy { it.height }!!.height } override var width: Int = 0 override var height: Int = 0 init { calcDimensions() } private var presentationUnderCursor: InlayPresentation? = null override fun paint(g: Graphics2D, attributes: TextAttributes) { var xOffset = 0 try { for (presentation in presentations) { presentation.paint(g, attributes) xOffset += presentation.width g.translate(presentation.width, 0) } } finally { g.translate(-xOffset, 0) } } private fun handleMouse( original: Point, action: (InlayPresentation, Point) -> Unit ) { val x = original.x val y = original.y if (x < 0 || x >= width || y < 0 || y >= height) return var xOffset = 0 for (presentation in presentations) { val presentationWidth = presentation.width if (x < xOffset + presentationWidth) { val translated = original.translateNew(-xOffset, 0) action(presentation, translated) return } xOffset += presentationWidth } } override fun mouseClicked(event: MouseEvent, translated: Point) { handleMouse(translated) { presentation, point -> presentation.mouseClicked(event, point) } } override fun mouseMoved(event: MouseEvent, translated: Point) { handleMouse(translated) { presentation, point -> if (presentation != presentationUnderCursor) { presentationUnderCursor?.mouseExited() presentationUnderCursor = presentation } presentation.mouseMoved(event, point) } } override fun mouseExited() { try { presentationUnderCursor?.mouseExited() } finally { presentationUnderCursor = null } } override fun updateState(previousPresentation: InlayPresentation): Boolean { if (previousPresentation !is SequencePresentation) return true if (previousPresentation.presentations.size != presentations.size) return true val previousPresentations = previousPresentation.presentations var changed = false for ((index, presentation) in presentations.withIndex()) { if (presentation.updateState(previousPresentations[index])) { changed = true } } return changed } override fun toString(): String = presentations.joinToString(" ", "[", "]") { "$it" } inner class InternalListener(private val currentPresentation: InlayPresentation) : PresentationListener { override fun contentChanged(area: Rectangle) { area.add(shiftOfCurrent(), 0) this@SequencePresentation.fireContentChanged(area) } override fun sizeChanged(previous: Dimension, current: Dimension) { val old = dimension() calcDimensions() val new = dimension() this@SequencePresentation.fireSizeChanged(old, new) } private fun shiftOfCurrent(): Int { var shift = 0 for (presentation in presentations) { if (presentation === currentPresentation) { return shift } shift += presentation.width } throw IllegalStateException() } } }
platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/SequencePresentation.kt
786365648
// 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.psi.impl import com.intellij.ide.highlighter.JavaFileType import com.intellij.lang.LighterASTNode import com.intellij.lang.java.JavaParserDefinition import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.JavaPsiFacade import com.intellij.psi.JavaTokenType import com.intellij.psi.PsiField import com.intellij.psi.impl.cache.RecordUtil import com.intellij.psi.impl.source.JavaLightStubBuilder import com.intellij.psi.impl.source.JavaLightTreeUtil import com.intellij.psi.impl.source.PsiMethodImpl import com.intellij.psi.impl.source.tree.ElementType import com.intellij.psi.impl.source.tree.JavaElementType import com.intellij.psi.impl.source.tree.LightTreeUtil import com.intellij.psi.impl.source.tree.RecursiveLighterASTNodeWalkingVisitor import com.intellij.psi.stub.JavaStubImplUtil import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.PropertyUtil import com.intellij.psi.util.PropertyUtilBase import com.intellij.util.indexing.* import com.intellij.util.io.DataExternalizer import com.intellij.util.io.DataInputOutputUtil import com.intellij.util.io.EnumeratorStringDescriptor import gnu.trove.TIntObjectHashMap import java.io.DataInput import java.io.DataOutput private val indexId = ID.create<Int, TIntObjectHashMap<PropertyIndexValue>>("java.simple.property") private object EmptyTIntObjectHashMap : TIntObjectHashMap<PropertyIndexValue>() { override fun put(key: Int, value: PropertyIndexValue?)= throw UnsupportedOperationException() } fun getFieldOfGetter(method: PsiMethodImpl): PsiField? = resolveFieldFromIndexValue(method, true) fun getFieldOfSetter(method: PsiMethodImpl): PsiField? = resolveFieldFromIndexValue(method, false) private fun resolveFieldFromIndexValue(method: PsiMethodImpl, isGetter: Boolean): PsiField? { val id = JavaStubImplUtil.getMethodStubIndex(method) if (id != -1) { val virtualFile = method.containingFile.virtualFile val data = FileBasedIndex.getInstance().getFileData(indexId, virtualFile, method.project) return data.values.firstOrNull()?.get(id)?.let { indexValue -> if (isGetter != indexValue.getter) return null val psiClass = method.containingClass val project = psiClass!!.project val expr = JavaPsiFacade.getElementFactory(project).createExpressionFromText(indexValue.propertyRefText, psiClass) return PropertyUtil.getSimplyReturnedField(expr) } } return null } data class PropertyIndexValue(val propertyRefText: String, val getter: Boolean) class JavaSimplePropertyIndex : SingleEntryFileBasedIndexExtension<TIntObjectHashMap<PropertyIndexValue>>() { private val allowedExpressions by lazy { TokenSet.create(ElementType.REFERENCE_EXPRESSION, ElementType.THIS_EXPRESSION, ElementType.SUPER_EXPRESSION) } override fun getIndexer(): SingleEntryIndexer<TIntObjectHashMap<PropertyIndexValue>> = object : SingleEntryIndexer<TIntObjectHashMap<PropertyIndexValue>>(false) { override fun computeValue(inputData: FileContent): TIntObjectHashMap<PropertyIndexValue>? { var result: TIntObjectHashMap<PropertyIndexValue>? = null val tree = (inputData as PsiDependentFileContent).lighterAST object : RecursiveLighterASTNodeWalkingVisitor(tree) { var methodIndex = 0 override fun visitNode(element: LighterASTNode) { if (JavaLightStubBuilder.isCodeBlockWithoutStubs(element)) return if (element.tokenType === JavaElementType.METHOD) { extractProperty(element)?.let { if (result == null) { result = TIntObjectHashMap<PropertyIndexValue>() } result!!.put(methodIndex, it) } methodIndex++ } super.visitNode(element) } private fun extractProperty(method: LighterASTNode): PropertyIndexValue? { var isConstructor = true var isGetter = true var isBooleanReturnType = false var isVoidReturnType = false var setterParameterName: String? = null var refText: String? = null for (child in tree.getChildren(method)) { when (child.tokenType) { JavaElementType.TYPE -> { val children = tree.getChildren(child) if (children.size != 1) return null val typeElement = children[0] if (typeElement.tokenType == JavaTokenType.VOID_KEYWORD) isVoidReturnType = true if (typeElement.tokenType == JavaTokenType.BOOLEAN_KEYWORD) isBooleanReturnType = true isConstructor = false } JavaElementType.PARAMETER_LIST -> { if (isGetter) { if (LightTreeUtil.firstChildOfType(tree, child, JavaElementType.PARAMETER) != null) return null } else { val parameters = LightTreeUtil.getChildrenOfType(tree, child, JavaElementType.PARAMETER) if (parameters.size != 1) return null setterParameterName = JavaLightTreeUtil.getNameIdentifierText(tree, parameters[0]) if (setterParameterName == null) return null } } JavaElementType.CODE_BLOCK -> { refText = if (isGetter) getGetterPropertyRefText(child) else getSetterPropertyRefText(child, setterParameterName!!) if (refText == null) return null } JavaTokenType.IDENTIFIER -> { if (isConstructor) return null val name = RecordUtil.intern(tree.charTable, child) val flavour = PropertyUtil.getMethodNameGetterFlavour(name) when (flavour) { PropertyUtilBase.GetterFlavour.NOT_A_GETTER -> { if (PropertyUtil.isSetterName(name)) { isGetter = false } else { return null } } PropertyUtilBase.GetterFlavour.BOOLEAN -> if (!isBooleanReturnType) return null else -> { } } if (isVoidReturnType && isGetter) return null } } } return refText?.let { PropertyIndexValue(it, isGetter) } } private fun getSetterPropertyRefText(codeBlock: LighterASTNode, setterParameterName: String): String? { val assignment = tree .getChildren(codeBlock) .singleOrNull { ElementType.JAVA_STATEMENT_BIT_SET.contains(it.tokenType) } ?.takeIf { it.tokenType == JavaElementType.EXPRESSION_STATEMENT } ?.let { LightTreeUtil.firstChildOfType(tree, it, JavaElementType.ASSIGNMENT_EXPRESSION) } if (assignment == null || LightTreeUtil.firstChildOfType(tree, assignment, JavaTokenType.EQ) == null) return null val operands = LightTreeUtil.getChildrenOfType(tree, assignment, ElementType.EXPRESSION_BIT_SET) if (operands.size != 2 || LightTreeUtil.toFilteredString(tree, operands[1], null) != setterParameterName) return null val lhsText = LightTreeUtil.toFilteredString(tree, operands[0], null) if (lhsText == setterParameterName) return null return lhsText } private fun getGetterPropertyRefText(codeBlock: LighterASTNode): String? { return tree .getChildren(codeBlock) .singleOrNull { ElementType.JAVA_STATEMENT_BIT_SET.contains(it.tokenType) } ?.takeIf { it.tokenType == JavaElementType.RETURN_STATEMENT} ?.let { LightTreeUtil.firstChildOfType(tree, it, allowedExpressions) } ?.takeIf(this::checkQualifiers) ?.let { LightTreeUtil.toFilteredString(tree, it, null) } } private fun checkQualifiers(expression: LighterASTNode): Boolean { if (!allowedExpressions.contains(expression.tokenType)) { return false } val qualifier = JavaLightTreeUtil.findExpressionChild(tree, expression) return qualifier == null || checkQualifiers(qualifier) } }.visitNode(tree.root) return result } } override fun getValueExternalizer(): DataExternalizer<TIntObjectHashMap<PropertyIndexValue>> = object: DataExternalizer<TIntObjectHashMap<PropertyIndexValue>> { override fun save(out: DataOutput, values: TIntObjectHashMap<PropertyIndexValue>) { DataInputOutputUtil.writeINT(out, values.size()) values.forEachEntry { id, value -> DataInputOutputUtil.writeINT(out, id) EnumeratorStringDescriptor.INSTANCE.save(out, value.propertyRefText) out.writeBoolean(value.getter) return@forEachEntry true } } override fun read(input: DataInput): TIntObjectHashMap<PropertyIndexValue> { val size = DataInputOutputUtil.readINT(input) if (size == 0) return EmptyTIntObjectHashMap val values = TIntObjectHashMap<PropertyIndexValue>(size) repeat(size) { val id = DataInputOutputUtil.readINT(input) val value = PropertyIndexValue(EnumeratorStringDescriptor.INSTANCE.read(input), input.readBoolean()) values.put(id, value) } return values } } override fun getName(): ID<Int, TIntObjectHashMap<PropertyIndexValue>> = indexId override fun getInputFilter(): FileBasedIndex.InputFilter = object : DefaultFileTypeSpecificInputFilter(JavaFileType.INSTANCE) { override fun acceptInput(file: VirtualFile): Boolean = JavaParserDefinition.JAVA_FILE.shouldBuildStubFor(file) } override fun getVersion(): Int = 3 }
java/java-indexing-impl/src/com/intellij/psi/impl/JavaSimplePropertyIndex.kt
3208541766
import kotlin.test.* val data = listOf("foo", "bar") val empty = listOf<String>() fun box() { assertEquals(-1, empty.lastIndex) assertEquals(1, data.lastIndex) }
backend.native/tests/external/stdlib/collections/ListSpecificTest/lastIndex.kt
1928256185
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME // FILE: Test.java public class Test { public static String invokeMethodWithPublicField() { C c = new C(); return c.foo; } } // FILE: simple.kt class C { @JvmField public val foo: String = "OK" } fun box(): String { return Test.invokeMethodWithPublicField() }
backend.native/tests/external/codegen/box/jvmField/simpleMemberProperty.kt
2060931554
// IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.KClass import kotlin.test.assertEquals annotation class Anno( val klass: KClass<*>, val kClasses: Array<KClass<*>>, vararg val kClassesVararg: KClass<*> ) @Anno(String::class, arrayOf(Int::class), Double::class) fun foo() {} fun Anno.checkReference(expected: Any?, x: Anno.() -> Any?) { assertEquals(expected, x()) } fun Anno.checkReferenceArray(expected: Any?, x: Anno.() -> Array<out Any?>) { assertEquals(expected, x()[0]) } fun checkBoundReference(expected: Any?, x: () -> Any?) { assertEquals(expected, x()) } fun checkBoundReferenceArray(expected: Any?, x: () -> Array<out Any?>) { assertEquals(expected, x()[0]) } fun box(): String { val k = ::foo.annotations.single() as Anno k.checkReference(String::class, Anno::klass) k.checkReferenceArray(Int::class, Anno::kClasses) k.checkReferenceArray(Double::class, Anno::kClassesVararg) checkBoundReference(String::class, k::klass) checkBoundReferenceArray(Int::class, k::kClasses) checkBoundReferenceArray(Double::class, k::kClassesVararg) return "OK" }
backend.native/tests/external/codegen/box/reflection/kClassInAnnotation/wrappingForCallableReferences.kt
3892979100
/* * Copyright 2010-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.kotlin.backend.konan.optimizations import org.jetbrains.kotlin.backend.konan.DirectedGraph import org.jetbrains.kotlin.backend.konan.DirectedGraphNode import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.KonanConfigKeys import org.jetbrains.kotlin.backend.konan.llvm.findMainEntryPoint import org.jetbrains.kotlin.konan.target.CompilerOutputKind internal class CallGraphNode(val graph: CallGraph, val symbol: DataFlowIR.FunctionSymbol) : DirectedGraphNode<DataFlowIR.FunctionSymbol> { override val key get() = symbol override val directEdges: List<DataFlowIR.FunctionSymbol> by lazy { graph.directEdges[symbol]!!.callSites .map { it.actualCallee } .filter { graph.reversedEdges.containsKey(it) } } override val reversedEdges: List<DataFlowIR.FunctionSymbol> by lazy { graph.reversedEdges[symbol]!! } class CallSite(val call: DataFlowIR.Node.Call, val actualCallee: DataFlowIR.FunctionSymbol) val callSites = mutableListOf<CallSite>() } internal class CallGraph(val directEdges: Map<DataFlowIR.FunctionSymbol, CallGraphNode>, val reversedEdges: Map<DataFlowIR.FunctionSymbol, MutableList<DataFlowIR.FunctionSymbol>>) : DirectedGraph<DataFlowIR.FunctionSymbol, CallGraphNode> { override val nodes get() = directEdges.values override fun get(key: DataFlowIR.FunctionSymbol) = directEdges[key]!! fun addEdge(caller: DataFlowIR.FunctionSymbol, callSite: CallGraphNode.CallSite) { directEdges[caller]!!.callSites += callSite reversedEdges[callSite.actualCallee]?.add(caller) } } internal class CallGraphBuilder(val context: Context, val moduleDFG: ModuleDFG, val externalModulesDFG: ExternalModulesDFG) { private val DEBUG = 0 private inline fun DEBUG_OUTPUT(severity: Int, block: () -> Unit) { if (DEBUG > severity) block() } private val hasMain = context.config.configuration.get(KonanConfigKeys.PRODUCE) == CompilerOutputKind.PROGRAM private val symbolTable = moduleDFG.symbolTable private fun DataFlowIR.Type.resolved(): DataFlowIR.Type.Declared { if (this is DataFlowIR.Type.Declared) return this val hash = (this as DataFlowIR.Type.External).hash return externalModulesDFG.publicTypes[hash] ?: error("Unable to resolve exported type $hash") } private fun DataFlowIR.FunctionSymbol.resolved(): DataFlowIR.FunctionSymbol { if (this is DataFlowIR.FunctionSymbol.External) return externalModulesDFG.publicFunctions[this.hash] ?: this return this } private fun DataFlowIR.Type.Declared.isSubtypeOf(other: DataFlowIR.Type.Declared): Boolean { return this == other || this.superTypes.any { it.resolved().isSubtypeOf(other) } } private val directEdges = mutableMapOf<DataFlowIR.FunctionSymbol, CallGraphNode>() private val reversedEdges = mutableMapOf<DataFlowIR.FunctionSymbol, MutableList<DataFlowIR.FunctionSymbol>>() private val callGraph = CallGraph(directEdges, reversedEdges) fun build(): CallGraph { val rootSet = if (hasMain) { listOf(symbolTable.mapFunction(findMainEntryPoint(context)!!).resolved()) + moduleDFG.functions .filter { it.value.isGlobalInitializer } .map { it.key } } else { moduleDFG.functions.keys.filterIsInstance<DataFlowIR.FunctionSymbol.Public>() } @Suppress("LoopToCallChain") for (symbol in rootSet) { if (!directEdges.containsKey(symbol)) dfs(symbol) } return callGraph } private fun dfs(symbol: DataFlowIR.FunctionSymbol) { val node = CallGraphNode(callGraph, symbol) directEdges.put(symbol, node) val list = mutableListOf<DataFlowIR.FunctionSymbol>() reversedEdges.put(symbol, list) val function = moduleDFG.functions[symbol] ?: externalModulesDFG.functionDFGs[symbol] val body = function!!.body body.nodes.filterIsInstance<DataFlowIR.Node.Call>() .forEach { val callee = it.callee.resolved() callGraph.addEdge(symbol, CallGraphNode.CallSite(it, callee)) if (callee is DataFlowIR.FunctionSymbol.Declared && it !is DataFlowIR.Node.VirtualCall && !directEdges.containsKey(callee)) dfs(callee) } } }
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/optimizations/CallGraphBuilder.kt
2551257815
class My { lateinit var x: String private set fun init(arg: String, f: (String) -> String) { x = f(arg) } } fun box(): String { val my = My() my.init("O") { it + "K" } return my.x }
backend.native/tests/external/codegen/box/properties/lateinit/privateSetterFromLambda.kt
666260470
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.chromeos.videocompositionsample.presentation.tools.schedulers import dev.chromeos.videocompositionsample.domain.schedulers.IObserverSchedulerProvider import dev.chromeos.videocompositionsample.domain.schedulers.ISchedulerProvider import dev.chromeos.videocompositionsample.domain.schedulers.IWorkSchedulerProvider import io.reactivex.Scheduler import javax.inject.Inject class SchedulerProvider @Inject constructor(private val workProvider: IWorkSchedulerProvider, private val observerProvider: IObserverSchedulerProvider ) : ISchedulerProvider { override fun main(): Scheduler { return observerProvider.get() } override fun background(): Scheduler { return workProvider.get() } }
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/tools/schedulers/SchedulerProvider.kt
244146490
// 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.java.ift.lesson.navigation import com.intellij.codeInsight.CodeInsightBundle import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.java.analysis.JavaAnalysisBundle import com.intellij.java.ift.JavaLessonsBundle import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.content.BaseLabel import com.intellij.ui.InplaceButton import com.intellij.ui.UIBundle import training.dsl.* import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.learn.course.KLesson class JavaInheritanceHierarchyLesson : KLesson("java.inheritance.hierarchy.lesson", JavaLessonsBundle.message("java.inheritance.hierarchy.lesson.name")) { override val existedFile: String = "src/InheritanceHierarchySample.java" override val lessonContent: LessonContext.() -> Unit = { caret("foo(demo)") actionTask("GotoImplementation") { restoreIfModifiedOrMoved() JavaLessonsBundle.message("java.inheritance.hierarchy.goto.implementation", action(it), code("SomeInterface#foo")) } task { text(JavaLessonsBundle.message("java.inheritance.hierarchy.choose.any.implementation", LessonUtil.rawEnter())) stateCheck { (virtualFile.name == "DerivedClass1.java" || virtualFile.name == "DerivedClass2.java") && atDeclarationPosition() } restoreAfterStateBecomeFalse { focusOwner is EditorComponentImpl } test { Thread.sleep(1000) invokeActionViaShortcut("ENTER") } } task("GotoSuperMethod") { text(JavaLessonsBundle.message("java.inheritance.hierarchy.navigate.to.base", action(it), icon(AllIcons.Gutter.ImplementingMethod))) stateCheck { virtualFile.name == "SomeInterface.java" && atDeclarationPosition() } restoreIfModifiedOrMoved() test { actions(it) } } task("GotoImplementation") { text(JavaLessonsBundle.message("java.inheritance.hierarchy.invoke.implementations.again", icon(AllIcons.Gutter.ImplementedMethod), action(it))) triggerByUiComponentAndHighlight { ui: InplaceButton -> ui.toolTipText == IdeBundle.message("show.in.find.window.button.name") } restoreIfModifiedOrMoved() test { actions(it) } } task { before { closeAllFindTabs() } text(JavaLessonsBundle.message("java.inheritance.hierarchy.open.in.find.tool.window", findToolWindow(), icon(ToolWindowManager.getInstance(project).getLocationIcon(ToolWindowId.FIND, AllIcons.General.Pin_tab)))) triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { ui: BaseLabel -> ui.text == (CodeInsightBundle.message("goto.implementation.findUsages.title", "foo")) || ui.text == (JavaAnalysisBundle.message("navigate.to.overridden.methods.title", "foo")) } restoreState(delayMillis = defaultRestoreDelay) { focusOwner is EditorComponentImpl } test { ideFrame { val target = previous.ui!! jComponent(target).click() jComponent(target).click() // for some magic reason one click sometimes doesn't work :( } } } task("HideActiveWindow") { text(JavaLessonsBundle.message("java.inheritance.hierarchy.hide.find.tool.window", action(it), findToolWindow())) checkToolWindowState("Find", false) restoreIfModifiedOrMoved() test { actions(it) } } actionTask("MethodHierarchy") { restoreIfModifiedOrMoved() JavaLessonsBundle.message("java.inheritance.hierarchy.open.method.hierarchy", action(it)) } task("HideActiveWindow") { text(JavaLessonsBundle.message("java.inheritance.hierarchy.hide.method.hierarchy", hierarchyToolWindow(), action(it))) checkToolWindowState("Hierarchy", false) restoreIfModifiedOrMoved() test { actions(it) } } actionTask("TypeHierarchy") { restoreIfModifiedOrMoved() JavaLessonsBundle.message("java.inheritance.hierarchy.open.class.hierarchy", action(it)) } text(JavaLessonsBundle.message("java.inheritance.hierarchy.last.note", action("GotoImplementation"), action("GotoSuperMethod"), action("MethodHierarchy"), action("TypeHierarchy"), action("GotoAction"), strong("hierarchy"))) } private fun TaskRuntimeContext.atDeclarationPosition(): Boolean { return editor.document.charsSequence.let { it.subSequence(editor.caretModel.currentCaret.offset, it.length).startsWith("foo(FileStructureDemo demo)") } } private fun TaskContext.findToolWindow() = strong(UIBundle.message("tool.window.name.find")) private fun TaskContext.hierarchyToolWindow() = strong(UIBundle.message("tool.window.name.hierarchy")) override val suitableTips = listOf("HierarchyBrowser") override val helpLinks: Map<String, String> get() = mapOf( Pair(JavaLessonsBundle.message("java.inheritance.hierarchy.help.link"), LessonUtil.getHelpLink("viewing-structure-and-hierarchy-of-the-source-code.html")), ) }
java/java-features-trainer/src/com/intellij/java/ift/lesson/navigation/JavaInheritanceHierarchyLesson.kt
2419316487
package chat.willow.kale.irc.prefix import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class PrefixSerialiserTests { lateinit var prefixSerialiser: IPrefixSerialiser @Before fun setUp() { prefixSerialiser = PrefixSerialiser } @Test fun test_serialise_NickOnly() { val prefix = prefixSerialiser.serialise(Prefix(nick = "nick")) assertEquals("nick", prefix) } @Test fun test_serialise_NickAndUser() { val prefix = prefixSerialiser.serialise(Prefix(nick = "nick", user = "user")) assertEquals("nick!user", prefix) } @Test fun test_serialise_NickAndHost() { val prefix = prefixSerialiser.serialise(Prefix(nick = "nick", host = "host")) assertEquals("nick@host", prefix) } @Test fun test_serialise_NickUserAndHost() { val prefix = prefixSerialiser.serialise(Prefix(nick = "nick", user = "user", host = "host")) assertEquals("nick!user@host", prefix) } }
src/test/kotlin/chat/willow/kale/irc/prefix/PrefixSerialiserTests.kt
3824661164
package test var Int.junk: Short get() = throw Exception() set(p: Short) = throw Exception() val String.junk: Int get() = throw Exception()
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/prop/ExtVarl.kt
2315809010
import android.app.Activity import android.os.Bundle class <caret>KotlinActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_kotlin) } }
plugins/kotlin/idea/tests/testData/android/gutterIcon/relatedFiles.kt
998618403
// IS_APPLICABLE: true val x = 1 val y = <caret>x::hashCode
plugins/kotlin/idea/tests/testData/intentions/convertReferenceToLambda/boundReference.kt
4263010717
fun a( l0: /*T1@*/MutableSet</*T0@*/Int>, l1: /*T3@*/MutableSet</*T2@*/Int>, l2: /*T5@*/MutableSet</*T4@*/Int>, l3: /*T7@*/MutableSet</*T6@*/Int>, l4: /*T9@*/MutableSet</*T8@*/Int> ) { l0/*T1@MutableSet<T0@Int>*/.add(1/*LIT*/) l1/*T3@MutableSet<T2@Int>*/.addAll(l1/*T3@MutableSet<T2@Int>*/) l2/*T5@MutableSet<T4@Int>*/.clear() l3/*T7@MutableSet<T6@Int>*/.removeAll(l1/*T3@MutableSet<T2@Int>*/) l4/*T9@MutableSet<T8@Int>*/.retainAll(l1/*T3@MutableSet<T2@Int>*/) } //T0 := T0 due to 'RECEIVER_PARAMETER' //T1 := LOWER due to 'USE_AS_RECEIVER' //T2 := T2 due to 'RECEIVER_PARAMETER' //T2 := T2 due to 'PARAMETER' //T3 <: UPPER due to 'PARAMETER' //T3 := LOWER due to 'USE_AS_RECEIVER' //T4 := T4 due to 'RECEIVER_PARAMETER' //T5 := LOWER due to 'USE_AS_RECEIVER' //T6 := T6 due to 'RECEIVER_PARAMETER' //T6 := T2 due to 'PARAMETER' //T3 <: UPPER due to 'PARAMETER' //T7 := LOWER due to 'USE_AS_RECEIVER' //T8 := T8 due to 'RECEIVER_PARAMETER' //T8 := T2 due to 'PARAMETER' //T3 <: UPPER due to 'PARAMETER' //T9 := LOWER due to 'USE_AS_RECEIVER'
plugins/kotlin/j2k/new/tests/testData/inference/mutability/setMutableCalls.kt
1727877544
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.kotlin.inspections import com.intellij.codeInspection.i18n.TitleCapitalizationInspection import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase class KtCapitalizationInspectionTest : LightJavaCodeInsightFixtureTestCase() { fun testBasic() { myFixture.enableInspections(TitleCapitalizationInspection()) myFixture.configureByText("Foo.kt", """ import org.jetbrains.annotations.* class Foo { fun consumeTitle(@Nls(capitalization=Nls.Capitalization.Title) <warning descr="[UNUSED_PARAMETER] Parameter 's' is never used">s</warning> : String) {} fun consumeSentence(@Nls(capitalization=Nls.Capitalization.Sentence) <warning descr="[UNUSED_PARAMETER] Parameter 's' is never used">s</warning> : String) {} fun foo(@Nls(capitalization=Nls.Capitalization.Sentence) s: String) { val s1 = <warning descr="The string is used in both title and sentence capitalization contexts">"Hello World"</warning> val s2 = <warning descr="String 'Hello World' is not properly capitalized. It should have sentence capitalization">"Hello World"</warning> consumeTitle("Hello World") consumeTitle(<warning descr="String 'Hello world' is not properly capitalized. It should have title capitalization">"Hello world"</warning>) consumeTitle(<warning descr="The sentence capitalization is provided where title capitalization is required">s</warning>) consumeTitle(s1) consumeSentence(<warning descr="String 'hello world' is not properly capitalized. It should have sentence capitalization">"hello world"</warning>) consumeSentence(<warning descr="String 'Hello World' is not properly capitalized. It should have sentence capitalization">"Hello World"</warning>) consumeSentence("Hello world") consumeSentence(s) consumeSentence(s1) consumeSentence(s2) } } """.trimIndent()) myFixture.testHighlighting() } fun testProperties() { val props = """ property.lowercase=hello world property.titlecase=Hello World""".trimIndent() myFixture.addFileToProject("MyBundle.properties", props) myFixture.enableInspections(TitleCapitalizationInspection()) myFixture.configureByText("Foo.kt", """ import org.jetbrains.annotations.* class Foo { fun message(@PropertyKey(resourceBundle = "MyBundle") key : String) : String = key fun consumeTitle(@Nls(capitalization=Nls.Capitalization.Title) <warning descr="[UNUSED_PARAMETER] Parameter 's' is never used">s</warning> : String) {} fun consumeSentence(@Nls(capitalization=Nls.Capitalization.Sentence) <warning descr="[UNUSED_PARAMETER] Parameter 's' is never used">s</warning> : String) {} fun test() { consumeTitle(<warning descr="String 'hello world' is not properly capitalized. It should have title capitalization">message("property.lowercase")</warning>) consumeSentence(this.<warning descr="String 'hello world' is not properly capitalized. It should have sentence capitalization">message("property.lowercase")</warning>) consumeTitle(message("property.titlecase")) consumeSentence(this.<warning descr="String 'Hello World' is not properly capitalized. It should have sentence capitalization">message("property.titlecase")</warning>) } } """.trimIndent()) myFixture.testHighlighting() } }
plugins/devkit/devkit-kotlin-tests/testSrc/org/jetbrains/idea/devkit/kotlin/inspections/KtCapitalizationInspectionTest.kt
3469979773
// WITH_STDLIB // PROBLEM: none fun test(): String { val x = 1 return "Foo: ${x.<caret>toString()}" }
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceToStringWithStringTemplate/stringTemplate.kt
3085127696
fun foo(p: Int) { x() if (y()) { print(<caret>p) } z() }
plugins/kotlin/idea/tests/testData/resolve/partialBodyResolve/Simple.kt
1129378157
package quickbeer.android.domain.reviewlist import quickbeer.android.data.repository.repository.ItemList /** * Maps a paged review to a list of review IDs. */ typealias ReviewIdList = ItemList<ReviewPage, Int>
app/src/main/java/quickbeer/android/domain/reviewlist/ReviewIdList.kt
4126370505
package todo.actions import com.github.andrewoma.flux.ActionDef import todo.stores.Todo import todo.stores.todoDispatcher object TodoActions { val create = ActionDef<CreatePayload>(todoDispatcher) val update = ActionDef<UpdatePayload>(todoDispatcher) val complete = ActionDef<CompletePayload>(todoDispatcher) val undoComplete = ActionDef<UndoCompletePayload>(todoDispatcher) val toggleCompleteAll = ActionDef<Nothing?>(todoDispatcher) val destroy = ActionDef<DestroyPayload>(todoDispatcher) val destroyCompleted = ActionDef<Nothing?>(todoDispatcher) fun toggleComplete(todo: Todo) { if (todo.complete) { undoComplete(UndoCompletePayload(todo.id)) } else { complete(CompletePayload(todo.id)) } } } interface TodoAction class CreatePayload(val text: String) : TodoAction class UpdatePayload(val id: String, val text: String) : TodoAction class UndoCompletePayload(val id: String) : TodoAction class CompletePayload(val id: String) : TodoAction class DestroyPayload(val id: String) : TodoAction
todo/src/main/kotlin/todo/actions/Actions.kt
1436918054
package ftl.adapter.google import ftl.api.Orientation import com.google.testing.model.Orientation as GoogleApiOrientation internal fun List<GoogleApiOrientation>.toApiModel(): List<Orientation> = map { googleApiOrientation -> Orientation( id = googleApiOrientation.id ?: UNABLE, name = googleApiOrientation.name ?: UNABLE, tags = googleApiOrientation.tags ?: emptyList() ) } private const val UNABLE = "[Unable to fetch]"
test_runner/src/main/kotlin/ftl/adapter/google/OrientationsAdapter.kt
2983113721
package com.cout970.modeler.core.model.mesh import com.cout970.modeler.api.model.mesh.IFaceIndex import com.cout970.modeler.api.model.mesh.IMesh import com.cout970.vector.api.IVector2 /** * Created by cout970 on 2017/05/07. */ class FaceIndex( val size: Int, val pos0: Int, val pos1: Int, val pos2: Int, val pos3: Int, val tex0: Int, val tex1: Int, val tex2: Int, val tex3: Int ) : IFaceIndex { override val vertexCount: Int get() = size override val pos: List<Int> get() = when (size) { 0 -> emptyList() 1 -> listOf(pos0) 2 -> listOf(pos0, pos1) 3 -> listOf(pos0, pos1, pos2) else -> listOf(pos0, pos1, pos2, pos3) } override val tex: List<Int> get() = when (size) { 0 -> emptyList() 1 -> listOf(tex0) 2 -> listOf(tex0, tex1) 3 -> listOf(tex0, tex1, tex2) else -> listOf(tex0, tex1, tex2, tex3) } companion object { fun from(pos: List<Int>, tex: List<Int>): FaceIndex { require(pos.size == tex.size) { "Sizes don't match: pos = ${pos.size}, tex = ${tex.size}" } return FaceIndex(pos.size, pos.getOrNull(0) ?: 0, pos.getOrNull(1) ?: 0, pos.getOrNull(2) ?: 0, pos.getOrNull(3) ?: 0, tex.getOrNull(0) ?: 0, tex.getOrNull(1) ?: 0, tex.getOrNull(2) ?: 0, tex.getOrNull(3) ?: 0 ) } } } fun IFaceIndex.getTextureVertex(mesh: IMesh): List<IVector2> { if (this.tex.size == 4 && this.tex[2] == this.tex[3]) { return listOf( mesh.tex[this.tex[0]], mesh.tex[this.tex[1]], mesh.tex[this.tex[2]] ) } return this.tex.map { mesh.tex[it] } }
src/main/kotlin/com/cout970/modeler/core/model/mesh/FaceIndex.kt
3527351101
package de.fabmax.kool.math import kotlin.math.sqrt import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue /** * Tests for Vec class */ class VecTest { @Test fun vec3Consts() { assertTrue(Vec3f.X_AXIS.x == 1f && Vec3f.X_AXIS.y == 0f && Vec3f.X_AXIS.z == 0f, "x != (1, 0, 0)") assertTrue(Vec3f.Y_AXIS.x == 0f && Vec3f.Y_AXIS.y == 1f && Vec3f.Y_AXIS.z == 0f, "y != (0, 1, 0)") assertTrue(Vec3f.Z_AXIS.x == 0f && Vec3f.Z_AXIS.y == 0f && Vec3f.Z_AXIS.z == 1f, "z != (0, 0, 1)") assertTrue(Vec3f.ZERO.x == 0f && Vec3f.ZERO.y == 0f && Vec3f.ZERO.z == 0f, "0 != (0, 0, 0)") } @Test fun vec3Len() { val t = Vec3f(2f, 3f, 4f) assertTrue(isFuzzyEqual(t.sqrLength(), 29f), "sqrLen failed") assertTrue(isFuzzyEqual(t.length(), sqrt(29f)), "length failed") assertTrue(isFuzzyEqual(t.norm(MutableVec3f()).length(), 1f), "norm failed") } @Test fun vec3Add() = assertTrue(add(Vec3f(1f, 2f, 3f), Vec3f(2f, 3f, 4f)).isFuzzyEqual(Vec3f(3f, 5f, 7f))) @Test fun vec3Sub() = assertTrue(subtract(Vec3f(2f, 3f, 4f), Vec3f(1f, 2f, 3f)).isFuzzyEqual(Vec3f(1f, 1f, 1f))) @Test fun vec3Scale() { assertTrue(scale(Vec3f(1f, 2f, 3f), 2f).isFuzzyEqual(Vec3f(2f, 4f, 6f))) } @Test fun vec3Dist() { assertTrue(isFuzzyEqual(Vec3f(1f, 2f, 3f).distance(Vec3f.ZERO), Vec3f(1f, 2f, 3f).length())) } @Test fun vec3Dot() { // dot prod assertEquals(Vec3f.X_AXIS * Vec3f.X_AXIS, 1f, "x * x != 1") assertEquals(Vec3f.Y_AXIS * Vec3f.Y_AXIS, 1f, "y * y != 1") assertEquals(Vec3f.Z_AXIS * Vec3f.Z_AXIS, 1f, "z * z != 1") assertEquals(Vec3f.X_AXIS * Vec3f.Y_AXIS, 0f, "x * y != 0") assertEquals(Vec3f.X_AXIS * Vec3f.Z_AXIS, 0f, "x * z != 0") assertEquals(Vec3f.Y_AXIS * Vec3f.Z_AXIS, 0f, "y * z != 0") } @Test fun vec3Cross() { // dot prod assertTrue(cross(Vec3f.X_AXIS, Vec3f.Y_AXIS).isFuzzyEqual(Vec3f.Z_AXIS), "x * y != z") assertTrue(cross(Vec3f.Z_AXIS, Vec3f.X_AXIS).isFuzzyEqual(Vec3f.Y_AXIS), "z * x != y") assertTrue(cross(Vec3f.Y_AXIS, Vec3f.Z_AXIS).isFuzzyEqual(Vec3f.X_AXIS), "y * z != x") } @Test fun vec3Rotate() { // dot prod assertTrue(Vec3f.X_AXIS.rotate(90f, Vec3f.Z_AXIS, MutableVec3f()).isFuzzyEqual(Vec3f.Y_AXIS), "x.rot(90, z) != y") assertTrue(Vec3f.Y_AXIS.rotate(90f, Vec3f.X_AXIS, MutableVec3f()).isFuzzyEqual(Vec3f.Z_AXIS), "y.rot(90, z) != z") assertTrue(Vec3f.Z_AXIS.rotate(90f, Vec3f.Y_AXIS, MutableVec3f()).isFuzzyEqual(Vec3f.X_AXIS), "z.rot(90, y) != x") } }
kool-core/src/jvmTest/kotlin/de/fabmax/kool/math/VecTest.kt
1639135186
/* * Copyright 1999-2017 Alibaba Group. * * 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.alibaba.p3c.idea.util import com.alibaba.p3c.idea.quickfix.AvoidStartWithDollarAndUnderLineNamingQuickFix import com.alibaba.p3c.idea.quickfix.ClassMustHaveAuthorQuickFix import com.alibaba.p3c.idea.quickfix.ConstantFieldShouldBeUpperCaseQuickFix import com.alibaba.p3c.idea.quickfix.LowerCamelCaseVariableNamingQuickFix import com.alibaba.p3c.idea.quickfix.VmQuietReferenceQuickFix import com.intellij.codeInspection.LocalQuickFix /** * * * @author caikang * @date 2017/02/06 */ object QuickFixes { val quickFixes = mutableMapOf(VmQuietReferenceQuickFix.ruleName to VmQuietReferenceQuickFix, ClassMustHaveAuthorQuickFix.ruleName to ClassMustHaveAuthorQuickFix, ConstantFieldShouldBeUpperCaseQuickFix.ruleName to ConstantFieldShouldBeUpperCaseQuickFix, AvoidStartWithDollarAndUnderLineNamingQuickFix.ruleName to AvoidStartWithDollarAndUnderLineNamingQuickFix, LowerCamelCaseVariableNamingQuickFix.ruleName to LowerCamelCaseVariableNamingQuickFix) fun getQuickFix(rule: String, isOnTheFly: Boolean): LocalQuickFix? { val quickFix = quickFixes[rule] ?: return null if (!quickFix.onlyOnThFly) { return quickFix } if (!isOnTheFly && quickFix.onlyOnThFly) { return null } return quickFix } }
idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/util/QuickFixes.kt
3885913445
package com.github.kerubistan.kerub.model class HostPubKey( val algorithm: String?, val format: String?, val fingerprint: String, val encoded: String)
src/main/kotlin/com/github/kerubistan/kerub/model/HostPubKey.kt
1709190372
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <alexander.orlov@loxal.net>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.ethereum.datasource /** * Indicator interface which narrows the Source contract: * the same Key always maps to the same Value, * there could be no put() with the same Key and different Value * Normally the Key is the hash of the Value * Usually such kind of sources are Merkle Trie backing stores * Created by Anton Nashatyrev on 08.11.2016. */ interface HashedKeySource<in Key, Value> : Source<Key, Value>
free-ethereum-core/src/main/java/org/ethereum/datasource/HashedKeySource.kt
3842896719