repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
drakeet/MultiType
library/src/test/kotlin/com/drakeet/multitype/OneToManyBuilderTest.kt
1
3577
/* * Copyright (c) 2016-present. Drakeet Xu * * 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.drakeet.multitype import androidx.recyclerview.widget.RecyclerView import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.check import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import org.junit.Test import kotlin.reflect.KClass /** * @author Drakeet Xu */ class OneToManyBuilderTest { private class Data private val adapter: MultiTypeAdapter = mock() private val oneToManyBuilder = OneToManyBuilder(adapter, Data::class.java) @Test fun testWithLinker() { oneToManyBuilder.to(mock(), mock()) oneToManyBuilder.withLinker(object : Linker<Data> { override fun index(position: Int, item: Data): Int { return position } }) verify(adapter, times(2)).register(check<Type<Data>> { assertThat(it.clazz).isEqualTo(Data::class.java) assertThat(it.linker.index(1, Data())).isEqualTo(1) }) oneToManyBuilder.withLinker { position, item -> position } verify(adapter, times(4)).register(check<Type<Data>> { assertThat(it.clazz).isEqualTo(Data::class.java) assertThat(it.linker.index(2, Data())).isEqualTo(2) }) } private abstract class DataItemViewDelegate : ItemViewDelegate<Data, RecyclerView.ViewHolder>() @Test fun testWithJavaClassLinker() { val itemViewDelegate1 = mock<ItemViewDelegate<Data, RecyclerView.ViewHolder>>() val itemViewDelegate2 = mock<DataItemViewDelegate>() oneToManyBuilder.to(itemViewDelegate1, itemViewDelegate2) oneToManyBuilder.withJavaClassLinker(object : JavaClassLinker<Data> { override fun index(position: Int, item: Data): Class<out ItemViewDelegate<Data, *>> { return if (position == 3) itemViewDelegate1.javaClass else itemViewDelegate2.javaClass } }) verify(adapter, times(2)).register(check<Type<Data>> { assertThat(it.clazz).isEqualTo(Data::class.java) assertThat(it.linker.index(3, Data())).isEqualTo(0) assertThat(it.linker.index(5, Data())).isEqualTo(1) }) oneToManyBuilder.withKotlinClassLinker { position, item -> if (position == 3) itemViewDelegate1::class else itemViewDelegate2::class } verify(adapter, times(4)).register(check<Type<Data>> { assertThat(it.clazz).isEqualTo(Data::class.java) assertThat(it.linker.index(3, Data())).isEqualTo(0) assertThat(it.linker.index(5, Data())).isEqualTo(1) }) oneToManyBuilder.withKotlinClassLinker(object : KotlinClassLinker<Data> { override fun index(position: Int, item: Data): KClass<out ItemViewDelegate<Data, *>> { return if (position == 3) itemViewDelegate1::class else itemViewDelegate2::class } }) verify(adapter, times(6)).register(check<Type<Data>> { assertThat(it.clazz).isEqualTo(Data::class.java) assertThat(it.linker.index(3, Data())).isEqualTo(0) assertThat(it.linker.index(5, Data())).isEqualTo(1) }) } }
apache-2.0
5f666589a6af49ad52ae88b019d2574a
36.260417
97
0.714565
3.974444
false
true
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge3d/Container3D.kt
1
525
package com.soywiz.korge3d import com.soywiz.kds.iterators.* @Korge3DExperimental open class Container3D : View3D() { val children = arrayListOf<View3D>() fun removeChild(child: View3D) { children.remove(child) } fun addChild(child: View3D) { child.removeFromParent() children += child child._parent = this child.transform.parent = this.transform } operator fun plusAssign(child: View3D) = addChild(child) override fun render(ctx: RenderContext3D) { children.fastForEach { it.render(ctx) } } }
apache-2.0
591daa0af0f2e25b2e28ae35ec6c1983
18.444444
57
0.725714
3.088235
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/VectorImage.kt
1
2118
package com.soywiz.korge.view import com.soywiz.korge.debug.* import com.soywiz.korge.render.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.color.* import com.soywiz.korim.format.* import com.soywiz.korim.vector.* import com.soywiz.korio.file.* import com.soywiz.korma.geom.* import com.soywiz.korma.geom.vector.* import com.soywiz.korui.* inline fun Container.vectorImage(shape: SizedDrawable, autoScaling: Boolean = true, callback: @ViewDslMarker VectorImage.() -> Unit = {}): VectorImage = VectorImage(shape, autoScaling).addTo(this, callback).apply { redrawIfRequired() } class VectorImage( shape: SizedDrawable, autoScaling: Boolean = true, ) : BaseGraphics(autoScaling), ViewFileRef by ViewFileRef.Mixin() { companion object { fun createDefault() = VectorImage(buildShape { fill(Colors.WHITE) { rect(0, 0, 100, 100) } }) } var shape: SizedDrawable = shape set(value) { if (field !== value) { field = value dirty = true redrawIfRequired() scale = 1.0 } } override fun drawShape(ctx: Context2d) { ctx.draw(shape) } override fun getShapeBounds(bb: BoundsBuilder) { bb.add(0.0, 0.0) bb.add(shape.width, shape.height) } override fun renderInternal(ctx: RenderContext) { lazyLoadRenderInternal(ctx, this) super.renderInternal(ctx) } override suspend fun forceLoadSourceFile(views: Views, currentVfs: VfsFile, sourceFile: String?) { baseForceLoadSourceFile(views, currentVfs, sourceFile) val vector = currentVfs["$sourceFile"].readVectorImage() println("VECTOR: $vector") shape = vector } override fun buildDebugComponent(views: Views, container: UiContainer) { container.uiCollapsibleSection("VectorImage") { uiEditableValue(this@VectorImage::sourceFile, kind = UiTextEditableValue.Kind.FILE(views.currentVfs) { it.extensionLC == "svg" }) } super.buildDebugComponent(views, container) } }
apache-2.0
5eaad6b5d4b531f9178ad909d4d80dcf
32.619048
235
0.654391
4.057471
false
false
false
false
Andr3Carvalh0/mGBA
app/src/main/java/io/mgba/utilities/Constants.kt
1
544
package io.mgba.utilities object Constants { val RELOAD_LIBRARY = "reload" val GAME_PATH = "gamesDir" val GAMES_INTENT = "games" val ARG_PLAY_GAME = "play_game" val ARG_SHEET_CONTENT = "sheet_content" val ARG_SHEET_IS_SHOWING = "sheet_is_showing" val PLATFORM_GBA_EXT = "gba" val MAIN_RECYCLER_CONTENT = "main_rv_content" val ARG_SETTINGS_ID = "settings_id_args" val ARG_PLATFORM = "platform" val PLATFORM_UNKNOWN = 0 val PLATFORM_GBC = 1 val PLATFORM_GBA = 2 val PLATFORM_FAVS = 3 }
mpl-2.0
638e6243a79442679d1068c9afee150a
24.904762
49
0.652574
3.218935
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/feed/configure/ConfigureItemLanguageDialogView.kt
1
3395
package org.wikipedia.feed.configure import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.FrameLayout import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.databinding.ItemFeedContentTypeLangSelectDialogBinding import org.wikipedia.views.DefaultViewHolder class ConfigureItemLanguageDialogView : FrameLayout { private val binding = ItemFeedContentTypeLangSelectDialogBinding.inflate(LayoutInflater.from(context), this, true) private lateinit var langList: List<String> private lateinit var disabledList: MutableList<String> constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) init { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) binding.languageList.layoutManager = LinearLayoutManager(context) } fun setContentType(langList: List<String>, disabledList: MutableList<String>) { this.langList = langList this.disabledList = disabledList binding.languageList.adapter = LanguageItemAdapter() } private inner class LanguageItemHolder constructor(itemView: View) : DefaultViewHolder<View>(itemView), OnClickListener { private lateinit var langCode: String private val container = itemView.findViewById<View>(R.id.feed_content_type_lang_container) private val checkbox = itemView.findViewById<CheckBox>(R.id.feed_content_type_lang_checkbox) private val langNameView = itemView.findViewById<TextView>(R.id.feed_content_type_lang_name) fun bindItem(langCode: String) { this.langCode = langCode container.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) langNameView.text = WikipediaApp.instance.languageState.getAppLanguageLocalizedName(langCode) container.setOnClickListener(this) checkbox.setOnClickListener(this) updateState() } override fun onClick(v: View) { if (disabledList.contains(langCode)) { disabledList.remove(langCode) } else { disabledList.add(langCode) } updateState() } private fun updateState() { checkbox.isChecked = !disabledList.contains(langCode) } } private inner class LanguageItemAdapter : RecyclerView.Adapter<LanguageItemHolder>() { override fun getItemCount(): Int { return langList.size } override fun onCreateViewHolder(parent: ViewGroup, type: Int): LanguageItemHolder { val view = inflate(context, R.layout.item_feed_content_type_lang_select_item, null) return LanguageItemHolder(view) } override fun onBindViewHolder(holder: LanguageItemHolder, pos: Int) { holder.bindItem(langList[pos]) } } }
apache-2.0
99a5a61a312f2a70109a1908031059bb
38.476744
125
0.711635
4.96345
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/sync/SyncSettingsFragment.kt
1
4870
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.fragment.sync import android.app.Dialog import android.os.Bundle import android.support.v7.app.AlertDialog import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import com.squareup.otto.Subscribe import nl.komponents.kovenant.combine.and import nl.komponents.kovenant.ui.alwaysUi import org.mariotaku.ktextension.weak import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.SYNC_PREFERENCES_NAME import de.vanita5.twittnuker.constant.dataSyncProviderInfoKey import de.vanita5.twittnuker.extension.applyTheme import de.vanita5.twittnuker.extension.dismissProgressDialog import de.vanita5.twittnuker.extension.onShow import de.vanita5.twittnuker.extension.showProgressDialog import de.vanita5.twittnuker.fragment.BaseDialogFragment import de.vanita5.twittnuker.fragment.BasePreferenceFragment import de.vanita5.twittnuker.util.TaskServiceRunner import de.vanita5.twittnuker.util.sync.DataSyncProvider class SyncSettingsFragment : BasePreferenceFragment() { private var syncProvider: DataSyncProvider? = null override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) syncProvider = kPreferences[dataSyncProviderInfoKey] setHasOptionsMenu(true) } override fun onStart() { super.onStart() bus.register(this) } override fun onStop() { bus.unregister(this) super.onStop() } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { preferenceManager.sharedPreferencesName = SYNC_PREFERENCES_NAME addPreferencesFromResource(R.xml.preferences_sync) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_sync_settings, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.disconnect -> { val df = DisconnectSyncConfirmDialogFragment() df.show(childFragmentManager, "disconnect_confirm") } R.id.sync_now -> { val providerInfo = kPreferences[dataSyncProviderInfoKey]!! syncController.performSync(providerInfo) } else -> { return false } } return true } @Subscribe fun onSyncFinishedEvent(event: TaskServiceRunner.SyncFinishedEvent) { listView?.adapter?.notifyDataSetChanged() } private fun cleanupAndDisconnect() { val providerInfo = kPreferences[dataSyncProviderInfoKey] ?: return val weakThis = weak() val task = showProgressDialog("cleanup_sync_cache"). and(syncController.cleanupSyncCache(providerInfo)) task.alwaysUi { val f = weakThis.get() ?: return@alwaysUi f.dismissProgressDialog("cleanup_sync_cache") f.kPreferences[dataSyncProviderInfoKey] = null DataSyncProvider.Factory.notifyUpdate(f.context) f.activity?.finish() } } class DisconnectSyncConfirmDialogFragment : BaseDialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(context) val providerInfo = kPreferences[dataSyncProviderInfoKey]!! val entry = DataSyncProvider.Factory.getProviderEntry(context, providerInfo.type)!! builder.setMessage(getString(R.string.message_sync_disconnect_from_name_confirm, entry.name)) builder.setPositiveButton(R.string.action_sync_disconnect) { _, _ -> (parentFragment as SyncSettingsFragment).cleanupAndDisconnect() } builder.setNegativeButton(android.R.string.cancel, null) val dialog = builder.create() dialog.onShow { it.applyTheme() } return dialog } } }
gpl-3.0
c9d09b62c3557eb3882bf7c5e76132ba
36.75969
105
0.705133
4.737354
false
false
false
false
stripe/stripe-android
identity/src/test/java/com/stripe/android/identity/networking/IdentityNetworkResponseFixtures.kt
1
9130
package com.stripe.android.identity.networking internal val VERIFICATION_PAGE_DATA_JSON_STRING = """ { "id": "vs_1KWvnMEAjaOkiuGMvfNAA0vo", "object": "identity.verification_page_data", "requirements": { "errors": [ ], "missing": [ "id_document_front", "id_document_back", "id_document_type" ] }, "status": "requires_input", "submitted": false } """.trimIndent() internal val VERIFICATION_PAGE_NOT_REQUIRE_LIVE_CAPTURE_JSON_STRING = """ { "id": "vs_1KgNstEAjaOkiuGMpFXVTocU", "object": "identity.verification_page", "biometric_consent": { "accept_button_text": "Accept and continue", "body": "\u003Cp\u003E\u003Cb\u003EHow Stripe will verify your identity\u003C/b\u003E\u003C/p\u003E\u003Cp\u003EStripe will use biometric technology (on images of you and your IDs) and other data sources to confirm your identity and for fraud and security purposes. Stripe will store these images and the results of this check and share them with mlgb.band.\u003C/p\u003E\u003Cp\u003E\u003Ca href='https://stripe.com/about'\u003ELearn about Stripe\u003C/a\u003E\u003C/p\u003E\u003Cp\u003E\u003Ca href='https://stripe.com/privacy-center/legal#stripe-identity'\u003ELearn how Stripe Identity works\u003C/a\u003E\u003C/p\u003E", "decline_button_text": "No, don't verify", "privacy_policy": "Data will be stored and may be used according to the \u003Ca href='https://stripe.com/privacy'\u003EStripe Privacy Policy\u003C/a\u003E and mlgb.band Privacy Policy.", "time_estimate": "Takes about 1–2 minutes.", "title": "mlgb.band uses Stripe to verify your identity", "scroll_to_continue_button_text": "Scroll to consent" }, "document_capture": { "autocapture_timeout": 8000, "file_purpose": "identity_private", "high_res_image_compression_quality": 0.92, "high_res_image_crop_padding": 0.08, "high_res_image_max_dimension": 3000, "low_res_image_compression_quality": 0.82, "low_res_image_max_dimension": 3000, "models": { "id_detector_min_iou": 0.8, "id_detector_min_score": 0.8, "id_detector_url": "https://b.stripecdn.com/gelato-statics-srv/assets/945cd2bb8681a56dd5b0344a009a1f2416619382/assets/id_detectors/tflite/2022-02-23/model.tflite" }, "motion_blur_min_duration": 500, "motion_blur_min_iou": 0.95, "require_live_capture": false }, "document_select": { "body": null, "button_text": "Next", "id_document_type_allowlist": { "passport": "Passport", "driving_license": "Driver's license", "id_card": "Identity card" }, "title": "Which form of identification do you want to use?" }, "fallback_url": "https://verify.stripe.com/start/test_YWNjdF8xSU84aDNFQWphT2tpdUdNLF9MTjg5dFZtRWV1T1c1QXBxMkJ6MTUwZlI5c3JtTE5U0100BzkFlqqD", "livemode": false, "requirements": { "missing": [ "biometric_consent", "id_document_front", "id_document_back", "id_document_type" ] }, "status": "requires_input", "submitted": false, "success": { "body": "\u003Cp\u003E\u003Cb\u003EThank you for providing your information\u003C/b\u003E\u003C/p\u003E\u003Cp\u003Emlgb.band will reach out if additional details are required.\u003C/p\u003E\u003Cp\u003E\u003Cb\u003ENext steps\u003C/b\u003E\u003C/p\u003E\u003Cp\u003Emlgb.band will contact you regarding the outcome of your identification process.\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EMore about Stripe Identity\u003C/b\u003E\u003C/p\u003E\u003Cp\u003E\u003Ca href='https://support.stripe.com/questions/common-questions-about-stripe-identity'\u003ECommon questions about Stripe Identity\u003C/a\u003E\u003C/p\u003E\u003Cp\u003E\u003Ca href='https://stripe.com/privacy-center/legal#stripe-identity'\u003ELearn how Stripe uses data\u003C/a\u003E\u003C/p\u003E\u003Cp\u003E\u003Ca href='https://stripe.com/privacy'\u003EStripe Privacy Policy\u003C/a\u003E\u003C/p\u003E\u003Cp\u003E\u003Ca href='mailto:[email protected]'\u003EContact Stripe\u003C/a\u003E\u003C/p\u003E", "button_text": "Complete", "title": "Verification pending" }, "unsupported_client": false } """.trimIndent() internal val VERIFICATION_PAGE_REQUIRE_LIVE_CAPTURE_JSON_STRING = """ { "id": "vs_1KgNstEAjaOkiuGMpFXVTocU", "object": "identity.verification_page", "biometric_consent": { "accept_button_text": "Accept and continue", "body": "\u003Cp\u003E\u003Cb\u003EHow Stripe will verify your identity\u003C/b\u003E\u003C/p\u003E\u003Cp\u003EStripe will use biometric technology (on images of you and your IDs) and other data sources to confirm your identity and for fraud and security purposes. Stripe will store these images and the results of this check and share them with mlgb.band.\u003C/p\u003E\u003Cp\u003E\u003Ca href='https://stripe.com/about'\u003ELearn about Stripe\u003C/a\u003E\u003C/p\u003E\u003Cp\u003E\u003Ca href='https://stripe.com/privacy-center/legal#stripe-identity'\u003ELearn how Stripe Identity works\u003C/a\u003E\u003C/p\u003E", "decline_button_text": "No, don't verify", "privacy_policy": "Data will be stored and may be used according to the \u003Ca href='https://stripe.com/privacy'\u003EStripe Privacy Policy\u003C/a\u003E and mlgb.band Privacy Policy.", "time_estimate": "Takes about 1–2 minutes.", "title": "mlgb.band uses Stripe to verify your identity", "scroll_to_continue_button_text": "Scroll to consent" }, "document_capture": { "autocapture_timeout": 8000, "file_purpose": "identity_private", "high_res_image_compression_quality": 0.92, "high_res_image_crop_padding": 0.08, "high_res_image_max_dimension": 3000, "low_res_image_compression_quality": 0.82, "low_res_image_max_dimension": 3000, "models": { "id_detector_min_iou": 0.8, "id_detector_min_score": 0.8, "id_detector_url": "https://b.stripecdn.com/gelato-statics-srv/assets/945cd2bb8681a56dd5b0344a009a1f2416619382/assets/id_detectors/tflite/2022-02-23/model.tflite" }, "motion_blur_min_duration": 500, "motion_blur_min_iou": 0.95, "require_live_capture": true }, "document_select": { "body": null, "button_text": "Next", "id_document_type_allowlist": { "passport": "Passport", "driving_license": "Driver's license", "id_card": "Identity card" }, "title": "Which form of identification do you want to use?" }, "fallback_url": "https://verify.stripe.com/start/test_YWNjdF8xSU84aDNFQWphT2tpdUdNLF9MTjg5dFZtRWV1T1c1QXBxMkJ6MTUwZlI5c3JtTE5U0100BzkFlqqD", "livemode": false, "requirements": { "missing": [ "biometric_consent", "id_document_front", "id_document_back", "id_document_type" ] }, "status": "requires_input", "submitted": false, "success": { "body": "\u003Cp\u003E\u003Cb\u003EThank you for providing your information\u003C/b\u003E\u003C/p\u003E\u003Cp\u003Emlgb.band will reach out if additional details are required.\u003C/p\u003E\u003Cp\u003E\u003Cb\u003ENext steps\u003C/b\u003E\u003C/p\u003E\u003Cp\u003Emlgb.band will contact you regarding the outcome of your identification process.\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EMore about Stripe Identity\u003C/b\u003E\u003C/p\u003E\u003Cp\u003E\u003Ca href='https://support.stripe.com/questions/common-questions-about-stripe-identity'\u003ECommon questions about Stripe Identity\u003C/a\u003E\u003C/p\u003E\u003Cp\u003E\u003Ca href='https://stripe.com/privacy-center/legal#stripe-identity'\u003ELearn how Stripe uses data\u003C/a\u003E\u003C/p\u003E\u003Cp\u003E\u003Ca href='https://stripe.com/privacy'\u003EStripe Privacy Policy\u003C/a\u003E\u003C/p\u003E\u003Cp\u003E\u003Ca href='mailto:[email protected]'\u003EContact Stripe\u003C/a\u003E\u003C/p\u003E", "button_text": "Complete", "title": "Verification pending" }, "unsupported_client": false } """.trimIndent() internal val ERROR_JSON_STRING = """ { "error": { "code": "resource_missing", "doc_url": "https://stripe.com/docs/error-codes/resource-missing", "message": "No such file upload: 'hightResImage'", "param": "collected_data[id_document][front][high_res_image]", "type": "invalid_request_error" } } """.trimIndent() internal val FILE_UPLOAD_SUCCESS_JSON_STRING = """ { "id": "file_1KZUtnEAjaOkiuGM9AuSSXXO", "object": "file", "created": 1646376359, "expires_at": null, "filename": "initialScreen.png", "purpose": "identity_private", "size": 136000, "title": null, "type": "png", "url": null } """.trimIndent()
mit
c7c338e2acd8641e97a19a6964b9f128
52.682353
979
0.665023
3.031894
false
false
false
false
exponent/exponent
packages/expo-updates/android/src/main/java/expo/modules/updates/UpdatesPackage.kt
2
2767
package expo.modules.updates import android.content.Context import android.content.pm.PackageManager import android.util.Log import androidx.annotation.UiThread import com.facebook.react.ReactInstanceManager import expo.modules.core.ExportedModule import expo.modules.core.interfaces.Package import expo.modules.core.interfaces.InternalModule import expo.modules.core.interfaces.ReactNativeHostHandler // these unused imports must stay because of versioning /* ktlint-disable no-unused-imports */ import expo.modules.updates.UpdatesController /* ktlint-enable no-unused-imports */ class UpdatesPackage : Package { override fun createInternalModules(context: Context): List<InternalModule> { return listOf(UpdatesService(context) as InternalModule) } override fun createExportedModules(context: Context): List<ExportedModule> { return listOf(UpdatesModule(context) as ExportedModule) } override fun createReactNativeHostHandlers(context: Context): List<ReactNativeHostHandler> { val handler: ReactNativeHostHandler = object : ReactNativeHostHandler { private var mShouldAutoSetup: Boolean? = null override fun getJSBundleFile(useDeveloperSupport: Boolean): String? { return if (shouldAutoSetup(context) && !useDeveloperSupport) UpdatesController.instance.launchAssetFile else null } override fun getBundleAssetName(useDeveloperSupport: Boolean): String? { return if (shouldAutoSetup(context) && !useDeveloperSupport) UpdatesController.instance.bundleAssetName else null } override fun onWillCreateReactInstanceManager(useDeveloperSupport: Boolean) { if (shouldAutoSetup(context) && !useDeveloperSupport) { UpdatesController.initialize(context) } } override fun onDidCreateReactInstanceManager(reactInstanceManager: ReactInstanceManager, useDeveloperSupport: Boolean) { if (shouldAutoSetup(context) && !useDeveloperSupport) { UpdatesController.instance.onDidCreateReactInstanceManager(reactInstanceManager) } } @UiThread private fun shouldAutoSetup(context: Context): Boolean { if (mShouldAutoSetup == null) { mShouldAutoSetup = try { val pm = context.packageManager val ai = pm.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA) ai.metaData.getBoolean("expo.modules.updates.AUTO_SETUP", true) } catch (e: Exception) { Log.e(TAG, "Could not read expo-updates configuration data in AndroidManifest", e) true } } return mShouldAutoSetup!! } } return listOf(handler) } companion object { private val TAG = UpdatesPackage::class.java.simpleName } }
bsd-3-clause
0b1e4f34d162f5331f752956253be6d5
37.430556
126
0.735092
4.778929
false
false
false
false
kunalsheth/units-of-measure
plugin/src/main/kotlin/info/kunalsheth/units/Source.kt
1
5762
/* * Copyright 2019 Kunal Sheth * * 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 info.kunalsheth.units import info.kunalsheth.units.data.Dimension import info.kunalsheth.units.data.Quantity import info.kunalsheth.units.data.Relation import info.kunalsheth.units.data.RelationType.Divide import info.kunalsheth.units.data.RelationType.Multiply import info.kunalsheth.units.data.UnitOfMeasure import java.io.OutputStream /** * Created by kunal on 8/5/17. */ fun writeBase(writer: OutputStream) = ::UnitsOfMeasurePlugin::class.java .getResourceAsStream("/info/kunalsheth/units/generated/Base.kt") .copyTo(writer) private const val underlying = "underlying" private const val siValue = "siValue" private const val timesOperationProof = "times" private const val divOperationProof = "div" private fun quan(d: Dimension) = "Quan<$d>" fun Dimension.src(relations: Set<Relation>, quantities: Set<Quantity>, units: Set<UnitOfMeasure>): String { return """ typealias $this = $safeName inline class $safeName(internal val $underlying: Double) : ${quan(this)} { override val $siValue get() = $underlying override val abrev get() = "$abbreviation" override fun new($siValue: Double) = $this($siValue) override operator fun unaryPlus() = $this(+$underlying) override operator fun unaryMinus() = $this(-$underlying) override operator fun plus(that: $this) = $this(this.$underlying + that.$underlying) override operator fun minus(that: $this) = $this(this.$underlying - that.$underlying) override operator fun times(that: Number) = $this(this.$underlying * that.toDouble()) override operator fun div(that: Number) = $this(this.$underlying / that.toDouble()) override operator fun rem(that: $this) = $this(this.$underlying % that.$underlying) override infix fun min(that: $this) = if (this < that) this else that override infix fun max(that: $this) = if (this > that) this else that override val abs get() = $this(abs($underlying)) override val signum get() = $underlying.sign override val isNegative get() = $underlying < 0 override val isZero get() = $underlying == 0.0 override val isPositive get() = $underlying > 0 override fun compareTo(other: $this) = this.$underlying.compareTo(other.$underlying) override fun toString() = "${'$'}$underlying ${'$'}abrev" // override fun equals(other: Any?) = other is $this && this.siValue == other.siValue } ${units.joinToString(separator = "") { it.src(quantities .takeIf { it.size == 1 } ?.run(Set<Quantity>::first) ) }} ${quantities.joinToString(separator = "", transform = Quantity::src)} ${relations.joinToString(separator = "\n", transform = Relation::src)} """ } private fun Relation.src(): String { fun jvmName(category: String) = """@JvmName("${a.safeName}_${f.name}_${b.safeName}_$category")""" return when (f) { Divide -> { val logic = "$result(this.$siValue / that.$siValue)" """ ${jvmName("generic")} operator fun $a.div(that: ${quan(b)}) = $logic // ${jvmName("concrete")} operator fun $a.div(that: $b) = $logic ${jvmName("proof")} fun p(thiz: ${quan(a)}, op: $divOperationProof, that: ${quan(b)}) = thiz.run { $logic } """.trimIndent() } Multiply -> { val logic = "$result(this.$siValue * that.$siValue)" """ ${jvmName("generic")} operator fun $a.times(that: ${quan(b)}) = $logic // ${jvmName("concrete")} operator fun $a.times(that: $b) = $logic ${jvmName("proof")} fun p(thiz: ${quan(a)}, op: $timesOperationProof, that: ${quan(b)}) = thiz.run { $logic } """.trimIndent() } } } private fun Quantity.src() = """ typealias $this = $dimension """ private fun UnitOfMeasure.src(quantity: Quantity?) = """ inline val Number.$this: ${quantity ?: dimension} get() = $dimension(toDouble() * $factorToSI) inline val $dimension.$this get() = $siValue * ${1 / factorToSI} object $this : UomConverter<$dimension>, ${quan(dimension)} by $dimension($factorToSI) { override val unitName = "$name" override fun invoke(x: Double) = x.$this override fun invoke(x: $dimension) = x.$this } """ val mathDependencies = setOf( Dimension(), Dimension(L = 1), Dimension(A = 1), Dimension(L = 1, A = 1), Dimension(L = 1, T = -1, A = 1), Dimension(L = 1, T = -2, A = 1) ) fun writeMath(writer: OutputStream) = ::UnitsOfMeasurePlugin::class.java .getResourceAsStream("/info/kunalsheth/units/math/Math.kt") .copyTo(writer)
mit
bd737a3de90351a3bc62f5c48476874f
40.460432
129
0.658625
3.941176
false
false
false
false
Undin/intellij-rust
coverage/src/main/kotlin/org/rust/coverage/RsCoverageAnnotator.kt
2
1311
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.coverage import com.intellij.coverage.SimpleCoverageAnnotator import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import java.io.File class RsCoverageAnnotator(project: Project) : SimpleCoverageAnnotator(project) { override fun fillInfoForUncoveredFile(file: File): FileCoverageInfo = FileCoverageInfo() override fun getLinesCoverageInformationString(info: FileCoverageInfo): String? = when { info.totalLineCount == 0 -> null info.coveredLineCount == 0 -> "no lines covered" info.coveredLineCount * 100 < info.totalLineCount -> "<1% lines covered" else -> "${calcCoveragePercentage(info)}% lines covered" } override fun getFilesCoverageInformationString(info: DirCoverageInfo): String? = when { info.totalFilesCount == 0 -> null info.coveredFilesCount == 0 -> "${info.coveredFilesCount} of ${info.totalFilesCount} files covered" else -> "${info.coveredFilesCount} of ${info.totalFilesCount} files" } companion object { fun getInstance(project: Project): RsCoverageAnnotator = project.service() } }
mit
d8ecd50d2aa67781177f3bb387d9512c
37.558824
111
0.694127
4.505155
false
false
false
false
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/model/Impuesto.kt
1
896
package com.quijotelui.model import org.hibernate.annotations.Immutable import java.io.Serializable import java.math.BigDecimal import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Table @Entity @Immutable @Table(name = "v_ele_impuestos") class Impuesto : Serializable { @Id @Column(name = "id") var id : Long? = null @Column(name = "codigo") var codigo : String? = null @Column(name = "numero") var numero : String? = null @Column(name = "codigo_impuesto") var codigoImpuesto : String? = null @Column(name = "codigo_porcentaje") var codigoPorcentaje : String? = null @Column(name = "base_imponible") var baseImponible : BigDecimal? = null @Column(name = "tarifa") var tarifa : BigDecimal? = null @Column(name = "valor") var valor : BigDecimal? = null }
gpl-3.0
4847215f071152e327a5219846844783
21.4
42
0.683036
3.555556
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/util/converter/RoomConverters.kt
2
1627
package me.proxer.app.util.converter import androidx.room.TypeConverter import me.proxer.library.enums.Device import me.proxer.library.enums.MessageAction import me.proxer.library.enums.TagSubType import me.proxer.library.enums.TagType import me.proxer.library.util.ProxerUtils import org.threeten.bp.Instant import java.util.Date /** * @author Ruben Gees */ @Suppress("unused") class RoomConverters { @TypeConverter fun fromDate(date: Date?) = date?.time @TypeConverter fun toDate(value: Long?) = value?.let { Date(it) } @TypeConverter fun fromInstant(date: Instant?) = date?.toEpochMilli() @TypeConverter fun toInstant(value: Long?) = value?.let { Instant.ofEpochMilli(it) } @TypeConverter fun fromMessageAction(value: MessageAction?) = value?.let { ProxerUtils.getSafeApiEnumName(it) } @TypeConverter fun toMessageAction(value: String?) = value?.let { ProxerUtils.toSafeApiEnum<MessageAction>(it) } @TypeConverter fun fromDevice(value: Device?) = value?.let { ProxerUtils.getSafeApiEnumName(it) } @TypeConverter fun toDevice(value: String?) = value?.let { ProxerUtils.toSafeApiEnum<Device>(it) } @TypeConverter fun fromTagType(value: TagType?) = value?.let { ProxerUtils.getSafeApiEnumName(it) } @TypeConverter fun toTagType(value: String?) = value?.let { ProxerUtils.toSafeApiEnum<TagType>(it) } @TypeConverter fun fromTagSubType(value: TagSubType?) = value?.let { ProxerUtils.getSafeApiEnumName(it) } @TypeConverter fun toTagSubType(value: String?) = value?.let { ProxerUtils.toSafeApiEnum<TagSubType>(it) } }
gpl-3.0
45f3a99b9ae065b8cd33b9f40b12bdb7
29.698113
101
0.72772
3.783721
false
false
false
false
wordpress-mobile/AztecEditor-Android
aztec/src/main/kotlin/org/wordpress/aztec/EnhancedMovementMethod.kt
1
4142
package org.wordpress.aztec import android.graphics.Rect import android.text.Spannable import android.text.method.ArrowKeyMovementMethod import android.text.style.ClickableSpan import android.view.MotionEvent import android.widget.TextView import org.wordpress.aztec.spans.AztecMediaClickableSpan import org.wordpress.aztec.spans.AztecURLSpan import org.wordpress.aztec.spans.UnknownClickableSpan /** * http://stackoverflow.com/a/23566268/569430 */ object EnhancedMovementMethod : ArrowKeyMovementMethod() { var taskListClickHandler: TaskListClickHandler? = null var isLinkTapEnabled = false var linkTappedListener: AztecText.OnLinkTappedListener? = null override fun onTouchEvent(widget: TextView, text: Spannable, event: MotionEvent): Boolean { val action = event.action if (action == MotionEvent.ACTION_UP) { var x = event.x.toInt() var y = event.y.toInt() x -= widget.totalPaddingLeft y -= widget.totalPaddingTop x += widget.scrollX y += widget.scrollY if (x < 0) return true val layout = widget.layout val line = layout.getLineForVertical(y) val off = layout.getOffsetForHorizontal(line, x.toFloat()) // This handles the case when the task list checkbox is clicked if (taskListClickHandler?.handleTaskListClick(text, off, x, widget.totalPaddingStart) == true) return true // get the character's position. This may be the left or the right edge of the character so, find the // other edge by inspecting nearby characters (if they exist) val charX = layout.getPrimaryHorizontal(off) val charPrevX = if (off > 0) layout.getPrimaryHorizontal(off - 1) else charX val charNextX = if (off < text.length) layout.getPrimaryHorizontal(off + 1) else charX val lineRect = Rect() layout.getLineBounds(line, lineRect) val clickedWithinLineHeight = y >= lineRect.top && y <= lineRect.bottom val clickedOnSpanToTheLeftOfCursor = x.toFloat() in charPrevX..charX val clickedOnSpanToTheRightOfCursor = x.toFloat() in charX..charNextX val clickedOnSpan = clickedWithinLineHeight && (clickedOnSpanToTheLeftOfCursor || clickedOnSpanToTheRightOfCursor) val clickedSpanBordersAnotherOne = (text.getSpans(off, off, ClickableSpan::class.java).size == 1 && text.getSpans(off + 1, off + 1, ClickableSpan::class.java).isNotEmpty()) val isClickedSpanAmbiguous = text.getSpans(off, off, ClickableSpan::class.java).size > 1 val failedToPinpointClickedSpan = (isClickedSpanAmbiguous || clickedSpanBordersAnotherOne) && !clickedOnSpanToTheLeftOfCursor && !clickedOnSpanToTheRightOfCursor var link: ClickableSpan? = null if (clickedOnSpan) { if (isClickedSpanAmbiguous) { if (clickedOnSpanToTheLeftOfCursor) { link = text.getSpans(off, off, ClickableSpan::class.java)[0] } else if (clickedOnSpanToTheRightOfCursor) { link = text.getSpans(off, off, ClickableSpan::class.java)[1] } } else { link = text.getSpans(off, off, ClickableSpan::class.java).firstOrNull() } } else if (failedToPinpointClickedSpan) { link = text.getSpans(off, off, ClickableSpan::class.java).firstOrNull { text.getSpanStart(it) == off } } if (link != null) { if (link is AztecMediaClickableSpan || link is UnknownClickableSpan) { link.onClick(widget) return true } else if (link is AztecURLSpan && isLinkTapEnabled) { linkTappedListener?.onLinkTapped(widget, link.url) ?: link.onClick(widget) return true } } } return super.onTouchEvent(widget, text, event) } }
mpl-2.0
47f8d4c834f791051a455601364dc250
42.145833
118
0.627958
4.680226
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/ui/crop/CropViewModel.kt
1
4284
package at.ac.tuwien.caa.docscan.ui.crop import android.graphics.PointF import android.os.Bundle import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import at.ac.tuwien.caa.docscan.db.model.Page import at.ac.tuwien.caa.docscan.db.model.exif.Rotation import at.ac.tuwien.caa.docscan.db.model.getSingleBoundaryPoints import at.ac.tuwien.caa.docscan.logic.* import at.ac.tuwien.caa.docscan.repository.ImageProcessorRepository import at.ac.tuwien.caa.docscan.ui.crop.CropViewActivity.Companion.EXTRA_PAGE import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.io.File import java.util.* class CropViewModel( extras: Bundle, private val imageProcessorRepository: ImageProcessorRepository, private val fileHandler: FileHandler, val preferencesHandler: PreferencesHandler ) : ViewModel() { val page = extras.getParcelable<Page>(EXTRA_PAGE)!! val observableInitBackNavigation = MutableLiveData<Event<Unit>>() val observableShowCroppingInfo = MutableLiveData<Event<Unit>>() val observableError = MutableLiveData<Event<Throwable>>() // note that the very first value of the model will force the image to load into the imageview. val observableModel = MutableLiveData<CropModel>() var isRotating = false private val file = fileHandler.createCacheFile(page.id) var model = CropModel( page.id, file, page.rotation, page.rotation, calculateImageResolution(file, page.rotation), page.getSingleBoundaryPoints() ) init { init() } private fun init() { viewModelScope.launch(Dispatchers.IO) { val pageFile = fileHandler.getFileByPage(page) ?: kotlin.run { observableInitBackNavigation.postValue(Event(Unit)) return@launch } // clear the currently cached file file.safelyDelete() // create a copy of the file, so any manipulations can be easily reverted. fileHandler.safelyCopyFile( pageFile, model.file ) observableModel.postValue(model) } } fun navigateBack() { viewModelScope.launch(Dispatchers.IO) { file.safelyDelete() observableInitBackNavigation.postValue(Event(Unit)) } } fun rotateBy90Degree(croppingPoints: List<PointF>) { if (isRotating) { return } isRotating = true viewModelScope.launch(Dispatchers.IO) { model.points = croppingPoints model.previousRotation = model.rotation model.rotation = model.rotation.rotateBy90Clockwise() imageProcessorRepository.rotateFile(model.file, model.rotation) model.meta = calculateImageResolution(model.file, model.rotation) observableModel.postValue(model) } } fun save(croppingPoints: List<PointF>) { viewModelScope.launch(Dispatchers.IO) { model.points = croppingPoints when(val resource = imageProcessorRepository.replacePageFileBy( pageId = page.id, cachedFile = model.file, rotation = model.rotation, croppingPoints = model.points )) { is Failure -> { observableError.postValue(Event(resource.exception)) } is Success -> { model.file.safelyDelete() if (preferencesHandler.showCroppingInfo) { observableShowCroppingInfo.postValue(Event(Unit)) } else { observableInitBackNavigation.postValue(Event(Unit)) } } } } } fun updateCroppingPoints(croppingPoints: List<PointF>) { model.points = croppingPoints } } data class CropModel( val id: UUID, val file: File, var previousRotation: Rotation, var rotation: Rotation, var meta: ImageMeta, var points: List<PointF> ) data class ImageMeta(val width: Int, val height: Int, val aspectRatio: Double)
lgpl-3.0
b517e617daa85a8b151bab89f3213f01
31.70229
99
0.634687
4.707692
false
false
false
false
wordpress-mobile/AztecEditor-Android
wordpress-shortcodes/src/main/java/org/wordpress/aztec/plugins/shortcodes/extensions/CaptionExtensions.kt
1
4839
package org.wordpress.aztec.plugins.shortcodes.extensions import android.text.Layout import android.text.Spanned import org.wordpress.aztec.AztecAttributes import org.wordpress.aztec.AztecText import org.wordpress.aztec.plugins.shortcodes.CaptionShortcodePlugin import org.wordpress.aztec.plugins.shortcodes.spans.CaptionShortcodeSpan import org.wordpress.aztec.plugins.shortcodes.spans.createCaptionShortcodeSpan import org.wordpress.aztec.spans.AztecImageSpan import org.wordpress.aztec.spans.IAztecAlignmentSpan import org.wordpress.aztec.spans.IAztecNestable import org.wordpress.aztec.util.SpanWrapper fun AztecText.getImageCaption(attributePredicate: AztecText.AttributePredicate): String { return this.text.getSpans(0, this.text.length, AztecImageSpan::class.java) .firstOrNull { attributePredicate.matches(it.attributes) } ?.getCaption() ?: "" } fun AztecText.getImageCaptionAttributes(attributePredicate: AztecText.AttributePredicate): AztecAttributes { return this.text.getSpans(0, this.text.length, AztecImageSpan::class.java) .firstOrNull { attributePredicate.matches(it.attributes) } ?.getCaptionAttributes() ?: AztecAttributes() } @JvmOverloads fun AztecText.setImageCaption(attributePredicate: AztecText.AttributePredicate, value: String, attrs: AztecAttributes? = null) { this.text.getSpans(0, this.text.length, AztecImageSpan::class.java) .firstOrNull { attributePredicate.matches(it.attributes) } ?.setCaption(value, attrs) } fun AztecText.removeImageCaption(attributePredicate: AztecText.AttributePredicate) { this.text.getSpans(0, this.text.length, AztecImageSpan::class.java) .firstOrNull { attributePredicate.matches(it.attributes) } ?.removeCaption() } fun AztecText.hasImageCaption(attributePredicate: AztecText.AttributePredicate): Boolean { this.text.getSpans(0, this.text.length, AztecImageSpan::class.java) .firstOrNull { attributePredicate.matches(it.attributes) } ?.let { val wrapper = SpanWrapper(text, it) return text.getSpans(wrapper.start, wrapper.end, CaptionShortcodeSpan::class.java).isNotEmpty() } return false } fun AztecImageSpan.getCaption(): String { textView?.get()?.text?.let { editable -> val wrapper = SpanWrapper(editable, this) editable.getSpans(wrapper.start, wrapper.end, CaptionShortcodeSpan::class.java).firstOrNull()?.let { return it.caption } } return "" } fun AztecImageSpan.getCaptionAttributes(): AztecAttributes { textView?.get()?.text?.let { editable -> val wrapper = SpanWrapper(editable, this) editable.getSpans(wrapper.start, wrapper.end, CaptionShortcodeSpan::class.java).firstOrNull()?.let { return it.attributes } } return AztecAttributes() } @JvmOverloads fun AztecImageSpan.setCaption(value: String, attrs: AztecAttributes? = null) { textView?.get()?.text?.let { editable -> val wrapper = SpanWrapper(editable, this) var captionSpan = editable.getSpans(wrapper.start, wrapper.end, CaptionShortcodeSpan::class.java)?.firstOrNull() if (captionSpan == null) { captionSpan = createCaptionShortcodeSpan( AztecAttributes(), CaptionShortcodePlugin.HTML_TAG, IAztecNestable.getNestingLevelAt(editable, wrapper.start), textView?.get()!!) editable.setSpan(captionSpan, wrapper.start, wrapper.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } captionSpan.caption = value if (captionSpan is IAztecAlignmentSpan) { attrs?.let { captionSpan.attributes = attrs if (captionSpan.attributes.hasAttribute(CaptionShortcodePlugin.ALIGN_ATTRIBUTE)) { when (captionSpan.attributes.getValue(CaptionShortcodePlugin.ALIGN_ATTRIBUTE)) { CaptionShortcodePlugin.ALIGN_RIGHT_ATTRIBUTE_VALUE -> captionSpan.align = Layout.Alignment.ALIGN_OPPOSITE CaptionShortcodePlugin.ALIGN_CENTER_ATTRIBUTE_VALUE -> captionSpan.align = Layout.Alignment.ALIGN_CENTER CaptionShortcodePlugin.ALIGN_LEFT_ATTRIBUTE_VALUE -> captionSpan.align = Layout.Alignment.ALIGN_NORMAL } } else { captionSpan.align = null } } } } } fun AztecImageSpan.removeCaption() { textView?.get()?.text?.let { editable -> val wrapper = SpanWrapper(editable, this) editable.getSpans(wrapper.start, wrapper.end, CaptionShortcodeSpan::class.java).firstOrNull()?.remove() } }
mpl-2.0
5112842bf7315dd868c2c6bca45486ca
38.991736
129
0.678653
4.5394
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/HabitButtonWidgetActivity.kt
1
4164
package com.habitrpg.android.habitica.ui.activities import android.app.Activity import android.appwidget.AppWidgetManager import android.content.Intent import android.os.Bundle import android.view.View import androidx.core.content.edit import androidx.preference.PreferenceManager import androidx.recyclerview.widget.LinearLayoutManager import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.TaskRepository import com.habitrpg.android.habitica.databinding.WidgetConfigureHabitButtonBinding import com.habitrpg.android.habitica.helpers.ExceptionHandler import com.habitrpg.android.habitica.modules.AppModule import com.habitrpg.android.habitica.ui.adapter.SkillTasksRecyclerViewAdapter import com.habitrpg.android.habitica.widget.HabitButtonWidgetProvider import com.habitrpg.shared.habitica.models.tasks.TaskType import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.launch import javax.inject.Inject import javax.inject.Named class HabitButtonWidgetActivity : BaseActivity() { private val job = SupervisorJob() private lateinit var binding: WidgetConfigureHabitButtonBinding @Inject lateinit var taskRepository: TaskRepository @field:[Inject Named(AppModule.NAMED_USER_ID)] lateinit var userId: String private var widgetId: Int = 0 private var adapter: SkillTasksRecyclerViewAdapter? = null override fun getLayoutResId(): Int { return R.layout.widget_configure_habit_button } override fun getContentView(): View { binding = WidgetConfigureHabitButtonBinding.inflate(layoutInflater) return binding.root } override fun injectActivity(component: UserComponent?) { component?.inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intent val extras = intent.extras if (extras != null) { widgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) } // If this activity was started with an intent without an app widget ID, // finish with an error. if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { finish() } var layoutManager: LinearLayoutManager? = binding.recyclerView.layoutManager as? LinearLayoutManager if (layoutManager == null) { layoutManager = LinearLayoutManager(this) binding.recyclerView.layoutManager = layoutManager } adapter = SkillTasksRecyclerViewAdapter() adapter?.getTaskSelectionEvents()?.subscribe( { task -> taskSelected(task.id) }, ExceptionHandler.rx() )?.let { compositeSubscription.add(it) } binding.recyclerView.adapter = adapter CoroutineScope(Dispatchers.Main + job).launch(ExceptionHandler.coroutine()) { adapter?.data = taskRepository.getTasks(TaskType.HABIT, userId, emptyArray()).firstOrNull() ?: listOf() } } private fun taskSelected(taskId: String?) { finishWithSelection(taskId) } private fun finishWithSelection(selectedTaskId: String?) { storeSelectedTaskId(selectedTaskId) val resultValue = Intent() resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId) setResult(Activity.RESULT_OK, resultValue) finish() val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, HabitButtonWidgetProvider::class.java) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(widgetId)) sendBroadcast(intent) } private fun storeSelectedTaskId(selectedTaskId: String?) { PreferenceManager.getDefaultSharedPreferences(this).edit { putString("habit_button_widget_$widgetId", selectedTaskId) } } }
gpl-3.0
3e4413baadf4281a0ad3a9bfdeb062e2
35.513514
120
0.716378
5.071864
false
false
false
false
austinv11/KotBot-IV
Core/src/main/kotlin/com/austinv11/kotbot/core/db/DatabaseManager.kt
1
1922
package com.austinv11.kotbot.core.db import com.austinv11.kotbot.core.api.commands.PermissionLevel import com.j256.ormlite.dao.Dao import com.j256.ormlite.dao.DaoManager import com.j256.ormlite.field.DataType import com.j256.ormlite.field.DatabaseField import com.j256.ormlite.jdbc.JdbcConnectionSource import com.j256.ormlite.table.DatabaseTable import com.j256.ormlite.table.TableUtils object DatabaseManager { /** * This is the url leading to the database. */ const val DATABASE_URL = "jdbc:sqlite:database.db" val CONNECTION_SOURCE = JdbcConnectionSource(DATABASE_URL) val PERMISSIONS_DAO: Dao<PermissionHolder, Int> = DaoManager.createDao(CONNECTION_SOURCE, PermissionHolder::class.java) init { TableUtils.createTableIfNotExists(CONNECTION_SOURCE, PermissionHolder::class.java) Runtime.getRuntime().addShutdownHook(Thread({ CONNECTION_SOURCE.close() })) } @DatabaseTable(tableName = "accounts") class PermissionHolder { constructor() constructor(user: String, permissions: PermissionLevel) { this.user = user this.permissions = permissions PERMISSIONS_DAO.create(this) } companion object Columns { const val ID = "id" const val USER_ID = "user" const val PERMISSION_LEVEL = "permissions" const val GUILD_ID = "guild" } @DatabaseField(columnName = ID, generatedId = true) var id: Int = 0 @DatabaseField(columnName = USER_ID, canBeNull = false) var user: String = "" @DatabaseField(columnName = PERMISSION_LEVEL, canBeNull = false, dataType = DataType.ENUM_STRING) var permissions: PermissionLevel = PermissionLevel.BASIC @DatabaseField(columnName = GUILD_ID ,canBeNull = false) var guild: String = "" } }
gpl-3.0
91403ad20599cf2ce9080ce22161b57d
31.576271
123
0.663892
4.358277
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/auth/ui/activity/SocialAuthActivity.kt
1
14970
package org.stepik.android.view.auth.ui.activity import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.text.Spannable import android.text.SpannableString import androidx.activity.viewModels import androidx.core.content.res.ResourcesCompat import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import com.facebook.CallbackManager import com.facebook.FacebookCallback import com.facebook.FacebookException import com.facebook.login.LoginManager import com.facebook.login.LoginResult import com.google.android.gms.auth.api.Auth import com.google.android.gms.common.api.GoogleApiClient import com.vk.api.sdk.VK import com.vk.api.sdk.auth.VKAccessToken import com.vk.api.sdk.auth.VKAuthCallback import com.vk.api.sdk.auth.VKScope import com.vk.api.sdk.exceptions.VKApiCodes import jp.wasabeef.recyclerview.animators.FadeInDownAnimator import kotlinx.android.synthetic.main.activity_auth_social.* import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.analytic.experiments.DeferredAuthSplitTest import org.stepic.droid.analytic.experiments.OnboardingSplitTestVersion2 import org.stepic.droid.base.App import org.stepic.droid.model.Credentials import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.ui.activities.MainFeedActivity import org.stepic.droid.ui.activities.SmartLockActivityBase import org.stepic.droid.ui.adapters.SocialAuthAdapter import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment import org.stepic.droid.ui.util.snackbar import org.stepic.droid.util.ProgressHelper import org.stepik.android.domain.auth.model.LoginFailType import org.stepik.android.model.Course import org.stepik.android.presentation.auth.SocialAuthPresenter import org.stepik.android.presentation.auth.SocialAuthView import org.stepik.android.view.auth.extension.getMessageFor import org.stepik.android.view.auth.model.AutoAuth import org.stepik.android.view.auth.model.SocialNetwork import org.stepik.android.view.base.ui.span.TypefaceSpanCompat import javax.inject.Inject class SocialAuthActivity : SmartLockActivityBase(), SocialAuthView { companion object { private const val REQUEST_CODE_GOOGLE_SIGN_IN = 7007 private const val KEY_SOCIAL_ADAPTER_STATE = "social_adapter_state_key" private const val KEY_SELECTED_SOCIAL_TYPE = "selected_social_type" private const val EXTRA_WAS_LOGOUT_KEY = "wasLogoutKey" private const val EXTRA_COURSE = "course" private const val EXTRA_IS_FROM_MAIN_FEED = "is_from_main_feed" private const val EXTRA_MAIN_CURRENT_INDEX = "main_current_index" fun createIntent(context: Context, course: Course? = null, wasLogout: Boolean = false): Intent = Intent(context, SocialAuthActivity::class.java) .putExtra(EXTRA_COURSE, course) .putExtra(EXTRA_WAS_LOGOUT_KEY, wasLogout) fun createIntent(context: Context, isFromMainFeed: Boolean, mainCurrentIndex: Int): Intent = Intent(context, SocialAuthActivity::class.java) .putExtra(EXTRA_IS_FROM_MAIN_FEED, isFromMainFeed) .putExtra(EXTRA_MAIN_CURRENT_INDEX, mainCurrentIndex) } @Inject lateinit var deferredAuthSplitTest: DeferredAuthSplitTest @Inject lateinit var onboardingSplitTestVersion2: OnboardingSplitTestVersion2 @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory @Inject internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper private val socialAuthPresenter: SocialAuthPresenter by viewModels { viewModelFactory } private val progressDialogFragment: DialogFragment = LoadingProgressDialogFragment.newInstance() private lateinit var callbackManager: CallbackManager private var selectedSocialType: SocialNetwork? = null private var course: Course? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_auth_social) course = intent.getParcelableExtra(EXTRA_COURSE) injectComponent() overridePendingTransition(R.anim.no_transition, R.anim.slide_out_to_bottom) dismissButton.setOnClickListener { onBackPressed() } dismissButton.isVisible = true // dismissButton.isVisible = deferredAuthSplitTest.currentGroup.isDeferredAuth || onboardingSplitTest.currentGroup == OnboardingSplitTest.Group.Personalized launchSignUpButton.setOnClickListener { analytic.reportEvent(Analytic.Interaction.CLICK_SIGN_UP) screenManager.showRegistration(this@SocialAuthActivity, course) } signInWithEmail.setOnClickListener { analytic.reportEvent(Analytic.Interaction.CLICK_SIGN_IN) screenManager.showLogin(this@SocialAuthActivity, null, null, AutoAuth.NONE, course) } initGoogleApiClient(true) { showNetworkError() } val recyclerState = savedInstanceState?.getSerializable(KEY_SOCIAL_ADAPTER_STATE) if (recyclerState is SocialAuthAdapter.State) { initSocialRecycler(recyclerState) } else { initSocialRecycler() } selectedSocialType = savedInstanceState?.getSerializable(KEY_SELECTED_SOCIAL_TYPE) as? SocialNetwork val signInString = getString(R.string.sign_in) val signInWithSocial = getString(R.string.sign_in_with_social_suffix) val spannableSignIn = SpannableString(signInString + signInWithSocial) val typefaceSpan = TypefaceSpanCompat(ResourcesCompat.getFont(this, R.font.roboto_medium)) spannableSignIn.setSpan(typefaceSpan, 0, signInString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) signInText.text = spannableSignIn callbackManager = CallbackManager.Factory.create() LoginManager.getInstance().registerCallback(callbackManager, object : FacebookCallback<LoginResult> { override fun onSuccess(loginResult: LoginResult) { socialAuthPresenter .authWithNativeCode(loginResult.accessToken.token, SocialNetwork.FACEBOOK) } override fun onCancel() {} override fun onError(exception: FacebookException) { analytic.reportError(Analytic.Login.FACEBOOK_ERROR, exception) showNetworkError() } }) if (checkPlayServices()) { googleApiClient?.registerConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks { override fun onConnected(bundle: Bundle?) { val wasLogout = intent?.getBooleanExtra(EXTRA_WAS_LOGOUT_KEY, false) ?: false if (wasLogout) { Auth.CredentialsApi.disableAutoSignIn(googleApiClient) } requestCredentials() } override fun onConnectionSuspended(cause: Int) {} }) } onNewIntent(intent) } private fun injectComponent() { App.component() .authComponentBuilder() .build() .inject(this) } override fun onResume() { super.onResume() /** * On Android 4, 5, 6 onSaveInstanceState is called after onStart * and we can't show fragment dialog after onSaveInstanceState */ socialAuthPresenter.attachView(this) } override fun onPause() { socialAuthPresenter.detachView(this) super.onPause() } private fun initSocialRecycler(state: SocialAuthAdapter.State = SocialAuthAdapter.State.NORMAL) { socialListRecyclerView.layoutManager = GridLayoutManager(this, 3) socialListRecyclerView.itemAnimator = FadeInDownAnimator() .apply { removeDuration = 0 } val adapter = SocialAuthAdapter(this::onSocialItemClicked, state) showMore.setOnClickListener { showMore.isVisible = false showLess.isVisible = true adapter.showMore() } showLess.setOnClickListener { showLess.isVisible = false showMore.isVisible = true adapter.showLess() } showLess.isVisible = state == SocialAuthAdapter.State.EXPANDED showMore.isVisible = state == SocialAuthAdapter.State.NORMAL socialListRecyclerView.adapter = adapter } private fun onSocialItemClicked(type: SocialNetwork) { analytic.reportEvent(Analytic.Interaction.CLICK_SIGN_IN_SOCIAL, type.identifier) when (type) { SocialNetwork.GOOGLE -> { if (googleApiClient == null) { analytic.reportEvent(Analytic.Interaction.GOOGLE_SOCIAL_IS_NOT_ENABLED) root_view.snackbar(messageRes = R.string.google_services_late) } else { val signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient) startActivityForResult(signInIntent, REQUEST_CODE_GOOGLE_SIGN_IN) } } SocialNetwork.FACEBOOK -> LoginManager.getInstance().logInWithReadPermissions(this, listOf("email")) SocialNetwork.VK -> VK.login(this, listOf(VKScope.OFFLINE, VKScope.EMAIL)) else -> { selectedSocialType = type screenManager.loginWithSocial(this, type) } } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) if (intent?.data != null) { redirectFromSocial(intent) } } private fun redirectFromSocial(intent: Intent) { val code = intent.data?.getQueryParameter("code") ?: return val socialType = selectedSocialType ?: return socialAuthPresenter.authWithCode(code, socialType) } override fun onCredentialsRetrieved(credentials: Credentials) { screenManager.showLogin(this, credentials.login, credentials.password, AutoAuth.SMART_LOCK, course) } override fun onBackPressed() { val fromMainFeed = intent?.extras?.getBoolean(EXTRA_IS_FROM_MAIN_FEED) ?: false val index = intent?.extras?.getInt(EXTRA_MAIN_CURRENT_INDEX) ?: MainFeedActivity.defaultIndex when { fromMainFeed -> screenManager.showMainFeed(this, index) course != null -> super.onBackPressed() (onboardingSplitTestVersion2.currentGroup == OnboardingSplitTestVersion2.Group.Personalized || onboardingSplitTestVersion2.currentGroup == OnboardingSplitTestVersion2.Group.ControlPersonalized) && !sharedPreferenceHelper.isPersonalizedOnboardingWasShown -> screenManager.showPersonalizedOnboarding(this) // deferredAuthSplitTest.currentGroup.isDeferredAuth -> // screenManager.showMainFeed(this, MainFeedActivity.CATALOG_INDEX) else -> screenManager.showMainFeed(this, MainFeedActivity.CATALOG_INDEX) } } override fun finish() { super.finish() overridePendingTransition(R.anim.no_transition, R.anim.slide_out_to_bottom) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (data != null && VK.onActivityResult(requestCode, resultCode, data, object : VKAuthCallback { override fun onLogin(token: VKAccessToken) { socialAuthPresenter .authWithNativeCode(token.accessToken, SocialNetwork.VK, token.email) } override fun onLoginFailed(errorCode: Int) { if (errorCode == VKApiCodes.CODE_AUTHORIZATION_FAILED) { showNetworkError() } } })) { // vk will handle at callback return } super.onActivityResult(requestCode, resultCode, data) callbackManager.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_GOOGLE_SIGN_IN && resultCode == Activity.RESULT_OK) { val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data) // here is not only fail due to Internet, fix it. see: https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInResult if (result?.isSuccess == true) { val authCode = result.signInAccount?.serverAuthCode if (authCode == null) { analytic.reportEvent(Analytic.Login.GOOGLE_AUTH_CODE_NULL) showNetworkError() return } socialAuthPresenter .authWithNativeCode(authCode, SocialNetwork.GOOGLE) } else { // check statusCode here https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes val statusCode = result?.status?.statusCode?.toString() ?: "was null" analytic.reportEvent(Analytic.Login.GOOGLE_FAILED_STATUS, statusCode) showNetworkError() } } } override fun setState(state: SocialAuthView.State) { if (state is SocialAuthView.State.Loading) { ProgressHelper.activate(progressDialogFragment, supportFragmentManager, LoadingProgressDialogFragment.TAG) } else { ProgressHelper.dismiss(supportFragmentManager, LoadingProgressDialogFragment.TAG) } when (state) { is SocialAuthView.State.Success -> screenManager.showMainFeedAfterLogin(this, course) } } override fun showAuthError(failType: LoginFailType) { root_view.snackbar(message = getMessageFor(failType)) // logout from socials VK.logout() if (googleApiClient?.isConnected == true) { Auth.GoogleSignInApi.signOut(googleApiClient) } // fb: LoginManager.getInstance().logOut() } override fun showNetworkError() { root_view.snackbar(messageRes = R.string.connectionProblems) } override fun onSocialLoginWithExistingEmail(email: String) { screenManager.showLogin(this, email, null, AutoAuth.NONE, course) } override fun onSaveInstanceState(outState: Bundle) { val adapter = socialListRecyclerView.adapter if (adapter is SocialAuthAdapter) { outState.putSerializable(KEY_SOCIAL_ADAPTER_STATE, adapter.state) } selectedSocialType?.let { outState.putSerializable(KEY_SELECTED_SOCIAL_TYPE, it) } super.onSaveInstanceState(outState) } }
apache-2.0
8bf1020e3e1c872afa8bafcc7bb3dad7
38.188482
181
0.678357
4.938964
false
false
false
false
android/tv-samples
ReferenceAppKotlin/app/src/main/java/com/android/tv/reference/watchnext/WatchNextWorker.kt
1
3977
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference.watchnext import android.annotation.SuppressLint import android.app.Application import android.content.Context import androidx.work.Worker import androidx.work.WorkerParameters import com.android.tv.reference.repository.VideoRepositoryFactory import com.android.tv.reference.shared.datamodel.VideoType import timber.log.Timber /** * Worker triggered by WorkManager to add/update/remove video to Watch Next channel. * * <code> * WorkManager.getInstance(context).enqueue(OneTimeWorkRequest.Builder(WatchNextWorker::class.java).build()) * </code> */ class WatchNextWorker(private val context: Context, params: WorkerParameters) : Worker(context, params) { /** * Worker thread to add/update/remove content from Watch Next channel. * Events triggered from player state change events & * playback lifecycle events (onPause) are consumed here. */ @SuppressLint("RestrictedApi") // Suppress RestrictedApi due to https://b.corp.google.com/issues/138150076 override fun doWork(): Result { // Step 1 : get the video information from the "inputData". val videoId = inputData.getString(WatchNextHelper.VIDEO_ID) val watchPosition = inputData.getLong(WatchNextHelper.CURRENT_POSITION, /* defaultValue= */ 0) val state = inputData.getString(WatchNextHelper.PLAYER_STATE) Timber.v("Work Manager called watch id $videoId , watchTime $watchPosition") // Step 2 : Check for invalid inputData. // If videoId is invalid, abort worker and return. if (videoId.isNullOrEmpty()) { Timber.e("Error.Invalid entry for Watch Next. videoid: $videoId") return Result.failure() } // Check for invalid player state. if ((state != WatchNextHelper.PLAY_STATE_PAUSED) and (state != WatchNextHelper.PLAY_STATE_ENDED) ) { Timber.e("Error.Invalid entry for Watch Next. Player state: $state") return Result.failure() } // Step 3: Get video object from videoId to be added to Watch Next. val video = VideoRepositoryFactory.getVideoRepository(context.applicationContext as Application) .getVideoById(videoId) Timber.v("Retrieved video from repository with id %s, %s", videoId, video) // Step 4 : Handle Watch Next for different types of content. when (video?.videoType) { VideoType.MOVIE -> { Timber.v("Add Movie to Watch Next : id = ${video.id}") WatchNextHelper.handleWatchNextForMovie(video, watchPosition.toInt(), state, context) } VideoType.EPISODE -> { Timber.v("Add Episode to Watch Next : id = ${video.id}") WatchNextHelper.handleWatchNextForEpisode( video, watchPosition.toInt(), state, VideoRepositoryFactory.getVideoRepository( context.applicationContext as Application), context) } VideoType.CLIP -> Timber.w( "NOT recommended to add Clips / Trailers /Short videos to Watch Next " ) else -> Timber.e("Invalid category for Video Type: ${video?.videoType}") } Timber.v("WatchNextWorker finished") return Result.success() } }
apache-2.0
fc766a71ad34567b5efd14921148120c
40
108
0.66432
4.673325
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/source/online/UrlImportableSource.kt
1
828
package eu.kanade.tachiyomi.source.online import android.net.Uri import eu.kanade.tachiyomi.source.Source import java.net.URI import java.net.URISyntaxException interface UrlImportableSource : Source { val matchingHosts: List<String> fun matchesUri(uri: Uri): Boolean { return (uri.host ?: "").toLowerCase() in matchingHosts } // This method is allowed to block for IO if necessary fun mapUrlToMangaUrl(uri: Uri): String? fun cleanMangaUrl(url: String): String { return try { val uri = URI(url) var out = uri.path if (uri.query != null) out += "?" + uri.query if (uri.fragment != null) out += "#" + uri.fragment out } catch (e: URISyntaxException) { url } } }
apache-2.0
ffed15191fe93735a3777aa361f32dec
25.741935
62
0.586957
4.181818
false
false
false
false
mtransitapps/parser
src/main/java/org/mtransit/parser/gtfs/data/GTripStop.kt
1
2521
package org.mtransit.parser.gtfs.data // https://developers.google.com/transit/gtfs/reference#stop_timestxt // https://gtfs.org/reference/static#stop_timestxt // -_trip_id field // - stop_id field data class GTripStop( val routeIdInt: Int, val tripIdInt: Int, val stopIdInt: Int, val stopSequence: Int ) { @Suppress("unused") constructor( routeAndTripUID: String, stopId: Int, stopSequence: Int ) : this( GTrip.split(routeAndTripUID), stopId, stopSequence ) @Suppress("unused") constructor( routeAndTripUID: String, tripIdInt: Int, stopId: Int, stopSequence: Int ) : this( GTrip.extractRouteIdInt(routeAndTripUID), tripIdInt, stopId, stopSequence ) constructor( routeAndTripUID: Pair<Int, Int>, stopId: Int, stopSequence: Int ) : this( routeAndTripUID.first, routeAndTripUID.second, stopId, stopSequence ) val uID by lazy { getNewUID(routeIdInt, tripIdInt, stopIdInt, stopSequence) } @Deprecated(message = "Not memory efficient") @Suppress("unused") val tripId = _tripId @Suppress("unused") private val _tripId: String get() { return GIDs.getString(tripIdInt) } @Deprecated(message = "Not memory efficient") @Suppress("unused") val stopId = _stopId private val _stopId: String get() { return GIDs.getString(stopIdInt) } @Suppress("unused") fun toStringPlus(): String { return toString() + "+(stopId:$_stopId)" + "+(tripId:$_tripId)" } companion object { const val ROUTE_ID = "route_id" const val TRIP_ID = "trip_id" const val STOP_ID = "stop_id" const val STOP_SEQUENCE = "stop_sequence" @JvmStatic fun getNewUID( tripUID: String, stopIdInt: Int, stopSequence: Int ) = "${tripUID}-${stopIdInt}-${stopSequence}" @JvmStatic fun getNewUID( routeIdInt: Int, tripIdInt: Int, stopIdInt: Int, stopSequence: Int ) = "${routeIdInt}-${tripIdInt}-${stopIdInt}-${stopSequence}" @Suppress("unused") @JvmStatic fun toStringPlus(gTripStops: Iterable<GTripStop>): String { return gTripStops.joinToString { it.toStringPlus() } } } }
apache-2.0
95ff8dc2e28527a30846d130678cb2f4
23.25
81
0.566045
4.112561
false
false
false
false
cyclestreets/android
libraries/cyclestreets-core/src/main/java/net/cyclestreets/api/client/JourneyStringTransformer.kt
1
2682
package net.cyclestreets.api.client import com.bazaarvoice.jolt.Chainr import com.bazaarvoice.jolt.JsonUtils import fr.arnaudguyon.xmltojsonlib.XmlToJson fun fromV1ApiXml(inputXml: String): String { val xmlToJson = XmlToJson.Builder(inputXml).build() val intermediateJson = xmlToJson.toString() return joltTransform(intermediateJson, V1API_XML_JOLT_SPEC) } fun fromV1ApiJson(inputJson: String): String { return joltTransform(inputJson, V1API_JSON_JOLT_SPEC) } // Uses https://github.com/bazaarvoice/jolt to transform JSON strings, without // the need for us to define intermediate object representations. private fun joltTransform(inputJson: String, specJson: String): String { val inputJsonObject = JsonUtils.jsonToObject(inputJson) val chainrSpecJson = JsonUtils.jsonToList(specJson) val chainr = Chainr.fromSpec(chainrSpecJson) val transformedOutput = chainr.transform(inputJsonObject) return JsonUtils.toJsonString(transformedOutput) } private const val V1API_XML_JOLT_SPEC = """[{ "operation": "shift", "spec": { "markers": { "waypoint": { "@": "waypoints" }, "marker": { "*": { "type": { "route": { "@(2)": "route" }, "segment": { "@(2)": "segments[]" } } } } } } }] """ // For A-B route, input json will have array of waypoints. // For circular route, input json has a single waypoint. // For circular routes it may also have a single poi or an array of pois (or none at all). // Convert these to arrays, do the transformation, then convert back to arrays if single // Note (if debugging) that the waypoints in the output may appear at the beginning or in the original place, // depending on whether they are an array of waypoints (A-B route) or a single item (circular route). private const val V1API_JSON_JOLT_SPEC = """ [// First, convert single waypoint / poi to array { "operation": "cardinality", "spec": { "waypoint": "MANY", "poi": "MANY" } }, // Now do the transformation, but note that 1-element arrays will get converted back to strings... { "operation": "shift", "spec": { "waypoint": { "*": { "\\@attributes": "waypoints" }}, "marker": { "*": { "\\@attributes": { "type": { "route": { "@(2)": "route" }, "segment": { "@(2)": "segments[]" } } } } }, "poi": { "*": { "\\@attributes": "pois" } }, "error": "Error" } }, // ... so we need to convert the strings back to arrays! { "operation": "cardinality", "spec": { "waypoints": "MANY", "pois": "MANY" } } ]"""
gpl-3.0
7d4722cd3d62ed73dd1209bf145e3386
27.231579
109
0.618195
3.6
false
false
false
false
rolandvitezhu/TodoCloud
app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/adapter/PredefinedListAdapter.kt
1
2090
package com.rolandvitezhu.todocloud.ui.activity.main.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import com.rolandvitezhu.todocloud.data.PredefinedList import com.rolandvitezhu.todocloud.databinding.ItemPredefinedlistBinding import com.rolandvitezhu.todocloud.di.FragmentScope import java.util.* import javax.inject.Inject @FragmentScope class PredefinedListAdapter @Inject constructor() : BaseAdapter() { val predefinedLists: MutableList<PredefinedList> override fun getCount(): Int { return predefinedLists.size } override fun getItem(position: Int): Any { return predefinedLists[position] } override fun getItemId(position: Int): Long { return 0 } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView val itemPredefinedlistBinding: ItemPredefinedlistBinding val layoutInflater = parent.context.getSystemService( Context.LAYOUT_INFLATER_SERVICE ) as LayoutInflater if (convertView == null) { itemPredefinedlistBinding = ItemPredefinedlistBinding.inflate( layoutInflater, parent, false ) convertView = itemPredefinedlistBinding.root } else { itemPredefinedlistBinding = convertView.tag as ItemPredefinedlistBinding } itemPredefinedlistBinding.predefinedListAdapter = this itemPredefinedlistBinding.predefinedList = predefinedLists[position] itemPredefinedlistBinding.executePendingBindings() convertView.tag = itemPredefinedlistBinding return convertView } fun update(predefinedLists: List<PredefinedList>?) { this.predefinedLists.clear() this.predefinedLists.addAll(predefinedLists!!) } fun clear() { predefinedLists.clear() notifyDataSetChanged() } init { predefinedLists = ArrayList() } }
mit
8408967ecbd6773d4733bcffd4bf4e45
28.871429
86
0.710048
5.372751
false
false
false
false
PolymerLabs/arcs
java/arcs/tools/VerifyPolicy.kt
1
1726
package arcs.tools import arcs.core.analysis.PolicyVerifier import arcs.core.data.proto.ManifestProto import arcs.core.data.proto.decodeRecipes import arcs.core.policy.proto.decode import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.CliktError import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.options.required import com.github.ajalt.clikt.parameters.types.file class VerifyPolicy : CliktCommand( name = "verify_policy", help = "Verifies that all recipes in an Arcs manifest file comply with their policies." ) { val manifest by option( help = "Arcs manifest to check, encoded as a binary proto file (.binarypb)" ).file().required() override fun run() { val manifestProto = ManifestProto.parseFrom(manifest.readBytes()) val recipes = manifestProto.decodeRecipes() val policies = manifestProto.policiesList.map { it.decode() }.associateBy { it.name } val policyVerifier = PolicyVerifier() recipes.forEach { recipe -> val policyName = recipe.policyName if (policyName == null) { val message = "Recipe '${recipe.name}' does not have a @policy annotation." if (recipe.particles.any { it.spec.dataflowType.egress }) { throw CliktError(message) } else { print("[WARNING] $message [No egress in recipe]\n") } } else { val policy = policies[policyName] ?: throw CliktError( "Recipe '${recipe.name}' refers to policy '$policyName', which does not " + "exist in the manifest." ) policyVerifier.verifyPolicy(recipe, policy) } } } } fun main(args: Array<String>) = VerifyPolicy().main(args)
bsd-3-clause
47052b3cd81923754dd11bfa759c5cec
34.958333
89
0.69467
4.080378
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/VibrationDialogFragment.kt
2
8777
package com.fsck.k9.ui.settings.account import android.app.Dialog import android.os.Build import android.os.Bundle import android.os.VibrationEffect import android.os.Vibrator import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.CheckedTextView import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.appcompat.widget.SwitchCompat import androidx.core.content.getSystemService import androidx.preference.PreferenceDialogFragmentCompat import com.fsck.k9.NotificationVibration import com.fsck.k9.VibratePattern import com.fsck.k9.ui.R import com.fsck.k9.ui.getEnum import com.fsck.k9.ui.putEnum class VibrationDialogFragment : PreferenceDialogFragmentCompat() { private val vibrator by lazy { requireContext().getSystemService<Vibrator>() ?: error("Vibrator service missing") } private val vibrationPreference: VibrationPreference get() = preference as VibrationPreference private lateinit var adapter: VibrationPatternAdapter override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = requireContext() val isVibrationEnabled: Boolean val vibratePattern: VibratePattern val vibrationTimes: Int if (savedInstanceState != null) { isVibrationEnabled = savedInstanceState.getBoolean(STATE_VIBRATE) vibratePattern = savedInstanceState.getEnum(STATE_VIBRATE_PATTERN) vibrationTimes = savedInstanceState.getInt(STATE_VIBRATION_TIMES) } else { isVibrationEnabled = vibrationPreference.isVibrationEnabled vibratePattern = vibrationPreference.vibratePattern vibrationTimes = vibrationPreference.vibrationTimes } adapter = VibrationPatternAdapter( isVibrationEnabled, entries = vibrationPreference.entries.map { it.toString() }, entryValues = vibrationPreference.entryValues.map { it.toString().toInt() }, vibratePattern, vibrationTimes ) return AlertDialog.Builder(context) .setAdapter(adapter, null) .setPositiveButton(R.string.okay_action, ::onClick) .setNegativeButton(R.string.cancel_action, ::onClick) .create() } override fun onDialogClosed(positiveResult: Boolean) { if (positiveResult) { vibrationPreference.setVibration( isVibrationEnabled = adapter.isVibrationEnabled, vibratePattern = adapter.vibratePattern, vibrationTimes = adapter.vibrationTimes ) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(STATE_VIBRATE, adapter.isVibrationEnabled) outState.putEnum(STATE_VIBRATE_PATTERN, adapter.vibratePattern) outState.putInt(STATE_VIBRATION_TIMES, adapter.vibrationTimes) } private fun playVibration() { val vibratePattern = adapter.vibratePattern val vibrationTimes = adapter.vibrationTimes val vibrationPattern = NotificationVibration.getSystemPattern(vibratePattern, vibrationTimes) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val vibrationEffect = VibrationEffect.createWaveform(vibrationPattern, -1) vibrator.vibrate(vibrationEffect) } else { @Suppress("DEPRECATION") vibrator.vibrate(vibrationPattern, -1) } } private inner class VibrationPatternAdapter( var isVibrationEnabled: Boolean, private val entries: List<String>, private val entryValues: List<Int>, initialVibratePattern: VibratePattern, initialVibrationTimes: Int ) : BaseAdapter() { private var checkedEntryIndex = entryValues.indexOf(initialVibratePattern.serialize()).takeIf { it != -1 } ?: 0 val vibratePattern: VibratePattern get() = VibratePattern.deserialize(entryValues[checkedEntryIndex]) var vibrationTimes = initialVibrationTimes override fun hasStableIds(): Boolean = true override fun getItemId(position: Int): Long = position.toLong() override fun getItemViewType(position: Int): Int { return when { position == 0 -> 0 position.toEntryIndex() < entries.size -> 1 else -> 2 } } override fun getViewTypeCount(): Int = 3 override fun getCount(): Int = entries.size + 2 override fun getItem(position: Int): Any? { return when { position == 0 -> null position.toEntryIndex() < entries.size -> entries[position.toEntryIndex()] else -> null } } private fun Int.toEntryIndex() = this - 1 override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { return when (getItemViewType(position)) { 0 -> getVibrationSwitchView(convertView, parent) 1 -> getVibrationPatternView(position, convertView, parent) 2 -> getVibrationTimesView(convertView, parent) else -> error("Unknown item type") } } private fun getVibrationSwitchView(convertView: View?, parent: ViewGroup?): View { return convertView.orInflate<View>(R.layout.preference_vibration_switch_item, parent) .apply { val switchButton = findViewById<SwitchCompat>(R.id.vibrationSwitch) switchButton.isChecked = isVibrationEnabled switchButton.setOnCheckedChangeListener { _, isChecked -> isVibrationEnabled = isChecked notifyDataSetChanged() } findViewById<View>(R.id.switchContainer).setOnClickListener { switchButton.toggle() } } } private fun getVibrationPatternView(position: Int, convertView: View?, parent: ViewGroup?): View { return convertView.orInflate<CheckedTextView>(R.layout.preference_vibration_pattern_item, parent) .apply { text = getItem(position) as String val entryIndex = position.toEntryIndex() isChecked = entryIndex == checkedEntryIndex isEnabled = isVibrationEnabled setOnClickListener { checkedEntryIndex = entryIndex playVibration() notifyDataSetChanged() } } } private fun getVibrationTimesView(convertView: View?, parent: ViewGroup?): View { return convertView.orInflate<View>(R.layout.preference_vibration_times_item, parent).apply { val vibrationTimesValue = findViewById<TextView>(R.id.vibrationTimesValue) vibrationTimesValue.text = vibrationTimes.toString() val vibrationTimesSeekBar = findViewById<SeekBar>(R.id.vibrationTimesSeekBar).apply { isEnabled = isVibrationEnabled } val progress = vibrationTimes - 1 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { vibrationTimesSeekBar.setProgress(progress, false) } else { vibrationTimesSeekBar.progress = progress } vibrationTimesSeekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { vibrationTimes = progress + 1 vibrationTimesValue.text = vibrationTimes.toString() } override fun onStartTrackingTouch(seekBar: SeekBar) = Unit override fun onStopTrackingTouch(seekBar: SeekBar) { playVibration() } }) } } @Suppress("UNCHECKED_CAST") private fun <T : View> View?.orInflate(layoutResId: Int, parent: ViewGroup?): T { val view = this ?: layoutInflater.inflate(layoutResId, parent, false) return view as T } } companion object { private const val STATE_VIBRATE = "vibrate" private const val STATE_VIBRATE_PATTERN = "vibratePattern" private const val STATE_VIBRATION_TIMES = "vibrationTimes" } }
apache-2.0
aa00602443d5ac25ff65e424c104feac
39.261468
119
0.628461
5.5236
false
false
false
false
Maccimo/intellij-community
platform/platform-impl/src/com/intellij/openapi/editor/toolbar/floating/EditorFloatingToolbar.kt
1
2363
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.toolbar.floating import com.intellij.openapi.Disposable import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.observable.util.whenDisposed import com.intellij.openapi.util.Disposer import java.awt.Component import java.awt.FlowLayout import javax.swing.BorderFactory import javax.swing.JPanel class EditorFloatingToolbar(editor: EditorImpl) : JPanel() { init { layout = FlowLayout(FlowLayout.RIGHT, 20, 20) border = BorderFactory.createEmptyBorder() isOpaque = false FloatingToolbarProvider.EP_NAME.forEachExtensionSafe { provider -> addFloatingToolbarComponent(editor, provider) } FloatingToolbarProvider.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<FloatingToolbarProvider> { override fun extensionAdded(extension: FloatingToolbarProvider, pluginDescriptor: PluginDescriptor) { addFloatingToolbarComponent(editor, extension) } }, editor.disposable) } private fun addFloatingToolbarComponent(editor: EditorImpl, provider: FloatingToolbarProvider) { if (provider.isApplicable(editor.dataContext)) { val disposable = createExtensionDisposable(provider, editor.disposable) val component = FloatingToolbarComponentImpl(editor, provider, disposable) add(component, disposable) } } private fun add(component: Component, parentDisposable: Disposable) { add(component) parentDisposable.whenDisposed { remove(component) } } private fun createExtensionDisposable(provider: FloatingToolbarProvider, parentDisposable: Disposable): Disposable { val disposable = Disposer.newDisposable() Disposer.register(parentDisposable, disposable) FloatingToolbarProvider.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<FloatingToolbarProvider> { override fun extensionRemoved(extension: FloatingToolbarProvider, pluginDescriptor: PluginDescriptor) { if (provider === extension) { Disposer.dispose(disposable) } } }, disposable) return disposable } }
apache-2.0
c65da2ead295d058d4248ce6f73c0741
39.741379
140
0.775709
5.006356
false
false
false
false
fcostaa/kotlin-rxjava-android
feature/wiki/src/main/kotlin/com/github/felipehjcosta/marvelapp/wiki/view/FadeBitmapDrawable.kt
1
2986
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.felipehjcosta.marvelapp.wiki.view import android.content.res.Resources import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.ColorFilter import android.graphics.Rect import android.graphics.drawable.AnimationDrawable import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.os.SystemClock import android.view.View internal class FadeBitmapDrawable( resources: Resources, bitmap: Bitmap, private var placeholder: Drawable?, fade: Boolean ) : BitmapDrawable(resources, bitmap) { private var startTimeMillis: Long = 0L private var animating: Boolean = false private var internalAlpha = ALPHA init { if (fade) { animating = true startTimeMillis = SystemClock.uptimeMillis() } } override fun draw(canvas: Canvas) { if (!animating) { super.draw(canvas) } else { val normalized = (SystemClock.uptimeMillis() - startTimeMillis) / FADE_DURATION if (normalized >= 1.0f) { animating = false placeholder = null super.draw(canvas) } else { placeholder?.draw(canvas) // setAlpha will call invalidateSelf and drive the animation. val partialAlpha = (internalAlpha * normalized).toInt() super.setAlpha(partialAlpha) super.draw(canvas) super.setAlpha(internalAlpha) } } } override fun setAlpha(alpha: Int) { internalAlpha = alpha placeholder?.alpha = alpha super.setAlpha(alpha) } override fun setColorFilter(cf: ColorFilter?) { placeholder?.colorFilter = cf super.setColorFilter(cf) } override fun onBoundsChange(bounds: Rect) { placeholder?.bounds = bounds super.onBoundsChange(bounds) } companion object { private const val FADE_DURATION = 400.0f private const val ALPHA = 0xFF } } fun View?.background(bitmap: Bitmap, fade: Boolean = false) { this?.run { val placeholder = background if (placeholder is AnimationDrawable) { placeholder.stop() } background = FadeBitmapDrawable(resources, bitmap, placeholder, fade) } }
mit
e785bc4871f87ba2af7a0ef67051ad79
29.161616
91
0.652043
4.747218
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/WPWebViewUsageCategory.kt
1
2400
package org.wordpress.android.ui import org.wordpress.android.viewmodel.wpwebview.WPWebViewViewModel import org.wordpress.android.viewmodel.wpwebview.WPWebViewViewModel.WebPreviewUiState.WebPreviewFullscreenUiState /** * This enum could be expanded to allow to re-use the WPWebViewActivity (including the direct usage of actionable empty * view) in other scenarios with different WebPreviewUiState, also menu can be customized with the same principle. */ enum class WPWebViewUsageCategory constructor(val value: Int, val menuUiState: WPWebViewMenuUiState) { WEBVIEW_STANDARD(0, WPWebViewMenuUiState()), REMOTE_PREVIEW_NOT_AVAILABLE(1, WPWebViewMenuUiState( browserMenuVisible = false, shareMenuVisible = false, refreshMenuVisible = false )), REMOTE_PREVIEW_NO_NETWORK(2, WPWebViewMenuUiState( browserMenuVisible = false, shareMenuVisible = false, refreshMenuVisible = false )), REMOTE_PREVIEWING(3, WPWebViewMenuUiState( browserMenuVisible = false, shareMenuVisible = false, refreshMenuVisible = true, refreshMenuShowAsAction = true )); companion object { @JvmStatic fun fromInt(value: Int): WPWebViewUsageCategory = WPWebViewUsageCategory.values().firstOrNull { it.value == value } ?: throw IllegalArgumentException("WebViewUsageCategory wrong value $value") @JvmStatic fun isActionableDirectUsage(state: WPWebViewUsageCategory) = state == WPWebViewUsageCategory.REMOTE_PREVIEW_NOT_AVAILABLE || state == WPWebViewUsageCategory.REMOTE_PREVIEW_NO_NETWORK @JvmStatic fun actionableDirectUsageToWebPreviewUiState( state: WPWebViewUsageCategory ): WPWebViewViewModel.WebPreviewUiState { return when (state) { REMOTE_PREVIEW_NOT_AVAILABLE -> WebPreviewFullscreenUiState.WebPreviewFullscreenNotAvailableUiState REMOTE_PREVIEW_NO_NETWORK -> WebPreviewFullscreenUiState.WebPreviewFullscreenErrorUiState( buttonVisibility = false ) WEBVIEW_STANDARD, REMOTE_PREVIEWING -> throw IllegalArgumentException("Mapping of $state to WebPreviewUiState not allowed.") } } } }
gpl-2.0
aa0a6669376ab0c796b079e086ce09c2
43.444444
119
0.677917
5.117271
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/benchmark/LocalCompletionBenchmark.kt
1
4292
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions.internal.benchmark import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogBuilder import com.intellij.ui.components.JBPanel import com.intellij.ui.components.JBTextField import com.intellij.uiDesigner.core.GridLayoutManager import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.actions.internal.benchmark.AbstractCompletionBenchmarkAction.Companion.randomElement import org.jetbrains.kotlin.idea.completion.CompletionBenchmarkSink import org.jetbrains.kotlin.idea.base.psi.getLineCount import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.endOffset import java.util.* import kotlin.properties.Delegates class LocalCompletionBenchmarkAction : AbstractCompletionBenchmarkAction() { override fun createBenchmarkScenario( project: Project, benchmarkSink: CompletionBenchmarkSink.Impl ): AbstractCompletionBenchmarkScenario? { val settings = showSettingsDialog() ?: return null val random = Random(settings.seed) fun collectFiles(): List<KtFile>? { val ktFiles = collectSuitableKotlinFiles(project) { it.getLineCount() >= settings.lines } if (ktFiles.size < settings.files) { showPopup(project, KotlinBundle.message("number.of.attempts.then.files.in.project.0", ktFiles.size)) return null } val result = mutableListOf<KtFile>() repeat(settings.files) { result += ktFiles.randomElement(random)!!.also { ktFiles.remove(it) } } return result } val ktFiles = collectFiles() ?: return null return LocalCompletionBenchmarkScenario(ktFiles, settings, project, benchmarkSink, random) } data class Settings(val seed: Long, val lines: Int, val files: Int, val functions: Int) private fun showSettingsDialog(): Settings? { var cSeed: JBTextField by Delegates.notNull() var cLines: JBTextField by Delegates.notNull() var cFiles: JBTextField by Delegates.notNull() var cFunctions: JBTextField by Delegates.notNull() val dialogBuilder = DialogBuilder() val jPanel = JBPanel<JBPanel<*>>(GridLayoutManager(4, 2)).apply { var i = 0 cSeed = addBoxWithLabel(KotlinBundle.message("random.seed"), default = "0", i = i++) cFiles = addBoxWithLabel(KotlinBundle.message("files.to.visit"), default = "20", i = i++) cFunctions = addBoxWithLabel(KotlinBundle.message("max.functions.to.visit"), default = "20", i = i++) cLines = addBoxWithLabel(KotlinBundle.message("file.lines"), default = "100", i = i) } dialogBuilder.centerPanel(jPanel) if (!dialogBuilder.showAndGet()) return null return Settings( cSeed.text.toLong(), cLines.text.toInt(), cFiles.text.toInt(), cFunctions.text.toInt() ) } } internal class LocalCompletionBenchmarkScenario( val files: List<KtFile>, val settings: LocalCompletionBenchmarkAction.Settings, project: Project, benchmarkSink: CompletionBenchmarkSink.Impl, random: Random ) : AbstractCompletionBenchmarkScenario(project, benchmarkSink, random) { override suspend fun doBenchmark() { val allResults = mutableListOf<Result>() files.forEach { file -> val functions = file.collectDescendantsOfType<KtFunction> { it.hasBlockBody() && it.bodyExpression != null }.toMutableList() val randomFunctions = generateSequence { functions.randomElement(random).also { functions.remove(it) } } randomFunctions.take(settings.functions).forEach { function -> val offset = function.bodyExpression!!.endOffset - 1 allResults += typeAtOffsetAndGetResult("listOf(1).", offset, file) } } saveResults(allResults) } }
apache-2.0
d61cbcd09660090114e2eb9578882a54
39.885714
158
0.686859
4.811659
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/serialonly/TPFCardTransitData.kt
1
2694
/* * TPFCardTransitData.kt * * Copyright 2019 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.serialonly import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.desfire.DesfireCard import au.id.micolous.metrodroid.card.desfire.DesfireCardTransitFactory import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.CardInfo import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.transit.TransitRegion import au.id.micolous.metrodroid.util.ImmutableByteArray @Parcelize data class TPFCardTransitData (private val mSerial: ImmutableByteArray): SerialOnlyTransitData() { override val reason: SerialOnlyTransitData.Reason get() = SerialOnlyTransitData.Reason.LOCKED override val serialNumber get() = formatSerial(mSerial) override val cardName get() = NAME companion object { private const val NAME = "TPF card" private val CARD_INFO = CardInfo( name = NAME, locationId = R.string.location_fribourg_ch, cardType = CardType.MifareDesfire, imageId = R.drawable.tpf_card, imageAlphaId = R.drawable.iso7810_id1_alpha, region = TransitRegion.SWITZERLAND, resourceExtraNote = R.string.card_note_card_number_only) private fun getSerial(card: DesfireCard) = card.tagId.reverseBuffer() private fun formatSerial(serial: ImmutableByteArray) = serial.toHexString().toUpperCase() } object Factory : DesfireCardTransitFactory { override fun earlyCheck(appIds: IntArray) = (0x43544b in appIds) override fun parseTransitData(card: DesfireCard) = TPFCardTransitData(mSerial = getSerial(card)) override fun parseTransitIdentity(card: DesfireCard) = TransitIdentity(NAME, formatSerial(getSerial(card))) override val allCards get() = listOf(CARD_INFO) } }
gpl-3.0
7049f7863dd2883529c4473ac78028d3
38.043478
98
0.717892
4.366288
false
false
false
false
squanchy-dev/squanchy-android
app/src/main/java/net/squanchy/navigation/firststart/FirstStartWithNoNetworkActivity.kt
1
7035
package net.squanchy.navigation.firststart import android.animation.Animator import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Context import android.content.Intent import android.graphics.drawable.AnimatedVectorDrawable import android.graphics.drawable.Drawable import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Property import android.view.View import android.view.animation.BounceInterpolator import android.view.animation.Interpolator import android.view.animation.LinearInterpolator import androidx.appcompat.app.AppCompatActivity import androidx.interpolator.view.animation.FastOutLinearInInterpolator import kotlinx.android.synthetic.main.activity_first_start_with_no_network.* import net.squanchy.R import net.squanchy.support.config.DialogLayoutParameters class FirstStartWithNoNetworkActivity : AppCompatActivity() { private lateinit var continuationIntent: Intent private var networkCallback = NetworkConnectedCallback() private var mainThreadHandler = Handler(Looper.getMainLooper()) private lateinit var connectivityManager: ConnectivityManager private var shortAnimationDuration: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_first_start_with_no_network) DialogLayoutParameters.wrapHeight(this) .applyTo(window) firstStartNevermind.setOnClickListener { finish() } continuationIntent = intent.getParcelableExtra(EXTRA_CONTINUATION_INTENT) connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager shortAnimationDuration = resources.getInteger(android.R.integer.config_shortAnimTime) } override fun onStart() { super.onStart() val networkRequest = NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build() connectivityManager.registerNetworkCallback(networkRequest, networkCallback) doIfAnimatedVectorDrawable(firstStartProgress.drawable) { start() } } override fun onStop() { super.onStop() connectivityManager.unregisterNetworkCallback(networkCallback) doIfAnimatedVectorDrawable(firstStartProgress.drawable) { stop() } } private fun doIfAnimatedVectorDrawable(drawable: Drawable, action: AnimatedVectorDrawable.() -> Unit) { if (drawable is AnimatedVectorDrawable) { action.invoke(drawable) } } private fun showNetworkAcquiredAndFinish() { firstStartCta.setText(R.string.first_start_with_no_network_network_connected) animate(firstStartProgress, popOut(), ::swapProgressWithSuccessAndContinue) .start() } private fun popOut(): (View) -> Animator = { AnimatorSet().apply { val alphaAnimator = createFadeAnimationFor(it, 1f, 0f) val scaleAnimator = createScaleAnimationFor(it, FastOutLinearInInterpolator(), 1f, 0f) playTogether(alphaAnimator, scaleAnimator) duration = shortAnimationDuration.toLong() } } private fun swapProgressWithSuccessAndContinue() { firstStartProgress.setImageResource(R.drawable.ic_circle_tick) animate(firstStartProgress, popBackIn()) { this.continueToScheduleAfterDelay() } .start() } private fun popBackIn(): (View) -> Animator = { AnimatorSet().apply { val alphaAnimator = createFadeAnimationFor(it, 0f, 1f) val scaleAnimator = createScaleAnimationFor(it, BounceInterpolator(), 0f, 1f) playTogether(alphaAnimator, scaleAnimator) duration = shortAnimationDuration.toLong() } } @Suppress("SpreadOperator") // We cannot avoid using the spread operator here, we use varargs APIs private fun createFadeAnimationFor(view: View, vararg values: Float): Animator { val property = Property.of(View::class.java, Float::class.java, "alpha") val animator = ObjectAnimator.ofFloat(view, property, *values) animator.interpolator = LinearInterpolator() return animator } @Suppress("SpreadOperator") // We cannot avoid using the spread operator here, we use varargs APIs private fun createScaleAnimationFor(view: View, interpolator: Interpolator, vararg values: Float): Animator { val scaleX = Property.of(View::class.java, Float::class.java, "scaleX") val scaleY = Property.of(View::class.java, Float::class.java, "scaleY") val animator = AnimatorSet() animator.playTogether( ObjectAnimator.ofFloat(view, scaleX, *values), ObjectAnimator.ofFloat(view, scaleY, *values) ) animator.interpolator = interpolator return animator } private fun animate(view: View, animationProducer: (View) -> Animator, endAction: () -> Unit): Animator { val animator = animationProducer.invoke(view) animator.addListener( object : AnimationEndListener { override fun onAnimationEnd(animation: Animator) = endAction() } ) return animator } private fun continueToScheduleAfterDelay() { firstStartProgress.postDelayed( { // We don't use the navigator here, we basically want to restart the whole flow startActivity(continuationIntent) finish() }, DELAY_AFTER_ANIMATIONS_MILLIS ) } private inner class NetworkConnectedCallback : ConnectivityManager.NetworkCallback() { private var receivedOnAvailable: Boolean = false override fun onAvailable(network: Network) { if (receivedOnAvailable) { return } receivedOnAvailable = true mainThreadHandler.post { this@FirstStartWithNoNetworkActivity.showNetworkAcquiredAndFinish() } } } private interface AnimationEndListener : Animator.AnimatorListener { override fun onAnimationStart(animation: Animator) { // No-op } override fun onAnimationCancel(animation: Animator) { // No-op } override fun onAnimationRepeat(animation: Animator) { // No-op } } companion object { private val EXTRA_CONTINUATION_INTENT = "${FirstStartWithNoNetworkActivity::class.java.name}.continuation_intent" private const val DELAY_AFTER_ANIMATIONS_MILLIS: Long = 700 fun createIntentContinuingTo(context: Context, continuationIntent: Intent) = Intent(context, FirstStartWithNoNetworkActivity::class.java).apply { putExtra(EXTRA_CONTINUATION_INTENT, continuationIntent) } } }
apache-2.0
be2d7ea57ca9fdbe0150179aacc06a08
35.640625
121
0.698792
5.127551
false
false
false
false
iPoli/iPoli-android
app/src/test/java/io/ipoli/android/pet/usecase/BuyPetUseCaseSpek.kt
1
2237
package io.ipoli.android.pet.usecase import io.ipoli.android.TestUtil import io.ipoli.android.pet.Pet import io.ipoli.android.pet.PetAvatar import io.ipoli.android.player.data.Inventory import io.ipoli.android.player.data.InventoryPet import io.ipoli.android.player.data.Player import org.amshove.kluent.* import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it /** * Created by Venelin Valkov <[email protected]> * on 12/6/17. */ object BuyPetUseCaseSpek : Spek({ describe("BuyPetUseCase") { fun executeUseCase(player: Player, pet: PetAvatar) = BuyPetUseCase(TestUtil.playerRepoMock(player)).execute(pet) it("should require not bought pet") { val pet = Pet( "", avatar = PetAvatar.ELEPHANT ) val player = TestUtil.player.copy( pet = pet, inventory = Inventory( pets = setOf( InventoryPet.createFromPet( pet ) ) ) ) val exec = { executeUseCase(player, pet.avatar) } exec shouldThrow IllegalArgumentException::class } it("should not buy when not enough gems") { val player = TestUtil.player.copy( gems = PetAvatar.ELEPHANT.gemPrice - 1, inventory = Inventory() ) val result = executeUseCase(player, PetAvatar.ELEPHANT) result.`should be`(BuyPetUseCase.Result.TooExpensive) } it("should buy pet") { val player = TestUtil.player.copy( gems = PetAvatar.ELEPHANT.gemPrice, inventory = Inventory() ) val result = executeUseCase(player, PetAvatar.ELEPHANT) result.`should be instance of`(BuyPetUseCase.Result.PetBought::class) val newPlayer = (result as BuyPetUseCase.Result.PetBought).player newPlayer.gems.`should be equal to`(player.gems - PetAvatar.ELEPHANT.gemPrice) newPlayer.hasPet(PetAvatar.ELEPHANT).`should be true`() } } })
gpl-3.0
4a28c18b81f2c1e8b3d61d65d498d6d8
33.96875
90
0.5865
4.519192
false
true
false
false
Turbo87/intellij-emberjs
src/test/kotlin/com/emberjs/translations/EmberI18nIndexTest.kt
1
2318
package com.emberjs.translations import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.util.indexing.FileBasedIndex import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.entry import java.nio.file.Paths class EmberI18nIndexTest : BasePlatformTestCase() { fun testSimpleKey() = doTest("foo", mapOf("en" to "bar baz", "de" to "Bar Baz")) fun testDottedKey() = doTest("user.edit.title", mapOf("en" to "Edit User", "de" to "Benutzer editieren")) fun testNestedKey() = doTest("button.add_user.text", mapOf("en" to "Add", "de" to "Hinzufügen")) fun testCombinedKey() = doTest("nested.and.dotted", mapOf("en" to "foobar")) fun testNotDefaultExport() = doTest("bar", emptyMap()) fun testWithoutDependency() = doTest("foo", emptyMap(), "no-dependencies") fun testAllKeys() { loadFixture("ember-i18n") val keys = EmberI18nIndex.getTranslationKeys(myFixture.project) assertThat(keys).contains("foo", "user.edit.title", "button.add_user.title") } fun testGetFilesWithKey() { loadFixture("ember-i18n") val result = EmberI18nIndex.getFilesWithKey("user.edit.title", myFixture.project).map { it.parent.name } assertThat(result).containsOnly("de", "en") } override fun getTestDataPath(): String? { val resource = ClassLoader.getSystemResource("com/emberjs/translations/fixtures") return Paths.get(resource.toURI()).toAbsolutePath().toString() } private fun loadFixture(fixtureName: String) { // Load fixture files into the project myFixture.copyDirectoryToProject(fixtureName, "/") // Rebuild index now that the `package.json` file is copied over FileBasedIndex.getInstance().requestRebuild(EmberI18nIndex.NAME) } private fun doTest(key: String, expected: Map<String, String>, fixtureName: String = "ember-i18n") { loadFixture(fixtureName) val translations = EmberI18nIndex.getTranslations(key, myFixture.project) if (expected.isEmpty()) { assertThat(translations).isEmpty() } else { val _expected = expected.entries.map { entry(it.key, it.value) }.toTypedArray() assertThat(translations).containsOnly(*_expected) } } }
apache-2.0
57a60ae6c84e84163b76b896b77c5411
40.375
112
0.685801
4.057793
false
true
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/privateToplevelProperty.kt
7
505
package privateToplevelProperty private var topLevelProperty: Int = 0 get() = 0 set(value) { field += value } open class C(val p: Int) { init { //Breakpoint! val x = topLevelProperty topLevelProperty = 4 } } fun main(args: Array<String>) { C(1) } // From KT-52372 // The fragment compiler includes the project file in the fragment compilation, // and rewrites the property access in the init block using the reflection API. // EXPRESSION: p // RESULT: 1: I
apache-2.0
10618ea23f930f543922206fc8918aef
20.083333
79
0.657426
3.740741
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/ui/ScratchTopPanel.kt
2
4933
// 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.scratch.ui import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.scratch.ScratchFile import org.jetbrains.kotlin.idea.scratch.ScratchFileAutoRunner import org.jetbrains.kotlin.idea.scratch.actions.ClearScratchAction import org.jetbrains.kotlin.idea.scratch.actions.RunScratchAction import org.jetbrains.kotlin.idea.scratch.actions.StopScratchAction import org.jetbrains.kotlin.idea.scratch.output.ScratchOutputHandlerAdapter class ScratchTopPanel(val scratchFile: ScratchFile) { private val moduleChooserAction: ModulesComboBoxAction = ModulesComboBoxAction(scratchFile) val actionsToolbar: ActionToolbar init { setupTopPanelUpdateHandlers() val toolbarGroup = DefaultActionGroup().apply { add(RunScratchAction()) add(StopScratchAction()) addSeparator() add(ClearScratchAction()) addSeparator() add(moduleChooserAction) add(IsMakeBeforeRunAction()) addSeparator() add(IsInteractiveCheckboxAction()) addSeparator() add(IsReplCheckboxAction()) } actionsToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.EDITOR_TOOLBAR, toolbarGroup, true) } private fun setupTopPanelUpdateHandlers() { scratchFile.addModuleListener { _, _ -> updateToolbar() } val toolbarHandler = createUpdateToolbarHandler() scratchFile.replScratchExecutor?.addOutputHandler(toolbarHandler) scratchFile.compilingScratchExecutor?.addOutputHandler(toolbarHandler) } private fun createUpdateToolbarHandler(): ScratchOutputHandlerAdapter { return object : ScratchOutputHandlerAdapter() { override fun onStart(file: ScratchFile) { updateToolbar() } override fun onFinish(file: ScratchFile) { updateToolbar() } } } private fun updateToolbar() { ApplicationManager.getApplication().invokeLater { actionsToolbar.updateActionsImmediately() } } private inner class IsMakeBeforeRunAction : SmallBorderCheckboxAction(KotlinJvmBundle.message("scratch.make.before.run.checkbox")) { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isVisible = scratchFile.module != null e.presentation.description = scratchFile.module?.let { selectedModule -> KotlinJvmBundle.message("scratch.make.before.run.checkbox.description", selectedModule.name) } } override fun isSelected(e: AnActionEvent): Boolean { return scratchFile.options.isMakeBeforeRun } override fun setSelected(e: AnActionEvent, isMakeBeforeRun: Boolean) { scratchFile.saveOptions { copy(isMakeBeforeRun = isMakeBeforeRun) } } override fun getActionUpdateThread() = ActionUpdateThread.BGT } private inner class IsInteractiveCheckboxAction : SmallBorderCheckboxAction( text = KotlinJvmBundle.message("scratch.is.interactive.checkbox"), description = KotlinJvmBundle.message("scratch.is.interactive.checkbox.description", ScratchFileAutoRunner.AUTO_RUN_DELAY_IN_SECONDS) ) { override fun isSelected(e: AnActionEvent): Boolean { return scratchFile.options.isInteractiveMode } override fun setSelected(e: AnActionEvent, isInteractiveMode: Boolean) { scratchFile.saveOptions { copy(isInteractiveMode = isInteractiveMode) } } override fun getActionUpdateThread() = ActionUpdateThread.BGT } private inner class IsReplCheckboxAction : SmallBorderCheckboxAction( text = KotlinJvmBundle.message("scratch.is.repl.checkbox"), description = KotlinJvmBundle.message("scratch.is.repl.checkbox.description") ) { override fun isSelected(e: AnActionEvent): Boolean { return scratchFile.options.isRepl } override fun setSelected(e: AnActionEvent, isRepl: Boolean) { scratchFile.saveOptions { copy(isRepl = isRepl) } if (isRepl) { // TODO start REPL process when checkbox is selected to speed up execution // Now it is switched off due to KT-18355: REPL process is keep alive if no command is executed //scratchFile.replScratchExecutor?.start() } else { scratchFile.replScratchExecutor?.stop() } } override fun getActionUpdateThread() = ActionUpdateThread.BGT } }
apache-2.0
7decc467de38ff3bbea6ab5cf5cfb80e
39.105691
158
0.687817
5.361957
false
false
false
false
jk1/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/project/convertModuleGroupsToQualifiedNames.kt
2
9217
// 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.ide.actions.project import com.intellij.CommonBundle import com.intellij.application.runInAllowSaveMode import com.intellij.codeInsight.intention.IntentionManager import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ex.InspectionProfileWrapper import com.intellij.codeInspection.ex.InspectionToolWrapper import com.intellij.codeInspection.ex.LocalInspectionToolWrapper import com.intellij.lang.StdLanguages import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LineExtensionInfo import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModulePointerManager import com.intellij.openapi.module.impl.ModulePointerManagerImpl import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiDocumentManager import com.intellij.ui.* import com.intellij.ui.components.JBLabel import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import java.awt.Color import java.awt.Font import java.util.function.Function import java.util.function.Supplier import javax.swing.Action import javax.swing.JCheckBox import javax.swing.JComponent import javax.swing.JPanel class ConvertModuleGroupsToQualifiedNamesDialog(val project: Project) : DialogWrapper(project) { private val editorArea: EditorTextField private val document: Document get() = editorArea.document private lateinit var modules: List<Module> private val recordPreviousNamesCheckBox: JCheckBox private var modified = false init { title = ProjectBundle.message("convert.module.groups.dialog.title") isModal = false setOKButtonText(ProjectBundle.message("convert.module.groups.button.text")) editorArea = EditorTextFieldProvider.getInstance().getEditorField(StdLanguages.TEXT, project, listOf(EditorCustomization { it.settings.apply { isLineNumbersShown = false isLineMarkerAreaShown = false isFoldingOutlineShown = false isRightMarginShown = false additionalLinesCount = 0 additionalColumnsCount = 0 isAdditionalPageAtBottom = false isShowIntentionBulb = false } (it as? EditorImpl)?.registerLineExtensionPainter(this::generateLineExtension) setupHighlighting(it) }, MonospaceEditorCustomization.getInstance())) document.addDocumentListener(object: DocumentListener { override fun documentChanged(event: DocumentEvent?) { modified = true } }, disposable) recordPreviousNamesCheckBox = JCheckBox(ProjectBundle.message("convert.module.groups.record.previous.names.text"), true) importRenamingScheme(emptyMap()) init() } private fun setupHighlighting(editor: Editor) { editor.putUserData(IntentionManager.SHOW_INTENTION_OPTIONS_KEY, false) val inspections = Supplier<List<InspectionToolWrapper<*, *>>> { listOf(LocalInspectionToolWrapper(ModuleNamesListInspection())) } val file = PsiDocumentManager.getInstance(project).getPsiFile(document) file?.putUserData(InspectionProfileWrapper.CUSTOMIZATION_KEY, Function { val profile = InspectionProfileImpl("Module names", inspections, null) for (spellCheckingToolName in SpellCheckingEditorCustomizationProvider.getInstance().spellCheckingToolNames) { profile.getToolsOrNull(spellCheckingToolName, project)?.isEnabled = false } InspectionProfileWrapper(profile) }) } override fun createCenterPanel(): JPanel { val text = XmlStringUtil.wrapInHtml(ProjectBundle.message("convert.module.groups.description.text")) val recordPreviousNames = com.intellij.util.ui.UI.PanelFactory.panel(recordPreviousNamesCheckBox) .withTooltip(ProjectBundle.message("convert.module.groups.record.previous.names.tooltip", ApplicationNamesInfo.getInstance().fullProductName)).createPanel() return JBUI.Panels.simplePanel(0, UIUtil.DEFAULT_VGAP) .addToCenter(editorArea) .addToTop(JBLabel(text)) .addToBottom(recordPreviousNames) } override fun getPreferredFocusedComponent(): JComponent = editorArea.focusTarget private fun generateLineExtension(line: Int): Collection<LineExtensionInfo> { val lineText = document.charsSequence.subSequence(document.getLineStartOffset(line), document.getLineEndOffset(line)).toString() if (line !in modules.indices || modules[line].name == lineText) return emptyList() val name = LineExtensionInfo(" <- ${modules[line].name}", JBColor.GRAY, null, null, Font.PLAIN) val groupPath = ModuleManager.getInstance(project).getModuleGroupPath(modules[line]) if (groupPath == null) { return listOf(name) } val group = LineExtensionInfo(groupPath.joinToString(separator = "/", prefix = " (", postfix = ")"), Color.GRAY, null, null, Font.PLAIN) return listOf(name, group) } fun importRenamingScheme(renamingScheme: Map<String, String>) { val moduleManager = ModuleManager.getInstance(project) fun getDefaultName(module: Module) = (moduleManager.getModuleGroupPath(module)?.let { it.joinToString(".") + "." } ?: "") + module.name val names = moduleManager.modules.associateBy({ it }, { renamingScheme.getOrElse(it.name, { getDefaultName(it) }) }) modules = moduleManager.modules.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { names[it]!! })) runWriteAction { document.setText(modules.joinToString("\n") { names[it]!! }) } modified = false } fun getRenamingScheme(): Map<String, String> { val lines = document.charsSequence.split('\n') return modules.withIndex().filter { lines[it.index] != it.value.name }.associateByTo(LinkedHashMap(), { it.value.name }, { if (it.index in lines.indices) lines[it.index] else it.value.name }) } override fun doCancelAction() { if (modified) { val answer = Messages.showYesNoCancelDialog(project, ProjectBundle.message("convert.module.groups.do.you.want.to.save.scheme"), ProjectBundle.message("convert.module.groups.dialog.title"), null) when (answer) { Messages.CANCEL -> return Messages.YES -> { if (!saveModuleRenamingScheme(this)) { return } } } } super.doCancelAction() } override fun doOKAction() { ModuleNamesListInspection.checkModuleNames(document.charsSequence.lines(), project) { line, message -> Messages.showErrorDialog(project, ProjectBundle.message("convert.module.groups.error.at.text", line + 1, StringUtil.decapitalize(message)), CommonBundle.getErrorTitle()) return } val renamingScheme = getRenamingScheme() if (renamingScheme.isNotEmpty()) { val model = ModuleManager.getInstance(project).modifiableModel val byName = modules.associateBy { it.name } for (entry in renamingScheme) { model.renameModule(byName[entry.key]!!, entry.value) } modules.forEach { model.setModuleGroupPath(it, null) } runInAllowSaveMode(isSaveAllowed = false) { runWriteAction { model.commit() } if (recordPreviousNamesCheckBox.isSelected) { (ModulePointerManager.getInstance(project) as ModulePointerManagerImpl).setRenamingScheme(renamingScheme) } } project.save() } super.doOKAction() } override fun createActions(): Array<Action> { return arrayOf(okAction, SaveModuleRenamingSchemeAction(this, { modified = false }), LoadModuleRenamingSchemeAction(this), cancelAction) } } class ConvertModuleGroupsToQualifiedNamesAction : DumbAwareAction(ProjectBundle.message("convert.module.groups.action.text"), ProjectBundle.message("convert.module.groups.action.description"), null) { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return ConvertModuleGroupsToQualifiedNamesDialog(project).show() } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.project != null && ModuleManager.getInstance(e.project!!).hasModuleGroups() } }
apache-2.0
214441339db16d319cee43ab7a7017e0
42.682464
140
0.731366
4.73395
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/VKBinding.kt
1
13128
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package vulkan import org.lwjgl.generator.* import vulkan.VKFunctionType.* import java.io.* private val NativeClass.capName: String get() = if (templateName.startsWith(prefix)) { if (prefix == "VK") "Vulkan${templateName.substring(2)}" else templateName } else { "${prefixTemplate}_$templateName" } private const val CAPS_INSTANCE = "VKCapabilitiesInstance" private const val CAPS_DEVICE = "VKCapabilitiesDevice" private val EXTENSION_TYPES = HashMap<String, String>() private val NativeClass.isInstanceExtension get() = EXTENSION_TYPES[templateName] == "instance" || templateName.startsWith("VK") private val NativeClass.isDeviceExtension get() = EXTENSION_TYPES[templateName] == "device" || templateName.startsWith("VK") private enum class VKFunctionType { PROC, GLOBAL, INSTANCE, DEVICE } private val Func.type: VKFunctionType get() = when { name == "vkGetInstanceProcAddr" -> PROC // dlsym/GetProcAddress parameters[0].nativeType !is WrappedPointerType -> GLOBAL // vkGetInstanceProcAddr: VK_NULL_HANDLE parameters[0].nativeType.let { it === VkInstance || it === VkPhysicalDevice } || EXTENSION_TYPES[nativeClass.templateName] == "instance" -> INSTANCE // vkGetInstanceProcAddr: instance handle else -> DEVICE // vkGetDeviceProcAddr: device handle } private val Func.isInstanceFunction get() = type === INSTANCE && !has<Macro>() private val Func.isDeviceFunction get() = type === DEVICE && !has<Macro>() private val EXTENSION_NAME = "[A-Za-z0-9_]+".toRegex() private fun getFunctionDependencyExpression(func: Func) = func.get<DependsOn>() .reference .let { expression -> if (EXTENSION_NAME.matches(expression)) "ext.contains(\"$expression\")" else expression } private fun PrintWriter.printCheckFunctions( nativeClass: NativeClass, commands: Map<String, Int>, dependencies: LinkedHashMap<String, Int>, filter: (Func) -> Boolean ) { print("checkFunctions(provider, caps, new int[] {") nativeClass.printPointers(this, { func -> val index = commands[func.name] if (func.has<DependsOn>()) { "flag${dependencies[getFunctionDependencyExpression(func)]} + $index" } else{ index.toString() } }, filter) print("},") nativeClass.printPointers(this, { "\"${it.name}\"" }, filter) print(")") } val VK_BINDING_INSTANCE = Generator.register(object : APIBinding( Module.VULKAN, CAPS_INSTANCE, APICapabilities.PARAM_CAPABILITIES ) { override fun shouldCheckFunctionAddress(function: Func): Boolean = function.nativeClass.templateName != "VK10" override fun generateFunctionAddress(writer: PrintWriter, function: Func) { writer.print("$t${t}long $FUNCTION_ADDRESS = ") writer.println(if (function.has<Capabilities>()) "${function.get<Capabilities>().expression}.${function.name};" else "${function.getParams { it.nativeType is WrappedPointerType }.first().name}${ if (function.isInstanceFunction && !function.parameters[0].nativeType.let { it === VkInstance || it === VkPhysicalDevice }) ".getCapabilitiesInstance()" else ".getCapabilities()" }.${function.name};" ) } private fun PrintWriter.checkExtensionFunctions(nativeClass: NativeClass, commands: Map<String, Int>) { val capName = nativeClass.capName print(""" private static boolean check_${nativeClass.templateName}(FunctionProvider provider, long[] caps, java.util.Set<String> ext) { if (!ext.contains("$capName")) { return false; }""") val dependencies = nativeClass.functions .filter { it.isInstanceFunction && it.has<DependsOn>() } .map(::getFunctionDependencyExpression) .foldIndexed(LinkedHashMap<String, Int>()) { index, map, expression -> if (!map.containsKey(expression)) { map[expression] = index } map } if (dependencies.isNotEmpty()) { println() dependencies.forEach { (expression, index) -> print("\n$t${t}int flag$index = $expression ? 0 : Integer.MIN_VALUE;") } } print("\n\n$t${t}return ") printCheckFunctions(nativeClass, commands, dependencies) { it.isInstanceFunction } println(" || reportMissing(\"VK\", \"$capName\");") println("$t}") } init { javaImport("static org.lwjgl.system.Checks.*") documentation = "Defines the enabled capabilities of a Vulkan {@code VkInstance}." } override fun PrintWriter.generateJava() { generateJavaPreamble() println("@SuppressWarnings(\"SimplifiableIfStatement\")") println("public class $CAPS_INSTANCE {") val classes = super.getClasses("VK") val instanceCommands = LinkedHashMap<String, Int>() classes.asSequence() .filter { it.hasNativeFunctions } .forEach { val functions = it.functions.asSequence() .filter { cmd -> if (cmd.isInstanceFunction) { if (!instanceCommands.contains(cmd.name)) { instanceCommands[cmd.name] = instanceCommands.size return@filter true } } false } .joinToString(",\n$t$t") { cmd -> cmd.name } if (functions.isNotEmpty()) { println("\n$t// ${it.templateName}") println("${t}public final long") println("$t$t$functions;") } } println( """ /** The Vulkan API version number. */ public final int apiVersion; """ ) classes .filter { EXTENSION_TYPES[it.templateName] ?: "instance" == "instance" } .forEach { println(it.getCapabilityJavadoc()) println("${t}public final boolean ${it.capName};") } print( """ $CAPS_INSTANCE(FunctionProvider provider, int apiVersion, Set<String> ext, Set<String> deviceExt) { this.apiVersion = apiVersion; long[] caps = new long[${instanceCommands.size}]; """ ) classes.forEach { val capName = it.capName if (it.functions.any { func -> func.isInstanceFunction }) { print( if (it.isInstanceExtension) "\n$t$t$capName = check_${it.templateName}(provider, caps, ext);" else "\n$t${t}check_${it.templateName}(provider, caps, deviceExt);" ) } else if (it.isInstanceExtension) { print("\n$t$t$capName = ext.contains(\"$capName\");") } } println() instanceCommands.forEach { (it, index) -> print("\n$t$t$it = caps[$index];") } print( """ } """) for (extension in classes) { if (extension.functions.any { it.isInstanceFunction }) { checkExtensionFunctions(extension, instanceCommands) } } println("\n}") } }) val VK_BINDING_DEVICE = Generator.register(object : GeneratorTarget(Module.VULKAN, CAPS_DEVICE) { private fun PrintWriter.checkExtensionFunctions(nativeClass: NativeClass, commands: Map<String, Int>) { val capName = nativeClass.capName val isDeviceExtension = nativeClass.isDeviceExtension val hasDependencies = nativeClass.functions.any { it.has<DependsOn>() } print(""" private static boolean check_${nativeClass.templateName}(FunctionProvider provider, long[] caps""") if (isDeviceExtension || hasDependencies) { print(", Set<String> ext") } else if (!isDeviceExtension) { print(", VKCapabilitiesInstance capsInstance") } print(""") { if (!${if (isDeviceExtension) { "ext.contains(\"$capName\")" } else { "capsInstance.$capName" }}) { return false; }""") val dependencies = nativeClass.functions .filter { it.isDeviceFunction && it.has<DependsOn>() } .map(::getFunctionDependencyExpression) .foldIndexed(LinkedHashMap<String, Int>()) { index, map, expression -> if (!map.containsKey(expression)) { map[expression] = index } map } if (dependencies.isNotEmpty()) { println() dependencies.forEach { (expression, index) -> print("\n$t${t}int flag$index = $expression ? 0 : Integer.MIN_VALUE;") } } print("\n\n$t${t}return ") printCheckFunctions(nativeClass, commands, dependencies) { it.isDeviceFunction } println(" || reportMissing(\"VK\", \"$capName\");") println("$t}") } init { javaImport( "java.util.*", "org.lwjgl.system.*", "static org.lwjgl.system.Checks.*" ) documentation = "Defines the enabled capabilities of a Vulkan {@code VkDevice}." } override fun PrintWriter.generateJava() { generateJavaPreamble() println("@SuppressWarnings(\"SimplifiableIfStatement\")") println("public class $CAPS_DEVICE {") val classes = VK_BINDING_INSTANCE.getClasses("VK") val deviceCommands = LinkedHashMap<String, Int>() classes.asSequence() .filter { it.hasNativeFunctions } .forEach { val functions = it.functions.asSequence() .filter { cmd -> if (cmd.type === DEVICE && !cmd.has<Macro>()) { if (!deviceCommands.contains(cmd.name)) { deviceCommands[cmd.name] = deviceCommands.size return@filter true } } false } .joinToString(",\n$t$t") { cmd -> cmd.name } if (functions.isNotEmpty()) { println("\n$t// ${it.templateName}") println("${t}public final long") println("$t$t$functions;") } } println( """ /** The Vulkan API version number. */ public final int apiVersion; """ ) classes .filter { EXTENSION_TYPES[it.templateName] ?: "device" == "device" } .forEach { println(it.getCapabilityJavadoc()) println("${t}public final boolean ${it.capName};") } print( """ $CAPS_DEVICE(FunctionProvider provider, VKCapabilitiesInstance capsInstance, int apiVersion, Set<String> ext) { this.apiVersion = apiVersion; long[] caps = new long[${deviceCommands.size}]; """ ) classes.forEach { val capName = it.capName if (it.functions.any { func -> func.isDeviceFunction }) { print( if (it.isDeviceExtension) "\n$t$t$capName = check_${it.templateName}(provider, caps, ext);" else "\n$t${t}check_${it.templateName}(provider, caps, capsInstance);" ) } else if (it.isDeviceExtension) { print("\n$t$t$capName = ext.contains(\"$capName\");") } } println() deviceCommands.forEach { (it, index) -> print("\n$t$t$it = caps[$index];") } print( """ } """) for (extension in classes) { if (extension.functions.any { it.isDeviceFunction }) { checkExtensionFunctions(extension, deviceCommands) } } println("\n}") } }) // DSL Extensions val GlobalCommand = Capabilities("VK.getGlobalCommands()") fun String.nativeClassVK( templateName: String, type: String, prefix: String = "VK", prefixMethod: String = prefix.lowercase(), postfix: String = "", init: (NativeClass.() -> Unit)? = null ): NativeClass { EXTENSION_TYPES[templateName] = type return nativeClass( Module.VULKAN, templateName, prefix = prefix, prefixMethod = prefixMethod, postfix = postfix, binding = VK_BINDING_INSTANCE, init = init ) }
bsd-3-clause
6eb62aa4a75fd36739af714f933b8e7a
32.492347
144
0.543495
4.942771
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/FrameLayoutNavMenuTriggerer.kt
1
2614
package org.wikipedia.views import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.view.MotionEvent import android.widget.FrameLayout import org.wikipedia.util.DimenUtil.roundedDpToPx import org.wikipedia.util.L10nUtil import kotlin.math.abs class FrameLayoutNavMenuTriggerer : FrameLayout { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet? = null) : super(context, attrs) constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) interface Callback { fun onNavMenuSwipeRequest(gravity: Int) } private var initialX = 0f private var initialY = 0f private var maybeSwiping = false var callback: Callback? = null override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { val action = ev.actionMasked if (CHILD_VIEW_SCROLLED) { CHILD_VIEW_SCROLLED = false initialX = ev.x initialY = ev.y } if (action == MotionEvent.ACTION_DOWN) { initialX = ev.x initialY = ev.y maybeSwiping = true } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { maybeSwiping = false } else if (action == MotionEvent.ACTION_MOVE && maybeSwiping) { if (abs((ev.y - initialY).toInt()) > SWIPE_SLOP_Y) { maybeSwiping = false } else if (abs(ev.x - initialX) > SWIPE_SLOP_X) { maybeSwiping = false if (callback != null) { // send an explicit event to children to cancel the current gesture that // they thought was occurring. val moveEvent = MotionEvent.obtain(ev) moveEvent.action = MotionEvent.ACTION_CANCEL post { super.dispatchTouchEvent(moveEvent) } // and trigger our custom swipe request! callback!!.onNavMenuSwipeRequest(if (L10nUtil.isDeviceRTL) if (ev.x > initialX) Gravity.END else Gravity.START else if (ev.x > initialX) Gravity.START else Gravity.END) } } } return false } companion object { private val SWIPE_SLOP_Y = roundedDpToPx(32f) private val SWIPE_SLOP_X = roundedDpToPx(100f) private var CHILD_VIEW_SCROLLED = false @JvmStatic fun setChildViewScrolled() { CHILD_VIEW_SCROLLED = true } } }
apache-2.0
265c540ec99151578d472f47a4155240
36.884058
133
0.611706
4.476027
false
false
false
false
stanfy/helium
codegen/swift/swift-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/swift/entity/registry/SwiftTypeRegistyy.kt
1
3875
package com.stanfy.helium.handler.codegen.swift.entity.registry import com.stanfy.helium.handler.codegen.swift.entity.entities.* import com.stanfy.helium.internal.utils.Names import com.stanfy.helium.model.Sequence import com.stanfy.helium.model.Type import com.stanfy.helium.model.constraints.ConstrainedType import com.stanfy.helium.model.constraints.EnumConstraint interface SwiftTypeRegistry { fun registerSwiftType(heliumType: Type): SwiftEntity fun registerEnumType(heliumType: Type): SwiftEntityEnum? fun registerMappings(mappings: Map<String, String>) fun simpleSequenceType(heliumType: Type): SwiftEntityArray fun propertyName(fieldName: String): String companion object { val EmptyResponse: SwiftEntity = SwiftEntityStruct("EmptyResponse") } } class SwiftTypeRegistryImpl : SwiftTypeRegistry { val registry = mutableMapOf<String, SwiftEntity>() override fun registerEnumType(heliumType: Type): SwiftEntityEnum? { val enum = enumType(heliumType) ?: return null registry.put(heliumType.name, enum) return enum } override fun registerSwiftType(heliumType: Type): SwiftEntity { return registry.getOrElse(heliumType.name) { val type: SwiftEntity = tryRegisterSequenceType(heliumType) ?: tryPrimitiveType(heliumType) ?: structType(heliumType) registry.put(heliumType.name, type) return type } } override fun registerMappings(mappings: Map<String, String>) { registry.putAll(mappings.mapValues { name -> SwiftEntityStruct(name.value) }) } private fun tryRegisterSequenceType(heliumType: Type): SwiftEntityArray? { if (heliumType !is Sequence) return null val itemType = registerSwiftType(heliumType.itemsType) return SwiftEntityArray(heliumType.name, itemType) } override fun simpleSequenceType(heliumType: Type): SwiftEntityArray { return SwiftEntityArray("", registerSwiftType(heliumType)) } fun structType(heliumType: Type): SwiftEntityStruct { return SwiftEntityStruct(className(heliumType.name)) } private fun tryPrimitiveType(heliumType: Type): SwiftEntityPrimitive? { return when (heliumType.name) { "int" -> SwiftEntityPrimitive("Int") "integer" -> SwiftEntityPrimitive("Int") "int32" -> SwiftEntityPrimitive("Int") "int64" -> SwiftEntityPrimitive("Int") "long" -> SwiftEntityPrimitive("Int") "double" -> SwiftEntityPrimitive("Double") "float" -> SwiftEntityPrimitive("Double") "float32" -> SwiftEntityPrimitive("Double") "float64" -> SwiftEntityPrimitive("Double") "string" -> SwiftEntityPrimitive("String") "bool" -> SwiftEntityPrimitive("Bool") "boolean" -> SwiftEntityPrimitive("Bool") else -> { null } } } fun enumType(heliumType: Type): SwiftEntityEnum? { if (heliumType !is ConstrainedType) return null val constraint = heliumType.constraints.first { con -> con is EnumConstraint } as? EnumConstraint<Any> ?: return null val enumValues = constraint.values .filterIsInstance<String>() .map { s -> SwiftEntityEnumCase( name = propertyName(s).capitalize(), value = s) } return SwiftEntityEnum(propertyName(heliumType.name).capitalize(), enumValues) } fun className(className: String) : String { val prettifiedName = Names.prettifiedName(Names.canonicalName(className)) if (arrayOf("Error").contains(prettifiedName)) { return "API" + prettifiedName } return prettifiedName } override fun propertyName(fieldName: String): String { val prettifiedName = Names.prettifiedName(Names.canonicalName(fieldName)) if (arrayOf("enum", "default", "let", "case", "self", "description").contains(prettifiedName)) { return prettifiedName + "Value" } return prettifiedName } }
apache-2.0
bfc19968d3a42e5bbfffdb33b46d085a
33.300885
121
0.71071
4.189189
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ConvertTwoComparisonsToRangeCheckInspection.kt
1
10838
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.branchedTransformations.evaluatesTo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.builtIns import org.jetbrains.kotlin.types.typeUtil.isPrimitiveNumberType import org.jetbrains.kotlin.util.OperatorNameConventions class ConvertTwoComparisonsToRangeCheckInspection : AbstractApplicabilityBasedInspection<KtBinaryExpression>(KtBinaryExpression::class.java), CleanupLocalInspectionTool { override fun inspectionText(element: KtBinaryExpression) = KotlinBundle.message("two.comparisons.should.be.converted.to.a.range.check") override val defaultFixText get() = KotlinBundle.message("convert.to.a.range.check") override fun isApplicable(element: KtBinaryExpression): Boolean { val rangeData = generateRangeExpressionData(element) ?: return false val function = element.getStrictParentOfType<KtNamedFunction>() if (function != null && function.hasModifier(KtTokens.OPERATOR_KEYWORD) && function.nameAsName == OperatorNameConventions.CONTAINS) { val context = element.analyze(BodyResolveMode.PARTIAL) val functionDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, function] val newExpression = rangeData.createExpression() val newContext = newExpression.analyzeAsReplacement(element, context) if (newExpression.operationReference.getResolvedCall(newContext)?.resultingDescriptor == functionDescriptor) return false } return true } override fun applyTo(element: KtBinaryExpression, project: Project, editor: Editor?) { val rangeData = generateRangeExpressionData(element) ?: return val replaced = element.replace(rangeData.createExpression()) (replaced as? KtBinaryExpression)?.right?.let { ReplaceRangeToWithUntilInspection.applyFixIfApplicable(it) } } private data class RangeExpressionData(val value: KtExpression, val min: String, val max: String) { fun createExpression(): KtBinaryExpression { val factory = KtPsiFactory(value) return factory.createExpressionByPattern( "$0 in $1..$2", value, factory.createExpression(min), factory.createExpression(max) ) as KtBinaryExpression } } private fun generateRangeExpressionData(condition: KtBinaryExpression): RangeExpressionData? { if (condition.operationToken != KtTokens.ANDAND) return null val firstCondition = condition.left as? KtBinaryExpression ?: return null val secondCondition = condition.right as? KtBinaryExpression ?: return null val firstOpToken = firstCondition.operationToken val secondOpToken = secondCondition.operationToken val firstLeft = firstCondition.left ?: return null val firstRight = firstCondition.right ?: return null val secondLeft = secondCondition.left ?: return null val secondRight = secondCondition.right ?: return null fun IElementType.isStrictComparison() = this == KtTokens.GT || this == KtTokens.LT val firstStrict = firstOpToken.isStrictComparison() val secondStrict = secondOpToken.isStrictComparison() fun IElementType.orderLessAndGreater(left: KtExpression, right: KtExpression): Pair<KtExpression, KtExpression>? = when (this) { KtTokens.GTEQ, KtTokens.GT -> right to left KtTokens.LTEQ, KtTokens.LT -> left to right else -> null } val (firstLess, firstGreater) = firstOpToken.orderLessAndGreater(firstLeft, firstRight) ?: return null val (secondLess, secondGreater) = secondOpToken.orderLessAndGreater(secondLeft, secondRight) ?: return null return generateRangeExpressionData(firstLess, firstGreater, firstStrict, secondLess, secondGreater, secondStrict) } private fun KtExpression.isSimple() = this is KtConstantExpression || this is KtNameReferenceExpression private fun generateRangeExpressionData( firstLess: KtExpression, firstGreater: KtExpression, firstStrict: Boolean, secondLess: KtExpression, secondGreater: KtExpression, secondStrict: Boolean ) = when { firstGreater !is KtConstantExpression && firstGreater.evaluatesTo(secondLess) -> generateRangeExpressionData( firstGreater, min = firstLess, max = secondGreater, incrementMinByOne = firstStrict, decrementMaxByOne = secondStrict ) firstLess !is KtConstantExpression && firstLess.evaluatesTo(secondGreater) -> generateRangeExpressionData( firstLess, min = secondLess, max = firstGreater, incrementMinByOne = secondStrict, decrementMaxByOne = firstStrict ) else -> null } private fun generateRangeExpressionData( value: KtExpression, min: KtExpression, max: KtExpression, incrementMinByOne: Boolean, decrementMaxByOne: Boolean ): RangeExpressionData? { fun KtExpression.getChangeBy(context: BindingContext, number: Int): String? { val type = getType(context) ?: return null if (!type.isValidTypeForIncrementDecrementByOne()) return null when (this) { is KtConstantExpression -> { val constantValue = ConstantExpressionEvaluator.getConstant(this, context)?.getValue(type) ?: return null return when { KotlinBuiltIns.isInt(type) -> (constantValue as Int + number).let { val text = this.text when { text.startsWith("0x") -> "0x${it.toString(16)}" text.startsWith("0b") -> "0b${it.toString(2)}" else -> it.toString() } } KotlinBuiltIns.isLong(type) -> (constantValue as Long + number).let { val text = this.text when { text.startsWith("0x") -> "0x${it.toString(16)}" text.startsWith("0b") -> "0b${it.toString(2)}" else -> it.toString() } } KotlinBuiltIns.isChar(type) -> "'${constantValue as Char + number}'" else -> null } } else -> return if (number >= 0) "($text + $number)" else "($text - ${-number})" } } // To avoid possible side effects if (!min.isSimple() || !max.isSimple()) return null val context = value.analyze() val valType = value.getType(context) val minType = min.getType(context) val maxType = max.getType(context) if (valType == null || minType == null || maxType == null) return null if (!valType.isComparable()) return null var minVal = min var maxVal = max if (minType != valType || maxType != valType) { //numbers can be compared to numbers of different types if (valType.isPrimitiveNumberType() && minType.isPrimitiveNumberType() && maxType.isPrimitiveNumberType()) { //char is comparable to chars only if (KotlinBuiltIns.isChar(valType) || KotlinBuiltIns.isChar(minType) || KotlinBuiltIns.isChar(maxType)) return null //floating point ranges can't contain integer types and vise versa if (valType.isInteger() && (minType.isFloatingPoint() || maxType.isFloatingPoint())) return null if (valType.isFloatingPoint()) { if (minType.isInteger()) minVal = KtPsiFactory(minVal).createExpression(getDoubleConstant(min, minType, context) ?: return null) if (maxType.isInteger()) maxVal = KtPsiFactory(maxVal).createExpression(getDoubleConstant(max, maxType, context) ?: return null) } } else { return null } } if (incrementMinByOne || decrementMaxByOne) { if (!valType.isValidTypeForIncrementDecrementByOne()) return null } val minText = if (incrementMinByOne) minVal.getChangeBy(context, 1) else minVal.text val maxText = if (decrementMaxByOne) maxVal.getChangeBy(context, -1) else maxVal.text return RangeExpressionData(value, minText ?: return null, maxText ?: return null) } private fun getDoubleConstant(intExpr: KtExpression, type: KotlinType, context: BindingContext): String? { val intConst = ConstantExpressionEvaluator.getConstant(intExpr, context)?.getValue(type) ?: return null return (intConst as? Number)?.toDouble()?.toString() } private fun KotlinType.isComparable() = DescriptorUtils.isSubtypeOfClass(this, this.builtIns.comparable) private fun KotlinType.isFloatingPoint(): Boolean { return KotlinBuiltIns.isFloat(this) || KotlinBuiltIns.isDouble(this) } private fun KotlinType.isInteger(): Boolean { return KotlinBuiltIns.isInt(this) || KotlinBuiltIns.isLong(this) || KotlinBuiltIns.isShort(this) || KotlinBuiltIns.isByte(this) } private fun KotlinType?.isValidTypeForIncrementDecrementByOne(): Boolean { this ?: return false return this.isInteger() || KotlinBuiltIns.isChar(this) } }
apache-2.0
153e7722eeaac042a172d54eadfb77e7
48.720183
158
0.656948
5.165872
false
false
false
false
dahlstrom-g/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/OneToOne.kt
3
14003
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage //region ------------------- Parent Entity -------------------------------- @Suppress("unused") interface OoParentEntity : WorkspaceEntity { val parentProperty: String val child: @Child OoChildEntity? val anotherChild: @Child OoChildWithNullableParentEntity? //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: OoParentEntity, ModifiableWorkspaceEntity<OoParentEntity>, ObjBuilder<OoParentEntity> { override var parentProperty: String override var entitySource: EntitySource override var child: OoChildEntity? override var anotherChild: OoChildWithNullableParentEntity? } companion object: Type<OoParentEntity, Builder>() { operator fun invoke(parentProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OoParentEntity { val builder = builder() builder.parentProperty = parentProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OoParentEntity, modification: OoParentEntity.Builder.() -> Unit) = modifyEntity(OoParentEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addOoParentEntity( parentProperty: String = "parent", source: EntitySource = MySource ): OoParentEntity { val ooParentEntity = OoParentEntity(parentProperty, source) this.addEntity(ooParentEntity) return ooParentEntity } //region ---------------- Child entity ---------------------- @Suppress("unused") interface OoChildEntity : WorkspaceEntity { val childProperty: String val parentEntity: OoParentEntity //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: OoChildEntity, ModifiableWorkspaceEntity<OoChildEntity>, ObjBuilder<OoChildEntity> { override var childProperty: String override var entitySource: EntitySource override var parentEntity: OoParentEntity } companion object: Type<OoChildEntity, Builder>() { operator fun invoke(childProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OoChildEntity { val builder = builder() builder.childProperty = childProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OoChildEntity, modification: OoChildEntity.Builder.() -> Unit) = modifyEntity(OoChildEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addOoChildEntity( OoParentEntity: OoParentEntity, childProperty: String = "child", source: EntitySource = MySource ): OoChildEntity { val ooChildEntity = OoChildEntity(childProperty, source) { this.parentEntity = OoParentEntity } this.addEntity(ooChildEntity) return ooChildEntity } //region ----------------- Child entity with a nullable parent ----------------------------- interface OoChildWithNullableParentEntity : WorkspaceEntity { val parentEntity: OoParentEntity? //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: OoChildWithNullableParentEntity, ModifiableWorkspaceEntity<OoChildWithNullableParentEntity>, ObjBuilder<OoChildWithNullableParentEntity> { override var parentEntity: OoParentEntity? override var entitySource: EntitySource } companion object: Type<OoChildWithNullableParentEntity, Builder>() { operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OoChildWithNullableParentEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OoChildWithNullableParentEntity, modification: OoChildWithNullableParentEntity.Builder.() -> Unit) = modifyEntity(OoChildWithNullableParentEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addOoChildWithNullableParentEntity( OoParentEntity: OoParentEntity, source: EntitySource = MySource ): OoChildWithNullableParentEntity { val ooChildWithNullableParentEntity = OoChildWithNullableParentEntity(source) { this.parentEntity = OoParentEntity } this.addEntity(ooChildWithNullableParentEntity) return ooChildWithNullableParentEntity } //region ------------------- Parent Entity with PersistentId -------------------------------- data class OoParentEntityId(val name: String) : PersistentEntityId<OoParentWithPidEntity> { override val presentableName: String get() = name } interface OoParentWithPidEntity : WorkspaceEntityWithPersistentId { val parentProperty: String override val persistentId: OoParentEntityId get() = OoParentEntityId(parentProperty) val childOne: @Child OoChildForParentWithPidEntity? val childThree: @Child OoChildAlsoWithPidEntity? //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: OoParentWithPidEntity, ModifiableWorkspaceEntity<OoParentWithPidEntity>, ObjBuilder<OoParentWithPidEntity> { override var parentProperty: String override var entitySource: EntitySource override var childOne: OoChildForParentWithPidEntity? override var childThree: OoChildAlsoWithPidEntity? } companion object: Type<OoParentWithPidEntity, Builder>() { operator fun invoke(parentProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OoParentWithPidEntity { val builder = builder() builder.parentProperty = parentProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OoParentWithPidEntity, modification: OoParentWithPidEntity.Builder.() -> Unit) = modifyEntity(OoParentWithPidEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addOoParentWithPidEntity( parentProperty: String = "parent", source: EntitySource = MySource ): OoParentWithPidEntity { val ooParentWithPidEntity = OoParentWithPidEntity(parentProperty, source) this.addEntity(ooParentWithPidEntity) return ooParentWithPidEntity } // ---------------- Child entity for parent with PersistentId for Nullable ref ---------------------- interface OoChildForParentWithPidEntity : WorkspaceEntity { val childProperty: String val parentEntity: OoParentWithPidEntity //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: OoChildForParentWithPidEntity, ModifiableWorkspaceEntity<OoChildForParentWithPidEntity>, ObjBuilder<OoChildForParentWithPidEntity> { override var childProperty: String override var entitySource: EntitySource override var parentEntity: OoParentWithPidEntity } companion object: Type<OoChildForParentWithPidEntity, Builder>() { operator fun invoke(childProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OoChildForParentWithPidEntity { val builder = builder() builder.childProperty = childProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OoChildForParentWithPidEntity, modification: OoChildForParentWithPidEntity.Builder.() -> Unit) = modifyEntity(OoChildForParentWithPidEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addOoChildForParentWithPidEntity( parentEntity: OoParentWithPidEntity, childProperty: String = "child", source: EntitySource = MySource ): OoChildForParentWithPidEntity { val ooChildForParentWithPidEntity = OoChildForParentWithPidEntity(childProperty, source) { this.parentEntity = parentEntity } this.addEntity(ooChildForParentWithPidEntity) return ooChildForParentWithPidEntity } // ---------------- Child with PersistentId for parent with PersistentId ---------------------- interface OoChildAlsoWithPidEntity : WorkspaceEntityWithPersistentId { val childProperty: String val parentEntity: OoParentWithPidEntity override val persistentId: OoChildEntityId get() = OoChildEntityId(childProperty) //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: OoChildAlsoWithPidEntity, ModifiableWorkspaceEntity<OoChildAlsoWithPidEntity>, ObjBuilder<OoChildAlsoWithPidEntity> { override var childProperty: String override var entitySource: EntitySource override var parentEntity: OoParentWithPidEntity } companion object: Type<OoChildAlsoWithPidEntity, Builder>() { operator fun invoke(childProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OoChildAlsoWithPidEntity { val builder = builder() builder.childProperty = childProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OoChildAlsoWithPidEntity, modification: OoChildAlsoWithPidEntity.Builder.() -> Unit) = modifyEntity(OoChildAlsoWithPidEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addOoChildAlsoWithPidEntity( parentEntity: OoParentWithPidEntity, childProperty: String = "child", source: EntitySource = MySource ): OoChildAlsoWithPidEntity { val ooChildAlsoWithPidEntity = OoChildAlsoWithPidEntity(childProperty, source) { this.parentEntity = parentEntity } this.addEntity(ooChildAlsoWithPidEntity) return ooChildAlsoWithPidEntity } // ------------------- Parent Entity without PersistentId for Nullable ref -------------------------------- interface OoParentWithoutPidEntity : WorkspaceEntity { val parentProperty: String val childOne: @Child OoChildWithPidEntity? //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: OoParentWithoutPidEntity, ModifiableWorkspaceEntity<OoParentWithoutPidEntity>, ObjBuilder<OoParentWithoutPidEntity> { override var parentProperty: String override var entitySource: EntitySource override var childOne: OoChildWithPidEntity? } companion object: Type<OoParentWithoutPidEntity, Builder>() { operator fun invoke(parentProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OoParentWithoutPidEntity { val builder = builder() builder.parentProperty = parentProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OoParentWithoutPidEntity, modification: OoParentWithoutPidEntity.Builder.() -> Unit) = modifyEntity(OoParentWithoutPidEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addOoParentWithoutPidEntity( parentProperty: String = "parent", source: EntitySource = MySource ): OoParentWithoutPidEntity { val ooParentWithoutPidEntity = OoParentWithoutPidEntity(parentProperty, source) this.addEntity(ooParentWithoutPidEntity) return ooParentWithoutPidEntity } // ---------------- Child entity with PersistentId for Nullable ref---------------------- data class OoChildEntityId(val name: String) : PersistentEntityId<OoChildWithPidEntity> { override val presentableName: String get() = name } interface OoChildWithPidEntity : WorkspaceEntityWithPersistentId { val childProperty: String val parentEntity: OoParentWithoutPidEntity override val persistentId: OoChildEntityId get() = OoChildEntityId(childProperty) //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: OoChildWithPidEntity, ModifiableWorkspaceEntity<OoChildWithPidEntity>, ObjBuilder<OoChildWithPidEntity> { override var childProperty: String override var entitySource: EntitySource override var parentEntity: OoParentWithoutPidEntity } companion object: Type<OoChildWithPidEntity, Builder>() { operator fun invoke(childProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OoChildWithPidEntity { val builder = builder() builder.childProperty = childProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OoChildWithPidEntity, modification: OoChildWithPidEntity.Builder.() -> Unit) = modifyEntity(OoChildWithPidEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addOoChildWithPidEntity( parentEntity: OoParentWithoutPidEntity, childProperty: String = "child", source: EntitySource = MySource ): OoChildWithPidEntity { val ooChildWithPidEntity = OoChildWithPidEntity(childProperty, source) { this.parentEntity = parentEntity } this.addEntity(ooChildWithPidEntity) return ooChildWithPidEntity }
apache-2.0
4dd7f37945945d2e30bfc21d6dde8251
35.371429
234
0.750196
5.476339
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/ui/EditorNotificationUsagesCollector.kt
9
1912
// 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.ui import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.events.EventFields.Class import com.intellij.internal.statistic.eventLog.events.PrimitiveEventField import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus.Internal private val GROUP = EventLogGroup( id = "editor.notification.panel", version = 3, ) private val PROVIDER_CLASS_FIELD = object : PrimitiveEventField<EditorNotificationProvider>() { private val delegate = Class("provider_class") override val name: String get() = delegate.name override val validationRule: List<String> get() = delegate.validationRule override fun addData( fuData: FeatureUsageData, value: EditorNotificationProvider, ) { delegate.addData(fuData, value.javaClass) } } private val NOTIFICATION_SHOWN_EVENT = GROUP.registerEvent( eventId = "notificationShown", eventField1 = PROVIDER_CLASS_FIELD, ) private val HANDLER_INVOKED_EVENT = GROUP.registerEvent( eventId = "handlerInvoked", eventField1 = PROVIDER_CLASS_FIELD, eventField2 = Class("handler_class"), ) @Internal internal fun logNotificationShown( project: Project, provider: EditorNotificationProvider, ) { NOTIFICATION_SHOWN_EVENT.log(project, provider) } @Internal internal fun logHandlerInvoked( project: Project, provider: EditorNotificationProvider, handlerClass: Class<*>, ) { HANDLER_INVOKED_EVENT.log(project, provider, handlerClass) } @Internal internal class EditorNotificationUsagesCollector : CounterUsagesCollector() { override fun getGroup() = GROUP }
apache-2.0
375097d6ed0cfc21465abcf555826832
27.132353
120
0.784519
4.335601
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IntroduceWhenSubjectInspection.kt
1
1718
// 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.inspections.branchedTransformations import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.idea.intentions.branchedTransformations.getSubjectToIntroduce import org.jetbrains.kotlin.idea.intentions.branchedTransformations.introduceSubject import org.jetbrains.kotlin.idea.util.textRangeIn import org.jetbrains.kotlin.psi.KtWhenExpression class IntroduceWhenSubjectInspection : AbstractApplicabilityBasedInspection<KtWhenExpression>(KtWhenExpression::class.java), CleanupLocalInspectionTool { override fun isApplicable(element: KtWhenExpression) = element.getSubjectToIntroduce() != null override fun inspectionHighlightRangeInElement(element: KtWhenExpression) = element.whenKeyword.textRangeIn(element) override fun inspectionText(element: KtWhenExpression) = KotlinBundle.message("when.with.subject.should.be.used") override val defaultFixText get() = KotlinBundle.message("introduce.when.subject") override fun fixText(element: KtWhenExpression): String { val subject = element.getSubjectToIntroduce() ?: return "" return KotlinBundle.message("introduce.0.as.subject.0.when", subject.text) } override fun applyTo(element: KtWhenExpression, project: Project, editor: Editor?) { element.introduceSubject() } }
apache-2.0
7e1335d4c43f50d550306542366ac855
49.529412
124
0.796275
5.190332
false
false
false
false
google/intellij-community
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/StoreSnapshotsAnalyzer.kt
2
3487
// 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.workspaceModel.ide import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity import com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl import com.intellij.workspaceModel.storage.impl.MatchedEntitySource import com.intellij.workspaceModel.storage.impl.SimpleEntityTypesResolver import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl import com.intellij.workspaceModel.storage.toBuilder import java.io.File import kotlin.system.exitProcess /** * This is a boilerplate code for analyzing state of entity stores that were received as attachments to exceptions */ fun main(args: Array<String>) { if (args.size != 1) { println("Usage: com.intellij.workspaceModel.ide.StoreSnapshotsAnalyzerKt <path to directory with storage files>") exitProcess(1) } val file = File(args[0]) if (!file.exists()) { throw IllegalArgumentException("$file doesn't exist") } if (file.isFile) { val serializer = EntityStorageSerializerImpl(SimpleEntityTypesResolver, VirtualFileUrlManagerImpl()) val storage = file.inputStream().use { serializer.deserializeCache(it).getOrThrow() } // Set a breakpoint and check println("Cache loaded: ${storage!!.entities(ModuleEntity::class.java).toList().size} modules") return } val leftFile = file.resolve("Left_Store") val rightFile = file.resolve("Right_Store") val rightDiffLogFile = file.resolve("Right_Diff_Log") val converterFile = file.resolve("ClassToIntConverter") val resFile = file.resolve("Res_Store") val serializer = EntityStorageSerializerImpl(SimpleEntityTypesResolver, VirtualFileUrlManagerImpl()) serializer.deserializeClassToIntConverter(converterFile.inputStream()) val resStore = serializer.deserializeCache(resFile.inputStream()).getOrThrow()!! val leftStore = serializer.deserializeCache(leftFile.inputStream()).getOrThrow() ?: throw IllegalArgumentException("Cannot load cache") if (file.resolve("Replace_By_Source").exists()) { val rightStore = serializer.deserializeCache(rightFile.inputStream()).getOrThrow()!! val allEntitySources = leftStore.entitiesBySource { true }.map { it.key }.toHashSet() allEntitySources.addAll(rightStore.entitiesBySource { true }.map { it.key }) val pattern = if (file.resolve("Report_Wrapped").exists()) { matchedPattern() } else { val sortedSources = allEntitySources.sortedBy { it.toString() } patternFilter(file.resolve("Replace_By_Source").readText(), sortedSources) } val expectedResult = leftStore.toBuilder() expectedResult.replaceBySource(pattern, rightStore) // Set a breakpoint and check println("storage loaded") } else { val rightStore = serializer.deserializeCacheAndDiffLog(rightFile.inputStream(), rightDiffLogFile.inputStream())!! val expectedResult = leftStore.toBuilder() expectedResult.addDiff(rightStore) // Set a breakpoint and check println("storage loaded") } } fun patternFilter(pattern: String, sortedSources: List<EntitySource>): (EntitySource) -> Boolean { return { val idx = sortedSources.indexOf(it) pattern[idx] == '1' } } fun matchedPattern(): (EntitySource) -> Boolean { return { it is MatchedEntitySource } }
apache-2.0
de76a108dfb85bbc9893934c8a9d282e
36.095745
140
0.751075
4.487773
false
false
false
false
apoi/quickbeer-next
app/src/main/java/quickbeer/android/ui/view/Button.kt
2
1823
package quickbeer.android.ui.view import android.content.Context import android.graphics.drawable.AnimatedVectorDrawable import android.graphics.drawable.Drawable import android.util.AttributeSet import androidx.core.content.res.ResourcesCompat import com.google.android.material.button.MaterialButton import quickbeer.android.R class Button @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : MaterialButton(context, attrs, defStyleAttr) { private val buttonText = text private val loadingIcon: Drawable = ResourcesCompat.getDrawable(resources, R.drawable.loading_icon_animated, context.theme)!! private var _isLoading: Boolean = false var isLoading: Boolean get() = _isLoading set(value) { if (value != _isLoading) { _isLoading = value isEnabled = !_isLoading updateText() updateIcon() } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) updateIcon() } private fun updateText() { text = if (isLoading) null else buttonText } private fun updateIcon() { if (!isLoading) { (loadingIcon as AnimatedVectorDrawable).stop() setCompoundDrawables(null, null, null, null) return } val width = loadingIcon.intrinsicWidth val height = loadingIcon.intrinsicHeight val left = (measuredWidth - iconPadding - width - paddingEnd - paddingStart) / 2 loadingIcon.setBounds(left, 0, left + width, height) (loadingIcon as AnimatedVectorDrawable).start() setCompoundDrawables(loadingIcon, null, null, null) } }
gpl-3.0
291135eecb3dd5a8c7fb70b847032691
29.898305
97
0.663193
5.049861
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/WithNullsMultiple.kt
2
2960
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage interface ParentWithNullsMultiple : WorkspaceEntity { val parentData: String @Child val children: List<ChildWithNullsMultiple> //region generated code @GeneratedCodeApiVersion(1) interface Builder : ParentWithNullsMultiple, ModifiableWorkspaceEntity<ParentWithNullsMultiple>, ObjBuilder<ParentWithNullsMultiple> { override var entitySource: EntitySource override var parentData: String override var children: List<ChildWithNullsMultiple> } companion object : Type<ParentWithNullsMultiple, Builder>() { operator fun invoke(parentData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ParentWithNullsMultiple { val builder = builder() builder.parentData = parentData builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ParentWithNullsMultiple, modification: ParentWithNullsMultiple.Builder.() -> Unit) = modifyEntity( ParentWithNullsMultiple.Builder::class.java, entity, modification) //endregion interface ChildWithNullsMultiple : WorkspaceEntity { val childData: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : ChildWithNullsMultiple, ModifiableWorkspaceEntity<ChildWithNullsMultiple>, ObjBuilder<ChildWithNullsMultiple> { override var entitySource: EntitySource override var childData: String } companion object : Type<ChildWithNullsMultiple, Builder>() { operator fun invoke(childData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildWithNullsMultiple { val builder = builder() builder.childData = childData builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ChildWithNullsMultiple, modification: ChildWithNullsMultiple.Builder.() -> Unit) = modifyEntity( ChildWithNullsMultiple.Builder::class.java, entity, modification) var ChildWithNullsMultiple.Builder.parent: ParentWithNullsMultiple? by WorkspaceEntity.extension() //endregion val ChildWithNullsMultiple.parent: ParentWithNullsMultiple? by WorkspaceEntity.extension()
apache-2.0
642bd497e41c93cfd2ec51e9c9ec74ee
35.54321
136
0.767905
5.512104
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/AbstractFont.kt
1
12205
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes.GETFIELD import org.objectweb.asm.Opcodes.IDIV import org.objectweb.asm.Opcodes.IINC import org.objectweb.asm.Opcodes.ISUB import org.objectweb.asm.Opcodes.LDC import org.objectweb.asm.Opcodes.PUTFIELD import org.objectweb.asm.Type.CHAR_TYPE import org.objectweb.asm.Type.INT_TYPE import org.objectweb.asm.Type.VOID_TYPE import org.runestar.client.common.startsWith 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.MethodParameters 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.withDimensions import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 import java.lang.reflect.Modifier @DependsOn(Rasterizer2D::class) class AbstractFont : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { Modifier.isAbstract(it.access) } .and { it.superType == type<Rasterizer2D>() } class pixels : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == Array<ByteArray>::class.type } } // always null? class kerning : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == ByteArray::class.type } } @MethodParameters("s") class decodeTag : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.arguments.size in 1..2 } .and { it.instructions.any { it.opcode == LDC && it.ldcCst == "/shad" } } } @MethodParameters("s") class stringWidth : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.arguments.size in 1..2 } .and { it.arguments.startsWith(String::class.type) } .and { it.instructions.any { it.opcode == LDC && it.ldcCst == "img=" } } } @MethodParameters("c") class charWidth : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.arguments.size in 1..2 } .and { it.arguments.startsWith(CHAR_TYPE) } } @MethodParameters("color", "shadow") class reset : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 2..3 } .and { it.arguments.startsWith(INT_TYPE, INT_TYPE) } } @MethodParameters("s", "lineWidths", "linesDst") class breakLines : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.arguments.size in 3..4 } .and { it.arguments.startsWith(String::class.type, IntArray::class.type, String::class.type.withDimensions(1)) } } @MethodParameters("s", "lineWidth") class lineWidth : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.arguments.size in 2..3 } .and { it.arguments.startsWith(String::class.type, INT_TYPE) } .and { it.instructions.any { it.opcode == IINC } } } @MethodParameters("s", "lineWidth") class lineCount : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.arguments.size in 2..3 } .and { it.arguments.startsWith(String::class.type, INT_TYPE) } .and { it.instructions.none { it.opcode == IINC } } } @DependsOn(stringWidth::class) class advances : OrderMapper.InMethod.Field(stringWidth::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == IntArray::class.type } } class widths : OrderMapper.InConstructor.Field(AbstractFont::class, 2) { override val constructorPredicate = predicateOf<Method2> { it.arguments.size > 2 } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class heights : OrderMapper.InConstructor.Field(AbstractFont::class, 3) { override val constructorPredicate = predicateOf<Method2> { it.arguments.size > 2 } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class leftBearings : OrderMapper.InConstructor.Field(AbstractFont::class, 0) { override val constructorPredicate = predicateOf<Method2> { it.arguments.size > 2 } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class topBearings : OrderMapper.InConstructor.Field(AbstractFont::class, 1) { override val constructorPredicate = predicateOf<Method2> { it.arguments.size > 2 } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } // p11: this = 10, max descent = 3, height = 12, max ascent = 9, main ascent = 8 // p12: this = 12, max descent = 4, height = 16, max ascent = 12, main ascent = 11 class ascent : OrderMapper.InConstructor.Field(AbstractFont::class, 0) { override val constructorPredicate = predicateOf<Method2> { it.arguments.size > 2 } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } // p11: 10 // p12: 12 class maxAscent : OrderMapper.InConstructor.Field(AbstractFont::class, -2) { override val constructorPredicate = predicateOf<Method2> { it.arguments.size > 2 } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } // p11: 2 // p12: 4 class maxDescent : OrderMapper.InConstructor.Field(AbstractFont::class, -1) { override val constructorPredicate = predicateOf<Method2> { it.arguments.size > 2 } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @MethodParameters("pixels", "x", "y", "width", "height", "color") class drawGlyph : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { Modifier.isAbstract(it.access) } .and { it.arguments == listOf(ByteArray::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } } @MethodParameters("pixels", "x", "y", "width", "height", "color", "alpha") class drawGlyphAlpha : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { Modifier.isAbstract(it.access) } .and { it.arguments == listOf(ByteArray::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } } @MethodParameters("s", "x", "y") class draw0 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE) } } @MethodParameters("s", "x", "y", "color", "shadow") class draw : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } .and { it.instructions.none { it.opcode == ISUB } } } @MethodParameters("s", "x", "y", "color", "shadow") class drawRightAligned : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } .and { it.instructions.any { it.opcode == ISUB } } .and { it.instructions.none { it.opcode == IDIV } } } @MethodParameters("s", "x", "y", "color", "shadow") class drawCentered : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } .and { it.instructions.any { it.opcode == ISUB } } .and { it.instructions.any { it.opcode == IDIV } } } @MethodParameters("s", "x", "y", "color", "shadow", "alpha") class drawAlpha : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } .and { it.instructions.none { it.opcode == IINC } } } @MethodParameters("s", "x", "y", "xs", "ys") class drawWithOffsets0 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE, IntArray::class.type, IntArray::class.type) } } @MethodParameters("s", "x", "y", "width", "height", "color", "shadow", "xAlignment", "yAlignment", "lineHeight") class drawLines : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } } @MethodParameters("s", "lineWidth") class calculateLineJustification : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE) } } @MethodParameters("s", "x", "y", "color", "shadow", "seed") class drawRandomAlphaAndSpacing : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } .and { it.instructions.any { it.isMethod && it.methodName == "setSeed" } } } @MethodParameters("s", "x", "y", "color", "shadow", "seed") class drawCenteredWave2 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } .and { it.instructions.any { it.opcode == LDC && it.ldcCst == 3.0 } } } @MethodParameters("s", "x", "y", "color", "shadow", "seed") class drawCenteredWave : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } .and { it.instructions.any { it.opcode == LDC && it.ldcCst == 2.0 } } } @MethodParameters("s", "x", "y", "color", "shadow", "seed", "seed2") class drawCenteredShake : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments == listOf(String::class.type, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE, INT_TYPE) } } @MethodParameters("bytes") class readMetrics : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments == listOf(ByteArray::class.type) } } }
mit
630d68d8c6378d5055a2b7eb49bfd1fc
50.50211
133
0.648996
3.958806
false
false
false
false
vhromada/Catalog
web/src/main/kotlin/com/github/vhromada/catalog/web/validator/UsernameValidator.kt
1
1541
package com.github.vhromada.catalog.web.validator import com.github.vhromada.catalog.common.filter.FieldOperation import com.github.vhromada.catalog.web.connector.AccountConnector import com.github.vhromada.catalog.web.connector.filter.AccountFilter import com.github.vhromada.catalog.web.fo.AccountFO import com.github.vhromada.catalog.web.service.AccountProvider import com.github.vhromada.catalog.web.validator.constraints.Username import org.springframework.beans.factory.annotation.Autowired import javax.validation.ConstraintValidator import javax.validation.ConstraintValidatorContext /** * A class represents validator for username constraint. * * @author Vladimir Hromada */ class UsernameValidator : ConstraintValidator<Username, AccountFO> { /** * Connector for accounts */ @Autowired private lateinit var connector: AccountConnector /** * Provider for account */ @Autowired private lateinit var accountProvider: AccountProvider override fun isValid(account: AccountFO?, constraintValidatorContext: ConstraintValidatorContext): Boolean { if (account == null) { return false } if (accountProvider.getAccount()?.username == account.username) { return true } val filter = AccountFilter( username = account.username!!, usernameOperation = FieldOperation.EQ ) filter.page = 1 filter.limit = 1 return connector.search(filter = filter).data.isEmpty() } }
mit
7d96ea80cebd4fff44cd767cdc748e08
31.104167
112
0.722907
4.756173
false
false
false
false
allotria/intellij-community
java/idea-ui/src/com/intellij/ide/SetupJavaProjectFromSourcesActivity.kt
2
10219
// 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.ide import com.google.common.collect.ArrayListMultimap import com.google.common.collect.Multimap import com.intellij.ide.impl.NewProjectUtil import com.intellij.ide.impl.NewProjectUtil.setCompilerOutputPath import com.intellij.ide.impl.ProjectViewSelectInTarget import com.intellij.ide.projectView.impl.ProjectViewPane import com.intellij.ide.util.DelegatingProgressIndicator import com.intellij.ide.util.importProject.JavaModuleInsight import com.intellij.ide.util.importProject.LibrariesDetectionStep import com.intellij.ide.util.importProject.RootDetectionProcessor import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.ide.util.projectWizard.importSources.impl.ProjectFromSourcesBuilderImpl import com.intellij.notification.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.module.JavaModuleType import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModuleType import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.modifyModules import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.openapi.roots.ui.configuration.SdkLookup import com.intellij.openapi.roots.ui.configuration.SdkLookupDecision import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vfs.* import com.intellij.platform.PlatformProjectOpenProcessor import com.intellij.platform.PlatformProjectOpenProcessor.Companion.isOpenedByPlatformProcessor import com.intellij.projectImport.ProjectOpenProcessor import com.intellij.util.ThrowableRunnable import java.io.File import java.util.concurrent.CompletableFuture import javax.swing.event.HyperlinkEvent private val NOTIFICATION_GROUP = NotificationGroup("Build Script Found", NotificationDisplayType.STICKY_BALLOON, true) private const val SCAN_DEPTH_LIMIT = 5 private const val MAX_ROOTS_IN_TRIVIAL_PROJECT_STRUCTURE = 3 private val LOG = logger<SetupJavaProjectFromSourcesActivity>() internal class SetupJavaProjectFromSourcesActivity : StartupActivity { override fun runActivity(project: Project) { if (ApplicationManager.getApplication().isHeadlessEnvironment) { return } if (!project.isOpenedByPlatformProcessor()) { return } // todo get current project structure, and later setup from sources only if it wasn't manually changed by the user val title = JavaUiBundle.message("task.searching.for.project.sources") ProgressManager.getInstance().run(object: Task.Backgroundable(project, title, true) { override fun run(indicator: ProgressIndicator) { val projectDir = project.baseDir val importers = searchImporters(projectDir) if (!importers.isEmpty) { showNotificationToImport(project, projectDir, importers) } else { setupFromSources(project, projectDir, indicator) } } }) } private fun searchImporters(projectDirectory: VirtualFile): ArrayListMultimap<ProjectOpenProcessor, VirtualFile> { val providersAndFiles = ArrayListMultimap.create<ProjectOpenProcessor, VirtualFile>() VfsUtil.visitChildrenRecursively(projectDirectory, object : VirtualFileVisitor<Void>(NO_FOLLOW_SYMLINKS, limit(SCAN_DEPTH_LIMIT)) { override fun visitFileEx(file: VirtualFile): Result { if (file.isDirectory && FileTypeRegistry.getInstance().isFileIgnored(file)) { return SKIP_CHILDREN } val providers = ProjectOpenProcessor.EXTENSION_POINT_NAME.extensionList.filter { provider -> provider.canOpenProject(file) && provider !is PlatformProjectOpenProcessor } for (provider in providers) { val files = providersAndFiles.get(provider) if (files.isEmpty()) { files.add(file) } else if (!VfsUtilCore.isAncestor(files.last(), file, true)) { // add only top-level file/folders for each of providers files.add(file) } } return CONTINUE } }) return providersAndFiles } private fun showNotificationToImport(project: Project, projectDirectory: VirtualFile, providersAndFiles: ArrayListMultimap<ProjectOpenProcessor, VirtualFile>) { val showFileInProjectViewListener = object : NotificationListener.Adapter() { override fun hyperlinkActivated(notification: Notification, e: HyperlinkEvent) { val file = LocalFileSystem.getInstance().findFileByPath(e.description) ProjectViewSelectInTarget.select(project, file, ProjectViewPane.ID, null, file, true) } } val title: String val content: String if (providersAndFiles.keySet().size == 1) { val processor = providersAndFiles.keySet().single() val files = providersAndFiles[processor] title = JavaUiBundle.message("build.script.found.notification", processor.name, files.size) content = filesToLinks(files, projectDirectory) } else { title = JavaUiBundle.message("build.scripts.from.multiple.providers.found.notification") content = formatContent(providersAndFiles, projectDirectory) } val notification = NOTIFICATION_GROUP.createNotification(title, content, NotificationType.INFORMATION, showFileInProjectViewListener) if (providersAndFiles.keySet().all { it.canImportProjectAfterwards() }) { val actionName = if (providersAndFiles.keySet().size > 1) { JavaUiBundle.message("build.script.found.notification.import.all") } else { JavaUiBundle.message("build.script.found.notification.import") } notification.addAction(NotificationAction.createSimpleExpiring(actionName) { for ((provider, files) in providersAndFiles.asMap()) { for (file in files) { provider.importProjectAfterwards(project, file) } } }) } notification.notify(project) } @NlsSafe private fun formatContent(providersAndFiles: Multimap<ProjectOpenProcessor, VirtualFile>, projectDirectory: VirtualFile): String { return providersAndFiles.asMap().entries.joinToString("<br/>") { (provider, files) -> provider.name + ": " + filesToLinks(files, projectDirectory) } } @NlsSafe private fun filesToLinks(files: MutableCollection<VirtualFile>, projectDirectory: VirtualFile) = files.joinToString { file -> "<a href='${file.path}'>${VfsUtil.getRelativePath(file, projectDirectory)}</a>" } private fun setupFromSources(project: Project, projectDir: VirtualFile, indicator: ProgressIndicator) { val builder = ProjectFromSourcesBuilderImpl(WizardContext(project, project), ModulesProvider.EMPTY_MODULES_PROVIDER) val projectPath = projectDir.path builder.baseProjectPath = projectPath val roots = RootDetectionProcessor.detectRoots(File(projectPath)) val rootsMap = RootDetectionProcessor.createRootsMap(roots) builder.setupProjectStructure(rootsMap) for (detector in rootsMap.keySet()) { val descriptor = builder.getProjectDescriptor(detector) val moduleInsight = JavaModuleInsight(DelegatingProgressIndicator(), builder.existingModuleNames, builder.existingProjectLibraryNames) descriptor.libraries = LibrariesDetectionStep.calculate(moduleInsight, builder) moduleInsight.scanModules() descriptor.modules = moduleInsight.suggestedModules } ApplicationManager.getApplication().invokeAndWait { builder.commit(project) val compileOutput = if (projectPath.endsWith('/')) "${projectPath}out" else "$projectPath/out" setCompilerOutputPath(project, compileOutput) } val modules = ModuleManager.getInstance(project).modules if (modules.any { it is JavaModuleType }) { findAndSetupJdk(project, indicator) } if (roots.size > MAX_ROOTS_IN_TRIVIAL_PROJECT_STRUCTURE) { notifyAboutAutomaticProjectStructure(project) } } private fun findAndSetupJdk(project: Project, indicator: ProgressIndicator) { val future = CompletableFuture<Sdk>() SdkLookup.newLookupBuilder() .withProgressIndicator(indicator) .withSdkType(JavaSdk.getInstance()) .withVersionFilter { true } .withProject(project) .onDownloadableSdkSuggested { SdkLookupDecision.STOP } .onSdkResolved { future.complete(it) } .executeLookup() try { val sdk = future.get() if (sdk != null) { WriteAction.runAndWait( ThrowableRunnable<Throwable> { NewProjectUtil.applyJdkToProject(project, sdk) } ) } } catch (t: Throwable) { LOG.warn("Couldn't lookup for a JDK", t) } } private fun notifyAboutAutomaticProjectStructure(project: Project) { val message = JavaUiBundle.message("project.structure.automatically.detected.notification") val notification = NOTIFICATION_GROUP.createNotification("", message, NotificationType.INFORMATION, null) notification.addAction(NotificationAction.createSimpleExpiring( JavaUiBundle.message("project.structure.automatically.detected.notification.gotit.action")) {}) notification.addAction(NotificationAction.createSimpleExpiring( JavaUiBundle.message("project.structure.automatically.detected.notification.configure.action")) { ProjectSettingsService.getInstance(project).openProjectSettings() }) notification.notify(project) } }
apache-2.0
9f99eca46b61426345ec863b8a6c407c
41.761506
140
0.739505
4.870829
false
false
false
false
allotria/intellij-community
platform/lang-api/src/com/intellij/execution/runners/ExecutionEnvironmentBuilder.kt
12
6916
// 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.execution.runners import com.intellij.execution.* import com.intellij.execution.configurations.ConfigurationPerRunnerSettings import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.configurations.RunProfile import com.intellij.execution.configurations.RunnerSettings import com.intellij.execution.ui.RunContentDescriptor import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.project.Project import com.intellij.openapi.util.UserDataHolderBase class ExecutionEnvironmentBuilder(private val project: Project, private var executor: Executor) { private var runProfile: RunProfile? = null private var target = DefaultExecutionTarget.INSTANCE private var runnerSettings: RunnerSettings? = null private var configurationSettings: ConfigurationPerRunnerSettings? = null private var contentToReuse: RunContentDescriptor? = null private var runnerAndConfigurationSettings: RunnerAndConfigurationSettings? = null private var runner: ProgramRunner<*>? = null private var executionId: Long? = null private var dataContext: DataContext? = null private val userData = UserDataHolderBase() private var modulePath: String? = null /** * Creates an execution environment builder initialized with a copy of the specified environment. * * @param env the environment to copy from. */ constructor(env: ExecutionEnvironment) : this(env.project, env.executor) { target = env.executionTarget runnerAndConfigurationSettings = env.runnerAndConfigurationSettings runProfile = env.runProfile runnerSettings = env.runnerSettings configurationSettings = env.configurationSettings runner = env.runner contentToReuse = env.contentToReuse env.copyUserDataTo(userData) } companion object { @JvmStatic @Throws(ExecutionException::class) fun create(project: Project, executor: Executor, runProfile: RunProfile): ExecutionEnvironmentBuilder { return createOrNull(project, executor, runProfile) ?: throw ExecutionException(ExecutionBundle.message("dialog.message.cannot.find.runner", runProfile.name)) } @JvmStatic fun createOrNull(project: Project, executor: Executor, runProfile: RunProfile): ExecutionEnvironmentBuilder? { val runner = ProgramRunner.getRunner(executor.id, runProfile) ?: return null return ExecutionEnvironmentBuilder(project, executor).runner(runner).runProfile(runProfile) } @JvmStatic fun createOrNull(executor: Executor, settings: RunnerAndConfigurationSettings): ExecutionEnvironmentBuilder? { val builder = createOrNull(executor, settings.configuration) return builder?.runnerAndSettings(builder.runner!!, settings) } @JvmStatic fun createOrNull(executor: Executor, configuration: RunConfiguration): ExecutionEnvironmentBuilder? { val builder = createOrNull(configuration.project, executor, configuration) builder?.runProfile(configuration) return builder } @JvmStatic @Throws(ExecutionException::class) fun create(executor: Executor, settings: RunnerAndConfigurationSettings): ExecutionEnvironmentBuilder { val configuration = settings.configuration val builder = create(configuration.project, executor, configuration) return builder.runnerAndSettings(builder.runner!!, settings) } @JvmStatic fun create(executor: Executor, configuration: RunConfiguration): ExecutionEnvironmentBuilder { return ExecutionEnvironmentBuilder(configuration.project, executor).runProfile(configuration) } } fun target(target: ExecutionTarget?): ExecutionEnvironmentBuilder { if (target != null) { this.target = target } return this } fun activeTarget(): ExecutionEnvironmentBuilder { target = ExecutionTargetManager.getActiveTarget(project) return this } fun runnerAndSettings(runner: ProgramRunner<*>, settings: RunnerAndConfigurationSettings): ExecutionEnvironmentBuilder { runnerAndConfigurationSettings = settings runProfile = settings.configuration runnerSettings = settings.getRunnerSettings(runner) configurationSettings = settings.getConfigurationSettings(runner) this.runner = runner return this } fun runnerSettings(runnerSettings: RunnerSettings?): ExecutionEnvironmentBuilder { this.runnerSettings = runnerSettings return this } fun contentToReuse(contentToReuse: RunContentDescriptor?): ExecutionEnvironmentBuilder { this.contentToReuse = contentToReuse return this } fun runProfile(runProfile: RunProfile): ExecutionEnvironmentBuilder { this.runProfile = runProfile return this } fun runner(runner: ProgramRunner<*>): ExecutionEnvironmentBuilder { this.runner = runner return this } fun dataContext(dataContext: DataContext?): ExecutionEnvironmentBuilder { this.dataContext = dataContext return this } fun executor(executor: Executor): ExecutionEnvironmentBuilder { this.executor = executor return this } fun executionId(executionId: Long): ExecutionEnvironmentBuilder { this.executionId = executionId return this } fun modulePath(modulePath: String): ExecutionEnvironmentBuilder { this.modulePath = modulePath return this } @JvmOverloads fun build(callback: ProgramRunner.Callback? = null): ExecutionEnvironment { var environment: ExecutionEnvironment? = null val environmentProvider = project.getService(ExecutionEnvironmentProvider::class.java) if (environmentProvider != null) { environment = environmentProvider.createExecutionEnvironment( project, runProfile!!, executor, target, runnerSettings, configurationSettings, runnerAndConfigurationSettings) } if (environment == null && runner == null) { runner = ProgramRunner.getRunner(executor.id, runProfile!!) } if (environment == null && runner == null) { throw IllegalStateException("Runner must be specified") } if (environment == null) { environment = ExecutionEnvironment(runProfile!!, executor, target, project, runnerSettings, configurationSettings, contentToReuse, runnerAndConfigurationSettings, runner!!, callback) } if (executionId != null) { environment.executionId = executionId!! } if (dataContext != null) { environment.setDataContext(dataContext!!) } if (modulePath != null) { environment.setModulePath(modulePath!!) } userData.copyUserDataTo(environment) return environment } @Throws(ExecutionException::class) fun buildAndExecute() { val environment = build() runner!!.execute(environment) } }
apache-2.0
0bd334980d1b99ec489adc577c57fa62
37.005495
140
0.749132
5.66421
false
true
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/ui/ext/HasSize.kt
1
1734
/* * (C) Copyright 2020 Lukas Morawietz (https://github.com/F43nd1r) * * 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.faendir.acra.ui.ext import com.vaadin.flow.component.HasSize enum class SizeUnit(val text: String) { PERCENTAGE("%"), PIXEL("px"), REM("rem"), EM("em"); } fun HasSize.setWidth(value: Int, unit: SizeUnit) { width = value.toString() + unit.text } fun HasSize.setMaxWidth(value: Int, unit: SizeUnit) { maxWidth = value.toString() + unit.text } fun HasSize.setMaxWidthFull() { setMaxWidth(100, SizeUnit.PERCENTAGE) } fun HasSize.setMinWidth(value: Int, unit: SizeUnit) { minWidth = value.toString() + unit.text } fun HasSize.setMinWidthFull() { setMinWidth(100, SizeUnit.PERCENTAGE) } fun HasSize.setHeight(value: Int, unit: SizeUnit) { height = value.toString() + unit.text } fun HasSize.setMaxHeight(value: Int, unit: SizeUnit) { maxHeight = value.toString() + unit.text } fun HasSize.setMaxHeightFull() { setMaxHeight(100, SizeUnit.PERCENTAGE) } fun HasSize.setMinHeight(value: Int, unit: SizeUnit) { minHeight = value.toString() + unit.text } fun HasSize.setMinHeightFull() { setMinHeight(100, SizeUnit.PERCENTAGE) }
apache-2.0
6f2de78d9eb0c9a79ee733d598f2a2e4
24.895522
75
0.708766
3.47495
false
false
false
false
google/Kotlin-FirViewer
src/main/kotlin/io/github/tgeng/firviewer/ObjectTreeModel.kt
1
5595
// Copyright 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 // // 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 io.github.tgeng.firviewer import com.intellij.openapi.project.Project import com.intellij.ui.JBSplitter import com.intellij.ui.components.JBScrollPane import com.intellij.ui.tree.BaseTreeModel import com.intellij.ui.treeStructure.Tree import com.intellij.util.ui.tree.TreeUtil import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import java.awt.event.MouseEvent import java.awt.event.MouseListener import java.util.concurrent.atomic.AtomicInteger import javax.swing.BoxLayout import javax.swing.JPanel import javax.swing.tree.TreePath import kotlin.reflect.KClass class ObjectTreeModel<T : Any>( private val ktFile: KtFile, private val tClass: KClass<T>, val ktFileToT: (KtFile) -> T, val acceptChildren: T.((T) -> Unit) -> Unit ) : BaseTreeModel<TreeNode<T>>() { private var root: TreeNode<T>? = null init { refresh() } override fun getRoot(): TreeNode<T> { return root!! } override fun getChildren(parent: Any?): List<TreeNode<T>> { val parent = parent as? TreeNode<*> ?: return emptyList() return parent.currentChildren as List<TreeNode<T>> } fun refresh() { val firFile = ktFileToT(ktFile) if (firFile != root?.t) { val newFileNode = TreeNode("", firFile) root = newFileNode } root!!.refresh(listOf(root!!)) treeStructureChanged(null, null, null) } private fun TreeNode<T>.refresh(path: List<TreeNode<T>>) { val newChildren = mutableListOf<TreeNode<T>>() val childNameAndValues = mutableListOf<Pair<Any?, String>>() t.traverseObjectProperty { name, value, _ -> when { tClass.isInstance(value) -> childNameAndValues += (value to name) value is Collection<*> -> value.filter { tClass.isInstance(it) } .forEachIndexed { index, value -> childNameAndValues += value to "$name[$index]" } else -> { } } } val childMap = childNameAndValues.toMap() val fieldCounter = AtomicInteger() t.acceptChildren { element -> newChildren += TreeNode( childMap[element] ?: "<prop${fieldCounter.getAndIncrement()}>", element ) } currentChildren = newChildren currentChildren.forEach { it.refresh(path + it) } } fun setupTreeUi(project: Project): TreeUiState { val tree = Tree(this) tree.cellRenderer = TreeObjectRenderer() val jbSplitter = JBSplitter(true).apply { firstComponent = JBScrollPane(tree).apply { horizontalScrollBar = null } } val tablePane = JPanel().apply { layout = BoxLayout(this, BoxLayout.Y_AXIS) } jbSplitter.secondComponent = JBScrollPane(tablePane) val state = TreeUiState( jbSplitter, tree, this, ObjectViewerUiState(tablePane) ) tree.addTreeSelectionListener { e -> if (e.newLeadSelectionPath != null) state.selectedTreePath = e.newLeadSelectionPath.getNamePath() val node = tree.lastSelectedPathComponent as? TreeNode<*> ?: return@addTreeSelectionListener tablePane.removeAll() state.objectViewerState.objectViewers.clear() val objectViewer = ObjectViewer.createObjectViewer( project, node.t, state.objectViewerState, 0, ktFile, node.t as? KtElement ) state.objectViewerState.objectViewers.add(objectViewer) tablePane.add(objectViewer.view) state.objectViewerState.selectedTablePath.firstOrNull()?.let { objectViewer.select(it) } highlightInEditor(node.t, project) tablePane.revalidate() tablePane.repaint() } tree.addMouseListener(object : MouseListener { override fun mouseClicked(e: MouseEvent) {} override fun mousePressed(e: MouseEvent?) {} override fun mouseReleased(e: MouseEvent?) { state.expandedTreePaths.clear() state.expandedTreePaths += TreeUtil.collectExpandedPaths(tree).map { path -> path.getNamePath() } } override fun mouseEntered(e: MouseEvent?) {} override fun mouseExited(e: MouseEvent?) {} }) return state } private fun TreePath.getNamePath(): List<String> { val result = mutableListOf<String>() for (i in 0 until pathCount) { result += (getPathComponent(i) as TreeNode<*>).name } return result } } data class TreeNode<T : Any>(val name: String = "", val t: T) { var currentChildren = mutableListOf<TreeNode<T>>() }
apache-2.0
612da2fed236b0d0668354e1a910e2f6
34.411392
113
0.61126
4.689858
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/DesktopLayout.kt
1
6102
// 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.wm.impl import com.intellij.configurationStore.serialize import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.wm.RegisterToolWindowTask import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.WindowInfo import com.intellij.util.xmlb.XmlSerializer import gnu.trove.THashMap import org.jdom.Element import java.util.* class DesktopLayout { companion object { const val TAG = "layout" } /** * Map between `id`s `WindowInfo`s. */ private val idToInfo = THashMap<String, WindowInfoImpl>() fun copy(): DesktopLayout { val result = DesktopLayout() result.idToInfo.ensureCapacity(idToInfo.size) idToInfo.forEachEntry { id, info -> val newInfo = info.copy() result.idToInfo.put(id, newInfo) true } return result } /** * Creates or gets `WindowInfo` for the specified `id`. */ internal fun getOrCreate(task: RegisterToolWindowTask): WindowInfoImpl { return idToInfo.getOrPut(task.id) { val info = createDefaultInfo(task.id) info.anchor = task.anchor info.isSplit = task.sideTool info } } private fun createDefaultInfo(id: String): WindowInfoImpl { val info = WindowInfoImpl() info.id = id info.isFromPersistentSettings = false info.order = getMaxOrder(idToInfo.values, info.anchor) + 1 return info } fun getInfo(id: String) = idToInfo.get(id) internal fun addInfo(id: String, info: WindowInfoImpl) { val old = idToInfo.put(id, info) LOG.assertTrue(old == null) } /** * Sets new `anchor` and `id` for the specified tool window. * Also the method properly updates order of all other tool windows. */ fun setAnchor(info: WindowInfoImpl, newAnchor: ToolWindowAnchor, suppliedNewOrder: Int) { var newOrder = suppliedNewOrder // if order isn't defined then the window will the last in the stripe if (newOrder == -1) { newOrder = getMaxOrder(idToInfo.values, newAnchor) + 1 } val oldAnchor = info.anchor // shift order to the right in the target stripe val infos = getAllInfos(idToInfo.values, newAnchor) for (i in infos.size - 1 downTo -1 + 1) { val info2 = infos[i] if (newOrder <= info2.order) { info2.order = info2.order + 1 } } // "move" window into the target position info.anchor = newAnchor info.order = newOrder // normalize orders in the source and target stripes normalizeOrder(getAllInfos(idToInfo.values, oldAnchor)) if (oldAnchor != newAnchor) { normalizeOrder(getAllInfos(idToInfo.values, newAnchor)) } } fun readExternal(layoutElement: Element) { val infoBinding = XmlSerializer.getBeanBinding(WindowInfoImpl::class.java) val list = mutableListOf<WindowInfoImpl>() for (element in layoutElement.getChildren(WindowInfoImpl.TAG)) { val info = WindowInfoImpl() infoBinding.deserializeInto(info, element) info.normalizeAfterRead() val id = info.id if (id == null) { LOG.warn("Skip invalid window info (no id): ${JDOMUtil.writeElement(element)}") continue } // if order isn't defined then window's button will be the last one in the stripe if (info.order == -1) { info.order = getMaxOrder(list, info.anchor) + 1 } idToInfo.put(id, info) list.add(info) } normalizeOrder(getAllInfos(list, ToolWindowAnchor.TOP)) normalizeOrder(getAllInfos(list, ToolWindowAnchor.LEFT)) normalizeOrder(getAllInfos(list, ToolWindowAnchor.BOTTOM)) normalizeOrder(getAllInfos(list, ToolWindowAnchor.RIGHT)) } val stateModificationCount: Long get() { if (idToInfo.isEmpty) { return 0 } var result = 0L for (info in idToInfo.values) { result += info.modificationCount } return result } fun writeExternal(tagName: String): Element? { if (idToInfo.isEmpty) { return null } val list = idToInfo.values.toMutableList() list.sortedWith(windowInfoComparator) val state = Element(tagName) for (info in list) { val element = serialize(info) if (element != null) { state.addContent(element) } } return state } } private val LOG = logger<DesktopLayout>() private fun getAnchorWeight(anchor: ToolWindowAnchor): Int { return when (anchor) { ToolWindowAnchor.TOP -> 1 ToolWindowAnchor.LEFT -> 2 ToolWindowAnchor.BOTTOM -> 3 ToolWindowAnchor.RIGHT -> 4 else -> 0 } } internal val windowInfoComparator: Comparator<WindowInfo> = Comparator { o1, o2 -> val anchorWeight = getAnchorWeight(o1.anchor) - getAnchorWeight(o2.anchor) if (anchorWeight == 0) o1.order - o2.order else anchorWeight } /** * Normalizes order of windows in the passed array. Note, that array should be * sorted by order (by ascending). Order of first window will be `0`. */ private fun normalizeOrder(infos: List<WindowInfoImpl>) { for (i in infos.indices) { infos[i].order = i } } /** * @param anchor anchor of the stripe. * @return maximum ordinal number in the specified stripe. Returns `-1` * if there is no any tool window with the specified anchor. */ private fun getMaxOrder(list: Collection<WindowInfoImpl>, anchor: ToolWindowAnchor): Int { var result = -1 for (info in list) { if (anchor == info.anchor && result < info.order) { result = info.order } } return result } /** * @return all (registered and not unregistered) `WindowInfos` for the specified `anchor`. * Returned infos are sorted by order. */ internal fun getAllInfos(list: Collection<WindowInfoImpl>, anchor: ToolWindowAnchor): List<WindowInfoImpl> { val result = mutableListOf<WindowInfoImpl>() for (info in list) { if (anchor == info.anchor) { result.add(info) } } result.sortWith(windowInfoComparator) return result }
apache-2.0
82f12b87efe41b3461dc97d62117e77f
28.336538
140
0.682563
4.025066
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/NoneChangeListFilteringStrategy.kt
1
1209
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.committed import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList import com.intellij.util.containers.ContainerUtil.newUnmodifiableList import javax.swing.JComponent import javax.swing.event.ChangeListener private val NONE_FILTER_KEY = CommittedChangesFilterKey("None", CommittedChangesFilterPriority.NONE) object NoneChangeListFilteringStrategy : ChangeListFilteringStrategy { override fun getKey(): CommittedChangesFilterKey = NONE_FILTER_KEY override fun getFilterUI(): JComponent? = null override fun addChangeListener(listener: ChangeListener) = Unit override fun removeChangeListener(listener: ChangeListener) = Unit override fun setFilterBase(changeLists: List<CommittedChangeList>) = Unit override fun resetFilterBase() = Unit override fun appendFilterBase(changeLists: List<CommittedChangeList>) = Unit override fun filterChangeLists(changeLists: List<CommittedChangeList>): List<CommittedChangeList> = newUnmodifiableList(changeLists) override fun toString(): String = "None" }
apache-2.0
17dfc18cfae374d27ff00fa95a4174c5
45.538462
140
0.818031
4.914634
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/functions/invoke/extensionInvokeOnExpr.kt
3
491
class A class B { operator fun A.invoke() = "##" operator fun A.invoke(i: Int) = "#${i}" } fun foo() = A() fun B.test(): String { if (A()() != "##") return "fail1" if (A()(1) != "#1") return "fail2" if (foo()() != "##") return "fail3" if (foo()(42) != "#42") return "fail4" if ((foo())(42) != "#42") return "fail5" if ({ -> A()}()() != "##") return "fail6" if ({ -> A()}()(37) != "#37") return "fail7" return "OK" } fun box(): String = B().test()
apache-2.0
5e59ce1e212d6f5d397033c08e0a571a
22.380952
48
0.441955
2.758427
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/compileKotlinAgainstKotlin/callsToMultifileClassFromOtherPackage.kt
2
472
// IGNORE_BACKEND: NATIVE // FILE: A.kt @file:[JvmName("MultifileClass") JvmMultifileClass] package a fun foo(): String = "OK" const val constOK: String = "OK" val valOK: String = "OK" var varOK: String = "Hmmm?" // FILE: B.kt import a.* fun box(): String { if (foo() != "OK") return "Fail function" if (constOK != "OK") return "Fail const" if (valOK != "OK") return "Fail val" varOK = "OK" if (varOK != "OK") return "Fail var" return varOK }
apache-2.0
764a09d0c54b2e433809dae03ef5bcb8
19.521739
51
0.605932
2.931677
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/battery/BatteryLevelReceiver.kt
2
1329
package abi43_0_0.expo.modules.battery import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import android.os.Bundle import android.util.Log import abi43_0_0.expo.modules.core.interfaces.services.EventEmitter class BatteryLevelReceiver(private val eventEmitter: EventEmitter?) : BroadcastReceiver() { private val BATTERY_LEVEL_EVENT_NAME = "Expo.batteryLevelDidChange" private fun onBatteryLevelChange(BatteryLevel: Float) { eventEmitter?.emit( BATTERY_LEVEL_EVENT_NAME, Bundle().apply { putFloat("batteryLevel", BatteryLevel) } ) } override fun onReceive(context: Context, intent: Intent) { val batteryIntent = context.applicationContext.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) if (batteryIntent == null) { Log.e("Battery", "ACTION_BATTERY_CHANGED unavailable. Events wont be received") return } val level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) val scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) val batteryLevel: Float = if (level != -1 && scale != -1) { level / scale.toFloat() } else { -1f } onBatteryLevelChange(batteryLevel) } }
bsd-3-clause
045ac06152e031a5e2ec9dfd1388e9da
33.076923
118
0.734387
4.153125
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/persistence/profile/ProfileRepo.kt
2
4855
package de.sudoq.persistence.profile import de.sudoq.model.game.Assistances import de.sudoq.model.game.GameSettings import de.sudoq.model.persistence.IRepo import de.sudoq.model.persistence.xml.profile.IProfilesListRepo import de.sudoq.model.profile.Profile import de.sudoq.model.profile.ProfileManager import de.sudoq.model.profile.Statistics import de.sudoq.persistence.XmlHelper import de.sudoq.persistence.XmlTree import java.io.File import java.io.IOException class ProfileRepo(private val profilesDir: File) : IRepo<Profile> { override fun create(): Profile { return create(newProfileID) } private fun create(id: Int): Profile { val newProfile = ProfileBE(id) newProfile.name = ProfileManager.DEFAULT_PROFILE_NAME newProfile.currentGame = -1 newProfile.assistances = GameSettings() newProfile.assistances.setAssistance(Assistances.markRowColumn) // this.gameSettings.setGestures(false); //this.appSettings.setDebug(false); newProfile.statistics = IntArray(Statistics.values().size) newProfile.statistics!![Statistics.fastestSolvingTime.ordinal] = ProfileManager.INITIAL_TIME_RECORD createProfileFiles(id) // save new profile xml val profileReloaded = updateBE(newProfile) return ProfileMapper.fromBE(profileReloaded) } /** * Erstellt die Ordnerstruktur und nötige Dateien für das Profil mit der * übergebenen ID * * @param id * ID des Profils */ private fun createProfileFiles(id: Int) { val profileDir = getProfileDirFor(id) profileDir.mkdir() File(profileDir, "games").mkdir() val games = File(profileDir, "games.xml") try { XmlHelper().saveXml(XmlTree("games"), games) } catch (e: IOException) { throw IllegalStateException("Invalid Profile", e) } } override fun read(id: Int): Profile { val profileDir = File(profilesDir, "profile_$id") val file = File(profileDir, "profile.xml") val p = ProfileBE(id) val helper = XmlHelper() p.fillFromXml(helper.loadXml(file)!!) return ProfileMapper.fromBE(p) } private fun readBE(id: Int): ProfileBE { val profileDir = File(profilesDir, "profile_$id") val file = File(profileDir, "profile.xml") val p = ProfileBE(id) val helper = XmlHelper() p.fillFromXml(helper.loadXml(file)!!) return p } override fun update(t: Profile): Profile { val profileBEIn = ProfileMapper.toBE(t) val profileBEOut = updateBE(profileBEIn) val profileOut = ProfileMapper.fromBE(profileBEOut) return profileOut } private fun updateBE(profileBE: ProfileBE): ProfileBE { try { val file = getProfileXmlFor(profileBE.id) val tree = profileBE.toXmlTree() val helper = XmlHelper() helper.saveXml(tree, file) return readBE(profileBE.id) //return the object that is now saved under that id } catch (e: IOException) { throw IllegalArgumentException("Something went wrong when writing xml", e) } } /** * Gibt die XML-Datei das aktuellen Profils zurück * * @param id * die id des Profils dessen xml gesucht ist * * @return File, welcher auf die XML Datei des aktuellen Profils zeigt */ private fun getProfileXmlFor(id: Int): File { return File(getProfileDirFor(id), "profile.xml") } @Throws(java.lang.IllegalArgumentException::class) override fun delete(id: Int) { val dir: File = getProfileDirFor(id) if (!dir.exists()) return if (!dir.deleteRecursively()) throw java.lang.IllegalArgumentException("Unable to delete given Profile") } /////// file operations /** * Gibt das Verzeichnis des Profils mit der gegebenen id zurueck * * @return File, welcher auf das Profilverzeichnis zeigt */ private fun getProfileDirFor(id: Int): File { return File(profilesDir.absolutePath + File.separator + "profile_$id") } /** * Gibt eine neue Profil ID zurück. Bestehende Profile dürfen nicht gelöscht * werden, sonder als solches markiert werden. * * @return the new Profile ID */ private val newProfileID: Int get() { val used = getProfileIdsList() var i = 1 while (used.contains(i)) i++ return i } private fun getProfileIdsList(): List<Int> { val profilesList : IProfilesListRepo = ProfilesListRepo(profilesDir) return profilesList.getProfileIdsList() } override fun ids(): List<Int> { TODO("Not yet implemented") } }
gpl-3.0
503e5ff1cb4eac2b8534cbb1f41ac40d
29.118012
107
0.641089
4.033278
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterMethodUsageProcessor.kt
6
5936
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.introduceParameter import com.intellij.psi.PsiElement import com.intellij.psi.PsiExpression import com.intellij.psi.PsiMethod import com.intellij.psi.search.GlobalSearchScope import com.intellij.refactoring.introduceParameter.IntroduceParameterData import com.intellij.refactoring.introduceParameter.IntroduceParameterMethodUsagesProcessor import com.intellij.usageView.UsageInfo import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor import org.jetbrains.kotlin.idea.j2k.j2k import org.jetbrains.kotlin.idea.refactoring.changeSignature.* import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallableDefinitionUsage import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinConstructorDelegationCallUsage import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinFunctionCallUsage import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinUsageInfo import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchOverriders import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import java.util.* class KotlinIntroduceParameterMethodUsageProcessor : IntroduceParameterMethodUsagesProcessor { override fun isMethodUsage(usage: UsageInfo): Boolean = (usage.element as? KtElement)?.let { it.getParentOfTypeAndBranch<KtCallElement>(true) { calleeExpression } != null } ?: false override fun findConflicts(data: IntroduceParameterData, usages: Array<UsageInfo>, conflicts: MultiMap<PsiElement, String>) { } private fun createChangeInfo(data: IntroduceParameterData, method: PsiElement): KotlinChangeInfo? { val psiMethodDescriptor = when (method) { is KtFunction -> method.unsafeResolveToDescriptor() as? FunctionDescriptor is PsiMethod -> method.getJavaMethodDescriptor() else -> null } ?: return null val changeSignatureData = KotlinChangeSignatureData(psiMethodDescriptor, method, Collections.singletonList(psiMethodDescriptor)) val changeInfo = KotlinChangeInfo(methodDescriptor = changeSignatureData, context = method) data.parameterListToRemove.sortedDescending().forEach { changeInfo.removeParameter(it) } // Temporarily assume that the new parameter is of Any type. Actual type is substituted during the signature update phase val defaultValueForCall = (data.parameterInitializer.expression as? PsiExpression)?.j2k() changeInfo.addParameter( KotlinParameterInfo( callableDescriptor = psiMethodDescriptor, name = data.parameterName, originalTypeInfo = KotlinTypeInfo(false, psiMethodDescriptor.builtIns.anyType), defaultValueForCall = defaultValueForCall ) ) return changeInfo } override fun processChangeMethodSignature(data: IntroduceParameterData, usage: UsageInfo, usages: Array<out UsageInfo>): Boolean { val element = usage.element as? KtFunction ?: return true val changeInfo = createChangeInfo(data, element) ?: return true // Java method is already updated at this point val addedParameterType = data.methodToReplaceIn.getJavaMethodDescriptor()!!.valueParameters.last().type changeInfo.newParameters.last().currentTypeInfo = KotlinTypeInfo(false, addedParameterType) val scope = element.useScope.let { if (it is GlobalSearchScope) GlobalSearchScope.getScopeRestrictedByFileTypes(it, KotlinFileType.INSTANCE) else it } val kotlinFunctions = HierarchySearchRequest(element, scope).searchOverriders().map { it.unwrapped }.filterIsInstance<KtFunction>() return (kotlinFunctions + element).all { KotlinCallableDefinitionUsage(it, changeInfo.originalBaseFunctionDescriptor, null, null, false).processUsage( changeInfo, it, usages ) }.apply { dropOverrideKeywordIfNecessary(element) } } override fun processChangeMethodUsage(data: IntroduceParameterData, usage: UsageInfo, usages: Array<out UsageInfo>): Boolean { val psiMethod = data.methodToReplaceIn val changeInfo = createChangeInfo(data, psiMethod) ?: return true val refElement = usage.element as? KtReferenceExpression ?: return true val callElement = refElement.getParentOfTypeAndBranch<KtCallElement>(true) { calleeExpression } ?: return true val delegateUsage = if (callElement is KtConstructorDelegationCall) { @Suppress("UNCHECKED_CAST") (KotlinConstructorDelegationCallUsage(callElement, changeInfo) as KotlinUsageInfo<KtCallElement>) } else { KotlinFunctionCallUsage(callElement, changeInfo.methodDescriptor.originalPrimaryCallable) } return delegateUsage.processUsage(changeInfo, callElement, usages) } override fun processAddSuperCall(data: IntroduceParameterData, usage: UsageInfo, usages: Array<out UsageInfo>): Boolean = true override fun processAddDefaultConstructor(data: IntroduceParameterData, usage: UsageInfo, usages: Array<out UsageInfo>): Boolean = true }
apache-2.0
c2055cd31b63f9d77610295f8d2d835c
55.533333
158
0.764319
5.406193
false
false
false
false
smmribeiro/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/tracker/LookupStateManager.kt
6
5020
// 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.stats.completion.tracker import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.completion.ml.storage.LookupStorage import com.intellij.completion.ml.util.RelevanceUtil import com.intellij.completion.ml.util.idString import com.intellij.stats.completion.LookupEntryInfo import com.intellij.stats.completion.LookupState import com.intellij.util.SlowOperations class LookupStateManager { private val elementToId = mutableMapOf<String, Int>() private val idToEntryInfo = mutableMapOf<Int, LookupEntryInfo>() private val lookupStringToHash = mutableMapOf<String, Int>() private var currentSessionFactors: Map<String, String> = emptyMap() fun update(lookup: LookupImpl, factorsUpdated: Boolean): LookupState { return SlowOperations.allowSlowOperations<LookupState, Throwable> { doUpdate(lookup, factorsUpdated) } } private fun doUpdate(lookup: LookupImpl, factorsUpdated: Boolean): LookupState { val ids = mutableListOf<Int>() val newIds = mutableSetOf<Int>() val items = lookup.items val currentPosition = items.indexOf(lookup.currentItem) val elementToId = mutableMapOf<String, Int>() for (item in items) { var id = getElementId(item) if (id == null) { id = registerElement(item) newIds.add(id) } elementToId[item.idString()] = id ids.add(id) } val storage = LookupStorage.get(lookup) val commonSessionFactors = storage?.sessionFactors?.getLastUsedCommonFactors() ?: emptyMap() val sessionFactorsToLog = computeSessionFactorsToLog(commonSessionFactors) if (factorsUpdated) { val infos = items.toLookupInfos(lookup, elementToId) val newInfos = infos.filter { it.id in newIds } val itemsDiff = infos.mapNotNull { idToEntryInfo[it.id]?.calculateDiff(it) } infos.forEach { idToEntryInfo[it.id] = it } return LookupState(ids, newInfos, itemsDiff, currentPosition, sessionFactorsToLog) } else { val newItems = items.filter { getElementId(it) in newIds }.toLookupInfos(lookup, elementToId) newItems.forEach { idToEntryInfo[it.id] = it } return LookupState(ids, newItems, emptyList(), currentPosition, sessionFactorsToLog) } } fun getElementId(item: LookupElement): Int? { val itemString = item.idString() return elementToId[itemString] } private fun computeSessionFactorsToLog(factors: Map<String, String>): Map<String, String> { if (factors == currentSessionFactors) return emptyMap() currentSessionFactors = factors return factors } private fun registerElement(item: LookupElement): Int { val itemString = item.idString() val newId = elementToId.size elementToId[itemString] = newId return newId } private fun List<LookupElement>.toLookupInfos(lookup: LookupImpl, elementToId: Map<String, Int>): List<LookupEntryInfo> { val item2relevance = calculateRelevance(lookup, this) return this.map { lookupElement -> val id = lookupElement.idString() val lookupString = lookupElement.lookupString val itemHash = getLookupStringHash(lookupString) LookupEntryInfo(elementToId.getValue(id), lookupString.length, itemHash, item2relevance.getValue(id)) } } private fun calculateRelevance(lookup: LookupImpl, items: List<LookupElement>): Map<String, Map<String, String>> { val lookupStorage = LookupStorage.get(lookup) if (lookupStorage?.shouldComputeFeatures() == false) { return items.associateBy({ it.idString() }, { emptyMap() }) } val result = mutableMapOf<String, Map<String, String>>() if (lookupStorage != null) { for (item in items) { val id = item.idString() val factors = lookupStorage.getItemStorage(id).getLastUsedFactors()?.mapValues { it.value.toString() } if (factors != null) { result[id] = factors } } } // fallback (get factors from the relevance objects) val rest = items.filter { it.idString() !in result } if (rest.isNotEmpty()) { val relevanceObjects = lookup.getRelevanceObjects(rest, false) for (item in rest) { val relevanceMap: Map<String, String> = relevanceObjects[item]?.let { objects -> val (relevanceMap, additionalMap) = RelevanceUtil.asRelevanceMaps(objects) val features = mutableMapOf<String, String>() relevanceMap.forEach { features[it.key] = it.value.toString() } additionalMap.forEach { features[it.key] = it.value.toString() } return@let features } ?: emptyMap() result[item.idString()] = relevanceMap } } return result } private fun getLookupStringHash(lookupString: String): Int { return lookupStringToHash.computeIfAbsent(lookupString) { lookupStringToHash.size } } }
apache-2.0
1c77fd5908c3d8dae2286cb0c32cea85
37.328244
140
0.707769
4.399649
false
false
false
false
QuixomTech/DeviceInfo
app/src/main/java/com/quixom/apps/deviceinfo/adapters/SimAdapter.kt
1
1515
package com.quixom.apps.deviceinfo.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.quixom.apps.deviceinfo.MainActivity import com.quixom.apps.deviceinfo.R import com.quixom.apps.deviceinfo.models.SimInfo import com.quixom.apps.deviceinfo.utilities.Methods /** * Created by quixomtech on 1/2/18. */ class SimAdapter(private val mainActivity: MainActivity, private var simInformationData: ArrayList<SimInfo>): RecyclerView.Adapter<SimAdapter.SimVH>(){ override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): SimVH { val itemView = LayoutInflater.from(mainActivity).inflate(R.layout.row_sim_item, parent, false) return SimVH(itemView) } override fun getItemCount(): Int = simInformationData.size override fun onBindViewHolder(holder: SimVH?, position: Int) { holder?.bindData(simInformationData[position]) } inner class SimVH(itemView: View): RecyclerView.ViewHolder(itemView) { fun bindData(simInfo: SimInfo) { val tvLabel: TextView? = itemView.findViewById(R.id.tvLabel) val tvSimInformation: TextView? = itemView.findViewById(R.id.tvSimInformation) tvLabel?.text = simInfo.simLable tvSimInformation?.text = simInfo.simData itemView.setOnClickListener({ Methods.avoidDoubleClicks(itemView) }) } } }
apache-2.0
d767e024f399ef333fbdf83bb47e430f
34.255814
151
0.725413
4.243697
false
false
false
false
mseroczynski/CityBikes
app/src/main/kotlin/pl/ches/citybikes/common/Consts.kt
1
554
package pl.ches.citybikes.common /** * @author Michał Seroczyński <[email protected]> */ class Consts { object Config { const val OK_HTTP_API_TIMEOUT_IN_S = 20L const val INITIAL_RADIUS_IN_KM = 3.0 const val LOCATION_UPDATE_INTERVAL_IN_MS = 1000L const val MAX_STATIONS_ON_LIST_COUNT = 50 const val DISTANCE_REFRESH_IN_S = 3L } object Prefs { const val FILE_NAME_CACHE_PREFS = "cache_prefs" const val PREF_KEY_LAST_AREAS_IDS = "last_areas" const val PREF_KEY_LAST_LOCATION = "last_location" } }
gpl-3.0
2708642915cc30af08baf9b950ba313f
24.090909
60
0.682971
3.22807
false
false
false
false
ninjahoahong/unstoppable
app/src/main/java/com/ninjahoahong/unstoppable/utils/Settings.kt
1
4494
package com.ninjahoahong.unstoppable.utils import android.content.Context import android.content.SharedPreferences import com.google.gson.GsonBuilder class Settings { companion object { private val DEFAULTS = arrayListOf<Setting>() private const val IDENTIFIER = "unstoppable_preferences" const val FIRST_TIME_PLAY = "FirstTimePlay" const val LONGEST_STREAK = "LongestStreak" init { DEFAULTS.add(object : Setting(FIRST_TIME_PLAY, false, Boolean::class.java) { override fun createDescription(context: Context): String? { return "Is the user using the application the first time." } }) DEFAULTS.add(object : Setting(LONGEST_STREAK, "0", String::class.java) { override fun createDescription(context: Context): String? { return "This is the most number of questions being answered correctly in a row." } }) } fun isNot(context: Context, key: String): Boolean { return !isTrue(context, key) } private fun isTrue(context: Context, key: String): Boolean { return Settings.getSettings(context).getBoolean(key, false) } private fun getLong(context: Context, key: String): Long? { val s = Settings.getSettings(context) return if (s.contains(key)) { s.getLong(key, 0) } else { null } } operator fun get(context: Context, key: String): String? { return get(context, key, "") } operator fun get(context: Context, key: String, defaultValue: String?): String? { return Settings.getSettings(context).getString(key, defaultValue) } operator fun set(context: Context, key: String, value: String?) { val editor = Settings.getSettings(context).edit() editor.putString(key, value) editor.apply() } operator fun set(context: Context, key: String, value: Boolean) { val editor = Settings.getSettings(context).edit() editor.putBoolean(key, value) editor.apply() } fun delete(context: Context, key: String) { val editor = Settings.getSettings(context).edit() editor.remove(key) editor.commit() } private fun getSettings(context: Context): SharedPreferences { return context.getSharedPreferences(IDENTIFIER, Context.MODE_PRIVATE) } fun getAny(context: Context, key: String, valueClass: Class<*>): Any? { return when (valueClass) { String::class.java -> Settings[context, key] Boolean::class.java -> Settings.isTrue(context, key) Long::class.java -> Settings.getLong(context, key) else -> Settings.getObject(key, valueClass, context) } } private fun <E> getObject(key: String, clazz: Class<E>, context: Context): E { val json = Settings[context, key, null] return GsonBuilder().create().fromJson(json, clazz) } fun contains(context: Context, key: String): Boolean = getSettings(context).contains(key) private fun setLong( context: Context, key: String, value: Long) { val editor = Settings.getSettings(context).edit() editor.putLong(key, value) editor.apply() } private fun <E> setObject( key: String, theObject: E, context: Context) { Settings[context, key] = GsonBuilder().create().toJson(theObject) } private fun setAny( context: Context, key: String, value: Any?, valueClass: Class<*>) { when (valueClass) { String::class.java -> Settings[context, key] = value as String? Boolean::class.java -> Settings[context, key] = value as Boolean Long::class.java -> Settings.setLong(context, key, value as Long) else -> Settings.setObject(key, value, context) } } fun setDefaultsIfNotSet(context: Context) { for (setting in DEFAULTS) { if (!Settings.contains(context, setting.key)) { Settings.setAny(context, setting.key, setting.defaultValue, setting.valueClass) } } } } }
mit
69bc2da5421b7e65a28cd9cd2e9ff118
36.773109
100
0.575879
4.695925
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/runtime/workers/freeze_stress.kt
2
4540
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package runtime.workers.freeze_stress import kotlin.test.* import kotlin.native.concurrent.* class Random(private var seed: Int) { fun next(): Int { seed = (1103515245 * seed + 12345) and 0x7fffffff return seed } fun next(maxExclusiveValue: Int) = if (maxExclusiveValue == 0) 0 else next() % maxExclusiveValue fun next(minInclusiveValue: Int, maxInclusiveValue: Int) = minInclusiveValue + next(maxInclusiveValue - minInclusiveValue + 1) } class Node(val id: Int) { var numberOfEdges = 0 lateinit var edge0: Node lateinit var edge1: Node lateinit var edge2: Node lateinit var edge3: Node lateinit var edge4: Node lateinit var edge5: Node lateinit var edge6: Node lateinit var edge7: Node lateinit var edge8: Node lateinit var edge9: Node fun addEdge(child: Node) { when (numberOfEdges) { 0 -> edge0 = child 1 -> edge1 = child 2 -> edge2 = child 3 -> edge3 = child 4 -> edge4 = child 5 -> edge5 = child 6 -> edge6 = child 7 -> edge7 = child 8 -> edge8 = child 9 -> edge9 = child else -> error("Too many edges") } ++numberOfEdges } fun getEdges(): List<Node> { val result = mutableListOf<Node>() if (numberOfEdges > 0) result += edge0 if (numberOfEdges > 1) result += edge1 if (numberOfEdges > 2) result += edge2 if (numberOfEdges > 3) result += edge3 if (numberOfEdges > 4) result += edge4 if (numberOfEdges > 5) result += edge5 if (numberOfEdges > 6) result += edge6 if (numberOfEdges > 7) result += edge7 if (numberOfEdges > 8) result += edge8 if (numberOfEdges > 9) result += edge9 return result } } class Graph(val nodes: List<Node>, val roots: List<Node>) fun min(x: Int, y: Int) = if (x < y) x else y fun max(x: Int, y: Int) = if (x > y) x else y @ThreadLocal val random = Random(42) fun generate(condensationSize: Int, branchingFactor: Int, swellingFactor: Int): Graph { var id = 0 val nodes = mutableListOf<Node>() fun genDAG(n: Int): Node { val node = Node(id++) nodes += node if (n == 1) return node val numberOfChildren = random.next(1, min(n - 1, branchingFactor)) val used = BooleanArray(n) val points = IntArray(numberOfChildren + 1) points[0] = 0 points[numberOfChildren] = n - 1 used[0] = true used[n - 1] = true for (i in 1 until numberOfChildren) { var p: Int do { p = random.next(1, n - 1) } while (used[p]) used[p] = true points[i] = p } points.sort() for (i in 1..numberOfChildren) { val childSize = points[i] - points[i - 1] val child = genDAG(childSize) if (random.next(2) == 0) node.addEdge(child) else child.addEdge(node) } return node } genDAG(condensationSize) val numberOfEnters = IntArray(condensationSize) for (node in nodes) for (edge in node.getEdges()) ++numberOfEnters[edge.id] val roots = nodes.filter { numberOfEnters[it.id] == 0 } for (i in 0 until condensationSize) { val node = nodes[i] val componentSize = random.next(1, swellingFactor) if (componentSize == 1 && random.next(2) == 0) continue val component = Array(componentSize) { if (it == 0) node else Node(id++).also { nodes += it } } for (j in 0 until componentSize) component[j].addEdge(component[(j - 1 + componentSize) % componentSize]) val numberOfAdditionalEdges = random.next((componentSize + 1) / 2) for (j in 0 until numberOfAdditionalEdges) component[random.next(componentSize)].addEdge(component[random.next(componentSize)]) } return Graph(nodes, roots) } fun freezeOneGraph() { val graph = generate(100, 5, 20) graph.roots.forEach { it.freeze() } for (node in graph.nodes) assert (node.isFrozen, { "All nodes should be frozen" }) } @Test fun runTest() { for (i in 0..1000) { freezeOneGraph() } println("OK") }
apache-2.0
bc075da6e8cc1594586425bbdeb9a48c
29.072848
101
0.571806
3.811923
false
false
false
false
androidx/androidx
compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text/CapitalizationAutoCorrectDemo.kt
3
3690
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.demos.text import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp private val KeyboardOptionsList = listOf( ImeOptionsData( keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, capitalization = KeyboardCapitalization.Characters ), name = "Capitalize Characters" ), ImeOptionsData( keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, capitalization = KeyboardCapitalization.Words ), name = "Capitalize Words" ), ImeOptionsData( keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, capitalization = KeyboardCapitalization.Sentences ), name = "Capitalize Sentences" ), ImeOptionsData( keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, autoCorrect = true ), name = "AutoCorrect On" ), ImeOptionsData( keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, autoCorrect = false ), name = "AutoCorrect Off" ) ) @Preview @Composable fun CapitalizationAutoCorrectDemo() { LazyColumn { items(KeyboardOptionsList) { data -> TagLine(tag = data.name) MyTextField(data) } } } @OptIn(ExperimentalComposeUiApi::class) @Composable private fun MyTextField(data: ImeOptionsData) { var state by rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue()) } val keyboardController = LocalSoftwareKeyboardController.current BasicTextField( modifier = demoTextFieldModifiers.defaultMinSize(100.dp), value = state, keyboardOptions = data.keyboardOptions, keyboardActions = KeyboardActions { keyboardController?.hide() }, onValueChange = { state = it }, textStyle = TextStyle(fontSize = fontSize8), cursorBrush = SolidColor(Color.Red) ) }
apache-2.0
ea861c2da463efc7e79e80527c41a079
33.495327
75
0.724119
4.973046
false
false
false
false
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/models/data/remote/RemoteDataStore.kt
1
12163
package taiwan.no1.app.ssfm.models.data.remote import android.content.Context import com.devrapid.kotlinknifer.observable import dagger.Lazy import io.reactivex.Observable import io.reactivex.ObservableEmitter import io.reactivex.internal.operators.observable.ObservableJust import io.reactivex.schedulers.Schedulers import taiwan.no1.app.ssfm.R import taiwan.no1.app.ssfm.internal.di.components.NetComponent import taiwan.no1.app.ssfm.models.data.IDataStore import taiwan.no1.app.ssfm.models.data.remote.services.MusicServices import taiwan.no1.app.ssfm.models.data.remote.services.v2.MusicV2Service import taiwan.no1.app.ssfm.models.entities.DetailMusicEntity import taiwan.no1.app.ssfm.models.entities.KeywordEntity import taiwan.no1.app.ssfm.models.entities.PlaylistEntity import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity import taiwan.no1.app.ssfm.models.entities.SearchMusicEntity import taiwan.no1.app.ssfm.models.entities.lastfm.AlbumEntity import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistEntity import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistSimilarEntity import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistTopAlbumEntity import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistTopTrackEntity import taiwan.no1.app.ssfm.models.entities.lastfm.TagEntity import taiwan.no1.app.ssfm.models.entities.lastfm.TagTopArtistEntity import taiwan.no1.app.ssfm.models.entities.lastfm.TopAlbumEntity import taiwan.no1.app.ssfm.models.entities.lastfm.TopArtistEntity import taiwan.no1.app.ssfm.models.entities.lastfm.TopTagEntity import taiwan.no1.app.ssfm.models.entities.lastfm.TopTrackEntity import taiwan.no1.app.ssfm.models.entities.lastfm.TrackSimilarEntity import taiwan.no1.app.ssfm.models.entities.v2.HotPlaylistEntity import taiwan.no1.app.ssfm.models.entities.v2.MusicEntity import taiwan.no1.app.ssfm.models.entities.v2.MusicRankEntity import taiwan.no1.app.ssfm.models.entities.v2.RankChartEntity import taiwan.no1.app.ssfm.models.entities.v2.SongListEntity import javax.inject.Inject import javax.inject.Named /** * Retrieving the data from remote server with [retrofit2] by http api. All return objects are [Observable] * to viewmodels. * * @author jieyi * @since 5/10/17 */ class RemoteDataStore constructor(private val context: Context) : IDataStore { @field:[Inject Named("music1")] lateinit var musicService1: Lazy<MusicServices> @field:[Inject Named("music2")] lateinit var musicService2: Lazy<MusicServices> @field:[Inject Named("music3")] lateinit var musicService3: Lazy<MusicServices> @field:[Inject Named("music4")] lateinit var musicV2Service: Lazy<MusicV2Service> private val lastFmKey by lazy { context.getString(R.string.lastfm_api_key) } init { NetComponent.Initializer.init().inject(this) } //region V1 override fun getSearchMusicRes(keyword: String, page: Int, pageSize: Int): Observable<SearchMusicEntity> { val query = mapOf( context.getString(R.string.t_pair1) to context.getString(R.string.v_pair1), context.getString(R.string.t_pair2) to keyword, context.getString(R.string.t_pair3) to page.toString(), context.getString(R.string.t_pair4) to pageSize.toString(), context.getString(R.string.t_pair5) to context.getString(R.string.v_pair5)) return musicService1.get().searchMusic(query) } override fun getDetailMusicRes(hash: String): Observable<DetailMusicEntity> { val query = mapOf( context.getString(R.string.t_pair6) to context.getString(R.string.v_pair6), context.getString(R.string.t_pair7) to context.getString(R.string.v_pair7), context.getString(R.string.t_pair8) to hash) return musicService2.get().getMusic(query) } //endregion //region V2 override fun searchMusic(keyword: String, page: Int, lang: String): Observable<MusicEntity> { val query = mapOf(context.getString(R.string.s_pair1) to page.toString(), context.getString(R.string.s_pair2) to keyword, context.getString(R.string.s_pair3) to context.getString(R.string.s_pair4), context.getString(R.string.s_pair5) to context.getString(R.string.s_pair6), context.getString(R.string.s_pair7) to "en") return musicV2Service.get().searchMusic(query) } override fun fetchRankMusic(rankType: Int): Observable<MusicRankEntity> { val query = mapOf(context.getString(R.string.r_pair1) to rankType.toString()) return musicV2Service.get().musicRanking(query) } override fun fetchHotPlaylist(page: Int): Observable<HotPlaylistEntity> { val query = mapOf(context.getString(R.string.s_pair1) to page.toString()) return musicV2Service.get().hotPlaylist(query) } override fun fetchPlaylistDetail(id: String): Observable<SongListEntity> { val query = mapOf(context.getString(R.string.b_pair1) to id) return musicV2Service.get().playlistDetail(query) } //endregion //region Chart override fun getChartTopArtist(page: Int, limit: Int): Observable<TopArtistEntity> { val query = mutableMapOf("page" to page.toString(), "limit" to limit.toString(), "method" to "chart.getTopArtists").baseLastFmParams() return musicService3.get().getChartTopArtist(query) } override fun getChartTopTracks(page: Int, limit: Int): Observable<TopTrackEntity> { val query = mutableMapOf("page" to page.toString(), "limit" to limit.toString(), "method" to "chart.getTopTracks").baseLastFmParams() return musicService3.get().getChartTopTrack(query) } override fun getChartTopTags(page: Int, limit: Int): Observable<TopTagEntity> { val query = mutableMapOf("page" to page.toString(), "limit" to limit.toString(), "method" to "chart.getTopTags").baseLastFmParams() return musicService3.get().getChartTopTag(query) } override fun getChartTop() = TODO() override fun addRankChart(entity: RankChartEntity) = TODO() override fun editRankChart(entity: RankChartEntity) = TODO() //endregion //region Artist override fun getArtistInfo(mbid: String, artist: String): Observable<ArtistEntity> { val query = mutableMapOf(mbid.takeIf { it.isNotBlank() }?.let { "mbid" to it } ?: "artist" to artist, "method" to "artist.getInfo").baseLastFmParams() return musicService3.get().getArtistInfo(query) } override fun getSimilarArtist(artist: String): Observable<ArtistSimilarEntity> { val query = mutableMapOf("artist" to artist, "limit" to 10.toString(), "method" to "artist.getSimilar").baseLastFmParams() return musicService3.get().getSimilarArtistInfo(query) } override fun getArtistTopAlbum(artist: String): Observable<ArtistTopAlbumEntity> { val query = mutableMapOf("artist" to artist, "method" to "artist.getTopAlbums").baseLastFmParams() return musicService3.get().getArtistTopAlbum(query) } override fun getArtistTopTrack(artist: String): Observable<ArtistTopTrackEntity> { val query = mutableMapOf("artist" to artist, "method" to "artist.getTopTracks").baseLastFmParams() return musicService3.get().getArtistTopTrack(query) } override fun getArtistTags(artist: String, session: Any): Observable<Collection<String>> = TODO() // ObservableJust(Artist.getTags(artist, session)) override fun getSimilarTracks(artist: String, track: String): Observable<TrackSimilarEntity> { val query = mutableMapOf("artist" to artist, "track" to track, "limit" to 10.toString(), "method" to "track.getSimilar").baseLastFmParams() return musicService3.get().getSimilarTrackInfo(query) } //endregion //region Album override fun getAlbumInfo(artist: String, albumOrMbid: String): Observable<AlbumEntity> { val query = mutableMapOf("method" to "album.getInfo").baseLastFmParams().apply { if (artist.isBlank()) put("mbid", albumOrMbid) else putAll(mapOf("artist" to artist, "album" to albumOrMbid)) } return musicService3.get().getAlbumInfo(query) } //endregion //region Tag override fun getTagTopAlbums(tag: String, page: Int, limit: Int): Observable<TopAlbumEntity> { val query = mutableMapOf("tag" to tag, "page" to page.toString(), "limit" to limit.toString(), "method" to "tag.getTopAlbums").baseLastFmParams() return musicService3.get().getTagTopAlbum(query) } override fun getTagTopArtists(tag: String, page: Int, limit: Int): Observable<TagTopArtistEntity> { val query = mutableMapOf("tag" to tag, "page" to page.toString(), "limit" to limit.toString(), "method" to "tag.getTopArtists").baseLastFmParams() return musicService3.get().getTagTopArtist(query) } override fun getTagTopTracks(tag: String, page: Int, limit: Int): Observable<TopTrackEntity> { val query = mutableMapOf("tag" to tag, "page" to page.toString(), "limit" to limit.toString(), "method" to "tag.getTopTracks").baseLastFmParams() return musicService3.get().getTagTopTrack(query) } override fun getTagInfo(tag: String): Observable<TagEntity> { val query = mutableMapOf("tag" to tag, "method" to "tag.getInfo").baseLastFmParams() return musicService3.get().getTagInfo(query) } //endregion //region Playlist override fun getPlaylists(id: Long): Observable<List<PlaylistEntity>> = TODO() override fun addPlaylist(entity: PlaylistEntity): Observable<PlaylistEntity> = TODO() override fun editPlaylist(entity: PlaylistEntity): Observable<Boolean> = TODO() override fun removePlaylist(entity: PlaylistEntity): Observable<Boolean> = TODO() override fun getPlaylistItems(playlistId: Long): Observable<List<PlaylistItemEntity>> = TODO() override fun addPlaylistItem(entity: PlaylistItemEntity): Observable<Boolean> = TODO() override fun removePlaylistItem(entity: PlaylistItemEntity): Observable<Boolean> = TODO() //endregion //region Search History override fun insertKeyword(keyword: String): Observable<Boolean> = TODO() override fun getKeywords(quantity: Int): Observable<List<KeywordEntity>> = TODO() override fun removeKeywords(keyword: String?): Observable<Boolean> = TODO() //endregion //region private /** * Wrapping the [Observable.create] with [Schedulers.IO]. * * @param block for processing program. * @return an [Observable] reference. */ private fun <O> observableCreateWrapper(block: (emitter: ObservableEmitter<O>) -> Unit): Observable<O> = observable { block(it); it.onComplete() } /** * Wrapping the [Observable.just] with [Schedulers.IO] * * @param data Omit data. * @return an [Observable] reference. */ private fun <O> observableJustWrapper(data: O): Observable<O> = ObservableJust(data) private fun MutableMap<String, String>.baseLastFmParams() = apply { putAll(mapOf("api_key" to lastFmKey, "format" to "json")) } //endregion }
apache-2.0
636d27bbdaa73522cc792172e203cbe0
39.013158
108
0.661021
4.210107
false
false
false
false
GunoH/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/Context.kt
3
10973
// 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.tools.projectWizard.core import org.jetbrains.kotlin.tools.projectWizard.core.entity.* import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.PluginProperty import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.PluginPropertyReference import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.PropertyContext import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.PropertyReference import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.* import org.jetbrains.kotlin.tools.projectWizard.core.service.ServicesManager import org.jetbrains.kotlin.tools.projectWizard.core.service.SettingSavingWizardService import org.jetbrains.kotlin.tools.projectWizard.core.service.WizardService import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.allIRModules import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.ModuleReference import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.path import kotlin.reflect.KClass class Context private constructor( val servicesManager: ServicesManager, private val isUnitTestMode: Boolean, private val settingContext: SettingContext, private val propertyContext: PropertyContext, val contextComponents: ContextComponents ) { private lateinit var plugins: List<Plugin> private val settingWritingContext = SettingsWriter() private val pluginSettings by lazy(LazyThreadSafetyMode.NONE) { plugins.flatMap(Plugin::settings).distinctBy(PluginSetting<*, *>::path) } fun <T> read(reader: Reader.() -> T): T = settingWritingContext.reader() fun <T> write(writer: Writer.() -> T): T = settingWritingContext.writer() fun <T> writeSettings(writer: SettingsWriter.() -> T): T = settingWritingContext.writer() constructor( pluginsCreator: PluginsCreator, servicesManager: ServicesManager, isUnitTestMode: Boolean, contextComponents: ContextComponents, ) : this( servicesManager, isUnitTestMode, SettingContext(), PropertyContext(), contextComponents, ) { plugins = pluginsCreator(this).onEach(::initPlugin) } fun withAdditionalServices(services: List<WizardService>) = Context( servicesManager.withAdditionalServices(services), isUnitTestMode, settingContext, propertyContext, contextComponents ).also { it.plugins = plugins } private fun initPlugin(plugin: Plugin) { for (property in plugin.properties) { propertyContext[property] = property.defaultValue } for (setting in plugin.settings) { settingContext.setPluginSetting(setting.reference, setting) } } private val pipelineLineTasks: List<PipelineTask> get() = plugins .flatMap { it.pipelineTasks } private val dependencyList: Map<PipelineTask, List<PipelineTask>> get() { val dependeeMap = pipelineLineTasks.flatMap { task -> task.after.map { after -> task to after } } val dependencyMap = pipelineLineTasks.flatMap { task -> task.before.map { before -> before to task } } return (dependeeMap + dependencyMap) .groupBy { it.first } .mapValues { it.value.map { it.second } } } fun sortTasks(): TaskResult<List<PipelineTask>> = TaskSorter().sort(pipelineLineTasks, dependencyList) open inner class Reader { val plugins: List<Plugin> get() = [email protected] val pluginSettings: List<PluginSetting<*, *>> get() = [email protected] val isUnitTestMode: Boolean get() = [email protected] inline fun <reified S : WizardService> service(noinline filter: (S) -> Boolean = { true }): S = serviceOrNull(filter) ?: error("Service ${S::class.simpleName} was not found") inline fun <reified S : WizardService> serviceOrNull(noinline filter: (S) -> Boolean = { true }): S? = servicesManager.serviceByClass(S::class, filter) val <T : Any> PluginProperty<T>.reference: PluginPropertyReference<T> get() = PluginPropertyReference(this) val <T : Any> PluginProperty<T>.propertyValue: T get() = propertyContext[this] ?: error("No value is present for property `$this`") val <T : Any> PropertyReference<T>.propertyValue: T get() = propertyContext[this] ?: error("No value is present for property `$this`") val <V : Any, T : SettingType<V>> SettingReference<V, T>.settingValue: V get() = settingContext[this] ?: error("No value is present for setting `$this`") val <V : Any> PluginSetting<V, SettingType<V>>.settingValue: V get() = settingContext[this.reference] ?: error("No value is present for setting `$this`") val <V : Any> PluginSetting<V, SettingType<V>>.notRequiredSettingValue: V? get() = settingContext[this.reference] fun <V : Any, T : SettingType<V>> SettingReference<V, T>.settingValue(): V = settingContext[this] ?: error("No value is present for setting `$this`") val <V : Any, T : SettingType<V>> SettingReference<V, T>.notRequiredSettingValue: V? get() = settingContext[this] fun <V : Any, T : SettingType<V>> SettingReference<V, T>.notRequiredSettingValue(): V? = settingContext[this] val <V : Any, T : SettingType<V>> PluginSettingReference<V, T>.pluginSetting: Setting<V, T> get() = settingContext.getPluginSetting(this) private fun <V : Any> Setting<V, SettingType<V>>.getSavedValueForSetting(): V? { if (!isSavable || this !is PluginSetting<*, *>) return null val serializer = type.serializer.safeAs<SettingSerializer.Serializer<V>>() ?: return null val savedValue = service<SettingSavingWizardService>().getSettingValue(path) ?: return null return serializer.fromString(savedValue) } val <V : Any> SettingReference<V, SettingType<V>>.savedOrDefaultValue: V? get() { val savedValue = setting.getSavedValueForSetting()?.takeIf { // loaded value might be no longer relevant for the current context, e.g. IDE plugins can be disabled read { setting.validator.validate(this, it) } == ValidationResult.OK } return savedValue ?: when (val defaultValue = setting.defaultValue) { is SettingDefaultValue.Value -> defaultValue.value is SettingDefaultValue.Dynamic<V> -> defaultValue.getter(this@Reader, this) null -> null } } val <V : Any, T : SettingType<V>> SettingReference<V, T>.setting: Setting<V, T> get() = with(this) { getSetting() } fun <V : Any, T : SettingType<V>> SettingReference<V, T>.validate() = setting.validator.validate(this@Reader, settingValue) inline operator fun <T> invoke(reader: Reader.() -> T): T = reader() } open inner class Writer : Reader() { @Deprecated("Allows to get SettingsWriter where it is not supposed to be") val unsafeSettingWriter: SettingsWriter get() = settingWritingContext val eventManager: EventManager get() = settingContext.eventManager fun <A, B : Any> Task1<A, B>.execute(value: A): TaskResult<B> { return action(this@Writer, value) } fun <T : Any> PluginProperty<T>.update( updater: suspend ComputeContext<*>.(T) -> TaskResult<T> ): TaskResult<Unit> = reference.update(updater) fun <T : Any> PropertyReference<T>.update( updater: suspend ComputeContext<*>.(T) -> TaskResult<T> ): TaskResult<Unit> = compute { val (newValue) = updater(propertyValue) propertyContext[this@update] = newValue } fun <T : Any> PluginProperty<List<T>>.addValues( vararg values: T ): TaskResult<Unit> = update { oldValues -> success(oldValues + values) } fun <T : Any> PluginProperty<List<T>>.addValues( values: List<T> ): TaskResult<Unit> = reference.addValues(values) fun <T : Any> PropertyReference<List<T>>.addValues( values: List<T> ): TaskResult<Unit> = update { oldValues -> success(oldValues + values) } @JvmName("write") inline operator fun <T> invoke(writer: Writer.() -> T): T = writer() } open inner class SettingsWriter : Writer() { fun <V : Any, T : SettingType<V>> SettingReference<V, T>.setValue(newValue: V) { settingContext[this] = newValue } fun <V : Any> PropertyReference<V>.initDefaultValue(newValue: V) { propertyContext[this] = property.defaultValue } fun <V : Any, T : SettingType<V>> SettingReference<V, T>.setSettingValueToItsDefaultIfItIsNotSetValue() { val defaultValue = savedOrDefaultValue ?: return if (notRequiredSettingValue == null) { setValue(defaultValue) } } @JvmName("writeSettings") inline operator fun <T> invoke(writer: SettingsWriter.() -> T): T = writer() } } class ContextComponents(val components: Map<KClass<*>, Any>) { constructor(vararg components: Pair<KClass<*>, Any>) : this(components.toMap()) inline fun <reified T : Any> get(): T { return components[T::class] as T } } fun Reader.getUnspecifiedSettings(phases: Set<GenerationPhase>): List<AnySetting> { val required = plugins .flatMap { plugin -> plugin.settings.mapNotNull { setting -> if (setting.neededAtPhase !in phases) return@mapNotNull null if (setting.isRequired) setting else null } }.toSet() val provided = pluginSettings.map(PluginSetting<*, *>::path).toSet() return required.filterNot { it.path in provided } } fun Reader.moduleByReference(reference: ModuleReference): Module = when (reference) { is ModuleReference.ByModule -> reference.module is ModuleReference.ByPath -> allIRModules.first { it.originalModule.path == reference.path }.originalModule } typealias Reader = Context.Reader typealias Writer = Context.Writer typealias SettingsWriter = Context.SettingsWriter
apache-2.0
9e6a03eb6c5ebd80e585f2a56aada5a6
39.345588
121
0.645402
4.583542
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/api/src/org/jetbrains/kotlin/idea/codeinsight/api/applicators/fixes/KotlinQuickFixesList.kt
5
4939
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes import com.intellij.codeInsight.intention.IntentionAction import com.intellij.psi.PsiElement import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.diagnostics.KtDiagnosticWithPsi import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixesPsiBasedFactory import org.jetbrains.kotlin.miniStdLib.annotations.PrivateForInline import kotlin.reflect.KClass class KotlinQuickFixesList @ForKtQuickFixesListBuilder @OptIn(PrivateForInline::class) constructor( private val quickFixes: Map<KClass<out KtDiagnosticWithPsi<*>>, List<KotlinQuickFixFactory>> ) { @OptIn(PrivateForInline::class) fun KtAnalysisSession.getQuickFixesFor(diagnostic: KtDiagnosticWithPsi<*>): List<IntentionAction> { val factories = quickFixes[diagnostic.diagnosticClass] ?: return emptyList() return factories.flatMap { createQuickFixes(it, diagnostic) } } @OptIn(PrivateForInline::class) private fun KtAnalysisSession.createQuickFixes( quickFixFactory: KotlinQuickFixFactory, diagnostic: KtDiagnosticWithPsi<*> ): List<IntentionAction> = when (quickFixFactory) { is KotlinQuickFixFactory.KotlinApplicatorBasedFactory -> { @Suppress("UNCHECKED_CAST") val factory = quickFixFactory.applicatorFactory as KotlinDiagnosticFixFactory<KtDiagnosticWithPsi<PsiElement>> createPlatformQuickFixes(diagnostic, factory) } is KotlinQuickFixFactory.KotlinQuickFixesPsiBasedFactory -> quickFixFactory.psiFactory.createQuickFix(diagnostic.psi) } companion object { @OptIn(ForKtQuickFixesListBuilder::class, PrivateForInline::class) fun createCombined(registrars: List<KotlinQuickFixesList>): KotlinQuickFixesList { val allQuickFixes = registrars.map { it.quickFixes }.merge() return KotlinQuickFixesList(allQuickFixes) } fun createCombined(vararg registrars: KotlinQuickFixesList): KotlinQuickFixesList { return createCombined(registrars.toList()) } } } class KtQuickFixesListBuilder private constructor() { @OptIn(PrivateForInline::class) private val quickFixes = mutableMapOf<KClass<out KtDiagnosticWithPsi<*>>, MutableList<KotlinQuickFixFactory>>() @OptIn(PrivateForInline::class) fun <DIAGNOSTIC_PSI : PsiElement, DIAGNOSTIC : KtDiagnosticWithPsi<DIAGNOSTIC_PSI>> registerPsiQuickFixes( diagnosticClass: KClass<DIAGNOSTIC>, vararg quickFixFactories: QuickFixesPsiBasedFactory<in DIAGNOSTIC_PSI> ) { for (quickFixFactory in quickFixFactories) { registerPsiQuickFix(diagnosticClass, quickFixFactory) } } @PrivateForInline fun <DIAGNOSTIC_PSI : PsiElement, DIAGNOSTIC : KtDiagnosticWithPsi<DIAGNOSTIC_PSI>> registerPsiQuickFix( diagnosticClass: KClass<DIAGNOSTIC>, quickFixFactory: QuickFixesPsiBasedFactory<in DIAGNOSTIC_PSI> ) { quickFixes.getOrPut(diagnosticClass) { mutableListOf() }.add(KotlinQuickFixFactory.KotlinQuickFixesPsiBasedFactory(quickFixFactory)) } @OptIn(PrivateForInline::class) fun <DIAGNOSTIC : KtDiagnosticWithPsi<*>> registerApplicators( quickFixFactories: Collection<KotlinDiagnosticFixFactory<out DIAGNOSTIC>> ) { quickFixFactories.forEach(::registerApplicator) } @OptIn(PrivateForInline::class) fun <DIAGNOSTIC : KtDiagnosticWithPsi<*>> registerApplicator( quickFixFactory: KotlinDiagnosticFixFactory<out DIAGNOSTIC> ) { quickFixes.getOrPut(quickFixFactory.diagnosticClass) { mutableListOf() } .add(KotlinQuickFixFactory.KotlinApplicatorBasedFactory(quickFixFactory)) } @OptIn(ForKtQuickFixesListBuilder::class, PrivateForInline::class) private fun build() = KotlinQuickFixesList(quickFixes) companion object { fun registerPsiQuickFix(init: KtQuickFixesListBuilder.() -> Unit) = KtQuickFixesListBuilder().apply(init).build() } } @PrivateForInline sealed class KotlinQuickFixFactory { class KotlinQuickFixesPsiBasedFactory( val psiFactory: QuickFixesPsiBasedFactory<*> ) : KotlinQuickFixFactory() class KotlinApplicatorBasedFactory( val applicatorFactory: KotlinDiagnosticFixFactory<*> ) : KotlinQuickFixFactory() } private fun <K, V> List<Map<K, List<V>>>.merge(): Map<K, List<V>> { return flatMap { it.entries } .groupingBy { it.key } .aggregate<Map.Entry<K, List<V>>, K, MutableList<V>> { _, accumulator, element, _ -> val list = accumulator ?: mutableListOf() list.addAll(element.value) list } } @RequiresOptIn annotation class ForKtQuickFixesListBuilder
apache-2.0
f62986c17172f8df774cc66c0e7d7958
40.504202
140
0.735372
4.785853
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/multiplatform/multilevelParents/common-1/common-1.kt
9
644
@file:Suppress("UNUSED_PARAMETER") package sample expect interface <!LINE_MARKER("descr='Has actuals in common-2 module'"), LINE_MARKER("descr='Is subclassed by B [common-1] B [common-2] Case_2_3 Click or press ... to navigate'")!>A<!> { fun common_1_A() } expect interface <!LINE_MARKER("descr='Has actuals in common-2 module'"), LINE_MARKER("descr='Is subclassed by Case_2_3 Click or press ... to navigate'")!>B<!> : A { fun <!LINE_MARKER("descr='Has actuals in common-2 module'")!>common_1_B<!>() } fun getB(): B = null!! class Out<out T>(val value: T) fun takeOutA_common_1(t: Out<A>) {} fun takeOutB_common_1(t: Out<B>) {}
apache-2.0
f5b2301dd753a14507e141c92b784332
34.777778
188
0.658385
3.096154
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/Reflection.kt
5
4461
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:OptIn(ExperimentalStdlibApi::class) package org.jetbrains.kotlin.idea.gradleTooling.reflect import org.gradle.api.logging.Logger import org.gradle.api.logging.Logging import kotlin.reflect.KClass import kotlin.reflect.KType import kotlin.reflect.typeOf internal inline fun <reified T> returnType(): TypeToken<T> = TypeToken.create() internal inline fun <reified T> parameter(value: T?): Parameter<T> = Parameter(TypeToken.create(), value) internal fun parameters(vararg parameter: Parameter<*>): ParameterList = if (parameter.isEmpty()) ParameterList.empty else ParameterList(parameter.toList()) internal class TypeToken<T> private constructor( val kotlinType: KType?, val kotlinClass: KClass<*>, val isMarkedNullable: Boolean ) { override fun toString(): String { return kotlinType?.toString() ?: (kotlinClass.java.name + if (isMarkedNullable) "?" else "") } companion object { inline fun <reified T> create(): TypeToken<T> { /* KType is not supported with older versions of Kotlin bundled in old Gradle versions (4.x) */ val type = runCatching { typeOf<T>() }.getOrNull() val isMarkedNullable = when { type != null -> type.isMarkedNullable else -> null is T } return TypeToken(type, T::class, isMarkedNullable) } } } interface ReflectionLogger { fun logIssue(message: String, exception: Throwable? = null) } fun ReflectionLogger(clazz: Class<*>) = ReflectionLogger(Logging.getLogger(clazz)) fun ReflectionLogger(logger: Logger): ReflectionLogger = GradleReflectionLogger(logger) private class GradleReflectionLogger(private val logger: Logger) : ReflectionLogger { override fun logIssue(message: String, exception: Throwable?) { assert(false) { message } logger.error("[Reflection Error] $message", exception) } } internal class Parameter<T>( /** * Optional, because this is not supported in old Gradle/Kotlin Versions */ val typeToken: TypeToken<T>, val value: T? ) internal class ParameterList(private val parameters: List<Parameter<*>>) : List<Parameter<*>> by parameters { companion object { val empty = ParameterList(emptyList()) } } internal inline fun <reified T> Any.callReflective( methodName: String, parameters: ParameterList, returnTypeToken: TypeToken<T>, logger: ReflectionLogger ): T? { val parameterClasses = parameters.map { parameter -> /* Ensure using the object representation for primitive types, when marked nullable */ if (parameter.typeToken.isMarkedNullable) parameter.typeToken.kotlinClass.javaObjectType else parameter.typeToken.kotlinClass.javaPrimitiveType ?: parameter.typeToken.kotlinClass.java } val method = try { this::class.java.getMethod(methodName, *parameterClasses.toTypedArray()) } catch (e: Exception) { logger.logIssue("Failed to invoke $methodName on ${this.javaClass.name}", e) return null } runCatching { @Suppress("Since15") method.trySetAccessible() } val returnValue = try { method.invoke(this, *parameters.map { it.value }.toTypedArray()) } catch (t: Throwable) { logger.logIssue("Failed to invoke $methodName on ${this.javaClass.name}", t) return null } if (returnValue == null) { if (!returnTypeToken.isMarkedNullable) { logger.logIssue("Method $methodName on ${this.javaClass.name} unexpectedly returned null (expected $returnTypeToken)") } return null } if (!returnTypeToken.kotlinClass.javaObjectType.isInstance(returnValue)) { logger.logIssue( "Method $methodName on ${this.javaClass.name} unexpectedly returned ${returnValue.javaClass.name}, which is " + "not an instance of ${returnTypeToken}" ) return null } return returnValue as T } internal fun Any.callReflectiveAnyGetter(methodName: String, logger: ReflectionLogger): Any? = callReflectiveGetter<Any>(methodName, logger) internal inline fun <reified T> Any.callReflectiveGetter(methodName: String, logger: ReflectionLogger): T? = callReflective(methodName, parameters(), returnType<T>(), logger)
apache-2.0
ead7ed06857a4f07e255447a4c9b34e4
35.876033
158
0.690876
4.584789
false
false
false
false
tlaukkan/kotlin-web-vr
client/src/lib/threejs/Extra/Core.kt
1
1912
package lib.threejs.Extra import lib.threejs.Geometry import lib.threejs.Matrix4 import lib.threejs.Vector2 @native("THREE.Curve") open class Curve() { //Functions //fun getPoint(t: Double): Unit = noImpl //fun getPointAt(u: Double): Unit = noImpl //fun getPoints(t: Array<Double>): Unit = noImpl //fun getSpacedPoints(u: Array<Double>): Unit = noImpl //fun getLength(): Unit = noImpl //fun getLengths(t: Array<Double>): Unit = noImpl //fun updateArcLengths(): Unit = noImpl //fun getUtoTmapping(u: Double, distance : Double): Unit = noImpl //fun getTangent(t: Double): Unit = noImpl //fun getTangentAt(u: Double): Unit = noImpl } @native("THREE.CurvePath") open class CurvePath() : Curve() { //Properties @native var curves: Array<Double> = noImpl @native var bends: Array<Double> = noImpl @native var autoClose: Boolean = noImpl //Functions fun createPointsGeometry(): Geometry = noImpl fun createSpacedPointsGeometry(divisions: Int): Geometry = noImpl } @native("THREE.Path") open class Path(points: Array<Vector2>) : CurvePath() { //Functions fun fromPoints(points: Array<Vector2>): Unit = noImpl fun moveTo(x: Double, y: Double): Unit = noImpl fun lineTo(x: Double, y: Double): Unit = noImpl //fun quadraticCurveTo(aCPx: Double, aCPy: Double, aX: Double, aY: Double): Unit = noImpl //fun bezierCurveTo(aCP1x: Double, aCP1y: Double, aCP2x: Double, aCP2y: Double, aX: Double, aY: Double): Unit = noImpl //fun splineThru(m: Matrix4): Unit = noImpl //fun arc(m: Matrix4): Unit = noImpl //fun absarc(m: Matrix4): Unit = noImpl //fun ellipse(m: Matrix4): Unit = noImpl //fun absellipse (m: Matrix4): Unit = noImpl //fun toShapes(): Unit = noImpl } @native("THREE.Shape") open class Shape() : Path(arrayOf()) { //Properties @native var lineDistances: Array<Double> = noImpl //Functions fun applyMatrix(m: Matrix4): Unit = noImpl }
mit
c37fcd15b47090d358afe4c2a39229c9
30.344262
120
0.691423
3.372134
false
false
false
false
kelemen/JTrim
buildSrc/src/main/kotlin/org/jtrim2/build/FinalReleaseTask.kt
1
2756
package org.jtrim2.build import java.io.File import java.nio.file.Files import javax.inject.Inject import org.gradle.api.DefaultTask import org.gradle.api.model.ObjectFactory import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction import org.gradle.kotlin.dsl.property import org.gradle.work.DisableCachingByDefault private const val VERSION_FILE = "version.txt" @DisableCachingByDefault(because = "We are always pushing new changes") open class FinalReleaseTask @Inject constructor(private val objects: ObjectFactory) : DefaultTask() { @Internal val repoServiceRef = objects.property<GitRepoService>() @Input val projectBaseVersion = objects.property<String>() @Input val projectVersion = objects.property<String>() @TaskAction fun finalizeRelease() { val projectVersion = projectVersion.get() val projectBaseVersion = projectBaseVersion.get() val repoService = repoServiceRef.get() val git = repoService.git(objects).jgit() val statusCommand = git.status() val status = statusCommand.call() if (status.untracked.isNotEmpty()) { throw RuntimeException("There are untracked files in the repository and so the release cannot be completed. Revert the changes already done manually.") } if (!status.isClean) { throw RuntimeException("The repository is not clean (contains uncommitted changes) and so the release cannot be completed. Revert the changes already done manually.") } val tagCommand = git.tag() tagCommand.name = "v$projectVersion" tagCommand.message = "Release of JTrim $projectVersion" tagCommand.call() val nextVersion = setNextVersion(repoService.repoRoot, projectBaseVersion) val addCommand = git.add() addCommand.addFilepattern(VERSION_FILE) addCommand.isUpdate = true addCommand.call() val commitCommand = git.commit() commitCommand.message = "Set the version to $nextVersion" commitCommand.call() println("New Release: $projectVersion, Next version = $nextVersion") } private fun setNextVersion(repoRoot: File, baseVersion: String): String { val nextVersion = incVersion(baseVersion) val versionFile = repoRoot.toPath().resolve(VERSION_FILE) Files.writeString(versionFile, nextVersion) return nextVersion } private fun incVersion(version: String): String { val sepIndex = version.lastIndexOf('.') val prefix = version.substring(0, sepIndex) val patchVersion = version.substring(sepIndex + 1).toInt() return prefix + '.' + (patchVersion + 1) } }
apache-2.0
d1c201c3cdc335bab42715391b1bb2a7
34.333333
178
0.698476
4.555372
false
false
false
false
xmartlabs/bigbang
ui/src/main/java/com/xmartlabs/bigbang/ui/common/recyclerview/RecyclerViewEmptySupport.kt
1
5164
package com.xmartlabs.bigbang.ui.common.recyclerview import android.content.Context import android.support.annotation.IdRes import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.view.View import com.xmartlabs.bigbang.ui.R /** * [RecyclerView] subclass that automatically handles empty state. * * A [RecyclerView] is in an empty state when its adapter holds zero items, * or if the callback function [.isInEmptyState] is set and returns true. * * In the empty state, the [] will be hidden and a view will be shown. * The empty state view to be shown can be defined in two ways: * * 1. By means of [.setEmptyView] method * 2. By setting the attribute `app:emptyViewId` in the recycler view and point to a view in the hierarchy */ class RecyclerViewEmptySupport @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : RecyclerView(context, attrs, defStyle) { private var emptyView: View? = null @IdRes private var emptyViewId: Int = 0 private var isInEmptyState: ((RecyclerView) -> Boolean)? = null private val emptyObserver = object : RecyclerView.AdapterDataObserver() { override fun onChanged() { super.onChanged() showCorrectView() } override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { super.onItemRangeInserted(positionStart, itemCount) showCorrectView() } override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) { super.onItemRangeRemoved(positionStart, itemCount) showCorrectView() } override fun onItemRangeChanged(positionStart: Int, itemCount: Int) { super.onItemRangeChanged(positionStart, itemCount) showCorrectView() } override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) { super.onItemRangeMoved(fromPosition, toPosition, itemCount) showCorrectView() } } init { bindAttributes(context, attrs) initializeEmptyView() } /** * Extracts the resource id from the [RecyclerView] attributes, if present. * * @param context The Context the view is running in, through which it can * * access the current theme, resources, etc. * * * @param attrs The attributes of the XML tag that is inflating the view. */ private fun bindAttributes(context: Context, attrs: AttributeSet?) { val attributes = context.obtainStyledAttributes(attrs, R.styleable.RecyclerViewEmptySupport, 0, 0) emptyViewId = attributes.getResourceId(R.styleable.RecyclerViewEmptySupport_emptyView, -1) attributes.recycle() } /** Initializes the empty view using the resource identifier [.emptyViewId], if it exists. */ private fun initializeEmptyView() { if (emptyViewId > 0) { post { rootView.findViewById<View>(emptyViewId)?.let { view -> emptyView = view showCorrectView() } } } } /** * Decides which view should be visible (recycler view or empty view) and shows it * To do that, it checks for the presence of [.isInEmptyState] callback and uses it to determine whether or not * the empty view should be shown. * If the callback was not set, then it uses the adapter item count information, where zero elements means the empty * state should be shown. */ private fun showCorrectView() { val adapter = adapter emptyView?.let { val hasItems = isInEmptyState?.let { it(this) } ?: (adapter == null || adapter.itemCount > 0) it.visibility = if (hasItems) View.GONE else View.VISIBLE visibility = if (hasItems) View.VISIBLE else View.GONE } } override fun setAdapter(adapter: RecyclerView.Adapter<*>?) { super.setAdapter(adapter) adapter?.let { try { adapter.registerAdapterDataObserver(emptyObserver) } catch (ignored: IllegalStateException) { // the observer is already registered } } emptyObserver.onChanged() } /** * Sets the empty view. * If null, the [.showCorrectView] method will yield no further effect, unless the [.emptyViewId] was * set and the [.resetState] is called. * * @param emptyView the empty view to show on empty state */ fun setEmptyView(emptyView: View?) { this.emptyView = emptyView } /** * Sets the empty state callback check. * The callback will be called each time a decision is to be made to whether show or hide the empty view. * * @param isInEmptyState the callback function to determine if the recycler view is in an empty state */ fun setIsInEmptyState(isInEmptyState: ((RecyclerView) -> Boolean)?) { this.isInEmptyState = isInEmptyState showCorrectView() } /** * Resets the state of the recycler view. * If no empty view is present, an attempt to retrieve it from the resource id will be made. * If it's already present, then the recycler view will check whether or not is in an empty state and act * accordingly (show/hide the empty view/itself). */ fun resetState() { if (emptyView == null) { initializeEmptyView() } else { showCorrectView() } } }
apache-2.0
bfddffcd627a09021f4c6772deb6c83d
32.751634
118
0.69694
4.394894
false
false
false
false
sybila/terminal-components
src/main/java/com/github/sybila/PivotChooser.kt
1
4902
package com.github.sybila import com.github.sybila.checker.Solver import com.github.sybila.checker.StateMap import com.github.sybila.checker.map.mutable.HashStateMap interface PivotChooser<T: Any> { fun choose(universe: StateMap<T>): StateMap<T> } class NaivePivotChooser<T: Any>(solver: Solver<T>) : PivotChooser<T>, Solver<T> by solver { override fun choose(universe: StateMap<T>): StateMap<T> { var uncovered = universe.entries().asSequence().fold(ff) { a, b -> a or b.second } val result = HashStateMap(ff, emptyMap()) while (uncovered.isSat()) { val (s, p) = universe.entries().asSequence().first { (it.second and uncovered).isSat() } result.setOrUnion(s, p and uncovered) uncovered = uncovered and p.not() } return result } } @Suppress("unused") class VolumePivotChooser<T: Any>(private val solver: ExplicitOdeFragment<T>) : PivotChooser<T>, Solver<T> by solver { override fun choose(universe: StateMap<T>): StateMap<T> { solver.run { // add volume to scope var uncovered = universe.entries().asSequence().fold(ff) { a, b -> a or b.second } val result = HashStateMap(ff, emptyMap()) while (uncovered.isSat()) { val (s, p) = universe.entries().asSequence().maxBy { (it.second and uncovered).volume() /// x.size }!! result.setOrUnion(s, p and uncovered) uncovered = uncovered and p.not() } return result } } } open class StructurePivotChooser<T: Any>(model: ExplicitOdeFragment<T>) : PivotChooser<T>, Solver<T> by model { // parameter sets for different predecessor - successor differences // [0] - no difference, [1] - one more predecessor than successor, ... protected val degreeDifference = model.run { Array<List<T>>(stateCount) { state -> fun MutableList<T>.setOrUnion(index: Int, value: T) { while (this.size <= index) add(ff) this[index] = this[index] or value } val successors = Count(model) state.successors(true).forEach { t -> if (t.target != state) { successors.push(t.bound) } } state.successors(true).asSequence().fold(Count(model)) { count, t -> if (t.target != state) { count.push(t.bound) } count } val predecessors = state.predecessors(true).asSequence().fold(Count(model)) { count, t -> if (t.target != state) { count.push(t.bound) } count } val result = ArrayList<T>() for (pI in (0 until predecessors.size)) { val p = predecessors[pI] for (sI in (0 until successors.size)) { val s = successors[sI] if (pI >= sI) { val k = p and s if (k.isSat()) { result.setOrUnion(pI - sI, k) } } } } result } } override fun choose(universe: StateMap<T>): StateMap<T> { var uncovered = universe.entries().asSequence().fold(ff) { a, b -> a or b.second } val result = HashStateMap(ff, emptyMap()) while (uncovered.isSat()) { val (s, p) = universe.entries().asSequence().maxBy { (s, p) -> degreeDifference[s].indexOfLast { (it and p and uncovered).isSat() } }!! val takeWith = p and uncovered and degreeDifference[s].last { (it and p and uncovered).isSat() } result.setOrUnion(s, takeWith) uncovered = uncovered and takeWith.not() } return result } } open class StructureAndCardinalityPivotChooser<T: Any>(model: ExplicitOdeFragment<T>) : StructurePivotChooser<T>(model) { override fun choose(universe: StateMap<T>): StateMap<T> { var uncovered = universe.entries().asSequence().fold(ff) { a, b -> a or b.second } val result = HashStateMap(ff, emptyMap()) while (uncovered.isSat()) { val (s, p) = universe.entries().asSequence().maxBy { (s, p) -> degreeDifference[s].indexOfLast { (it and p and uncovered).isSat() } }!! val takeWith = p and uncovered result.setOrUnion(s, takeWith) uncovered = uncovered and takeWith.not() } return result } }
gpl-3.0
23162c9187efcd0c7a5e7d24708e50ad
40.201681
121
0.51428
4.353464
false
false
false
false
7449/Album
core/src/main/java/com/gallery/core/extensions/ExtensionsPermission.kt
1
782
package com.gallery.core.extensions import android.Manifest import android.content.Context import android.content.pm.PackageManager import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment enum class PermissionCode { READ, WRITE } /** 检查相机权限 */ fun Fragment.checkCameraPermissionExpand() = requireContext().checkSelfPermissionExpand(Manifest.permission.CAMERA) /** 检查读写权限 */ fun Fragment.checkWritePermissionExpand() = requireContext().checkSelfPermissionExpand(Manifest.permission.WRITE_EXTERNAL_STORAGE) /** 判断是否获得权限 */ fun Context.checkSelfPermissionExpand(name: String) = ContextCompat.checkSelfPermission(this, name) == PackageManager.PERMISSION_GRANTED
mpl-2.0
45be88f037dca876589c8b49f4ba7131
29
94
0.766846
4.416667
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/TextToSpeechActionType.kt
1
685
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.http_shortcuts.scripting.ActionAlias import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO class TextToSpeechActionType : BaseActionType() { override val type = TYPE override fun fromDTO(actionDTO: ActionDTO) = TextToSpeechAction( message = actionDTO.getString(0) ?: "", language = actionDTO.getString(1) ?: "", ) override fun getAlias() = ActionAlias( functionName = FUNCTION_NAME, parameters = 2, ) companion object { private const val TYPE = "text_to_speech" private const val FUNCTION_NAME = "speak" } }
mit
96e7b81f82a91c2dba764e8c905e7055
27.541667
68
0.686131
4.126506
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/ImageGetter.kt
1
3830
package ch.rmy.android.http_shortcuts.utils import android.content.Context import android.graphics.BitmapFactory import android.graphics.drawable.Drawable import android.text.Html.ImageGetter import android.util.Base64 import androidx.core.content.res.ResourcesCompat import androidx.core.graphics.drawable.toDrawable import ch.rmy.android.framework.extensions.dimen import ch.rmy.android.framework.extensions.logException import ch.rmy.android.http_shortcuts.R import com.squareup.picasso.MemoryPolicy import com.squareup.picasso.NetworkPolicy import com.squareup.picasso.Picasso import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class ImageGetter( private val context: Context, private val onImageLoaded: () -> Unit, private val coroutineScope: CoroutineScope, ) : ImageGetter { override fun getDrawable(source: String?): Drawable { val placeholderSize = dimen(context, R.dimen.html_image_placeholder_size) val drawableWrapper = DrawableWrapper(ResourcesCompat.getDrawable(context.resources, R.drawable.image_placeholder, null)!!) drawableWrapper.setBounds(0, 0, placeholderSize, placeholderSize) if (source == null) { return drawableWrapper } coroutineScope.launch { try { val drawable = withContext(Dispatchers.IO) { when { source.isBase64EncodedImage() -> { try { val imageAsBytes = source.getBase64ImageData() BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.size) ?: throw UnsupportedImageSourceException() } catch (e: IllegalArgumentException) { throw UnsupportedImageSourceException() } } source.run { startsWith("https://", ignoreCase = true) || startsWith("http://", ignoreCase = true) } -> { Picasso.get() .load(source) .networkPolicy(NetworkPolicy.NO_CACHE) .memoryPolicy(MemoryPolicy.NO_CACHE) .get() } else -> throw UnsupportedImageSourceException() } .toDrawable(context.resources) } drawableWrapper.wrappedDrawable = drawable drawableWrapper.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight) onImageLoaded() } catch (e: CancellationException) { throw e } catch (e: Exception) { if (e !is UnsupportedImageSourceException) { logException(e) } drawableWrapper.wrappedDrawable = ResourcesCompat.getDrawable(context.resources, R.drawable.bitsies_cancel, null)!! drawableWrapper.setBounds(0, 0, placeholderSize * 2, placeholderSize * 2) onImageLoaded() } } return drawableWrapper } private class UnsupportedImageSourceException : Exception() companion object { private fun String.isBase64EncodedImage(): Boolean = matches("^data:image/[^;]+;base64,.+".toRegex(RegexOption.IGNORE_CASE)) private fun String.getBase64ImageData(): ByteArray = dropWhile { it != ',' } .drop(1) .let { Base64.decode(it, Base64.DEFAULT) } } }
mit
9e6207c4c41c88a2d1ccdbda85e260f5
41.087912
131
0.589817
5.487106
false
false
false
false
7449/Album
wechat/src/main/java/com/gallery/ui/wechat/widget/WeChatGallerySelectItem.kt
1
1711
package com.gallery.ui.wechat.widget import android.content.Context import android.graphics.Color import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import android.widget.ImageView import com.gallery.core.entity.ScanEntity import com.gallery.core.extensions.hideExpand import com.gallery.core.extensions.showExpand import com.gallery.ui.wechat.databinding.WechatGalleryLayoutSelectItemBinding class WeChatGallerySelectItem @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private val viewBinding: WechatGalleryLayoutSelectItemBinding = WechatGalleryLayoutSelectItemBinding.inflate(LayoutInflater.from(getContext()), this, true) init { setBackgroundColor(Color.BLACK) } val imageView: ImageView get() = viewBinding.selectWeChatImageView private val gifView: ImageView get() = viewBinding.selectWeChatGif private val videoView: ImageView get() = viewBinding.selectWeChatVideo private val view: View get() = viewBinding.selectWeChatView fun update(scanEntity: ScanEntity, idList: List<Long>, isPrev: Boolean) { gifView.visibility = if (scanEntity.isGif) View.VISIBLE else View.GONE videoView.visibility = if (scanEntity.isVideo) View.VISIBLE else View.GONE if (!isPrev) { view.hideExpand() return } idList.find { it == scanEntity.id }?.let { view.showExpand() } ?: view.hideExpand() } }
mpl-2.0
395564e10c38527eaca7ba9b8dad6219
30.942308
103
0.6955
4.587131
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/preference/BingRulePreference.kt
2
7052
/* * Copyright 2018 New Vector Ltd * * 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 im.vector.preference import android.content.Context import android.text.TextUtils import android.util.AttributeSet import android.view.View import android.widget.RadioGroup import android.widget.TextView import androidx.preference.PreferenceViewHolder import im.vector.R import org.matrix.androidsdk.rest.model.bingrules.BingRule class BingRulePreference : VectorPreference { /** * @return the selected bing rule */ var rule: BingRule? = null private set constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) init { layoutResource = R.layout.vector_preference_bing_rule } /** * @return the bing rule status index */ val ruleStatusIndex: Int get() { if (null != rule) { if (TextUtils.equals(rule!!.ruleId, BingRule.RULE_ID_SUPPRESS_BOTS_NOTIFICATIONS)) { if (rule!!.shouldNotNotify()) { return if (rule!!.isEnabled) { NOTIFICATION_OFF_INDEX } else { NOTIFICATION_SILENT_INDEX } } else if (rule!!.shouldNotify()) { return NOTIFICATION_NOISY_INDEX } } if (rule!!.isEnabled) { return if (rule!!.shouldNotNotify()) { NOTIFICATION_OFF_INDEX } else if (null != rule!!.notificationSound) { NOTIFICATION_NOISY_INDEX } else { NOTIFICATION_SILENT_INDEX } } } return NOTIFICATION_OFF_INDEX } /** * Update the bing rule. * * @param aBingRule */ fun setBingRule(aBingRule: BingRule) { rule = aBingRule refreshSummary() } /** * Refresh the summary */ private fun refreshSummary() { summary = context.getString(when (ruleStatusIndex) { NOTIFICATION_OFF_INDEX -> R.string.notification_off NOTIFICATION_SILENT_INDEX -> R.string.notification_silent else -> R.string.notification_noisy }) } /** * Create a bing rule with the updated required at index. * * @param index index * @return a bing rule with the updated flags / null if there is no update */ fun createRule(index: Int): BingRule? { var rule: BingRule? = null if (null != this.rule && index != ruleStatusIndex) { rule = BingRule(this.rule!!) if (TextUtils.equals(rule.ruleId, BingRule.RULE_ID_SUPPRESS_BOTS_NOTIFICATIONS)) { when (index) { NOTIFICATION_OFF_INDEX -> { rule.isEnabled = true rule.setNotify(false) } NOTIFICATION_SILENT_INDEX -> { rule.isEnabled = false rule.setNotify(false) } NOTIFICATION_NOISY_INDEX -> { rule.isEnabled = true rule.setNotify(true) rule.notificationSound = BingRule.ACTION_VALUE_DEFAULT } } return rule } if (NOTIFICATION_OFF_INDEX == index) { if (TextUtils.equals(this.rule!!.kind, BingRule.KIND_UNDERRIDE) || TextUtils.equals(rule.ruleId, BingRule.RULE_ID_SUPPRESS_BOTS_NOTIFICATIONS)) { rule.setNotify(false) } else { rule.isEnabled = false } } else { rule.isEnabled = true rule.setNotify(true) rule.setHighlight(!TextUtils.equals(this.rule!!.kind, BingRule.KIND_UNDERRIDE) && !TextUtils.equals(rule.ruleId, BingRule.RULE_ID_INVITE_ME) && NOTIFICATION_NOISY_INDEX == index) if (NOTIFICATION_NOISY_INDEX == index) { rule.notificationSound = if (TextUtils.equals(rule.ruleId, BingRule.RULE_ID_CALL)) BingRule.ACTION_VALUE_RING else BingRule.ACTION_VALUE_DEFAULT } else { rule.removeNotificationSound() } } } return rule } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) holder.itemView?.findViewById<TextView>(android.R.id.summary)?.visibility = View.GONE holder.itemView?.setOnClickListener(null) holder.itemView?.setOnLongClickListener(null) val radioGroup = holder.findViewById(R.id.bingPreferenceRadioGroup) as? RadioGroup radioGroup?.setOnCheckedChangeListener(null) when (ruleStatusIndex) { NOTIFICATION_OFF_INDEX -> { radioGroup?.check(R.id.bingPreferenceRadioBingRuleOff) } NOTIFICATION_SILENT_INDEX -> { radioGroup?.check(R.id.bingPreferenceRadioBingRuleSilent) } else -> { radioGroup?.check(R.id.bingPreferenceRadioBingRuleNoisy) } } radioGroup?.setOnCheckedChangeListener { group, checkedId -> when (checkedId) { R.id.bingPreferenceRadioBingRuleOff -> { onPreferenceChangeListener?.onPreferenceChange(this, NOTIFICATION_OFF_INDEX) } R.id.bingPreferenceRadioBingRuleSilent -> { onPreferenceChangeListener?.onPreferenceChange(this, NOTIFICATION_SILENT_INDEX) } R.id.bingPreferenceRadioBingRuleNoisy -> { onPreferenceChangeListener?.onPreferenceChange(this, NOTIFICATION_NOISY_INDEX) } } } } companion object { // index in mRuleStatuses private const val NOTIFICATION_OFF_INDEX = 0 private const val NOTIFICATION_SILENT_INDEX = 1 private const val NOTIFICATION_NOISY_INDEX = 2 } }
apache-2.0
a56607b20757146082c437c0de209c71
33.237864
105
0.55502
5.033547
false
false
false
false
sky-map-team/stardroid
app/src/main/java/com/google/android/stardroid/math/LatLong.kt
1
1788
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.stardroid.math /** * A simple struct for latitude and longitude. */ data class LatLong(private val _latitudeDeg: Float, private val _longitudeDeg: Float) { val latitude = _latitudeDeg.coerceIn(-90f, 90f) val longitude = flooredMod(_longitudeDeg + 180f, 360f) - 180f /** * This constructor automatically downcasts the latitude and longitude to * floats, so that the previous constructor can be used. It is added as a * convenience method, since many of the GPS methods return doubles. */ constructor(latitude: Double, longitude: Double) : this( latitude.toFloat(), longitude.toFloat() ) /** * Angular distance between the two points. * @param other * @return degrees */ fun distanceFrom(other: LatLong): Float { // Some misuse of the astronomy math classes val otherPnt = getGeocentricCoords( other.longitude, other.latitude ) val thisPnt = getGeocentricCoords( longitude, latitude ) val cosTheta = thisPnt.cosineSimilarity(otherPnt) return MathUtils.acos(cosTheta) * 180f / PI } }
apache-2.0
c78efc8e98096f6497b0bd0e6f8e9b7a
34.078431
87
0.676174
4.277512
false
false
false
false
dodyg/Kotlin101
src/Functions/Cascades/Cascades.kt
1
1029
package Functions.Cascades fun main(Args : Array<String>) { /* This call utilizes extension function and infix call. It is handy to deal with pesky Java object initializations */ var superman = Superman() with { name = "Lux Luthor" punch() kick() sidekick = Spiderman() with { special() } } } public infix fun <T> T.with(operations : T.() -> Unit) : T { operations() return this } public class Superman() { var name : String = "Clark Kent" var sidekick : Sidekick = Robin() public fun punch() : Unit = println("$name punches") public fun fly() : Unit = println("$name flies") public fun kick() : Unit = println("$name kicks") } interface Sidekick { public fun special() } public class Spiderman() : Sidekick { var name : String = "Peter Parker" override fun special() = println("$name webs") } public class Robin() : Sidekick { var name : String = "Robin" override fun special() = println("$name is useless") }
bsd-3-clause
473dcf19e54a8c89f1468006e4002c83
24.121951
122
0.61516
3.701439
false
false
false
false
blademainer/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/NetService.kt
3
4441
package org.jetbrains.builtInWebServer import com.intellij.execution.ExecutionException import com.intellij.execution.filters.TextConsoleBuilder import com.intellij.execution.process.OSProcessHandler import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.util.Consumer import com.intellij.util.net.NetUtils import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.AsyncValueLoader import org.jetbrains.concurrency.Promise import org.jetbrains.util.concurrency import org.jetbrains.util.concurrency.toPromise import javax.swing.Icon val LOG: Logger = Logger.getInstance(NetService::class.java) public abstract class NetService @jvmOverloads protected constructor(protected val project: Project, private val consoleManager: ConsoleManager = ConsoleManager()) : Disposable { protected val processHandler: AsyncValueLoader<OSProcessHandler> = object : AsyncValueLoader<OSProcessHandler>() { override fun isCancelOnReject() = true private fun doGetProcessHandler(port: Int): OSProcessHandler? { try { return createProcessHandler(project, port) } catch (e: ExecutionException) { LOG.error(e) return null } } override fun load(promise: AsyncPromise<OSProcessHandler>): Promise<OSProcessHandler> { val port = NetUtils.findAvailableSocketPort() val processHandler = doGetProcessHandler(port) if (processHandler == null) { promise.setError("rejected") return promise } promise.rejected(Consumer { processHandler.destroyProcess() Promise.logError(LOG, it) }) val processListener = MyProcessAdapter() processHandler.addProcessListener(processListener) processHandler.startNotify() if (promise.getState() == Promise.State.REJECTED) { return promise } ApplicationManager.getApplication().executeOnPooledThread(object : Runnable { override fun run() { if (promise.getState() != Promise.State.REJECTED) { try { connectToProcess(promise.toPromise(), port, processHandler, processListener) } catch (e: Throwable) { if (!promise.setError(e)) { LOG.error(e) } } } } }) return promise } override fun disposeResult(processHandler: OSProcessHandler) { try { closeProcessConnections() } finally { processHandler.destroyProcess() } } } throws(ExecutionException::class) protected abstract fun createProcessHandler(project: Project, port: Int): OSProcessHandler? protected open fun connectToProcess(promise: concurrency.AsyncPromise<OSProcessHandler>, port: Int, processHandler: OSProcessHandler, errorOutputConsumer: Consumer<String>) { promise.setResult(processHandler) } protected abstract fun closeProcessConnections() override fun dispose() { processHandler.reset() } protected open fun configureConsole(consoleBuilder: TextConsoleBuilder) { } protected abstract fun getConsoleToolWindowId(): String protected abstract fun getConsoleToolWindowIcon(): Icon public open fun getConsoleToolWindowActions(): ActionGroup = DefaultActionGroup() private inner class MyProcessAdapter : ProcessAdapter(), Consumer<String> { override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) { print(event.getText(), ConsoleViewContentType.getConsoleViewType(outputType)) } private fun print(text: String, contentType: ConsoleViewContentType) { consoleManager.getConsole(this@NetService).print(text, contentType) } override fun processTerminated(event: ProcessEvent) { processHandler.reset() print("${getConsoleToolWindowId()} terminated\n", ConsoleViewContentType.SYSTEM_OUTPUT) } override fun consume(message: String) { print(message, ConsoleViewContentType.ERROR_OUTPUT) } } }
apache-2.0
e1066a4412f0e77d0857b5186a180ce8
33.434109
178
0.731817
5.146002
false
false
false
false
aosp-mirror/platform_frameworks_support
buildSrc/src/main/kotlin/androidx/build/PublishDocsRules.kt
1
8067
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build import androidx.build.ArtifactsPredicate.All import androidx.build.ArtifactsPredicate.Exact import androidx.build.ArtifactsPredicate.Group import androidx.build.Strategy.TipOfTree import androidx.build.Strategy.Prebuilts import androidx.build.Strategy.Ignore val RELEASE_RULE = docsRules("public") { val defaultVersion = "1.0.0-alpha3" prebuilts(LibraryGroups.ANNOTATION, defaultVersion) prebuilts(LibraryGroups.APPCOMPAT, defaultVersion) prebuilts(LibraryGroups.ASYNCLAYOUTINFLATER, defaultVersion) prebuilts(LibraryGroups.BROWSER, defaultVersion) prebuilts(LibraryGroups.CAR, defaultVersion) .addStubs("car/car-stubs/android.car.jar") prebuilts(LibraryGroups.CARDVIEW, defaultVersion) prebuilts(LibraryGroups.COLLECTION, defaultVersion) prebuilts(LibraryGroups.CONTENTPAGER, defaultVersion) prebuilts(LibraryGroups.COORDINATORLAYOUT, defaultVersion) prebuilts(LibraryGroups.CORE, defaultVersion) prebuilts(LibraryGroups.CURSORADAPTER, defaultVersion) prebuilts(LibraryGroups.CUSTOMVIEW, defaultVersion) prebuilts(LibraryGroups.DOCUMENTFILE, defaultVersion) prebuilts(LibraryGroups.DRAWERLAYOUT, defaultVersion) prebuilts(LibraryGroups.DYNAMICANIMATION, defaultVersion) prebuilts(LibraryGroups.EMOJI, defaultVersion) prebuilts(LibraryGroups.EXIFINTERFACE, defaultVersion) prebuilts(LibraryGroups.FRAGMENT, defaultVersion) prebuilts(LibraryGroups.GRIDLAYOUT, defaultVersion) prebuilts(LibraryGroups.HEIFWRITER, defaultVersion) prebuilts(LibraryGroups.INTERPOLATOR, defaultVersion) prebuilts(LibraryGroups.LEANBACK, defaultVersion) prebuilts(LibraryGroups.LEGACY, defaultVersion) prebuilts(LibraryGroups.LOADER, defaultVersion) prebuilts(LibraryGroups.LOCALBROADCASTMANAGER, defaultVersion) prebuilts(LibraryGroups.MEDIA, defaultVersion) prebuilts(LibraryGroups.MEDIAROUTER, defaultVersion) prebuilts(LibraryGroups.PALETTE, defaultVersion) prebuilts(LibraryGroups.PERCENTLAYOUT, defaultVersion) prebuilts(LibraryGroups.PREFERENCE, defaultVersion) prebuilts(LibraryGroups.PRINT, defaultVersion) prebuilts(LibraryGroups.RECOMMENDATION, defaultVersion) prebuilts(LibraryGroups.RECYCLERVIEW, defaultVersion) prebuilts(LibraryGroups.SLICE, defaultVersion) prebuilts(LibraryGroups.SLIDINGPANELAYOUT, defaultVersion) prebuilts(LibraryGroups.SWIPEREFRESHLAYOUT, defaultVersion) prebuilts(LibraryGroups.TEXTCLASSIFIER, defaultVersion) prebuilts(LibraryGroups.TRANSITION, defaultVersion) prebuilts(LibraryGroups.TVPROVIDER, defaultVersion) prebuilts(LibraryGroups.VECTORDRAWABLE, defaultVersion) prebuilts(LibraryGroups.VIEWPAGER, defaultVersion) prebuilts(LibraryGroups.WEAR, defaultVersion) .addStubs("wear/wear_stubs/com.google.android.wearable-stubs.jar") prebuilts(LibraryGroups.WEBKIT, defaultVersion) val flatfootVersion = "2.0.0-alpha1" prebuilts(LibraryGroups.ROOM, flatfootVersion) prebuilts(LibraryGroups.PERSISTENCE, flatfootVersion) prebuilts(LibraryGroups.LIFECYCLE, flatfootVersion) prebuilts(LibraryGroups.ARCH_CORE, flatfootVersion) prebuilts(LibraryGroups.PAGING, flatfootVersion) prebuilts(LibraryGroups.NAVIGATION, "1.0.0-alpha01") prebuilts(LibraryGroups.WORKMANAGER, "1.0.0-alpha02") default(Ignore) } val TIP_OF_TREE = docsRules("tipOfTree") { default(TipOfTree) } /** * Rules are resolved in addition order. So if you have two rules that specify how docs should be * built for a module, first defined rule wins. */ fun docsRules(name: String, init: PublishDocsRulesBuilder.() -> Unit): PublishDocsRules { val f = PublishDocsRulesBuilder(name) f.init() return f.build() } class PublishDocsRulesBuilder(private val name: String) { private val rules: MutableList<DocsRule> = mutableListOf() /** * docs for projects within [groupName] will be built from sources. */ fun tipOfTree(groupName: String) { rules.add(DocsRule(Group(groupName), TipOfTree)) } /** * docs for a project with the given [groupName] and [name] will be built from sources. */ fun tipOfTree(groupName: String, name: String) { rules.add(DocsRule(Exact(groupName, name), TipOfTree)) } /** * docs for a project with the given [groupName] and [name] will be built from a prebuilt with * the given [version]. */ fun prebuilts(groupName: String, moduleName: String, version: String) { rules.add(DocsRule(Exact(groupName, moduleName), Prebuilts(Version(version)))) } /** * docs for projects within [groupName] will be built from prebuilts with the given [version] */ fun prebuilts(groupName: String, version: String) = prebuilts(groupName, Version(version)) /** * docs for projects within [groupName] will be built from prebuilts with the given [version] */ fun prebuilts(groupName: String, version: Version): Prebuilts { val strategy = Prebuilts(version) rules.add(DocsRule(Group(groupName), strategy)) return strategy } /** * defines a default strategy for building docs */ fun default(strategy: Strategy) { rules.add(DocsRule(All, strategy)) } /** * docs for projects within [groupName] won't be built */ fun ignore(groupName: String) { rules.add(DocsRule(Group(groupName), Ignore)) } /** * docs for a specified project won't be built */ fun ignore(groupName: String, name: String) { rules.add(DocsRule(Exact(groupName, name), Ignore)) } fun build() = PublishDocsRules(name, rules) } sealed class ArtifactsPredicate { abstract fun apply(inGroup: String, inName: String): Boolean object All : ArtifactsPredicate() { override fun apply(inGroup: String, inName: String) = true } class Group(val group: String) : ArtifactsPredicate() { override fun apply(inGroup: String, inName: String) = inGroup == group override fun toString() = "\"$group\"" } class Exact(val group: String, val name: String) : ArtifactsPredicate() { override fun apply(inGroup: String, inName: String) = group == inGroup && name == inName override fun toString() = "\"$group\", \"$name\"" } } data class DocsRule(val predicate: ArtifactsPredicate, val strategy: Strategy) { override fun toString(): String { if (predicate is All) { return "default($strategy)" } return when (strategy) { is Prebuilts -> "prebuilts($predicate, \"${strategy.version}\")" is Ignore -> "ignore($predicate)" is TipOfTree -> "tipOfTree($predicate)" } } } sealed class Strategy { object TipOfTree : Strategy() object Ignore : Strategy() class Prebuilts(val version: Version) : Strategy() { var stubs: MutableList<String>? = null fun addStubs(path: String) { if (stubs == null) { stubs = mutableListOf() } stubs!!.add(path) } override fun toString() = "Prebuilts(\"$version\")" } } class PublishDocsRules(val name: String, private val rules: List<DocsRule>) { fun resolve(groupName: String, moduleName: String): DocsRule { return rules.find { it.predicate.apply(groupName, moduleName) } ?: throw Error() } }
apache-2.0
fdbfdc7687b32c281d245aa36713f486
37.602871
98
0.713648
4.22356
false
false
false
false
ZoranPandovski/al-go-rithms
sort/bubble_sort/kotlin/BubbleSort.kt
3
567
import java.util.Arrays fun bubbleSort(arr: Array<Int>) { var swapOccurred: Boolean var len = arr.lastIndex do { swapOccurred = false for (i in 0 until len) { if (arr[i] > arr[i+1]) { arr[i] = arr[i+1].also {arr[i+1] = arr[i]} swapOccurred = true } } len-- } while (swapOccurred) } fun main(args: Array<String>) { val arr = arrayOf(1, 3, 5, 4, 2, 6, 8, 9, 7, 10, 13, 15, 17, 16, 14, 12, 19, 18, 11) bubbleSort(arr) println(Arrays.toString(arr)) }
cc0-1.0
4a826ff59aa4317c630cf1520bca0c28
21.72
88
0.507937
3.081522
false
false
false
false
samthor/intellij-community
platform/configuration-store-impl/src/ModuleStateStorageManager.kt
17
3332
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.ide.highlighter.ModuleFileType import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.StateStorageOperation import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.TrackingPathMacroSubstitutor import com.intellij.openapi.module.Module import com.intellij.openapi.module.impl.ModuleEx import com.intellij.openapi.module.impl.ModuleManagerImpl import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.PathUtilRt import org.jdom.Element class ModuleStateStorageManager(macroSubstitutor: TrackingPathMacroSubstitutor, module: Module) : StateStorageManagerImpl("module", macroSubstitutor, module) { override fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation) = StoragePathMacros.MODULE_FILE override fun pathRenamed(oldPath: String, newPath: String, event: VFileEvent?) { try { super.pathRenamed(oldPath, newPath, event) } finally { val requestor = event?.getRequestor() if (requestor == null || requestor !is StateStorage /* not renamed as result of explicit rename */) { val module = componentManager as ModuleEx val oldName = module.getName() module.rename(StringUtil.trimEnd(PathUtilRt.getFileName(newPath), ModuleFileType.DOT_DEFAULT_EXTENSION)) ModuleManagerImpl.getInstanceImpl(module.getProject()).fireModuleRenamedByVfsEvent(module, oldName) } } } override fun beforeElementLoaded(element: Element) { val optionElement = Element("component").setAttribute("name", "DeprecatedModuleOptionManager") val iterator = element.getAttributes().iterator() for (attribute in iterator) { if (attribute.getName() != ProjectStateStorageManager.VERSION_OPTION) { iterator.remove() optionElement.addContent(Element("option").setAttribute("key", attribute.getName()).setAttribute("value", attribute.getValue())) } } element.addContent(optionElement) } override fun beforeElementSaved(element: Element) { val componentIterator = element.getChildren("component").iterator() for (component in componentIterator) { if (component.getAttributeValue("name") == "DeprecatedModuleOptionManager") { componentIterator.remove() for (option in component.getChildren("option")) { element.setAttribute(option.getAttributeValue("key"), option.getAttributeValue("value")) } break; } } // need be last for compat reasons element.setAttribute(ProjectStateStorageManager.VERSION_OPTION, "4") } }
apache-2.0
899fe202082c0e636c13a2ea3cf8c0bb
42.285714
159
0.752101
4.794245
false
true
false
false
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/maps/management/controllers/FotoOpdrachtController.kt
1
6003
package nl.rsdt.japp.jotial.maps.management.controllers import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.os.Parcel import android.os.Parcelable import android.util.Pair import com.google.android.gms.maps.model.MarkerOptions import com.google.gson.Gson import com.google.gson.reflect.TypeToken import nl.rsdt.japp.R import nl.rsdt.japp.application.Japp import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.jotial.data.structures.area348.BaseInfo import nl.rsdt.japp.jotial.data.structures.area348.FotoOpdrachtInfo import nl.rsdt.japp.jotial.io.AppData import nl.rsdt.japp.jotial.maps.management.MapItemUpdatable import nl.rsdt.japp.jotial.maps.management.MarkerIdentifier import nl.rsdt.japp.jotial.maps.management.StandardMapItemController import nl.rsdt.japp.jotial.maps.management.transformation.AbstractTransducer import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap import nl.rsdt.japp.jotial.maps.wrapper.IMarker import nl.rsdt.japp.jotial.net.apis.FotoApi import retrofit2.Call import retrofit2.Callback import java.util.* import kotlin.collections.ArrayList /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 31-7-2016 * Description... */ class FotoOpdrachtController (iJotiMap: IJotiMap): StandardMapItemController<FotoOpdrachtInfo, FotoOpdrachtController.FotoOpdrachtTransducer.Result>(iJotiMap) { override val id: String get() = CONTROLLER_ID override val storageId: String get() = STORAGE_ID override val bundleId: String get() = BUNDLE_ID override val transducer: FotoOpdrachtTransducer get() = FotoOpdrachtTransducer() override fun update(mode: String, callback: Callback<ArrayList<FotoOpdrachtInfo>>) { val api = Japp.getApi(FotoApi::class.java) when (mode) { MapItemUpdatable.MODE_ALL -> api.getAll(JappPreferences.accountKey).enqueue(callback) MapItemUpdatable.MODE_LATEST -> api.getAll(JappPreferences.accountKey).enqueue(callback) } } override fun searchFor(query: String): IMarker? { val results = ArrayList<BaseInfo>() var info: FotoOpdrachtInfo? for (i in items.indices) { info = items[i] var current: String? val items = arrayOf(info.info, info.extra) for (x in items.indices) { current = items[x] if (current?.toLowerCase(Locale.ROOT)?.startsWith(query)==true) results.add(info) } } return null } override fun provide(): MutableList<String> { val results = ArrayList<String>() for (info in items) { results.add(info.info?: "null") results.add(info.extra?: "null") } return results } class FotoOpdrachtTransducer : AbstractTransducer<ArrayList<FotoOpdrachtInfo>, FotoOpdrachtTransducer.Result>() { override fun load(): ArrayList<FotoOpdrachtInfo>? { return AppData.getObject<ArrayList<FotoOpdrachtInfo>>(STORAGE_ID, object : TypeToken<ArrayList<FotoOpdrachtInfo>>() {}.type) } override fun transduceToBundle(bundle: Bundle) { load()?.let { bundle.putParcelable(BUNDLE_ID, generate(it)) } } override fun generate(data: ArrayList<FotoOpdrachtInfo>): Result { if (data.isEmpty()) return Result() val result = Result() result.bundleId = BUNDLE_ID result.addItems(data) if (isSaveEnabled) { AppData.saveObjectAsJson(data, STORAGE_ID) } /** * Loops through each FotoOpdrachtInfo. */ for (info in data) { val identifier = MarkerIdentifier.Builder() .setType(MarkerIdentifier.TYPE_FOTO) .add("info", info.info) .add("extra", info.extra) .add("icon", info.associatedDrawable.toString()) .create() val mOptions = MarkerOptions() mOptions.anchor(0.5f, 0.5f) mOptions.position(info.latLng) mOptions.title(Gson().toJson(identifier)) val bm: Bitmap = if (info.klaar == 1) { BitmapFactory.decodeResource(Japp.instance!!.resources, R.drawable.camera_20x20_klaar) } else { BitmapFactory.decodeResource(Japp.instance!!.resources, R.drawable.camera_20x20) } result.add(Pair(mOptions, bm)) } return result } /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 31-7-2016 * Description... */ class Result : AbstractTransducer.StandardResult<FotoOpdrachtInfo> { constructor() /** * Reconstructs the result. * * @param in The parcel where the result was written to */ protected constructor(`in`: Parcel) : super(`in`) { items = `in`.createTypedArrayList(FotoOpdrachtInfo.CREATOR) } override fun writeToParcel(dest: Parcel, flags: Int) { super.writeToParcel(dest, flags) dest.writeTypedList(items) } companion object CREATOR: Parcelable.Creator<Result> { override fun createFromParcel(`in`: Parcel): Result { return Result(`in`) } override fun newArray(size: Int): Array<Result?> { return arrayOfNulls(size) } } } } companion object { val CONTROLLER_ID = "FotoOpdrachtController" val STORAGE_ID = "STORAGE_FOTO" val BUNDLE_ID = "FOTO" val REQUEST_ID = "REQUEST_FOTO" } }
apache-2.0
29b417ae932616a0b05a3ce7a8e64b69
31.983516
160
0.606363
4.35
false
false
false
false
blastrock/kaqui
app/src/main/java/org/kaqui/testactivities/TextTestFragment.kt
1
8882
package org.kaqui.testactivities import android.os.Build import android.os.Bundle import android.text.InputType import android.text.method.KeyListener import android.view.* import android.view.inputmethod.EditorInfo import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.fragment.app.Fragment import org.jetbrains.anko.* import org.jetbrains.anko.support.v4.UI import org.kaqui.* import org.kaqui.model.Certainty import org.kaqui.model.Kana import org.kaqui.model.getQuestionText import org.kaqui.model.text import java.util.* class TextTestFragment : Fragment(), TestFragment { companion object { private const val TAG = "TextTestFragment" const val defaultInputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS @JvmStatic fun newInstance() = TextTestFragment() } private lateinit var answerField: EditText private var answerKeyListener: KeyListener? = null private lateinit var correctAnswer: TextView private var answer: String? = null private lateinit var answerButtons: List<Button> private lateinit var nextButton: Button private lateinit var testQuestionLayout: TestQuestionLayout private val testFragmentHolder get() = (requireActivity() as TestFragmentHolder) private val testEngine get() = testFragmentHolder.testEngine private val testType get() = testFragmentHolder.testType private val currentKana get() = testEngine.currentQuestion.contents as Kana override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { super.onCreate(savedInstanceState) val questionMinSize = 30 val answerButtons = mutableListOf<Button>() testQuestionLayout = TestQuestionLayout() val mainBlock = UI { testQuestionLayout.makeMainBlock(requireActivity(), this, questionMinSize, forceLandscape = true) { wrapInScrollView(this) { verticalLayout { correctAnswer = textView { textAlignment = TextView.TEXT_ALIGNMENT_CENTER visibility = View.GONE textSize = 18f backgroundColor = requireContext().getColorFromAttr(R.attr.correctAnswerBackground) }.lparams(width = matchParent, height = wrapContent) answerField = editText { gravity = Gravity.CENTER inputType = defaultInputType if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO setOnEditorActionListener { v, actionId, event -> if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_NULL) if (event == null || event.action == KeyEvent.ACTION_DOWN) [email protected](v, Certainty.SURE) else if (event.action == KeyEvent.ACTION_UP) true else false else false } answerKeyListener = keyListener }.lparams(width = matchParent) linearLayout { val maybeButton = button(R.string.maybe) { setExtTint(R.attr.backgroundMaybe) setOnClickListener { [email protected](this, Certainty.MAYBE) } }.lparams(weight = 1f) val sureButton = button(R.string.sure) { setExtTint(R.attr.backgroundSure) setOnClickListener { [email protected](this, Certainty.SURE) } }.lparams(weight = 1f) answerButtons.add(maybeButton) answerButtons.add(sureButton) }.lparams(width = matchParent, height = wrapContent) linearLayout { val dontKnowButton = button(R.string.dont_know) { setExtTint(R.attr.backgroundDontKnow) setOnClickListener { [email protected](this, Certainty.DONTKNOW) } }.lparams(width = matchParent) answerButtons.add(dontKnowButton) }.lparams(width = matchParent, height = wrapContent) nextButton = button(R.string.next) { setOnClickListener { [email protected]() } } }.lparams(width = matchParent, height = wrapContent) } } }.view testQuestionLayout.questionText.setOnLongClickListener { if (testEngine.currentDebugData != null) showItemProbabilityData(requireContext(), testEngine.currentQuestion.text, testEngine.currentDebugData!!) true } this.answerButtons = answerButtons if (savedInstanceState != null) { answer = if (savedInstanceState.containsKey("answer")) savedInstanceState.getString("answer") else null } refreshQuestion() return mainBlock } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) if (answer != null) outState.putString("answer", answer!!) } private fun refreshState() { if (answer != null) { answerField.setText(answer!!, TextView.BufferType.NORMAL) answerField.backgroundColor = requireContext().getColorFromAttr(R.attr.wrongAnswerBackground) answerField.keyListener = null correctAnswer.text = currentKana.romaji correctAnswer.visibility = View.VISIBLE for (button in answerButtons) button.visibility = View.GONE nextButton.visibility = View.VISIBLE } else { answerField.text.clear() val attrs = requireContext().obtainStyledAttributes(intArrayOf(android.R.attr.editTextBackground)) answerField.background = attrs.getDrawable(0) attrs.recycle() answerField.inputType = defaultInputType correctAnswer.visibility = View.GONE for (button in answerButtons) button.visibility = View.VISIBLE nextButton.visibility = View.GONE } } override fun setSensible(e: Boolean) { nextButton.isClickable = e for (button in answerButtons) { button.isClickable = e } } override fun refreshQuestion() { testQuestionLayout.questionText.text = testEngine.currentQuestion.getQuestionText(testType) refreshState() answerField.requestFocus() } private fun onTextAnswerClicked(view: View, certainty: Certainty): Boolean { if (answer != null) { onNextClicked() return true } if (certainty == Certainty.DONTKNOW) answerField.text.clear() val result = if (certainty == Certainty.DONTKNOW) { Certainty.DONTKNOW } else { val answer = answerField.text.trim().toString().lowercase(Locale.ROOT) if (answer.isBlank()) return true if (answer == currentKana.romaji) { certainty } else { Certainty.DONTKNOW } } testFragmentHolder.onAnswer(view, result, null) if (result != Certainty.DONTKNOW) testFragmentHolder.nextQuestion() else { answer = answerField.text.toString() refreshState() } return true } private fun onNextClicked() { answer = null testFragmentHolder.nextQuestion() } }
mit
e94c3f697b28d895754bf2ee715b1181
37.960526
155
0.555843
5.679028
false
true
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/CompositeFixedGeneImpact.kt
1
4860
package org.evomaster.core.search.impact.impactinfocollection import org.evomaster.core.search.gene.root.CompositeFixedGene import org.evomaster.core.search.gene.Gene /** * this impact could be applied to CompositeFixedGene in general that only handles impacts of children * however, you could also create a specific impact for the gene, such as DateGeneImpact, ObjectGeneImpact */ class CompositeFixedGeneImpact( sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo, /** * key is index_name of the gene * value is the impact for the corresponding child gene */ val childrenImpacts : MutableMap<String, Impact> = mutableMapOf() ) : GeneImpact(sharedImpactInfo, specificImpactInfo){ companion object{ private fun getKey(index: Int, name: String) = "${index}_$name" } constructor( id : String, gene: CompositeFixedGene, ) : this( SharedImpactInfo(id), SpecificImpactInfo(), childrenImpacts= gene.getViewOfChildren().mapIndexed { index, g -> Pair(getKey(index, g.name), ImpactUtils.createGeneImpact(g, g.name)) }.toMap().toMutableMap()) override fun copy(): CompositeFixedGeneImpact { return CompositeFixedGeneImpact( shared.copy(), specific.copy(), childrenImpacts = childrenImpacts.map { Pair(it.key, it.value.copy()) }.toMap().toMutableMap()) } override fun clone(): CompositeFixedGeneImpact { return CompositeFixedGeneImpact( shared.clone(), specific.clone(), childrenImpacts = childrenImpacts.map { it.key to it.value.clone() }.toMap().toMutableMap() ) } fun getChildImpact(index: Int, name: String): Impact? = childrenImpacts[getKey(index, name)] override fun countImpactWithMutatedGeneWithContext(gc: MutatedGeneWithContext, noImpactTargets: Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean) { countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene) if (gc.previous == null && impactTargets.isNotEmpty()) return if (gc.current !is CompositeFixedGene) throw IllegalArgumentException("gc.current ${gc.current::class.java.simpleName} should be CompositeFixedGene") if (gc.previous == null){ gc.current.getViewOfChildren().forEachIndexed { index, i-> val fImpact = childrenImpacts[getKey(index, i.name)] as? GeneImpact ?:throw IllegalArgumentException("impact should be gene impact") val mutatedGeneWithContext = MutatedGeneWithContext(previous = null, current = i, action = "none", position = -1, numOfMutatedGene = gc.current.getViewOfChildren().size) fImpact.countImpactWithMutatedGeneWithContext(mutatedGeneWithContext, noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation) } return } if (gc.previous !is CompositeFixedGene) throw IllegalArgumentException("gc.previous ${gc.previous::class.java.simpleName} should be ObjectGene") val mutatedFields = gc.current.getViewOfChildren().zip(gc.previous.getViewOfChildren()) { cf, pf -> Pair(Pair(gc.current.getViewOfChildren().indexOf(cf), Pair(cf, pf)), cf.containsSameValueAs(pf)) }.filter { !it.second }.map { it.first } val onlyManipulation = mutatedFields.size > 1 && impactTargets.isNotEmpty() mutatedFields.forEach {p-> val g = p.second val fImpact = getChildImpact(p.first, g.first.name) as? GeneImpact?:throw IllegalArgumentException("impact should be gene impact") val mutatedGeneWithContext = MutatedGeneWithContext(previous = g.second, current = g.first, action = "none", position = -1, numOfMutatedGene = gc.numOfMutatedGene * mutatedFields.size) fImpact.countImpactWithMutatedGeneWithContext(mutatedGeneWithContext, noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation) } } override fun validate(gene: Gene): Boolean = gene is CompositeFixedGene override fun flatViewInnerImpact(): Map<String, Impact> { val map = mutableMapOf<String, Impact>() childrenImpacts.forEach { (t, u) -> map.putIfAbsent("${getId()}-$t", u) if (u is GeneImpact && u.flatViewInnerImpact().isNotEmpty()) map.putAll(u.flatViewInnerImpact()) } return map } override fun innerImpacts(): List<Impact> { return childrenImpacts.values.toList() } }
lgpl-3.0
f2c309eac3237df2b6beb8d92a91d8cd
48.10101
223
0.690329
4.919028
false
false
false
false
guildenstern70/KotlinLearn
src/main/kotlin/ifwhen.kt
1
834
/* * KOTLIN LEARN * * MIT License (MIT) * Copyright (c) 2015-2020 Alessio Saltarin * */ package net.littlelite.kotlinlearn fun ifelse(a: Int, b: Int): Int { return if (a > b) a else b } fun ifwhen(a: Int, b: Int): Int { val max: Int = if (a > b) a else b // As expression when (max) { 1 -> println("max == 1") 2 -> println("max == 2") else -> { // Note the block println("max is neither 1 nor 2") } } val validNumbers = arrayOf(1, 2, 3, 4) when (max) { in 1..10 -> println("max is in the range") in validNumbers -> println("max is valid") !in 10..20 -> println("max is outside the range") else -> println("none of the above") } println("max = $max") return max }
mit
32636acb1772c698da1e9f6a6d2f95ca
16.020408
57
0.5
3.296443
false
false
false
false
gradle/gradle
build-logic/binary-compatibility/src/test/kotlin/gradlebuild/binarycompatibility/AbstractBinaryCompatibilityTest.kt
2
13217
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gradlebuild.binarycompatibility import org.gradle.kotlin.dsl.* import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.UnexpectedBuildFailure import org.hamcrest.CoreMatchers import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.rules.TemporaryFolder import java.io.File import java.nio.file.Files abstract class AbstractBinaryCompatibilityTest { @get:Rule val tmpDir = TemporaryFolder() private val rootDir: File get() = tmpDir.root internal fun checkBinaryCompatibleKotlin(v1: String = "", v2: String, block: CheckResult.() -> Unit = {}): CheckResult = runKotlinBinaryCompatibilityCheck(v1, v2) { assertBinaryCompatible() block() } internal fun checkNotBinaryCompatibleKotlin(v1: String = "", v2: String, block: CheckResult.() -> Unit = {}): CheckResult = runKotlinBinaryCompatibilityCheck(v1, v2) { assertNotBinaryCompatible() block() } internal fun checkBinaryCompatibleJava(v1: String = "", v2: String, block: CheckResult.() -> Unit = {}): CheckResult = runJavaBinaryCompatibilityCheck(v1, v2) { assertBinaryCompatible() block() } internal fun checkNotBinaryCompatibleJava(v1: String = "", v2: String, block: CheckResult.() -> Unit = {}): CheckResult = runJavaBinaryCompatibilityCheck(v1, v2) { assertNotBinaryCompatible() block() } internal fun checkBinaryCompatible(v1: File.() -> Unit = {}, v2: File.() -> Unit = {}, block: CheckResult.() -> Unit = {}): CheckResult = runBinaryCompatibilityCheck(v1, v2) { assertBinaryCompatible() block() } internal fun checkNotBinaryCompatible(v1: File.() -> Unit = {}, v2: File.() -> Unit = {}, block: CheckResult.() -> Unit = {}): CheckResult = runBinaryCompatibilityCheck(v1, v2) { assertNotBinaryCompatible() block() } private fun CheckResult.assertBinaryCompatible() { assertTrue(richReport.toAssertionMessage("Expected to be compatible but the check failed"), isBinaryCompatible) } private fun CheckResult.assertNotBinaryCompatible() { assertFalse(richReport.toAssertionMessage("Expected to be breaking but the check passed"), isBinaryCompatible) } private fun RichReport.toAssertionMessage(message: String) = if (isEmpty) "$message with an empty report" else "$message\n${toText().prependIndent(" ")}" private fun runKotlinBinaryCompatibilityCheck(v1: String, v2: String, block: CheckResult.() -> Unit = {}): CheckResult = runBinaryCompatibilityCheck( v1 = { withFile( "kotlin/com/example/Source.kt", """ package com.example import org.gradle.api.Incubating import javax.annotation.Nullable $v1 """ ) }, v2 = { withFile( "kotlin/com/example/Source.kt", """ package com.example import org.gradle.api.Incubating import javax.annotation.Nullable $v2 """ ) }, block = block ) private fun runJavaBinaryCompatibilityCheck(v1: String, v2: String, block: CheckResult.() -> Unit = {}): CheckResult = runBinaryCompatibilityCheck( v1 = { withFile( "java/com/example/Source.java", """ package com.example; import org.gradle.api.Incubating; import javax.annotation.Nullable; $v1 """ ) }, v2 = { withFile( "java/com/example/Source.java", """ package com.example; import org.gradle.api.Incubating; import javax.annotation.Nullable; $v2 """ ) }, block = block ) /** * Runs the binary compatibility check against two source trees. * * The fixture build supports both Java and Kotlin sources. * * @param v1 sources producer for V1, receiver is the `src/main` directory * @param v2 sources producer for V2, receiver is the `src/main` directory * @param block convenience block invoked on the result * @return the check result */ private fun runBinaryCompatibilityCheck(v1: File.() -> Unit, v2: File.() -> Unit, block: CheckResult.() -> Unit = {}): CheckResult { rootDir.withFile("version.txt", "1.0") val inputBuildDir = rootDir.withUniqueDirectory("input-build").apply { withSettings("""include("v1", "v2", "binary-compatibility")""") withBuildScript( """ import gradlebuild.identity.extension.ModuleIdentityExtension plugins { base kotlin("jvm") version "$embeddedKotlinVersion" apply false } subprojects { apply(plugin = "gradlebuild.module-identity") apply(plugin = "kotlin") the<ModuleIdentityExtension>().baseName.set("api-module") repositories { mavenCentral() } dependencies { "implementation"(gradleApi()) "implementation"(kotlin("stdlib")) } } project(":v1") { version = "1.0" } project(":v2") { version = "2.0" } """ ) withDirectory("v1/src/main").v1() withDirectory("v2/src/main").v2() withDirectory("binary-compatibility").apply { withBuildScript( """ import japicmp.model.JApiChangeStatus import gradlebuild.binarycompatibility.* import gradlebuild.binarycompatibility.filters.* tasks.register<JapicmpTask>("checkBinaryCompatibility") { dependsOn(":v1:jar", ":v2:jar") val v1 = rootProject.project(":v1") val v1Jar = v1.tasks.named("jar") val v2 = rootProject.project(":v2") val v2Jar = v2.tasks.named("jar") oldArchives.from(v1Jar) oldClasspath.from(v1.configurations.named("runtimeClasspath"), v1Jar) newArchives.from(v2Jar) newClasspath.from(v2.configurations.named("runtimeClasspath"), v2Jar) onlyModified.set(false) failOnModification.set(false) // we rely on the rich report to fail txtOutputFile.set(file("build/japi-report.txt")) richReport { title.set("Gradle Binary Compatibility Check") destinationDir.set(file("build/japi")) reportName.set("japi.html") includedClasses.set(listOf(".*")) excludedClasses.set(emptyList()) } BinaryCompatibilityHelper.setupJApiCmpRichReportRules( this, AcceptedApiChanges.parse("{acceptedApiChanges:[]}"), rootProject.files("v2/src/main/kotlin"), "2.0", file("test-api-changes.json"), rootProject.layout.projectDirectory ) } """ ) } } val runner = GradleRunner.create() .withProjectDir(inputBuildDir) .withPluginClasspath() .withArguments(":binary-compatibility:checkBinaryCompatibility", "-s") val (buildResult, failure) = try { runner.build()!! to null } catch (ex: UnexpectedBuildFailure) { ex.buildResult!! to ex } println(buildResult.output) val richReportFile = inputBuildDir.resolve("binary-compatibility/build/japi/japi.html").apply { assertTrue("Rich report file exists", isFile) } return CheckResult(failure, scrapeRichReport(richReportFile), buildResult).apply { println(richReport.toText()) block() } } internal data class CheckResult( val checkFailure: UnexpectedBuildFailure?, val richReport: RichReport, val buildResult: BuildResult ) { val isBinaryCompatible = checkFailure == null fun assertEmptyReport() { assertHasNoError() assertHasNoWarning() assertHasNoInformation() } fun assertHasNoError() { assertTrue("Has no error (${richReport.errors})", richReport.errors.isEmpty()) } fun assertHasNoWarning() { assertTrue("Has no warning (${richReport.warnings})", richReport.warnings.isEmpty()) } fun assertHasNoInformation() { assertTrue("Has no information (${richReport.information})", richReport.information.isEmpty()) } fun assertHasErrors(vararg errors: String) { assertThat("Has errors", richReport.errors.map { it.message }, CoreMatchers.equalTo(errors.toList())) } fun assertHasWarnings(vararg warnings: String) { assertThat("Has warnings", richReport.warnings.map { it.message }, CoreMatchers.equalTo(warnings.toList())) } fun assertHasInformation(vararg information: String) { assertThat("Has information", richReport.information.map { it.message }, CoreMatchers.equalTo(information.toList())) } fun assertHasErrors(vararg errors: List<String>) { assertHasErrors(*errors.toList().flatten().toTypedArray()) } fun assertHasErrors(vararg errorWithDetail: Pair<String, List<String>>) { assertThat("Has errors", richReport.errors, CoreMatchers.equalTo(errorWithDetail.map { ReportMessage(it.first, it.second) })) } fun newApi(thing: String, desc: String): String = "$thing ${describe(thing, desc)}: New public API in 2.0 (@Incubating)" fun added(thing: String, desc: String): List<String> = listOf( "$thing ${describe(thing, desc)}: Is not annotated with @Incubating.", "$thing ${describe(thing, desc)}: Is not annotated with @since 2.0." ) fun removed(thing: String, desc: String): Pair<String, List<String>> = "$thing ${describe(thing, desc)}: Is not binary compatible." to listOf("$thing has been removed") private fun describe(thing: String, desc: String) = if (thing == "Field") desc else "com.example.$desc" } protected fun File.withFile(path: String, text: String = ""): File = resolve(path).apply { parentFile.mkdirs() writeText(text.trimIndent()) } private fun File.withUniqueDirectory(prefixPath: String): File = Files.createTempDirectory( withDirectory(prefixPath.substringBeforeLast("/")).toPath(), prefixPath.substringAfterLast("/") ).toFile() private fun File.withDirectory(path: String): File = resolve(path).apply { mkdirs() } private fun File.withSettings(text: String = ""): File = withFile("settings.gradle.kts", text) private fun File.withBuildScript(text: String = ""): File = withFile("build.gradle.kts", text) }
apache-2.0
e209a392ff133957a814639b691b3570
34.151596
137
0.546493
5.087375
false
false
false
false
davinkevin/Podcast-Server
backend/src/main/kotlin/com/github/davinkevin/podcastserver/manager/downloader/FfmpegDownloader.kt
1
5062
package com.github.davinkevin.podcastserver.manager.downloader import com.github.davinkevin.podcastserver.download.DownloadRepository import com.github.davinkevin.podcastserver.entity.Status import com.github.davinkevin.podcastserver.messaging.MessagingTemplate import com.github.davinkevin.podcastserver.service.ffmpeg.FfmpegService import com.github.davinkevin.podcastserver.service.ProcessService import com.github.davinkevin.podcastserver.service.storage.FileStorageService import net.bramp.ffmpeg.builder.FFmpegBuilder import net.bramp.ffmpeg.progress.ProgressListener import org.slf4j.LoggerFactory import org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE import org.springframework.context.annotation.Scope import org.springframework.stereotype.Component import java.nio.file.Files import java.nio.file.Path import java.time.Clock import java.util.* @Scope(SCOPE_PROTOTYPE) @Component class FfmpegDownloader( downloadRepository: DownloadRepository, template: MessagingTemplate, clock: Clock, file: FileStorageService, val ffmpegService: FfmpegService, val processService: ProcessService ) : AbstractDownloader(downloadRepository, template, clock, file) { private val log = LoggerFactory.getLogger(FfmpegDownloader::class.java) lateinit var process: Process private var globalDuration = 0.0 private var alreadyDoneDuration = 0.0 override fun download(): DownloadingItem { log.debug("Download {}", downloadingInformation.item.title) target = computeTargetFile(downloadingInformation) globalDuration = downloadingInformation.urls .sumOf { ffmpegService.getDurationOf(it.toASCIIString(), downloadingInformation.userAgent) } val multiDownloads = downloadingInformation.urls.map { download(it.toASCIIString()) } Result.runCatching { if (multiDownloads.any { it.isFailure }) { val cause = multiDownloads.first { it.isFailure }.exceptionOrNull() throw RuntimeException("Error during download of a part", cause) } ffmpegService.concat( target, *multiDownloads.map { it.getOrNull()!! }.toTypedArray() ) } multiDownloads .filter { it.isSuccess } .map { it.getOrNull()!! } .forEach { Result.runCatching { Files.deleteIfExists(it) } } if (downloadingInformation.item.status == Status.STARTED) { finishDownload() } return downloadingInformation.item } private fun download(url: String): Result<Path> { val duration = ffmpegService.getDurationOf(url, downloadingInformation.userAgent) val subTarget = Files.createTempFile("podcast-server", downloadingInformation.item.id.toString()) val userAgent = downloadingInformation.userAgent ?: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36" val command = FFmpegBuilder() .addUserAgent(userAgent) .addInput(url) .addOutput(subTarget.toAbsolutePath().toString()) .setFormat("mp4") .setAudioBitStreamFilter(FfmpegService.AUDIO_BITSTREAM_FILTER_AAC_ADTSTOASC) .setVideoCodec(FfmpegService.CODEC_COPY) .setAudioCodec(FfmpegService.CODEC_COPY) .done() return Result.runCatching { process = ffmpegService.download(url, command, handleProgression(alreadyDoneDuration, globalDuration)) processService.waitFor(process) alreadyDoneDuration += duration subTarget } .onFailure { Files.deleteIfExists(subTarget) } } private fun handleProgression(alreadyDoneDuration: Double, globalDuration: Double) = ProgressListener{ broadcastProgression(((it.out_time_ns.toFloat() + alreadyDoneDuration.toFloat()) / globalDuration.toFloat() * 100).toInt()) } private fun broadcastProgression(progress: Int) { if (downloadingInformation.item.progression == progress) return downloadingInformation = downloadingInformation.progression(progress) log.debug("Progression : {}", downloadingInformation.item.progression) broadcast(downloadingInformation.item) } override fun stopDownload() { try { process.destroy() super.stopDownload() } catch (e: Exception) { log.error("Error during stop of process :", e) failDownload() } } override fun compatibility(downloadingInformation: DownloadingInformation) = if (downloadingInformation.urls.map { it.toASCIIString().lowercase(Locale.getDefault()) }.all { "m3u8" in it || "mp4" in it }) 10 else Integer.MAX_VALUE } private fun FFmpegBuilder.addUserAgent(userAgent: String) = addExtraArgs("-headers", "User-Agent: $userAgent")
apache-2.0
c3367e4dacc18cd631b9d93ec20095e5
38.858268
182
0.688266
4.730841
false
false
false
false
davinkevin/Podcast-Server
backend/src/test/kotlin/com/github/davinkevin/podcastserver/find/finders/dailymotion/DailymotionFinderTest.kt
1
8539
package com.github.davinkevin.podcastserver.find.finders.dailymotion import com.github.davinkevin.podcastserver.MockServer import com.github.davinkevin.podcastserver.config.WebClientConfig import com.github.davinkevin.podcastserver.fileAsString import com.github.davinkevin.podcastserver.find.FindCoverInformation import com.github.davinkevin.podcastserver.remapToMockServer import com.github.davinkevin.podcastserver.service.image.CoverInformation import com.github.tomakehurst.wiremock.WireMockServer import com.github.tomakehurst.wiremock.client.WireMock.* import org.mockito.kotlin.any import org.mockito.kotlin.whenever import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration import org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration import org.springframework.boot.test.context.TestConfiguration import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Import import org.springframework.test.context.junit.jupiter.SpringExtension import reactor.core.publisher.Mono import reactor.kotlin.core.publisher.toMono import reactor.test.StepVerifier import java.net.URI import com.github.davinkevin.podcastserver.service.image.ImageService @ExtendWith(SpringExtension::class) class DailymotionFinderTest( @Autowired val finder: DailymotionFinder ) { @MockBean lateinit var image: ImageService @Nested @DisplayName("should find") inner class ShouldFind { @Nested @ExtendWith(MockServer::class) @DisplayName("with success") inner class WithSuccess { @Test fun `information about dailymotion podcast with url`(backend: WireMockServer) { /* Given */ val url = "https://www.dailymotion.com/karimdebbache" whenever(image.fetchCoverInformation(URI("http://s2.dmcdn.net/PB4mc/720x720-AdY.jpg"))) .thenReturn(CoverInformation( url = URI("http://s2.dmcdn.net/PB4mc/720x720-AdY.jpg"), height = 123, width = 456 ).toMono()) backend.stubFor(get(urlPathEqualTo("/user/karimdebbache")) .withQueryParam("fields", equalTo("avatar_720_url,description,username")) .willReturn(okJson(fileAsString("/remote/podcast/dailymotion/karimdebbache.json")))) /* When */ StepVerifier.create(finder.findInformation(url)) /* Then */ .expectSubscription() .assertNext { assertThat(it.url).isEqualTo(URI(url)) assertThat(it.title).isEqualTo("karimdebbache") assertThat(it.type).isEqualTo("Dailymotion") assertThat(it.cover).isEqualTo(FindCoverInformation( url = URI("http://s2.dmcdn.net/PB4mc/720x720-AdY.jpg"), height = 123, width = 456 )) assertThat(it.description).isEqualTo("""CHROMA est une CHROnique de cinéMA sur Dailymotion, dont la première saison se compose de dix épisodes, à raison d’un par mois, d’une durée comprise entre quinze et vingt minutes. Chaque épisode est consacré à un film en particulier.""") } .verifyComplete() } @Test fun `information about dailymotion podcast with url but with no cover`(backend: WireMockServer) { /* Given */ val url = "https://www.dailymotion.com/karimdebbache" whenever(image.fetchCoverInformation(any())).thenReturn(Mono.empty()) backend.stubFor(get(urlPathEqualTo("/user/karimdebbache")) .withQueryParam("fields", equalTo("avatar_720_url,description,username")) .willReturn(okJson(fileAsString("/remote/podcast/dailymotion/karimdebbache.json")))) /* When */ StepVerifier.create(finder.findInformation(url)) /* Then */ .expectSubscription() .assertNext { assertThat(it.url).isEqualTo(URI(url)) assertThat(it.title).isEqualTo("karimdebbache") assertThat(it.type).isEqualTo("Dailymotion") assertThat(it.cover).isNull() assertThat(it.description).isEqualTo("""CHROMA est une CHROnique de cinéMA sur Dailymotion, dont la première saison se compose de dix épisodes, à raison d’un par mois, d’une durée comprise entre quinze et vingt minutes. Chaque épisode est consacré à un film en particulier.""") } .verifyComplete() } @Test fun `information about dailymotion podcast with no description`(backend: WireMockServer) { /* Given */ val url = "https://www.dailymotion.com/karimdebbache" whenever(image.fetchCoverInformation(any())).thenReturn(Mono.empty()) backend.stubFor(get(urlPathEqualTo("/user/karimdebbache")) .withQueryParam("fields", equalTo("avatar_720_url,description,username")) .willReturn(okJson(fileAsString("/remote/podcast/dailymotion/karimdebbache-without-description.json")))) /* When */ StepVerifier.create(finder.findInformation(url)) /* Then */ .expectSubscription() .assertNext { assertThat(it.url).isEqualTo(URI(url)) assertThat(it.title).isEqualTo("karimdebbache") assertThat(it.type).isEqualTo("Dailymotion") assertThat(it.description).isEqualTo("") } .verifyComplete() } } @Nested @DisplayName("with error") inner class WithError { @Test fun `if username can't be extracted from url`() { /* Given */ val url = "https://www.toto.com/karimdebbache" /* When */ StepVerifier.create(finder.findInformation(url)) /* Then */ .expectSubscription() .expectErrorMessage("username not found int url $url") .verify() } } } @DisplayName("shoud be compatible") @ParameterizedTest(name = "with {0}") @ValueSource(strings = [ "https://www.dailymotion.com/karimdebbache/", "http://www.dailymotion.com/karimdebbache/" ]) fun `should be compatible with`(/* Given */ url: String) { /* When */ val compatibility = finder.compatibility(url) /* Then */ assertThat(compatibility).isEqualTo(1) } @DisplayName("shoud not be compatible") @ParameterizedTest(name = "with {0}") @ValueSource(strings = [ "https://www.france2.tv/france-2/vu/", "https://www.foo.com/france-2/vu/", "https://www.mycanal.fr/france-2/vu/", "https://www.6play.fr/france-2/vu/" ]) fun `should not be compatible`(/* Given */ url: String) { /* When */ val compatibility = finder.compatibility(url) /* Then */ assertThat(compatibility).isEqualTo(Int.MAX_VALUE) } @TestConfiguration @Import(DailymotionFinderConfig::class, WebClientAutoConfiguration::class, JacksonAutoConfiguration::class, WebClientConfig::class) class LocalTestConfiguration { @Bean fun webClientCustomization() = remapToMockServer("api.dailymotion.com") } }
apache-2.0
b4842d1ed776af11f09f8fbc3ab78dbf
44.292553
305
0.600352
4.751674
false
true
false
false
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/data/netease/NeteaseCloudMusicApi.kt
1
12156
package tech.summerly.quiet.data.netease import android.content.ContentResolver import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import tech.summerly.quiet.AppContext import tech.summerly.quiet.R import tech.summerly.quiet.bean.MusicSearchResult import tech.summerly.quiet.bean.Mv import tech.summerly.quiet.bean.Playlist import tech.summerly.quiet.data.cache.CacheApi import tech.summerly.quiet.data.model.PersistentCookieStore import tech.summerly.quiet.data.netease.result.* import tech.summerly.quiet.extensions.exeception.errorResponse import tech.summerly.quiet.extensions.exeception.fetchDataFailed import tech.summerly.quiet.extensions.md5 import tech.summerly.quiet.extensions.string import tech.summerly.quiet.module.common.bean.Music import tech.summerly.quiet.module.common.bean.MusicType /** * author : SUMMERLY * e-mail : [email protected] * time : 2017/8/23 * desc : */ class NeteaseCloudMusicApi constructor(private val musicService: CloudMusicService) { companion object { val instance by lazy { val cookieStore = PersistentCookieStore(AppContext.instance) val musicService = CloudMusicServiceProvider.provideCloudMusicService(cookieStore) NeteaseCloudMusicApi(musicService) } } private val mapper = NeteaseResultMapper() /** * 搜索服务 * type: 1: 单曲 * 10: 专辑 * 100: 歌手 * 1000: 歌单 * 1002: 用户 * 1004: MV * 1006: 歌词 * 1009: 电台 */ fun searchMusic(keyword: String, offset: Int = 0, limit: Int = 30): Observable<MusicSearchResult> { val params = Crypto.encrypt(""" { "csrf_token" : "", "limit" : $limit , "type" : 1 , "s" : "$keyword", "offset" : $offset } """.trimIndent()) return musicService.searchMusic(params) .map { MusicSearchResult(keyword = keyword, musics = it.result.songs?.map { mapper.convertToMusic(it) } ?: emptyList(), total = it.result.songCount, offset = offset) } .flatMap { result -> //获取音乐URL fetchFmMusicUrl(result.musics) .map { result } } } fun musicDetail(id: Long): Observable<MusicDetailResultBean> { val encrypt = Crypto.encrypt(""" { "c" : "[{\"id\" : $id}]", "ids": "[$id]", "csrf_token": "" } """.trimIndent()) return musicService.musicDetail(encrypt) } /** * [ids] 歌曲id * [bitrate] 比特率 */ fun musicUrl(vararg ids: Long, bitrate: Int = 999000): Observable<List<MusicUrlResultBean.Datum>> { val encrypt = Crypto.encrypt(""" { "ids" : ["${ids.joinToString(",")}"], "br" : $bitrate, "csrf_token" : "" } """.trimIndent() ) return musicService.musicUrl(encrypt) .map { (data, code) -> if (code != 200) { errorResponse(code) } if (data == null || data.isEmpty()) { fetchDataFailed() } data.forEach { //缓存获得的链接 CacheApi.cacheMusicUrl(it.id, MusicType.NETEASE, it.url) } ArrayList(data) } } /** * 获取指定ID的音乐的播放链接 */ fun musicUrl(id: Long, bitrate: Int = 999000): Observable<String> { return musicUrl(ids = id, bitrate = bitrate) .map { it[0].url ?: error("can not get $id's url") } } /** * 获取指定 id 歌曲的歌词 */ fun lyric(id: Long): Observable<LyricResultBean> { return musicService.lyric(id, Crypto.encrypt("{}")) } fun login(phone: String, password: String): Observable<LoginResultBean> { val encrypt = Crypto.encrypt(""" { "phone" : "$phone", "password" : "${password.md5()}", "rememberLogin" : "true" } """.trimIndent()) return musicService.login(encrypt) } fun getUserPlayerList(userId: Long, offset: Int = 0, limit: Int = 1000): Observable<List<Playlist>> { val encrypt = Crypto.encrypt(""" { "offset" : $offset , "uid" : "$userId", "limit" : $limit , "csrf_token" : "" } """.trimIndent()) return musicService.userPlayList(encrypt) .map { (_, playlist, code) -> if (code != 200) { errorResponse(code) } if (playlist == null) { fetchDataFailed() } playlist.map(mapper::convertToPlaylist) } } fun recommendSongs(): Observable<Playlist> { val encrypt = Crypto.encrypt(""" {"offset":0,"total":true,"limit":20,"csrf_token":""} """.trimIndent()) return musicService.recommendSongs(encrypt) .map { if (it.code != 200) { errorResponse(it.code) } if (it.recommend == null) { fetchDataFailed() } val musics = it.recommend.map { mapper.convertToMusic(it) } Playlist( id = 0, name = string(R.string.netease_daily_recommend), coverImageUrl ="${ContentResolver.SCHEME_ANDROID_RESOURCE}://" + "tech.summerly.quiet/drawable/netease_background", musics = musics, type = MusicType.NETEASE ) }.flatMap(this::fetchFmMusicUrl) } //type :表示签到类型, 0:Android 1:PC fun dailySign(): Observable<DailySignResultBean> { val encrypt = Crypto.encrypt(""" { "csrf_token":"", "type": 0 } """.trimIndent()) return musicService.dailySign(encrypt) } fun userDetail(id: Long): Observable<UserDetailResultBean> { val encrypt = Crypto.encrypt(""" { "csrf_token":"" } """.trimIndent()) return musicService.userDetail(id, encrypt) } fun recommendPlaylist(): Observable<List<Playlist>> { val encrypt = Crypto.encrypt(""" { "csrf_token":"" } """.trimIndent()) return musicService.recommendPlaylist(encrypt) .map { if (it.code != 200) { errorResponse(it.code) } if (it.recommend == null) { fetchDataFailed() } it.recommend.map { mapper.convertToPlaylist(it) } } } fun recommendMv(): Observable<RecommendMvResultBean> { val encrypt = Crypto.encrypt(""" { "csrf_token":"" } """.trimIndent()) return musicService.recommendMv(encrypt) } fun refreshLogin() { } fun playListDetail(playlistId: Long, offset: Int = 0): Observable<Playlist> { val encrypt = Crypto.encrypt(""" { "id":"$playlistId", "offset":$offset, "total":true, "limit":1000, "n":1000, "csrf_token":"" } """.trimIndent()) return musicService.playlistDetail(encrypt) .map { (playlist, code) -> // log("playListDetail" + it.body()) // val playlistDetailResult = it.body() ?: fetchDataFailed() if (code != 200 || playlist == null) { errorResponse(code) } val toPlaylist = mapper.convertToPlaylist(playlist) //在此api的返回Json中,只有 album 有 picUrl,所以直接将 album的 picUri作为音乐封面 toPlaylist.musics.forEach { music -> music.picUrl = music.album.picUrl } toPlaylist } .flatMap(this::fetchFmMusicUrl) } fun mvDetail(id: Long): Observable<Mv> { val params = Crypto.encrypt(""" { "id":"$id" } """.trimIndent()) return musicService.mvDetail(params) .map { if (it.code != 200 || it.data == null) { errorResponse(it.code) } mapper.convertToMv(it.data) } } fun personalFm(): Observable<List<Music>> { val params = Crypto.encrypt(""" {"csrf_token":""} """.trimIndent()) return musicService.personalFm(params) .map { if (it.code != 200 || it.data == null) { errorResponse(it.code) } it.data.map(mapper::convertToMusic) }.flatMap(this::fetchFmMusicUrl) } /** * Boolean 为 true 代表操作(喜欢或者移除喜欢)成功 */ fun like(id: Long, like: Boolean = true): Observable<Boolean> { val params = Crypto.encrypt(""" { "csrf_token" : "", "trackId" : "$id", "like" : $like } """.trimIndent()) return musicService.like(id, like, params) .map { it.code == 200 } } fun throwTrashFm(id: Long): Observable<Boolean> { val params = Crypto.encrypt(""" { "csrf_token" : "", "songId" : "$id" } """.trimIndent()) return musicService.fmTrash(id, params) .map { it.code == 200 } } private fun <T : Music> fetchFmMusicUrl(musics: List<T>): Observable<List<T>> { return musicUrl(*musics.map { it.id }.toLongArray()) .map { datums -> musics.forEach { music -> datums.find { it.id == music.id }?.let { (_, url, bitrate, _, md5) -> music.url = url music.bitrate = bitrate music.md5 = md5 } } musics } .subscribeOn(Schedulers.io()) } /** * 为Playlist中的音乐填充其真正的播放地址 */ private fun fetchFmMusicUrl(playlist: Playlist): Observable<Playlist> { return musicUrl(*playlist.musics.map { it.id }.toLongArray()) .map { datums -> playlist.musics.forEach { music -> datums.find { it.id == music.id }?.let { (_, url, bitrate, _, md5) -> music.url = url music.bitrate = bitrate music.md5 = md5 } } playlist } } }
gpl-2.0
b08b14fa46103abf1843596657995755
31.504087
105
0.449698
4.842875
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/base/util/PermissionUtil.kt
1
1054
package com.arcao.geocaching4locus.base.util import android.Manifest import android.content.Context import android.content.pm.PackageManager import androidx.core.content.ContextCompat object PermissionUtil { val PERMISSION_LOCATION_GPS = arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) val PERMISSION_LOCATION_WIFI = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION) fun hasPermission(context: Context, vararg permissions: String): Boolean { for (permission in permissions) { if (ContextCompat.checkSelfPermission( context, permission ) == PackageManager.PERMISSION_DENIED ) return false } return true } } val Context.hasGpsLocationPermission get() = PermissionUtil.hasPermission(this, *PermissionUtil.PERMISSION_LOCATION_GPS) val Context.hasWifiLocationPermission get() = PermissionUtil.hasPermission(this, *PermissionUtil.PERMISSION_LOCATION_WIFI)
gpl-3.0
9e88864826ad053a474bcb348c599978
31.9375
88
0.713472
4.902326
false
false
false
false
stokito/IdeaSingletonInspection
src/main/java/com/github/stokito/IdeaSingletonInspection/quickFixes/InstanceGettersReturnTypeFix.kt
1
1001
package com.github.stokito.IdeaSingletonInspection.quickFixes import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod class InstanceGettersReturnTypeFix : LocalQuickFix { override fun getName(): String { return "Set correct return type" } override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val instanceGetter = descriptor.psiElement as PsiMethod assert(instanceGetter.parent is PsiClass) val instanceGetterClass = instanceGetter.parent as PsiClass assert(instanceGetterClass.nameIdentifier != null) val nameIdentifier = instanceGetterClass.nameIdentifier!! val returnTypeElement = instanceGetter.returnTypeElement!! returnTypeElement.replace(nameIdentifier.copy()) } override fun getFamilyName(): String { return name } }
apache-2.0
ae383c17dd690ffd163446b7dc75384f
36.074074
76
0.76024
5.213542
false
false
false
false
Nagarajj/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/PauseTaskHandlerSpec.kt
1
2257
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.natpryce.hamkrest.absent import com.natpryce.hamkrest.should.shouldMatch import com.netflix.spinnaker.orca.ExecutionStatus import com.netflix.spinnaker.orca.pipeline.model.Pipeline import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.* import com.netflix.spinnaker.spek.shouldEqual import com.nhaarman.mockito_kotlin.* import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek object PauseTaskHandlerSpec : SubjectSpek<PauseTaskHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() subject { PauseTaskHandler(queue, repository) } fun resetMocks() = reset(queue, repository) describe("when a task is paused") { val pipeline = pipeline { application = "foo" stage { type = multiTaskStage.type multiTaskStage.buildTasks(this) } } val message = PauseTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1") beforeGroup { whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the task state in the stage") { verify(repository).storeStage(check { it.getTasks().first().apply { status shouldEqual ExecutionStatus.PAUSED endTime shouldMatch absent() } }) } it("pauses the stage") { verify(queue).push(PauseStage(message)) } } })
apache-2.0
e0b2bb8113686650ddb316df2d99958b
29.093333
102
0.71821
4.234522
false
false
false
false
jsargent7089/android
src/test/java/com/nextcloud/client/network/ConnectivityServiceTest.kt
1
11383
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2020 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.network import android.net.ConnectivityManager import android.net.NetworkInfo import com.nextcloud.client.account.Server import com.nextcloud.client.account.User import com.nextcloud.client.account.UserAccountManager import com.nextcloud.client.logger.Logger import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import com.owncloud.android.lib.resources.status.OwnCloudVersion import org.apache.commons.httpclient.HttpClient import org.apache.commons.httpclient.HttpStatus import org.apache.commons.httpclient.methods.GetMethod import org.junit.Assert.assertFalse import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Suite import org.mockito.ArgumentCaptor import org.mockito.Mock import org.mockito.MockitoAnnotations import java.net.URI @RunWith(Suite::class) @Suite.SuiteClasses( ConnectivityServiceTest.Disconnected::class, ConnectivityServiceTest.IsConnected::class, ConnectivityServiceTest.WifiConnectionWalledStatusOnLegacyServer::class, ConnectivityServiceTest.WifiConnectionWalledStatus::class ) class ConnectivityServiceTest { internal abstract class Base { companion object { fun mockNetworkInfo(connected: Boolean, connecting: Boolean, type: Int): NetworkInfo { val networkInfo = mock<NetworkInfo>() whenever(networkInfo.isConnectedOrConnecting).thenReturn(connected or connecting) whenever(networkInfo.isConnected).thenReturn(connected) whenever(networkInfo.type).thenReturn(type) return networkInfo } const val SERVER_BASE_URL = "https://test.server.com" } @Mock lateinit var platformConnectivityManager: ConnectivityManager @Mock lateinit var networkInfo: NetworkInfo @Mock lateinit var accountManager: UserAccountManager @Mock lateinit var clientFactory: ClientFactory @Mock lateinit var client: HttpClient @Mock lateinit var getRequest: GetMethod @Mock lateinit var requestBuilder: ConnectivityServiceImpl.GetRequestBuilder @Mock lateinit var logger: Logger val baseServerUri = URI.create(SERVER_BASE_URL) val newServer = Server(baseServerUri, OwnCloudVersion.nextcloud_14) val legacyServer = Server(baseServerUri, OwnCloudVersion.nextcloud_13) @Mock lateinit var user: User lateinit var connectivityService: ConnectivityServiceImpl @Before fun setUpMocks() { MockitoAnnotations.initMocks(this) connectivityService = ConnectivityServiceImpl( platformConnectivityManager, accountManager, clientFactory, requestBuilder, logger ) whenever(platformConnectivityManager.activeNetworkInfo).thenReturn(networkInfo) whenever(platformConnectivityManager.allNetworkInfo).thenReturn(arrayOf(networkInfo)) whenever(requestBuilder.invoke(any())).thenReturn(getRequest) whenever(clientFactory.createPlainClient()).thenReturn(client) whenever(user.server).thenReturn(newServer) whenever(accountManager.user).thenReturn(user) } } internal class Disconnected : Base() { @Test fun `wifi is disconnected`() { whenever(networkInfo.isConnectedOrConnecting).thenReturn(false) whenever(networkInfo.type).thenReturn(ConnectivityManager.TYPE_WIFI) connectivityService.connectivity.apply { assertFalse(isConnected) assertTrue(isWifi) } } @Test fun `no active network`() { whenever(platformConnectivityManager.activeNetworkInfo).thenReturn(null) assertSame(Connectivity.DISCONNECTED, connectivityService.connectivity) } } internal class IsConnected : Base() { @Test fun `connected to wifi`() { whenever(networkInfo.isConnectedOrConnecting).thenReturn(true) whenever(networkInfo.type).thenReturn(ConnectivityManager.TYPE_WIFI) assertTrue(connectivityService.connectivity.isConnected) assertTrue(connectivityService.connectivity.isWifi) } @Test fun `connected to wifi and vpn`() { whenever(networkInfo.isConnectedOrConnecting).thenReturn(true) whenever(networkInfo.type).thenReturn(ConnectivityManager.TYPE_VPN) val wifiNetworkInfoList = arrayOf( mockNetworkInfo( connected = true, connecting = true, type = ConnectivityManager.TYPE_VPN ), mockNetworkInfo( connected = true, connecting = true, type = ConnectivityManager.TYPE_WIFI ) ) whenever(platformConnectivityManager.allNetworkInfo).thenReturn(wifiNetworkInfoList) connectivityService.connectivity.let { assertTrue(it.isConnected) assertTrue(it.isWifi) } } @Test fun `connected to mobile network`() { whenever(networkInfo.isConnectedOrConnecting).thenReturn(true) whenever(networkInfo.type).thenReturn(ConnectivityManager.TYPE_MOBILE) whenever(platformConnectivityManager.allNetworkInfo).thenReturn(arrayOf(networkInfo)) connectivityService.connectivity.let { assertTrue(it.isConnected) assertFalse(it.isWifi) } } } internal class WifiConnectionWalledStatusOnLegacyServer : Base() { @Before fun setUp() { whenever(networkInfo.isConnectedOrConnecting).thenReturn(true) whenever(networkInfo.type).thenReturn(ConnectivityManager.TYPE_WIFI) whenever(user.server).thenReturn(legacyServer) assertTrue("Precondition failed", connectivityService.connectivity.let { it.isConnected && it.isWifi }) } fun mockResponse(maintenance: Boolean = true, httpStatus: Int = HttpStatus.SC_OK) { whenever(client.executeMethod(getRequest)).thenReturn(httpStatus) val body = """{"maintenance":$maintenance}""" whenever(getRequest.responseContentLength).thenReturn(body.length.toLong()) whenever(getRequest.responseBodyAsString).thenReturn(body) } @Test fun `false maintenance status flag is used`() { mockResponse(maintenance = false, httpStatus = HttpStatus.SC_OK) assertFalse(connectivityService.isInternetWalled) } @Test fun `true maintenance status flag is used`() { mockResponse(maintenance = true, httpStatus = HttpStatus.SC_OK) assertTrue(connectivityService.isInternetWalled) } @Test fun `maintenance flag is ignored when non-200 HTTP code is returned`() { mockResponse(maintenance = false, httpStatus = HttpStatus.SC_NO_CONTENT) assertTrue(connectivityService.isInternetWalled) } @Test fun `status endpoint is used to determine internet state`() { mockResponse() connectivityService.isInternetWalled val urlCaptor = ArgumentCaptor.forClass(String::class.java) verify(requestBuilder).invoke(urlCaptor.capture()) assertTrue("Invalid URL used to check status", urlCaptor.value.endsWith("/status.php")) } } internal class WifiConnectionWalledStatus : Base() { @Before fun setUp() { whenever(networkInfo.isConnectedOrConnecting).thenReturn(true) whenever(networkInfo.type).thenReturn(ConnectivityManager.TYPE_WIFI) whenever(accountManager.getServerVersion(any())).thenReturn(OwnCloudVersion.nextcloud_14) assertTrue("Precondition failed", connectivityService.connectivity.let { it.isConnected && it.isWifi }) } @Test fun `check request is not sent when server uri is not set`() { // GIVEN // network connectivity is present // user has no server URI (empty) val serverWithoutUri = Server(URI(""), OwnCloudVersion.nextcloud_14) whenever(user.server).thenReturn(serverWithoutUri) // WHEN // connectivity is checked val result = connectivityService.isInternetWalled // THEN // connection is walled // request is not sent assertTrue("Server should not be accessible", result) verify(requestBuilder, never()).invoke(any()) verify(client, never()).executeMethod(any()) verify(client, never()).executeMethod(any(), any()) verify(client, never()).executeMethod(any(), any(), any()) } fun mockResponse(contentLength: Long = 0, status: Int = HttpStatus.SC_OK) { whenever(client.executeMethod(any())).thenReturn(status) whenever(getRequest.statusCode).thenReturn(status) whenever(getRequest.responseContentLength).thenReturn(contentLength) } @Test fun `status 204 means internet is not walled`() { mockResponse(contentLength = 0, status = HttpStatus.SC_NO_CONTENT) assertFalse(connectivityService.isInternetWalled) } @Test fun `other status than 204 means internet is walled`() { mockResponse(contentLength = 0, status = HttpStatus.SC_GONE) assertTrue(connectivityService.isInternetWalled) } @Test fun `index endpoint is used to determine internet state`() { mockResponse() connectivityService.isInternetWalled val urlCaptor = ArgumentCaptor.forClass(String::class.java) verify(requestBuilder).invoke(urlCaptor.capture()) assertTrue("Invalid URL used to check status", urlCaptor.value.endsWith("/index.php/204")) } } }
gpl-2.0
7fe73dba390138faf9f9e8cdc9219e63
37.586441
102
0.656593
5.30676
false
true
false
false
carlphilipp/chicago-commutes
android-app/src/main/kotlin/fr/cph/chicago/redux/Actions.kt
1
4923
/** * Copyright 2021 Carl-Philipp Harmant * * * 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 fr.cph.chicago.redux import fr.cph.chicago.R import fr.cph.chicago.core.model.BikeStation import fr.cph.chicago.core.model.BusRoute import fr.cph.chicago.core.model.TrainArrival import fr.cph.chicago.core.model.dto.BusArrivalDTO import fr.cph.chicago.core.model.dto.BusArrivalStopDTO import fr.cph.chicago.core.model.dto.FavoritesDTO import fr.cph.chicago.core.model.dto.RoutesAlertsDTO import fr.cph.chicago.core.model.dto.TrainArrivalDTO import org.apache.commons.lang3.StringUtils import org.rekotlin.Action data class ResetStateAction(val unit: Unit = Unit) : Action data class UpdateStatus(val status: Status) : Action data class DefaultSettingsAction( val ctaTrainKey: String, val ctaBusKey: String, val googleStreetKey: String ) : Action data class BaseAction( val localError: Boolean = false, val trainArrivalsDTO: TrainArrivalDTO = TrainArrivalDTO(mutableMapOf(), false), val busArrivalsDTO: BusArrivalDTO = BusArrivalDTO(listOf(), false), val trainFavorites: List<String> = listOf(), val busFavorites: List<String> = listOf(), val busRouteFavorites: List<String> = listOf(), val bikeFavorites: List<String> = listOf() ) : Action data class FavoritesAction( val favoritesDTO: FavoritesDTO = FavoritesDTO( trainArrivalDTO = TrainArrivalDTO(mutableMapOf(), false), busArrivalDTO = BusArrivalDTO(listOf(), false), bikeError = false, bikeStations = listOf()) ) : Action // Bus Routes data class BusRoutesAction( val busRoutes: List<BusRoute> = listOf(), val error: Boolean = false, val errorMessage: Int = R.string.message_something_went_wrong ) : Action // Bus Routes + Bike stations data class BusRoutesAndBikeStationAction( val busRoutes: List<BusRoute> = listOf(), val bikeStations: List<BikeStation> = listOf(), val busRoutesError: Boolean = false, val bikeStationsError: Boolean = false ) : Action // Train station activity data class TrainStationAction( val trainStationId: String = StringUtils.EMPTY, val trainArrival: TrainArrival = TrainArrival(), val error: Boolean = false, val errorMessage: Int = R.string.message_something_went_wrong ) : Action // Bus stop activity data class BusStopArrivalsAction( // input val busRouteId: String = StringUtils.EMPTY, val busStopId: String = StringUtils.EMPTY, val bound: String = StringUtils.EMPTY, val boundTitle: String = StringUtils.EMPTY, // output val busArrivalStopDTO: BusArrivalStopDTO = BusArrivalStopDTO(), val error: Boolean = false, val errorMessage: Int = R.string.message_something_went_wrong ) : Action // Bike station data class BikeStationAction( val bikeStations: List<BikeStation> = listOf(), val error: Boolean = false, val errorMessage: Int = R.string.message_something_went_wrong ) : Action data class AlertAction( val routesAlertsDTO: List<RoutesAlertsDTO> = listOf(), val error: Boolean = false, val errorMessage: Int = R.string.message_something_went_wrong ) : Action data class AddTrainFavoriteAction( val id: String = StringUtils.EMPTY, val trainFavorites: List<String> = listOf() ) : Action data class RemoveTrainFavoriteAction( val id: String =StringUtils.EMPTY, val trainFavorites: List<String> = listOf() ) : Action data class AddBusFavoriteAction( val busRouteId: String = StringUtils.EMPTY, val busStopId: String = StringUtils.EMPTY, val boundTitle: String = StringUtils.EMPTY, val busRouteName: String = StringUtils.EMPTY, val busStopName: String = StringUtils.EMPTY, val busFavorites: List<String> = listOf(), val busRouteFavorites: List<String> = listOf() ) : Action data class RemoveBusFavoriteAction( val busRouteId: String = StringUtils.EMPTY, val busStopId: String = StringUtils.EMPTY, val boundTitle: String = StringUtils.EMPTY, val busFavorites: List<String> = listOf(), val busRouteFavorites: List<String> = listOf() ) : Action data class AddBikeFavoriteAction( val id: String = StringUtils.EMPTY, val stationName: String = StringUtils.EMPTY, val bikeFavorites: List<String> = listOf() ) : Action data class RemoveBikeFavoriteAction( val id: String = StringUtils.EMPTY, val bikeFavorites: List<String> = listOf() ) : Action
apache-2.0
7181f23b4d20a95cdfdc0ebcc086cc60
32.263514
83
0.733699
4.105922
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/data/feed/FeedItem.kt
1
1655
package mil.nga.giat.mage.data.feed import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.ForeignKey.CASCADE import com.google.gson.JsonElement import com.google.gson.annotations.SerializedName import mil.nga.sf.Geometry @Entity(tableName = "feed_item", primaryKeys = ["id", "feed_id"], foreignKeys = [ ForeignKey(entity = Feed::class, parentColumns = ["id"], childColumns = ["feed_id"], onDelete = CASCADE) ] ) data class FeedItem( @SerializedName("id") @ColumnInfo(name = "id") val id: String, @SerializedName("geometry") @ColumnInfo(name = "geometry", typeAffinity = ColumnInfo.BLOB) val geometry: Geometry?, @SerializedName("properties") @ColumnInfo(name = "properties") val properties: JsonElement?, @ColumnInfo(name = "feed_id") var feedId: String ) { @ColumnInfo(name = "timestamp") var timestamp: Long? = null } @Entity(tableName = "feed_item", primaryKeys = ["id", "feed_id"], foreignKeys = [ ForeignKey(entity = Feed::class, parentColumns = ["id"], childColumns = ["feed_id"], onDelete = CASCADE) ] ) data class MappableFeedItem( @SerializedName("id") @ColumnInfo(name = "id") val id: String, @SerializedName("geometry") @ColumnInfo(name = "geometry", typeAffinity = ColumnInfo.BLOB) val geometry: Geometry, @SerializedName("properties") @ColumnInfo(name = "properties") val properties: JsonElement?, @ColumnInfo(name = "feed_id") var feedId: String ) { @ColumnInfo(name = "timestamp") var timestamp: Long? = null }
apache-2.0
35ca03fb1c206459d8e2b512717a877e
23.716418
65
0.663444
3.978365
false
false
false
false
maskaravivek/apps-android-commons
app/src/main/java/fr/free/nrw/commons/customselector/helper/ImageHelper.kt
3
2280
package fr.free.nrw.commons.customselector.helper import fr.free.nrw.commons.customselector.model.Folder import fr.free.nrw.commons.customselector.model.Image /** * Image Helper object, includes all the static functions required by custom selector. */ object ImageHelper { /** * Returns the list of folders from given image list. */ fun folderListFromImages(images: List<Image>): ArrayList<Folder> { val folderMap: MutableMap<Long, Folder> = LinkedHashMap() for (image in images) { val bucketId = image.bucketId val bucketName = image.bucketName var folder = folderMap[bucketId] if (folder == null) { folder = Folder(bucketId, bucketName) folderMap[bucketId] = folder } folder.images.add(image) } return ArrayList(folderMap.values) } /** * Filters the images based on the given bucketId (folder) */ fun filterImages(images: ArrayList<Image>, bukketId: Long?): ArrayList<Image> { if (bukketId == null) return images val filteredImages = arrayListOf<Image>() for (image in images) { if (image.bucketId == bukketId) { filteredImages.add(image) } } return filteredImages } /** * getIndex: Returns the index of image in given list. */ fun getIndex(list: ArrayList<Image>, image: Image): Int { return list.indexOf(image) } /** * getIndex: Returns the index of image in given list. */ fun getIndexFromId(list: ArrayList<Image>, imageId: Long): Int { for(i in list){ if(i.id == imageId) return list.indexOf(i) } return 0; } /** * Gets the list of indices from the master list. */ fun getIndexList(list: ArrayList<Image>, masterList: ArrayList<Image>): ArrayList<Int> { // Can be optimised as masterList is sorted by time. val indexes = arrayListOf<Int>() for(image in list) { val index = getIndex(masterList, image) if (index == -1) { continue } indexes.add(index) } return indexes } }
apache-2.0
01df622f984bf80b1d8f4b24908a8d6b
27.873418
92
0.57807
4.505929
false
false
false
false